Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(cli): add non-interactive config commands (#2426)
Hao Zhe7898a19b36c8
diff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rsindex f2bbef96c..07d775f65 100644--- a/crates/ov_cli/src/base_client.rs+++ b/crates/ov_cli/src/base_client.rs@@ -264,7 +264,10 @@ impl BaseClient {};if !status.is_success() {- return Err(Error::Api(api_error_from_envelope(&json, status)));+ return Err(Error::api_with_status(+ api_error_from_envelope(&json, status),+ status.as_u16(),+ ));}if let Some(error) = json.get("error") {@@ -277,7 +280,10 @@ impl BaseClient {.get("message").and_then(|m| m.as_str()).unwrap_or("Unknown error");- return Err(Error::Api(format!("[{}] {}", code, message)));+ return Err(Error::api_with_status(+ format!("[{}] {}", code, message),+ status.as_u16(),+ ));}}diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 1e427357d..ab34d60d9 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -282,7 +282,7 @@ impl HttpClient {}};- return Err(Error::Api(error_msg));+ return Err(Error::api(error_msg));}response@@ -776,7 +776,7 @@ impl HttpClient {}};- return Err(Error::Api(error_msg));+ return Err(Error::api(error_msg));}let bytes = responsediff --git a/crates/ov_cli/src/commands/chat.rs b/crates/ov_cli/src/commands/chat.rsindex 46ce212aa..bb7336cf5 100644--- a/crates/ov_cli/src/commands/chat.rs+++ b/crates/ov_cli/src/commands/chat.rs@@ -129,10 +129,16 @@ impl ChatCommand {fn resolve_auth(&self) -> Result<ChatAuth> {let config = Config::load()?;+ let auth = config.effective_auth_with_overrides(+ self.api_key.clone(),+ self.account.clone(),+ self.user.clone(),+ false,+ );Ok(ChatAuth {- api_key: self.api_key.clone().or(config.api_key),- account: self.account.clone().or(config.account),- user: self.user.clone().or(config.user),+ api_key: auth.api_key,+ account: auth.account,+ user: auth.user,})}@@ -189,7 +195,7 @@ impl ChatCommand {if !response.status().is_success() {let status = response.status();let text = response.text().await.unwrap_or_default();- return Err(Error::Api(format!("Request failed ({}): {}", status, text)));+ return Err(Error::api(format!("Request failed ({}): {}", status, text)));}let chat_response: ChatResponse = response@@ -233,7 +239,7 @@ impl ChatCommand {if !response.status().is_success() {let status = response.status();let text = response.text().await.unwrap_or_default();- return Err(Error::Api(format!("Request failed ({}): {}", status, text)));+ return Err(Error::api(format!("Request failed ({}): {}", status, text)));}// Process the SSE stream@@ -426,7 +432,7 @@ impl ChatCommand {if !response.status().is_success() {let status = response.status();let text = response.text().await.unwrap_or_default();- return Err(Error::Api(format!("Request failed ({}): {}", status, text)));+ return Err(Error::api(format!("Request failed ({}): {}", status, text)));}let chat_response: ChatResponse = response@@ -479,7 +485,7 @@ impl ChatCommand {if !response.status().is_success() {let status = response.status();let text = response.text().await.unwrap_or_default();- return Err(Error::Api(format!("Request failed ({}): {}", status, text)));+ return Err(Error::api(format!("Request failed ({}): {}", status, text)));}let mut response = response;diff --git a/crates/ov_cli/src/commands/session.rs b/crates/ov_cli/src/commands/session.rsindex 3f1c60239..064b858e7 100644--- a/crates/ov_cli/src/commands/session.rs+++ b/crates/ov_cli/src/commands/session.rs@@ -374,7 +374,7 @@ pub async fn add_memory(let session_response: serde_json::Value = client.post("/api/v1/sessions", &json!({})).await?;let mut profile_lines: Vec<serde_json::Value> = extract_profile_lines(&session_response);let session_id = session_response["session_id"].as_str().ok_or_else(|| {- crate::error::Error::Api("Failed to get session_id from new session response".to_string())+ crate::error::Error::api("Failed to get session_id from new session response".to_string())})?;// 2. Add messages (batch)diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rsindex af7fd1637..9bbaeecd0 100644--- a/crates/ov_cli/src/config.rs+++ b/crates/ov_cli/src/config.rs@@ -47,24 +47,50 @@ pub struct Config {pub user: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub agent_id: Option<String>,- #[serde(default = "default_timeout", skip_serializing_if = "is_default_timeout")]+ #[serde(+ default = "default_timeout",+ skip_serializing_if = "is_default_timeout"+ )]pub timeout: f64,- #[serde(default = "default_output_format", skip_serializing_if = "is_default_output")]+ #[serde(+ default = "default_output_format",+ skip_serializing_if = "is_default_output"+ )]pub output: String,- #[serde(default = "default_echo_command", skip_serializing_if = "is_default_echo_command")]+ #[serde(+ default = "default_echo_command",+ skip_serializing_if = "is_default_echo_command"+ )]pub echo_command: bool,- #[serde(default = "default_show_progress", skip_serializing_if = "is_default_show_progress")]+ #[serde(+ default = "default_show_progress",+ skip_serializing_if = "is_default_show_progress"+ )]pub show_progress: bool,- #[serde(default = "default_verbose", skip_serializing_if = "is_default_verbose")]+ #[serde(+ default = "default_verbose",+ skip_serializing_if = "is_default_verbose"+ )]pub verbose: bool,#[serde(default, skip_serializing_if = "is_default_profile")]pub profile: bool,#[serde(default, skip_serializing_if = "UploadConfig::is_default")]pub upload: UploadConfig,- #[serde(default, alias = "extra_header", skip_serializing_if = "Option::is_none")]+ #[serde(+ default,+ alias = "extra_header",+ skip_serializing_if = "Option::is_none"+ )]pub extra_headers: Option<std::collections::HashMap<String, String>>,}+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct EffectiveAuth {+ pub api_key: Option<String>,+ pub account: Option<String>,+ pub user: Option<String>,+}+fn default_url() -> String {DEFAULT_SELF_MANAGED_URL.to_string()}@@ -227,6 +253,38 @@ impl Config {.map_err(|e| Error::Config(format!("Failed to write config file: {}", e)))?;Ok(())}++ pub(crate) fn effective_auth(&self, sudo: bool) -> EffectiveAuth {+ self.effective_auth_with_overrides(None, None, None, sudo)+ }++ pub(crate) fn effective_auth_with_overrides(+ &self,+ api_key_override: Option<String>,+ account_override: Option<String>,+ user_override: Option<String>,+ sudo: bool,+ ) -> EffectiveAuth {+ let api_key = if sudo {+ self.root_api_key.clone()+ } else {+ api_key_override.or_else(|| self.api_key.clone())+ };+ let account = account_override.or_else(|| self.account.clone());+ let user = user_override.or_else(|| self.user.clone());++ let send_identity = if sudo {+ true+ } else {+ api_key.is_none() || api_key.as_deref() == self.root_api_key.as_deref()+ };++ EffectiveAuth {+ api_key,+ account: send_identity.then_some(account).flatten(),+ user: send_identity.then_some(user).flatten(),+ }+ }}pub fn default_config_path() -> Result<PathBuf> {@@ -329,6 +387,72 @@ mod tests {assert_eq!(config.root_api_key.as_deref(), Some("root-key"));}+ #[test]+ fn effective_auth_omits_stale_identity_for_regular_user_key() {+ let config = Config {+ api_key: Some("user-key".to_string()),+ root_api_key: Some("root-key".to_string()),+ account: Some("stale-account".to_string()),+ user: Some("stale-user".to_string()),+ ..Config::default()+ };++ let auth = config.effective_auth(false);++ assert_eq!(auth.api_key.as_deref(), Some("user-key"));+ assert!(auth.account.is_none());+ assert!(auth.user.is_none());+ }++ #[test]+ fn effective_auth_sends_identity_for_root_as_normal() {+ let config = Config {+ api_key: Some("root-key".to_string()),+ root_api_key: Some("root-key".to_string()),+ account: Some("acme".to_string()),+ user: Some("alice".to_string()),+ ..Config::default()+ };++ let auth = config.effective_auth(false);++ assert_eq!(auth.api_key.as_deref(), Some("root-key"));+ assert_eq!(auth.account.as_deref(), Some("acme"));+ assert_eq!(auth.user.as_deref(), Some("alice"));+ }++ #[test]+ fn effective_auth_sends_identity_for_no_key_configs() {+ let config = Config {+ account: Some("default".to_string()),+ user: Some("default".to_string()),+ ..Config::default()+ };++ let auth = config.effective_auth(false);++ assert!(auth.api_key.is_none());+ assert_eq!(auth.account.as_deref(), Some("default"));+ assert_eq!(auth.user.as_deref(), Some("default"));+ }++ #[test]+ fn effective_auth_uses_root_key_and_identity_for_sudo() {+ let config = Config {+ api_key: Some("user-key".to_string()),+ root_api_key: Some("root-key".to_string()),+ account: Some("acme".to_string()),+ user: Some("alice".to_string()),+ ..Config::default()+ };++ let auth = config.effective_auth(true);++ assert_eq!(auth.api_key.as_deref(), Some("root-key"));+ assert_eq!(auth.account.as_deref(), Some("acme"));+ assert_eq!(auth.user.as_deref(), Some("alice"));+ }+#[test]fn config_deserializes_account_id_and_user_id_aliases() {let config: Config = serde_json::from_str(diff --git a/crates/ov_cli/src/config_agent.rs b/crates/ov_cli/src/config_agent.rsnew file mode 100644index 000000000..8cc23bf67--- /dev/null+++ b/crates/ov_cli/src/config_agent.rs@@ -0,0 +1,1306 @@+use std::{+ env, fs,+ io::{self, Read},+ path::PathBuf,+};++use colored::Colorize;+use serde::Serialize;+use serde_json::json;+use uuid::Uuid;++use crate::{+ CliContext, ConfigAddCloudArgs, ConfigAddSelfManagedArgs, ConfigAddTarget, ConfigDeleteArgs,+ ConfigEditArgs,+ config::{Config, DEFAULT_SELF_MANAGED_URL, display_config_home},+ config_wizard::{+ ApiKeyRole, ConfigKind, ConfigStore, VOLCENGINE_CLOUD_URL, configs_equivalent,+ normalize_self_managed_url, self_managed_allows_empty_api_key,+ self_managed_requires_api_key, validate_account_id_value,+ validate_candidate_config_with_role, validate_config_name, validate_user_id_value,+ },+ error::Error,+ output::OutputFormat,+ theme,+};++const EXIT_BAD_INPUT: i32 = 2;+const EXIT_EXISTS_DIFFERENT: i32 = 3;+const EXIT_VALIDATION: i32 = 4;+const EXIT_AUTH: i32 = 5;+const EXIT_REFUSED: i32 = 6;++#[derive(Debug, Clone)]+pub(crate) struct AgentError {+ code: &'static str,+ message: String,+ exit_code: i32,+}++impl AgentError {+ fn bad_input(message: impl Into<String>) -> Self {+ Self {+ code: "bad_input",+ message: message.into(),+ exit_code: EXIT_BAD_INPUT,+ }+ }++ fn exists_different(message: impl Into<String>) -> Self {+ Self {+ code: "config_exists",+ message: message.into(),+ exit_code: EXIT_EXISTS_DIFFERENT,+ }+ }++ fn validation(message: impl Into<String>) -> Self {+ Self {+ code: "validation_failed",+ message: message.into(),+ exit_code: EXIT_VALIDATION,+ }+ }++ fn auth(message: impl Into<String>) -> Self {+ Self {+ code: "auth_mismatch",+ message: message.into(),+ exit_code: EXIT_AUTH,+ }+ }++ fn refused(message: impl Into<String>) -> Self {+ Self {+ code: "refused",+ message: message.into(),+ exit_code: EXIT_REFUSED,+ }+ }++ pub(crate) fn exit_code(&self) -> i32 {+ self.exit_code+ }+}++type AgentResult<T> = std::result::Result<T, AgentError>;++#[derive(Debug, Clone, Copy)]+enum SecretInput<'a> {+ None,+ Stdin,+ Env(&'a str),+}++#[derive(Debug, Clone, Serialize)]+pub(crate) struct ValidationSummary {+ status: &'static str,+}++#[derive(Debug, Clone, Serialize)]+pub(crate) struct AddEditResult {+ action: &'static str,+ name: String,+ kind: &'static str,+ url: String,+ saved_path: String,+ active_path: Option<String>,+ activated: bool,+ validation: ValidationSummary,+ #[serde(skip)]+ root_key_only: bool,+}++#[derive(Debug, Clone, Serialize)]+pub(crate) struct SwitchResult {+ action: &'static str,+ name: String,+ kind: &'static str,+ url: String,+ active_path: String,+ activated: bool,+}++#[derive(Debug, Clone, Serialize)]+pub(crate) struct DeleteResult {+ action: &'static str,+ name: String,+ deleted: bool,+ already_absent: bool,+}++#[derive(Debug, Clone, Serialize)]+pub(crate) struct ListEntry {+ name: String,+ kind: &'static str,+ url: String,+ active: bool,+}++#[derive(Debug)]+pub(crate) enum AgentOutput {+ AddEdit(AddEditResult),+ Switch(SwitchResult),+ Delete(DeleteResult),+ List(Vec<ListEntry>),+}++pub(crate) async fn add(target: ConfigAddTarget, _ctx: &CliContext) -> AgentResult<AgentOutput> {+ let store = ConfigStore::new().map_err(config_error)?;+ let result = match target {+ ConfigAddTarget::Cloud(args) => add_cloud(&store, args).await?,+ ConfigAddTarget::SelfManaged(args) => add_self_managed(&store, args).await?,+ };+ Ok(AgentOutput::AddEdit(result))+}++pub(crate) async fn edit(args: ConfigEditArgs, _ctx: &CliContext) -> AgentResult<AgentOutput> {+ let store = ConfigStore::new().map_err(config_error)?;+ Ok(AgentOutput::AddEdit(edit_saved_config(&store, args).await?))+}++pub(crate) fn switch(name: String, _ctx: &CliContext) -> AgentResult<AgentOutput> {+ let store = ConfigStore::new().map_err(config_error)?;+ validate_config_name(&name).map_err(config_error)?;+ let config = store.load_saved_config(&name).map_err(|error| {+ AgentError::bad_input(format!("Could not load saved config '{name}': {error}"))+ })?;+ store.activate_config(&name).map_err(config_error)?;+ Ok(AgentOutput::Switch(SwitchResult {+ action: "switch",+ name,+ kind: ConfigKind::from_config(&config).label(),+ url: config.url,+ active_path: path_string(store.active_path()),+ activated: true,+ }))+}++pub(crate) fn list(_ctx: &CliContext) -> AgentResult<AgentOutput> {+ let store = ConfigStore::new().map_err(config_error)?;+ let entries = store+ .list_configs()+ .map_err(config_error)?+ .into_iter()+ .map(|entry| ListEntry {+ name: entry.name,+ kind: entry.kind.label(),+ url: entry.config.url,+ active: entry.is_active,+ })+ .collect();+ Ok(AgentOutput::List(entries))+}++pub(crate) fn delete(args: ConfigDeleteArgs, _ctx: &CliContext) -> AgentResult<AgentOutput> {+ let store = ConfigStore::new().map_err(config_error)?;+ delete_saved_config(&store, args)+}++fn delete_saved_config(store: &ConfigStore, args: ConfigDeleteArgs) -> AgentResult<AgentOutput> {+ validate_config_name(&args.name).map_err(config_error)?;+ let path = store.saved_config_path(&args.name).map_err(config_error)?;+ if !path.exists() {+ return Ok(AgentOutput::Delete(DeleteResult {+ action: "delete",+ name: args.name,+ deleted: false,+ already_absent: true,+ }));+ }++ match store.load_saved_config(&args.name) {+ Ok(_) => {+ if store+ .is_config_name_active(&args.name)+ .map_err(config_error)?+ {+ return Err(AgentError::refused(+ "Cannot delete the active config. Run 'ov config switch <name>' first.",+ ));+ }+ }+ Err(error) if !args.force => {+ return Err(AgentError::bad_input(format!(+ "Saved config '{}' cannot be read: {error}. Pass --force to delete the file.",+ args.name+ )));+ }+ Err(_) => {}+ }++ fs::remove_file(&path).map_err(|error| {+ AgentError::bad_input(format!("Failed to delete config '{}': {error}", args.name))+ })?;+ Ok(AgentOutput::Delete(DeleteResult {+ action: "delete",+ name: args.name,+ deleted: true,+ already_absent: false,+ }))+}++pub(crate) fn print_success(output: AgentOutput, ctx: &CliContext) {+ match ctx.output_format {+ OutputFormat::Json => {+ let result = match output {+ AgentOutput::AddEdit(result) => json!(result),+ AgentOutput::Switch(result) => json!(result),+ AgentOutput::Delete(result) => json!(result),+ AgentOutput::List(result) => json!(result),+ };+ println!("{}", json!({ "status": "ok", "result": result }));+ }+ OutputFormat::Table => match output {+ AgentOutput::AddEdit(result) => print_add_edit_result(&result),+ AgentOutput::Switch(result) => {+ println!(+ "{} {}",+ theme::success("✓").bold(),+ theme::success(format!("Switched active config to '{}'.", result.name)).bold()+ );+ println!(+ "{} {}",+ theme::muted("Active config:"),+ theme::sky_value(result.active_path)+ );+ }+ AgentOutput::Delete(result) => {+ if result.already_absent {+ println!(+ "{} {}",+ theme::success("✓").bold(),+ theme::muted(format!("Config '{}' was already absent.", result.name))+ );+ } else {+ println!(+ "{} {}",+ theme::success("✓").bold(),+ theme::success(format!("Deleted config '{}'.", result.name)).bold()+ );+ }+ }+ AgentOutput::List(entries) => print_list_result(&entries),+ },+ }+}++pub(crate) fn print_error(error: &AgentError, ctx: &CliContext) {+ match ctx.output_format {+ OutputFormat::Json => eprintln!(+ "{}",+ json!({+ "status": "error",+ "error": {+ "code": error.code,+ "message": error.message,+ }+ })+ ),+ OutputFormat::Table => {+ eprintln!(+ "{} [{}] {}",+ theme::error("Error").bold(),+ theme::error(error.code),+ theme::body(&error.message)+ );+ }+ }+}++async fn add_cloud(store: &ConfigStore, args: ConfigAddCloudArgs) -> AgentResult<AddEditResult> {+ let name = config_name_or_generate(store, args.name, ConfigKind::VolcengineCloud)?;+ let api_key = read_required_secret(+ secret_input(args.api_key_stdin, args.api_key_env.as_deref()),+ "cloud API key",+ )?;+ validate_optional_identity(args.account.as_deref(), args.user.as_deref())?;++ let config = Config {+ url: VOLCENGINE_CLOUD_URL.to_string(),+ api_key: Some(api_key),+ root_api_key: None,+ account: args.account,+ user: args.user,+ ..Config::default()+ };++ if let Some(result) = existing_add_preflight(+ store,+ &name,+ ConfigKind::VolcengineCloud,+ &config,+ args.activate,+ args.force,+ )? {+ return Ok(result);+ }++ validate_config_for_write(&config, ConfigKind::VolcengineCloud, true).await?;+ save_new_config(+ store,+ &name,+ ConfigKind::VolcengineCloud,+ &config,+ args.activate,+ args.force,+ "add",+ )+}++async fn add_self_managed(+ store: &ConfigStore,+ args: ConfigAddSelfManagedArgs,+) -> AgentResult<AddEditResult> {+ let name = config_name_or_generate(store, args.name, ConfigKind::SelfManaged)?;+ validate_optional_identity(args.account.as_deref(), args.user.as_deref())?;+ let api_key = read_optional_secret(+ secret_input(args.api_key_stdin, args.api_key_env.as_deref()),+ "API key",+ )?;+ let root_api_key = read_optional_secret(+ secret_input(args.root_api_key_stdin, args.root_api_key_env.as_deref()),+ "root API key",+ )?;+ let url = normalize_self_managed_url(args.url.as_deref().unwrap_or(DEFAULT_SELF_MANAGED_URL));++ let config = build_self_managed_config(url, api_key, root_api_key, args.account, args.user)?;++ if let Some(result) = existing_add_preflight(+ store,+ &name,+ ConfigKind::SelfManaged,+ &config,+ args.activate,+ args.force,+ )? {+ return Ok(result);+ }++ validate_config_for_write(&config, ConfigKind::SelfManaged, false).await?;++ save_new_config(+ store,+ &name,+ ConfigKind::SelfManaged,+ &config,+ args.activate,+ args.force,+ "add",+ )+}++async fn edit_saved_config(+ store: &ConfigStore,+ args: ConfigEditArgs,+) -> AgentResult<AddEditResult> {+ validate_config_name(&args.name).map_err(config_error)?;+ let existing = store.load_saved_config(&args.name).map_err(|error| {+ AgentError::bad_input(format!(+ "Could not load saved config '{}': {error}",+ args.name+ ))+ })?;+ let old_kind = ConfigKind::from_config(&existing);+ let existing_root_as_normal = root_as_normal(&existing);+ let api_key_touched = args.api_key_stdin || args.api_key_env.is_some() || args.clear_api_key;+ let root_key_touched =+ args.root_api_key_stdin || args.root_api_key_env.is_some() || args.clear_root_api_key;+ let new_name = args.new_name.clone().unwrap_or_else(|| args.name.clone());+ validate_config_name(&new_name).map_err(config_error)?;+ validate_optional_identity(args.account.as_deref(), args.user.as_deref())?;++ if old_kind == ConfigKind::VolcengineCloud && args.url.is_some() {+ return Err(AgentError::bad_input(+ "Volcengine Cloud configs use a fixed server URL.",+ ));+ }++ let api_secret = read_optional_secret(+ secret_input(args.api_key_stdin, args.api_key_env.as_deref()),+ "API key",+ )?;+ let root_secret = read_optional_secret(+ secret_input(args.root_api_key_stdin, args.root_api_key_env.as_deref()),+ "root API key",+ )?;++ let mut edited = existing.clone();+ if let Some(url) = args.url.as_deref() {+ edited.url = normalize_self_managed_url(url);+ }+ if args.clear_api_key {+ edited.api_key = None;+ }+ if let Some(api_key) = api_secret {+ edited.api_key = Some(api_key);+ }+ if args.clear_root_api_key {+ edited.root_api_key = None;+ if existing_root_as_normal && !api_key_touched {+ edited.api_key = None;+ }+ }+ if let Some(root_api_key) = root_secret {+ if !api_key_touched && (existing_root_as_normal || existing.api_key.is_none()) {+ edited.api_key = Some(root_api_key.clone());+ }+ edited.root_api_key = Some(root_api_key);+ }+ if args.account.is_some() {+ edited.account = args.account;+ }+ if args.user.is_some() {+ edited.user = args.user;+ }+ if !api_key_touched+ && !root_key_touched+ && existing_root_as_normal+ && edited.api_key.as_deref() != edited.root_api_key.as_deref()+ {+ edited.api_key = edited.root_api_key.clone();+ }++ let new_kind = ConfigKind::from_config(&edited);+ if new_kind == ConfigKind::SelfManaged {+ finalize_self_managed_identity(&mut edited)?;+ }+ validate_config_for_write(&edited, new_kind, new_kind == ConfigKind::VolcengineCloud).await?;++ save_edited_config(+ store,+ &args.name,+ &new_name,+ &edited,+ args.activate,+ args.force,+ )+}++fn build_self_managed_config(+ url: String,+ api_key: Option<String>,+ root_api_key: Option<String>,+ mut account: Option<String>,+ mut user: Option<String>,+) -> AgentResult<Config> {+ if api_key.is_none() && root_api_key.is_none() && self_managed_requires_api_key(&url) {+ return Err(AgentError::bad_input(+ "Remote self-managed servers require --api-key-stdin, --api-key-env, --root-api-key-stdin, or --root-api-key-env.",+ ));+ }++ if api_key.is_none() && root_api_key.is_none() && self_managed_allows_empty_api_key(&url) {+ account.get_or_insert_with(|| "default".to_string());+ user.get_or_insert_with(|| "default".to_string());+ }++ let mut config = Config {+ url: url.trim_end_matches('/').to_string(),+ api_key,+ root_api_key,+ account,+ user,+ ..Config::default()+ };++ finalize_self_managed_identity(&mut config)?;++ Ok(config)+}++fn finalize_self_managed_identity(config: &mut Config) -> AgentResult<()> {+ if config.api_key.is_none() {+ config.api_key = config.root_api_key.clone();+ }++ if root_as_normal(config) && (config.account.is_none() || config.user.is_none()) {+ return Err(AgentError::auth(+ "Root API keys require explicit --account and --user.",+ ));+ }++ Ok(())+}++async fn validate_config_for_write(+ config: &Config,+ kind: ConfigKind,+ require_api_key: bool,+) -> AgentResult<()> {+ if let Some(root_key) = config.root_api_key.as_deref() {+ let mut root_probe = config.clone();+ root_probe.api_key = Some(root_key.to_string());+ match validate_candidate_config_with_role(&root_probe, true).await {+ Ok(Some(ApiKeyRole::Root)) => {}+ Ok(Some(ApiKeyRole::Regular)) | Ok(None) => {+ return Err(AgentError::auth(+ "The supplied root API key was not accepted as a root key.",+ ));+ }+ Err(error) => return Err(validation_error(kind, error)),+ }+ }++ let api_key_role = match validate_candidate_config_with_role(config, require_api_key).await {+ Ok(role) => role,+ Err(error) => return Err(validation_error(kind, error)),+ };++ if kind == ConfigKind::SelfManaged+ && api_key_role == Some(ApiKeyRole::Root)+ && !root_as_normal(config)+ {+ return Err(AgentError::auth(+ "The supplied API key is a root key. Use --root-api-key-stdin/--root-api-key-env with --account and --user.",+ ));+ }++ Ok(())+}++fn root_as_normal(config: &Config) -> bool {+ config+ .root_api_key+ .as_ref()+ .is_some_and(|root_key| config.api_key.as_deref() == Some(root_key.as_str()))+}++fn save_new_config(+ store: &ConfigStore,+ name: &str,+ kind: ConfigKind,+ config: &Config,+ activate: bool,+ force: bool,+ action: &'static str,+) -> AgentResult<AddEditResult> {+ let saved_path = store.saved_config_path(name).map_err(config_error)?;+ if saved_path.exists() {+ let existing = store.load_saved_config(name).map_err(config_error)?;+ if configs_equivalent(&existing, config).map_err(config_error)? {+ if activate {+ store.activate_config(name).map_err(config_error)?;+ }+ return Ok(add_edit_result(store, action, name, kind, config, activate));+ }+ if !force {+ return Err(AgentError::exists_different(format!(+ "Config '{name}' already exists with different values. Pass --force to replace it."+ )));+ }+ if store.is_config_name_active(name).map_err(config_error)? && !activate {+ return Err(AgentError::refused(+ "Replacing the active saved config requires --activate.",+ ));+ }+ }++ if activate {+ // Saved and active config files are separate writes: validate first,+ // write the saved config, then write active ovcli.conf.+ store+ .save_and_activate(name, config)+ .map_err(config_error)?;+ } else {+ store+ .save_named_config(name, config)+ .map_err(config_error)?;+ }+ Ok(add_edit_result(store, action, name, kind, config, activate))+}++fn existing_add_preflight(+ store: &ConfigStore,+ name: &str,+ kind: ConfigKind,+ config: &Config,+ activate: bool,+ force: bool,+) -> AgentResult<Option<AddEditResult>> {+ let saved_path = store.saved_config_path(name).map_err(config_error)?;+ if !saved_path.exists() {+ return Ok(None);+ }++ let existing = store.load_saved_config(name).map_err(config_error)?;+ if configs_equivalent(&existing, config).map_err(config_error)? {+ if activate {+ store.activate_config(name).map_err(config_error)?;+ }+ return Ok(Some(add_edit_result(+ store, "add", name, kind, config, activate,+ )));+ }+ if !force {+ return Err(AgentError::exists_different(format!(+ "Config '{name}' already exists with different values. Pass --force to replace it."+ )));+ }+ if store.is_config_name_active(name).map_err(config_error)? && !activate {+ return Err(AgentError::refused(+ "Replacing the active saved config requires --activate.",+ ));+ }++ Ok(None)+}++fn save_edited_config(+ store: &ConfigStore,+ old_name: &str,+ new_name: &str,+ config: &Config,+ activate: bool,+ force: bool,+) -> AgentResult<AddEditResult> {+ let old_config = store.load_saved_config(old_name).map_err(config_error)?;+ let renamed = old_name != new_name;+ let new_path = store.saved_config_path(new_name).map_err(config_error)?;+ if renamed && new_path.exists() {+ let existing_new = store.load_saved_config(new_name).map_err(config_error)?;+ if !configs_equivalent(&existing_new, config).map_err(config_error)? && !force {+ return Err(AgentError::exists_different(format!(+ "Config '{new_name}' already exists with different values. Pass --force to replace it."+ )));+ }+ if store+ .is_config_name_active(new_name)+ .map_err(config_error)?+ {+ return Err(AgentError::refused(+ "Cannot overwrite another active saved config.",+ ));+ }+ if force || configs_equivalent(&existing_new, config).map_err(config_error)? {+ fs::remove_file(&new_path).map_err(|error| {+ AgentError::bad_input(format!(+ "Failed to replace existing config '{new_name}': {error}"+ ))+ })?;+ }+ }++ let content_changed = !configs_equivalent(&old_config, config).map_err(config_error)?;+ if renamed || content_changed {+ store+ .save_edited_config(old_name, new_name, config)+ .map_err(config_error)?;+ }+ if activate {+ // This intentionally activates after the saved file update; there is no+ // cross-file lock between ovcli.conf.<name> and ovcli.conf.+ store.activate_config(new_name).map_err(config_error)?;+ }++ Ok(add_edit_result(+ store,+ "edit",+ new_name,+ ConfigKind::from_config(config),+ config,+ activate,+ ))+}++fn add_edit_result(+ store: &ConfigStore,+ action: &'static str,+ name: &str,+ kind: ConfigKind,+ config: &Config,+ activated: bool,+) -> AddEditResult {+ AddEditResult {+ action,+ name: name.to_string(),+ kind: kind.label(),+ url: config.url.clone(),+ saved_path: store+ .saved_config_path(name)+ .map(path_string)+ .unwrap_or_else(|_| format!("ovcli.conf.{name}")),+ active_path: activated.then(|| path_string(store.active_path())),+ activated,+ validation: ValidationSummary { status: "passed" },+ root_key_only: config.api_key.is_none() && config.root_api_key.is_some(),+ }+}++fn print_add_edit_result(result: &AddEditResult) {+ let verb = if result.action == "add" {+ "Saved"+ } else {+ "Updated"+ };+ let active_copy = if result.activated {+ " and made it active"+ } else {+ ""+ };+ println!(+ "{} {}",+ theme::success("✓").bold(),+ theme::success(format!("{verb} config '{}'{}.", result.name, active_copy)).bold()+ );+ println!(+ "{} {}",+ theme::muted("Saved to:"),+ theme::sky_value(&result.saved_path)+ );+ if let Some(active_path) = &result.active_path {+ println!(+ "{} {}",+ theme::muted("Active config:"),+ theme::sky_value(active_path)+ );+ } else if no_active_config() {+ println!(+ "{} {}",+ theme::warning("Note:"),+ theme::muted(+ "No active config is set. Run 'ov config switch <name>' or add with --activate."+ )+ );+ }+ if result.root_key_only {+ eprintln!(+ "{} {}",+ theme::warning("Note:"),+ theme::muted(+ "This config has only a root API key. Normal commands require --sudo or a regular API key."+ )+ );+ }+}++fn print_list_result(entries: &[ListEntry]) {+ if entries.is_empty() {+ println!("{}", theme::muted("No saved configs found."));+ return;+ }+ println!(+ "{:<24} {:<18} {:<42} {}",+ theme::heading("Name").bold(),+ theme::heading("Type").bold(),+ theme::heading("URL").bold(),+ theme::heading("Active").bold()+ );+ for entry in entries {+ let active = if entry.active {+ theme::error("[Active]").bold().to_string()+ } else {+ String::new()+ };+ println!(+ "{:<24} {:<18} {:<42} {}",+ theme::command(&entry.name).bold(),+ theme::muted(entry.kind),+ theme::sky_value(&entry.url),+ active+ );+ }+}++fn read_required_secret(input: SecretInput<'_>, label: &str) -> AgentResult<String> {+ read_optional_secret(input, label)?.ok_or_else(|| {+ AgentError::bad_input(format!(+ "Missing {label}. Use --api-key-stdin or --api-key-env <ENV>."+ ))+ })+}++fn read_optional_secret(input: SecretInput<'_>, label: &str) -> AgentResult<Option<String>> {+ let value = match input {+ SecretInput::None => return Ok(None),+ SecretInput::Stdin => {+ let mut value = String::new();+ io::stdin().read_to_string(&mut value).map_err(|error| {+ AgentError::bad_input(format!("Failed to read {label} from stdin: {error}"))+ })?;+ value+ }+ SecretInput::Env(name) => env::var(name).map_err(|_| {+ AgentError::bad_input(format!(+ "Environment variable '{name}' for {label} is unset."+ ))+ })?,+ };+ let trimmed = value.trim();+ if trimmed.is_empty() {+ return Err(AgentError::bad_input(format!("{label} cannot be empty.")));+ }+ Ok(Some(trimmed.to_string()))+}++fn secret_input<'a>(stdin: bool, env_name: Option<&'a str>) -> SecretInput<'a> {+ if stdin {+ SecretInput::Stdin+ } else if let Some(env_name) = env_name {+ SecretInput::Env(env_name)+ } else {+ SecretInput::None+ }+}++fn config_name_or_generate(+ store: &ConfigStore,+ name: Option<String>,+ kind: ConfigKind,+) -> AgentResult<String> {+ if let Some(name) = name {+ validate_config_name(&name).map_err(config_error)?;+ return Ok(name);+ }++ let prefix = match kind {+ ConfigKind::VolcengineCloud => "cloud",+ ConfigKind::SelfManaged => "local",+ };+ for _ in 0..32 {+ let suffix = Uuid::new_v4().simple().to_string();+ let candidate = format!("{prefix}-{}", &suffix[..6]);+ if !store+ .saved_config_path(&candidate)+ .map_err(config_error)?+ .exists()+ {+ return Ok(candidate);+ }+ }+ Err(AgentError::bad_input(+ "Could not generate a unique config name. Pass --name explicitly.",+ ))+}++fn validate_optional_identity(account: Option<&str>, user: Option<&str>) -> AgentResult<()> {+ if let Some(account) = account {+ validate_account_id_value(account).map_err(config_error)?;+ }+ if let Some(user) = user {+ validate_user_id_value(user).map_err(config_error)?;+ }+ Ok(())+}++fn validation_error(kind: ConfigKind, error: Error) -> AgentError {+ match error {+ Error::Api { message, .. } => AgentError::auth(format!(+ "{} {message}",+ match kind {+ ConfigKind::VolcengineCloud => "Check the API key.",+ ConfigKind::SelfManaged => "Check the API key, account, and user.",+ }+ )),+ Error::Network(message) => AgentError::validation(format!(+ "{} {message}",+ match kind {+ ConfigKind::VolcengineCloud => "Could not reach Volcengine Cloud.",+ ConfigKind::SelfManaged => "Could not reach the self-managed server.",+ }+ )),+ Error::Config(message) => AgentError::bad_input(message),+ other => AgentError::validation(format!("Validation failed: {other}")),+ }+}++fn config_error(error: Error) -> AgentError {+ AgentError::bad_input(error.to_string())+}++fn no_active_config() -> bool {+ ConfigStore::new()+ .ok()+ .and_then(|store| store.load_active().ok())+ .flatten()+ .is_none()+}++fn path_string(path: impl Into<PathBuf>) -> String {+ path.into().display().to_string()+}++#[allow(dead_code)]+fn config_home_string() -> String {+ display_config_home()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::config_wizard::ConfigStore;+ use std::time::{SystemTime, UNIX_EPOCH};+ use tokio::{+ io::{AsyncReadExt, AsyncWriteExt},+ net::TcpListener,+ };++ fn unique_dir(name: &str) -> PathBuf {+ let suffix = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .expect("clock should be valid")+ .as_nanos();+ std::env::temp_dir().join(format!("openviking-agent-config-{name}-{suffix}"))+ }++ fn sample_config(url: &str, api_key: Option<&str>) -> Config {+ let mut config = Config::default();+ config.url = url.to_string();+ config.api_key = api_key.map(ToString::to_string);+ config+ }++ fn edit_args(name: &str) -> ConfigEditArgs {+ ConfigEditArgs {+ name: name.to_string(),+ new_name: None,+ url: None,+ api_key_stdin: false,+ api_key_env: None,+ clear_api_key: false,+ root_api_key_stdin: false,+ root_api_key_env: None,+ clear_root_api_key: false,+ account: None,+ user: None,+ activate: false,+ force: false,+ }+ }++ fn http_response(status: u16, body: &str) -> String {+ let reason = match status {+ 200 => "OK",+ 401 => "Unauthorized",+ 403 => "Forbidden",+ 404 => "Not Found",+ 500 => "Internal Server Error",+ _ => "OK",+ };+ format!(+ "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",+ body.len()+ )+ }++ async fn spawn_root_validation_server(+ root_api_key: &'static str,+ account: &'static str,+ user: &'static str,+ ) -> String {+ let listener = TcpListener::bind("127.0.0.1:0")+ .await+ .expect("test server should bind");+ let addr = listener.local_addr().expect("test server should have addr");+ tokio::spawn(async move {+ for _ in 0..6 {+ let Ok((mut stream, _)) = listener.accept().await else {+ return;+ };+ let mut buffer = vec![0; 4096];+ let Ok(read) = stream.read(&mut buffer).await else {+ return;+ };+ let request = String::from_utf8_lossy(&buffer[..read]);+ let lower_request = request.to_ascii_lowercase();+ let root_header = format!("x-api-key: {root_api_key}");+ let account_header = format!("x-openviking-account: {account}");+ let user_header = format!("x-openviking-user: {user}");+ let has_root_identity = lower_request.contains(&root_header)+ && lower_request.contains(&account_header)+ && lower_request.contains(&user_header);+ let response = if request.starts_with("GET /health ") {+ http_response(200, r#"{"healthy":true,"auth_mode":"api_key"}"#)+ } else if request.starts_with("GET /api/v1/system/status ") && has_root_identity {+ http_response(200, r#"{"status":"ok","result":{"initialized":true}}"#)+ } else if request.starts_with("GET /api/v1/admin/accounts ") && has_root_identity {+ http_response(200, r#"{"accounts":[]}"#)+ } else {+ http_response(+ 401,+ r#"{"error":{"code":"AuthenticationError","message":"invalid auth"}}"#,+ )+ };+ let _ = stream.write_all(response.as_bytes()).await;+ }+ });+ format!("http://{addr}")+ }++ #[test]+ fn generated_agent_config_name_has_expected_prefix() {+ let dir = unique_dir("name");+ fs::create_dir_all(&dir).expect("dir should exist");+ let store = ConfigStore::for_config_dir(dir);+ let name = config_name_or_generate(&store, None, ConfigKind::VolcengineCloud)+ .expect("name should generate");+ assert!(name.starts_with("cloud-"));+ validate_config_name(&name).expect("generated name should be valid");+ }++ #[test]+ fn identical_existing_add_succeeds_without_force() {+ let dir = unique_dir("identical");+ fs::create_dir_all(&dir).expect("dir should exist");+ let store = ConfigStore::for_config_dir(dir);+ let config = sample_config("http://127.0.0.1:1933", Some("key"));+ store+ .save_named_config("local", &config)+ .expect("config should be saved");++ let result = save_new_config(+ &store,+ "local",+ ConfigKind::SelfManaged,+ &config,+ false,+ false,+ "add",+ )+ .expect("identical config should be idempotent");++ assert_eq!(result.name, "local");+ assert!(!result.activated);+ }++ #[test]+ fn different_existing_add_requires_force() {+ let dir = unique_dir("different");+ fs::create_dir_all(&dir).expect("dir should exist");+ let store = ConfigStore::for_config_dir(dir);+ store+ .save_named_config(+ "local",+ &sample_config("http://127.0.0.1:1933", Some("old")),+ )+ .expect("config should be saved");++ let error = save_new_config(+ &store,+ "local",+ ConfigKind::SelfManaged,+ &sample_config("http://127.0.0.1:1933", Some("new")),+ false,+ false,+ "add",+ )+ .expect_err("different config should require --force");++ assert_eq!(error.exit_code(), EXIT_EXISTS_DIFFERENT);+ }++ #[test]+ fn self_managed_root_only_config_populates_normal_and_root_keys() {+ let config = build_self_managed_config(+ "http://127.0.0.1:1933".to_string(),+ None,+ Some("root-key".to_string()),+ Some("acme".to_string()),+ Some("alice".to_string()),+ )+ .expect("root-only self-managed config should build");++ assert_eq!(config.api_key.as_deref(), Some("root-key"));+ assert_eq!(config.root_api_key.as_deref(), Some("root-key"));+ assert_eq!(config.account.as_deref(), Some("acme"));+ assert_eq!(config.user.as_deref(), Some("alice"));+ }++ #[test]+ fn self_managed_user_and_root_keys_stay_separate() {+ let config = build_self_managed_config(+ "https://ov.example.com".to_string(),+ Some("user-key".to_string()),+ Some("root-key".to_string()),+ Some("acme".to_string()),+ Some("alice".to_string()),+ )+ .expect("self-managed config with both keys should build");++ assert_eq!(config.api_key.as_deref(), Some("user-key"));+ assert_eq!(config.root_api_key.as_deref(), Some("root-key"));+ }++ #[test]+ fn self_managed_root_key_requires_explicit_identity() {+ let error = build_self_managed_config(+ "http://127.0.0.1:1933".to_string(),+ None,+ Some("root-key".to_string()),+ None,+ Some("alice".to_string()),+ )+ .expect_err("root key without account should fail");++ assert_eq!(error.exit_code(), EXIT_AUTH);+ }++ #[test]+ fn self_managed_finalization_promotes_root_only_to_root_as_normal() {+ let mut config = sample_config("http://127.0.0.1:1933", None);+ config.root_api_key = Some("root-key".to_string());+ config.account = Some("acme".to_string());+ config.user = Some("alice".to_string());++ finalize_self_managed_identity(&mut config).expect("root-only config should finalize");++ assert_eq!(config.api_key.as_deref(), Some("root-key"));+ assert_eq!(config.root_api_key.as_deref(), Some("root-key"));+ }++ #[test]+ fn self_managed_finalization_rejects_root_as_normal_without_identity() {+ let mut config = sample_config("http://127.0.0.1:1933", None);+ config.root_api_key = Some("root-key".to_string());+ config.user = Some("alice".to_string());++ let error = finalize_self_managed_identity(&mut config)+ .expect_err("root-as-normal requires explicit account and user");++ assert_eq!(error.exit_code(), EXIT_AUTH);+ }++ #[test]+ fn add_and_edit_finalization_converge_on_root_as_normal_shape() {+ let add_config = build_self_managed_config(+ "http://127.0.0.1:1933".to_string(),+ None,+ Some("root-key".to_string()),+ Some("acme".to_string()),+ Some("alice".to_string()),+ )+ .expect("add path should build root-as-normal config");++ let mut edit_config = sample_config("http://127.0.0.1:1933", None);+ edit_config.root_api_key = Some("root-key".to_string());+ edit_config.account = Some("acme".to_string());+ edit_config.user = Some("alice".to_string());+ finalize_self_managed_identity(&mut edit_config)+ .expect("edit path should finalize to root-as-normal config");++ assert_eq!(edit_config.api_key, add_config.api_key);+ assert_eq!(edit_config.root_api_key, add_config.root_api_key);+ assert_eq!(edit_config.account, add_config.account);+ assert_eq!(edit_config.user, add_config.user);+ }++ #[tokio::test]+ async fn edit_clear_api_key_with_root_identity_becomes_root_as_normal() {+ let dir = unique_dir("edit-clear-api-root-normal");+ fs::create_dir_all(&dir).expect("dir should exist");+ let store = ConfigStore::for_config_dir(dir);+ let url = spawn_root_validation_server("root-key", "acme", "alice").await;+ let mut config = sample_config(&url, Some("user-key"));+ config.root_api_key = Some("root-key".to_string());+ config.account = Some("acme".to_string());+ config.user = Some("alice".to_string());+ store+ .save_named_config("local", &config)+ .expect("config should be saved");++ let mut args = edit_args("local");+ args.clear_api_key = true;+ edit_saved_config(&store, args)+ .await+ .expect("clear API key should promote root key for normal commands");++ let saved = store+ .load_saved_config("local")+ .expect("saved config should load");+ assert_eq!(saved.api_key.as_deref(), Some("root-key"));+ assert_eq!(saved.root_api_key.as_deref(), Some("root-key"));+ assert_eq!(saved.account.as_deref(), Some("acme"));+ assert_eq!(saved.user.as_deref(), Some("alice"));+ }++ #[tokio::test]+ async fn edit_clear_api_key_with_root_without_identity_is_refused() {+ let dir = unique_dir("edit-clear-api-root-no-identity");+ fs::create_dir_all(&dir).expect("dir should exist");+ let store = ConfigStore::for_config_dir(dir);+ let mut config = sample_config("http://127.0.0.1:1933", Some("user-key"));+ config.root_api_key = Some("root-key".to_string());+ store+ .save_named_config("local", &config)+ .expect("config should be saved");++ let mut args = edit_args("local");+ args.clear_api_key = true;+ let error = edit_saved_config(&store, args)+ .await+ .expect_err("root-as-normal edit without identity should fail");++ assert_eq!(error.exit_code(), EXIT_AUTH);+ assert!(error.message.contains("--account and --user"));+ }++ #[test]+ fn replacing_active_saved_config_requires_activate() {+ let dir = unique_dir("active-replace");+ fs::create_dir_all(&dir).expect("dir should exist");+ let store = ConfigStore::for_config_dir(dir);+ let old_config = sample_config("http://127.0.0.1:1933", Some("old"));+ store+ .save_and_activate("local", &old_config)+ .expect("config should be active");++ let error = save_new_config(+ &store,+ "local",+ ConfigKind::SelfManaged,+ &sample_config("http://127.0.0.1:1933", Some("new")),+ false,+ true,+ "add",+ )+ .expect_err("replacing active saved config without --activate is refused");++ assert_eq!(error.exit_code(), EXIT_REFUSED);+ }++ #[test]+ fn deleting_missing_config_is_successful_noop() {+ let dir = unique_dir("delete-missing");+ fs::create_dir_all(&dir).expect("dir should exist");+ let store = ConfigStore::for_config_dir(dir);++ let output = delete_saved_config(+ &store,+ ConfigDeleteArgs {+ name: "missing".to_string(),+ force: false,+ },+ )+ .expect("missing delete should be idempotent");++ let AgentOutput::Delete(result) = output else {+ panic!("expected delete result");+ };+ assert!(!result.deleted);+ assert!(result.already_absent);+ }++ #[test]+ fn deleting_active_config_is_refused() {+ let dir = unique_dir("delete-active");+ fs::create_dir_all(&dir).expect("dir should exist");+ let store = ConfigStore::for_config_dir(dir);+ store+ .save_and_activate(+ "local",+ &sample_config("http://127.0.0.1:1933", Some("key")),+ )+ .expect("config should be active");++ let error = delete_saved_config(+ &store,+ ConfigDeleteArgs {+ name: "local".to_string(),+ force: true,+ },+ )+ .expect_err("active delete should be refused");++ assert_eq!(error.exit_code(), EXIT_REFUSED);+ }+}diff --git a/crates/ov_cli/src/config_command_ui.rs b/crates/ov_cli/src/config_command_ui.rsindex b0177007b..f8a228f8d 100644--- a/crates/ov_cli/src/config_command_ui.rs+++ b/crates/ov_cli/src/config_command_ui.rs@@ -379,7 +379,7 @@ impl ValidationFailureKind {match error {Error::Network(message) if message.contains("unhealthy") => Self::Unhealthy,Error::Network(_) => Self::Network,- Error::Api(message) if looks_like_auth_error(message) => Self::Auth,+ Error::Api { message, .. } if looks_like_auth_error(message) => Self::Auth,_ => Self::Other,}}diff --git a/crates/ov_cli/src/config_wizard/mod.rs b/crates/ov_cli/src/config_wizard/mod.rsindex 5951f31fa..0e6a2e13f 100644--- a/crates/ov_cli/src/config_wizard/mod.rs+++ b/crates/ov_cli/src/config_wizard/mod.rs@@ -1,6 +1,11 @@mod store;mod wizard;-pub(crate) use store::{ConfigKind, ConfigStore};+pub(crate) use store::{+ ApiKeyRole, ConfigKind, ConfigStore, VOLCENGINE_CLOUD_URL, configs_equivalent,+ normalize_self_managed_url, self_managed_allows_empty_api_key,+ self_managed_requires_api_key, validate_account_id_value,+ validate_candidate_config_with_role, validate_config_name, validate_user_id_value,+};pub use store::{redacted_config_value, validate_config};pub use wizard::run_config_wizard;diff --git a/crates/ov_cli/src/config_wizard/store.rs b/crates/ov_cli/src/config_wizard/store.rsindex 5854bdc61..ab7f04697 100644--- a/crates/ov_cli/src/config_wizard/store.rs+++ b/crates/ov_cli/src/config_wizard/store.rs@@ -44,6 +44,12 @@ pub(crate) enum ApiKeyRole {Regular,}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum IdentityField {+ Account,+ User,+}+#[derive(Debug, Clone)]pub struct ConfigDraft {pub name: String,@@ -112,6 +118,15 @@ impl ConfigStore {)?))}+ pub(crate) fn load_saved_config(&self, name: &str) -> Result<Config> {+ let path = self.saved_config_path(name)?;+ if !path.exists() {+ return Err(Error::Config(format!("Config '{name}' does not exist")));+ }+ Config::from_file(&path.to_string_lossy())+ .map_err(|e| Error::Config(format!("Failed to read config '{name}': {e}")))+ }+pub fn list_configs(&self) -> Result<Vec<ConfigEntry>> {let mut configs = Vec::new();@@ -338,6 +353,53 @@ pub fn validate_config_name(name: &str) -> Result<()> {Ok(())}+pub(crate) fn validate_account_id_value(value: &str) -> Result<()> {+ validate_identity_value(value, IdentityField::Account)+}++pub(crate) fn validate_user_id_value(value: &str) -> Result<()> {+ validate_identity_value(value, IdentityField::User)+}++pub(crate) fn validate_identity_value(value: &str, field: IdentityField) -> Result<()> {+ let field_name = match field {+ IdentityField::Account => "Account ID",+ IdentityField::User => "User ID",+ };+ let identifier_name = match field {+ IdentityField::Account => "account_id",+ IdentityField::User => "user_id",+ };+ let trimmed = value.trim();+ if trimmed.is_empty() {+ return Err(Error::Config(format!("{field_name} cannot be empty")));+ }+ if trimmed != value {+ return Err(Error::Config(format!(+ "{field_name} cannot start or end with whitespace"+ )));+ }+ if matches!(field, IdentityField::Account) && trimmed.starts_with('_') {+ return Err(Error::Config(+ "Account ID cannot start with '_'".to_string(),+ ));+ }+ if !trimmed+ .chars()+ .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.' | '@'))+ {+ return Err(Error::Config(format!(+ "{field_name} can only contain letters, numbers, '_', '-', '.', and '@'"+ )));+ }+ if trimmed.matches('@').count() > 1 {+ return Err(Error::Config(format!(+ "{identifier_name} must have at most one '@'"+ )));+ }+ Ok(())+}+pub fn build_config(draft: &ConfigDraft) -> Result<Config> {validate_config_name(&draft.name)?;@@ -401,15 +463,15 @@ pub(crate) fn normalize_self_managed_url(url: &str) -> String {if trimmed.eq_ignore_ascii_case("::1") || trimmed.eq_ignore_ascii_case("[::1]") {return format!("http://[::1]:{DEFAULT_SELF_MANAGED_PORT}");}- if let Some(port) = trimmed.strip_prefix("[::1]:") {- if !port.trim().is_empty() {- return format!("http://[::1]:{port}");- }+ if let Some(port) = trimmed.strip_prefix("[::1]:")+ && !port.trim().is_empty()+ {+ return format!("http://[::1]:{port}");}- if let Some(port) = trimmed.strip_prefix("::1:") {- if !port.trim().is_empty() {- return format!("http://[::1]:{port}");- }+ if let Some(port) = trimmed.strip_prefix("::1:")+ && !port.trim().is_empty()+ {+ return format!("http://[::1]:{port}");}if Url::parse(trimmed).is_ok() {@@ -466,12 +528,13 @@ pub(crate) async fn validate_candidate_config_with_role(}let timeout = config.timeout.clamp(1.0, 10.0);+ let auth = config.effective_auth(false);let client = BaseClient::new(&config.url,- api_key.clone(),+ auth.api_key.clone(),config.agent_id.clone(),- config.account.clone(),- config.user.clone(),+ auth.account,+ auth.user,timeout,config.profile,config.extra_headers.clone(),@@ -488,11 +551,11 @@ pub(crate) async fn validate_candidate_config_with_role());}- if should_run_authenticated_probe(&value, require_api_key, api_key.is_some()) {+ if should_run_authenticated_probe(&value, require_api_key, auth.api_key.is_some()) {let _: Value = client.get("/api/v1/system/status", &[]).await?;}- if api_key.is_some() {+ if auth.api_key.is_some() {return detect_api_key_role(&client).await.map(Some);}@@ -502,11 +565,32 @@ pub(crate) async fn validate_candidate_config_with_role(async fn detect_api_key_role(client: &BaseClient) -> Result<ApiKeyRole> {match client.get::<Value>("/api/v1/admin/accounts", &[]).await {Ok(_) => Ok(ApiKeyRole::Root),- Err(Error::Api(_)) => Ok(ApiKeyRole::Regular),+ Err(Error::Api {+ status: Some(status),+ ..+ }) if admin_probe_regular_key_status(status) => Ok(ApiKeyRole::Regular),+ Err(Error::Api { message, status }) => Err(Error::Api { message, status }),Err(error) => Err(error),}}+fn admin_probe_regular_key_status(status: u16) -> bool {+ matches!(+ status,+ // 401/403 means the key works but does not have admin access.+ 401 | 403+ // Some self-managed deployments may not expose the admin endpoint.+ // Treat explicit absence as regular access rather than blocking a+ // valid non-admin setup.+ | 404+ )+}++#[cfg(test)]+fn admin_probe_ambiguous_status(status: u16) -> bool {+ matches!(status, 408 | 429 | 500..=599)+}+fn should_run_authenticated_probe(health: &Value,require_api_key: bool,@@ -568,7 +652,7 @@ fn write_file_atomically(path: &Path, content: &[u8]) -> Result<()> {Ok(())}-fn configs_equivalent(left: &Config, right: &Config) -> Result<bool> {+pub(crate) fn configs_equivalent(left: &Config, right: &Config) -> Result<bool> {Ok(serde_json::to_value(left)? == serde_json::to_value(right)?)}@@ -582,7 +666,8 @@ fn non_empty_option(value: Option<&str>) -> Option<String> {#[cfg(test)]mod tests {use super::{- ApiKeyRole, ConfigDraft, ConfigKind, ConfigStore, VOLCENGINE_CLOUD_URL, build_config,+ ApiKeyRole, ConfigDraft, ConfigKind, ConfigStore, VOLCENGINE_CLOUD_URL,+ admin_probe_ambiguous_status, admin_probe_regular_key_status, build_config,should_run_authenticated_probe, validate_candidate_config,validate_candidate_config_with_role, validate_config_name, validation_error_copy,};@@ -854,6 +939,24 @@ mod tests {assert_eq!(regular_role, Some(ApiKeyRole::Regular));}+ #[tokio::test]+ async fn api_key_role_detection_fails_on_ambiguous_admin_probe_errors() {+ let url = spawn_admin_probe_500_server("maybe-root").await;+ let config = sample_config(&url, Some("maybe-root"));++ let error = validate_candidate_config_with_role(&config, true)+ .await+ .expect_err("admin probe 500 should not be classified as regular");++ assert!(matches!(+ error,+ crate::error::Error::Api {+ status: Some(500),+ ..+ }+ ));+ }+#[tokio::test]async fn self_managed_config_with_api_key_validates_authenticated_probe() {let url = spawn_auth_probe_server("good-key").await;@@ -863,7 +966,7 @@ mod tests {.await.expect_err("bad self-managed API key should fail validation");- assert!(matches!(error, crate::error::Error::Api(_)));+ assert!(matches!(error, crate::error::Error::Api { .. }));}#[tokio::test]@@ -875,7 +978,7 @@ mod tests {.await.expect_err("auth-required local server should reject empty API key");- assert!(matches!(error, crate::error::Error::Api(_)));+ assert!(matches!(error, crate::error::Error::Api { .. }));}#[test]@@ -899,9 +1002,21 @@ mod tests {));}+ #[test]+ fn admin_probe_status_classification_is_explicit() {+ assert!(admin_probe_regular_key_status(401));+ assert!(admin_probe_regular_key_status(403));+ assert!(admin_probe_regular_key_status(404));+ assert!(admin_probe_ambiguous_status(408));+ assert!(admin_probe_ambiguous_status(429));+ assert!(admin_probe_ambiguous_status(500));+ assert!(admin_probe_ambiguous_status(503));+ assert!(!admin_probe_regular_key_status(500));+ }+#[test]fn validation_error_copy_hides_raw_backend_details() {- let error = crate::error::Error::Api(+ let error = crate::error::Error::api("[AuthenticationError] invalid key. Request ID: 02177930089909800000000000000000ffff".to_string(),);@@ -1135,10 +1250,53 @@ mod tests {format!("http://{addr}")}+ async fn spawn_admin_probe_500_server(api_key: &'static str) -> String {+ let listener = TcpListener::bind("127.0.0.1:0")+ .await+ .expect("test server should bind");+ let addr = listener.local_addr().expect("test server should have addr");+ tokio::spawn(async move {+ for _ in 0..3 {+ let Ok((mut stream, _)) = listener.accept().await else {+ return;+ };+ let mut buffer = vec![0; 4096];+ let Ok(read) = stream.read(&mut buffer).await else {+ return;+ };+ let request = String::from_utf8_lossy(&buffer[..read]);+ let lower_request = request.to_ascii_lowercase();+ let api_header = format!("x-api-key: {api_key}");+ let response = if request.starts_with("GET /health ") {+ http_response(200, r#"{"healthy":true,"auth_mode":"api_key"}"#)+ } else if request.starts_with("GET /api/v1/system/status ") {+ if lower_request.contains(&api_header) {+ http_response(200, r#"{"status":"ok","result":{"initialized":true}}"#)+ } else {+ http_response(+ 401,+ r#"{"error":{"code":"AuthenticationError","message":"invalid key"}}"#,+ )+ }+ } else if request.starts_with("GET /api/v1/admin/accounts ") {+ http_response(+ 500,+ r#"{"error":{"code":"INTERNAL","message":"admin probe failed"}}"#,+ )+ } else {+ http_response(404, r#"{"error":{"message":"not found"}}"#)+ };+ let _ = stream.write_all(response.as_bytes()).await;+ }+ });+ format!("http://{addr}")+ }+fn http_response(status: u16, body: &str) -> String {let reason = match status {200 => "OK",401 => "Unauthorized",+ 500 => "Internal Server Error",404 => "Not Found",_ => "OK",};diff --git a/crates/ov_cli/src/config_wizard/wizard.rs b/crates/ov_cli/src/config_wizard/wizard.rsindex cf0ed7cc5..d37f12d36 100644--- a/crates/ov_cli/src/config_wizard/wizard.rs+++ b/crates/ov_cli/src/config_wizard/wizard.rs@@ -24,9 +24,10 @@ use crate::{use serde_json::Value;use super::store::{- ApiKeyRole, ConfigDraft, ConfigEntry, ConfigKind, ConfigStore, VOLCENGINE_CLOUD_URL,- build_config, self_managed_allows_empty_api_key, validate_candidate_config,- validate_candidate_config_with_role, validate_config_name, validation_error_copy,+ ApiKeyRole, ConfigDraft, ConfigEntry, ConfigKind, ConfigStore, IdentityField,+ VOLCENGINE_CLOUD_URL, build_config, self_managed_allows_empty_api_key,+ validate_candidate_config, validate_candidate_config_with_role, validate_config_name,+ validate_identity_value, validation_error_copy,};const VOLCENGINE_API_KEY_URL: &str =@@ -58,12 +59,6 @@ enum SelfManagedEditKeyAction {ClearAllKeys,}-#[derive(Clone, Copy)]-enum IdentityField {- Account,- User,-}-const OV_LOGO_LINES: [&str; 14] = [""," ⢻⣶⣄",@@ -522,55 +517,6 @@ pub(crate) fn should_prompt_root_identity(&& (api_key_was_entered || is_blank(account) || is_blank(user))}-#[cfg(test)]-fn validate_account_id_value(value: &str) -> Result<()> {- validate_identity_value(value, IdentityField::Account)-}--#[cfg(test)]-fn validate_user_id_value(value: &str) -> Result<()> {- validate_identity_value(value, IdentityField::User)-}--fn validate_identity_value(value: &str, field: IdentityField) -> Result<()> {- let field_name = match field {- IdentityField::Account => "Account ID",- IdentityField::User => "User ID",- };- let identifier_name = match field {- IdentityField::Account => "account_id",- IdentityField::User => "user_id",- };- let trimmed = value.trim();- if trimmed.is_empty() {- return Err(Error::Config(format!("{field_name} cannot be empty")));- }- if trimmed != value {- return Err(Error::Config(format!(- "{field_name} cannot start or end with whitespace"- )));- }- if matches!(field, IdentityField::Account) && trimmed.starts_with('_') {- return Err(Error::Config(- "Account ID cannot start with '_'".to_string(),- ));- }- if !trimmed- .chars()- .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.' | '@'))- {- return Err(Error::Config(format!(- "{field_name} can only contain letters, numbers, '_', '-', '.', and '@'"- )));- }- if trimmed.matches('@').count() > 1 {- return Err(Error::Config(format!(- "{identifier_name} must have at most one '@'"- )));- }- Ok(())-}-fn print_header() {let lines = wizard_header_lines();println!();@@ -802,12 +748,13 @@ async fn status_box_runtime(active: Option<&Config>) -> StatusBoxRuntime {return StatusBoxRuntime::not_configured();};+ let auth = config.effective_auth(false);let client = BaseClient::new(config.url.clone(),- config.api_key.clone(),+ auth.api_key,config.agent_id.clone(),- config.account.clone(),- config.user.clone(),+ auth.account,+ auth.user,STATUS_BOX_PROBE_TIMEOUT_SECS,config.profile,config.extra_headers.clone(),@@ -3833,13 +3780,14 @@ mod tests {should_prompt_root_identity, status_box_lines, status_box_lines_with_runtime,status_box_width, status_payload_is_healthy, styled_logo_to_width_for_color_level,styled_wordmark_line_for_color_level, tagline_ice_color_for_theme,- user_key_redirect_labels, validate_account_id_value, validate_config_name, validate_draft,- validate_user_id_value, volcengine_api_key_helper_lines, wizard_header_lines,- wordmark_gradient_color_for_theme, wordmark_lines, wordmark_width,+ user_key_redirect_labels, validate_config_name, validate_draft,+ volcengine_api_key_helper_lines, wizard_header_lines, wordmark_gradient_color_for_theme,+ wordmark_lines, wordmark_width,};use crate::config::Config;use crate::config_wizard::store::{- ApiKeyRole, ConfigDraft, ConfigEntry, ConfigKind, ConfigStore,+ ApiKeyRole, ConfigDraft, ConfigEntry, ConfigKind, ConfigStore, validate_account_id_value,+ validate_user_id_value,};use crate::theme::{self, ThemeColor};use colored::Colorize;diff --git a/crates/ov_cli/src/error.rs b/crates/ov_cli/src/error.rsindex 05303364c..a73950278 100644--- a/crates/ov_cli/src/error.rs+++ b/crates/ov_cli/src/error.rs@@ -14,8 +14,11 @@ pub enum Error {#[error("Network error: {0}")]Network(String),- #[error("API error: {0}")]- Api(String),+ #[error("API error: {message}")]+ Api {+ message: String,+ status: Option<u16>,+ },#[error("Client error: {0}")]Client(String),@@ -42,4 +45,20 @@ pub enum Error {AlreadyReported,}+impl Error {+ pub fn api(message: impl Into<String>) -> Self {+ Self::Api {+ message: message.into(),+ status: None,+ }+ }++ pub fn api_with_status(message: impl Into<String>, status: u16) -> Self {+ Self::Api {+ message: message.into(),+ status: Some(status),+ }+ }+}+pub type Result<T> = std::result::Result<T, Error>;diff --git a/crates/ov_cli/src/error_ui.rs b/crates/ov_cli/src/error_ui.rsindex 6aad4af54..f746529a0 100644--- a/crates/ov_cli/src/error_ui.rs+++ b/crates/ov_cli/src/error_ui.rs@@ -230,7 +230,7 @@ pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &ErrorErrorAction::new("ov health", copy(language, "Run a quick server health check", "快速检查服务器健康状态")),ErrorAction::new("ov config switch", copy(language, "Switch to another config", "切换到其他配置")),]),- Error::Api(message) if looks_like_auth_error(message) => ErrorReport::new(+ Error::Api { message, .. } if looks_like_auth_error(message) => ErrorReport::new(copy(language, "Authentication Error", "认证错误"),copy(language, "OpenViking rejected the API key for the active config.", "OpenViking 拒绝了当前配置的 API Key。"),)@@ -240,7 +240,7 @@ pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &ErrorErrorAction::new("ov config", copy(language, "Edit this config", "编辑这个配置")),ErrorAction::new("ov config switch", copy(language, "Use another config", "使用其他配置")),]),- Error::Api(message) => ErrorReport::new(+ Error::Api { message, .. } => ErrorReport::new(copy(language, "OpenViking API Error", "OpenViking API 错误"),api_error_message(language, message),)@@ -1031,7 +1031,7 @@ Usage: ov config [OPTIONS] [COMMAND]#[test]fn runtime_api_error_hides_raw_detail_by_default() {- let error = Error::Api(+ let error = Error::api("[AuthenticationError] API key invalid. Request ID: 02177930089909800000000000000000".to_string(),);@@ -1051,7 +1051,7 @@ Usage: ov config [OPTIONS] [COMMAND]#[test]fn runtime_api_error_shows_sanitized_detail_by_default() {- let error = Error::Api(+ let error = Error::api("[InvalidRequest] resource not found. Request ID: 02177930089909800000000000000000".to_string(),);@@ -1070,7 +1070,7 @@ Usage: ov config [OPTIONS] [COMMAND]#[test]fn runtime_api_error_summarizes_json_error_envelope() {- let error = Error::Api(+ let error = Error::api(r#"{"error":{"code":"PermissionDenied","message":"root key required","request_id":"abc"}}"#.to_string(),);diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex da12eab5a..d5314b379 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -3,6 +3,7 @@ use crate::PrivacyCommands;use crate::client;use crate::commands;use crate::config::merge_csv_options;+use crate::config_agent;use crate::error::{Error, Result};use crate::theme;use crate::tui;@@ -73,12 +74,13 @@ pub async fn handle_add_resource(} else {ctx.config.timeout};+ let auth = ctx.config.effective_auth(ctx.sudo);let client = client::HttpClient::new(&ctx.config.url,- ctx.config.api_key.clone(),+ auth.api_key,ctx.config.agent_id.clone(),- ctx.config.account.clone(),- ctx.config.user.clone(),+ auth.account,+ auth.user,effective_timeout,ctx.profile.unwrap_or(ctx.config.profile),ctx.config.extra_headers.clone(),@@ -570,7 +572,7 @@ use crate::output;// Config commands intentionally edit the persisted ovcli.conf files. Runtime// overrides carried in CliContext should not change what gets shown or saved.-pub async fn handle_config(cmd: Option<ConfigCommands>, _ctx: CliContext) -> Result<()> {+pub async fn handle_config(cmd: Option<ConfigCommands>, ctx: CliContext) -> Result<()> {match cmd {Some(ConfigCommands::Show) => {let config = Config::load()?;@@ -606,11 +608,43 @@ pub async fn handle_config(cmd: Option<ConfigCommands>, _ctx: CliContext) -> Res}}}- Some(ConfigCommands::Switch) => handle_config_switch().await,+ Some(ConfigCommands::Switch { name: None }) => handle_config_switch().await,+ Some(ConfigCommands::Switch { name: Some(name) }) => {+ handle_config_agent_result(config_agent::switch(name, &ctx), &ctx)+ }+ Some(ConfigCommands::List) => handle_config_agent_result(config_agent::list(&ctx), &ctx),+ Some(ConfigCommands::Delete(args)) => {+ handle_config_agent_result(config_agent::delete(args, &ctx), &ctx)+ }+ Some(ConfigCommands::Add { target }) => {+ let result = config_agent::add(target, &ctx).await;+ handle_config_agent_result(result, &ctx)+ }+ Some(ConfigCommands::Edit(args)) => {+ let result = config_agent::edit(args, &ctx).await;+ handle_config_agent_result(result, &ctx)+ }None => config_wizard::run_config_wizard().await,}}+fn handle_config_agent_result(+ result: std::result::Result<config_agent::AgentOutput, config_agent::AgentError>,+ ctx: &CliContext,+) -> Result<()> {+ match result {+ Ok(output) => {+ config_agent::print_success(output, ctx);+ Ok(())+ }+ Err(error) => {+ let exit_code = error.exit_code();+ config_agent::print_error(&error, ctx);+ std::process::exit(exit_code);+ }+ }+}+pub async fn handle_language(value: Option<String>) -> Result<()> {let language = match value {Some(value) => Language::from_code(&value).ok_or_else(|| {@@ -1321,7 +1355,7 @@ pub async fn handle_glob(node_limit: i32,ctx: CliContext,) -> Result<()> {- let params = vec![+ let params = [format!("--uri={}", uri),format!("-n {}", node_limit),format!("\"{}\"", pattern),diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rsindex 2cbccb2b5..c7245a50c 100644--- a/crates/ov_cli/src/help_ui.rs+++ b/crates/ov_cli/src/help_ui.rs@@ -175,6 +175,21 @@ const CONFIG_STATUS: &[HelpCommand] = &[description: "Switch active config",badge: None,},+ HelpCommand {+ name: "config add",+ description: "Add a config non-interactively",+ badge: None,+ },+ HelpCommand {+ name: "config list",+ description: "List saved configs",+ badge: None,+ },+ HelpCommand {+ name: "config delete",+ description: "Delete a saved config",+ badge: None,+ },HelpCommand {name: "language",description: "Choose CLI display language (alias: lang)",@@ -1552,12 +1567,20 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[CommandHelpSpec {path: &["config"],purpose: "Add, edit, delete, show, validate, or switch OpenViking CLI configs.",- usage: "ov config [show|validate|switch]",+ usage: "ov config [show|validate|switch|list|add|edit|delete]",examples: &[HelpItem {label: "ov config",description: "Open the interactive config manager.",},+ HelpItem {+ label: "ov config add cloud --api-key-stdin --activate",+ description: "Create and activate a cloud config from stdin.",+ },+ HelpItem {+ label: "ov config list -o json",+ description: "List saved configs for automation.",+ },HelpItem {label: "ov config validate",description: "Probe the active config.",@@ -1577,7 +1600,23 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[},HelpItem {label: "switch",- description: "Switch the active saved config.",+ description: "Switch the active saved config interactively or by name.",+ },+ HelpItem {+ label: "list",+ description: "List saved configs.",+ },+ HelpItem {+ label: "add",+ description: "Add a cloud or self-managed config without prompts.",+ },+ HelpItem {+ label: "edit",+ description: "Edit a saved config without prompts.",+ },+ HelpItem {+ label: "delete",+ description: "Delete a saved config without prompts.",},],next_steps: &[@@ -1640,12 +1679,21 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[CommandHelpSpec {path: &["config", "switch"],purpose: "Switch the active CLI config to a saved config.",- usage: "ov config switch",- examples: &[HelpItem {- label: "ov config switch",- description: "Choose a saved config and make it active.",+ usage: "ov config switch [name]",+ examples: &[+ HelpItem {+ label: "ov config switch",+ description: "Choose a saved config interactively.",+ },+ HelpItem {+ label: "ov config switch prod",+ description: "Activate a saved config without prompts.",+ },+ ],+ arguments: &[HelpItem {+ label: "name",+ description: "Optional saved config name. Omit it for the interactive picker.",}],- arguments: &[],common_options: &[],advanced_options: &[],subcommands: &[],@@ -1660,6 +1708,300 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[},],},+ CommandHelpSpec {+ path: &["config", "list"],+ purpose: "List saved CLI configs and mark which one is active.",+ usage: "ov config list",+ examples: &[+ HelpItem {+ label: "ov config list",+ description: "Show saved configs in a readable table.",+ },+ HelpItem {+ label: "ov config list -o json",+ description: "Return saved configs as JSON for automation.",+ },+ ],+ arguments: &[],+ common_options: &[],+ advanced_options: &[],+ subcommands: &[],+ next_steps: &[+ HelpItem {+ label: "ov config switch <name>",+ description: "Activate a saved config.",+ },+ HelpItem {+ label: "ov config add --help",+ description: "Create a new saved config.",+ },+ ],+ },+ CommandHelpSpec {+ path: &["config", "add"],+ purpose: "Create a saved CLI config without opening the interactive wizard.",+ usage: "ov config add <cloud|self-managed> [options]",+ examples: &[+ HelpItem {+ label: "printf '%s' \"$OV_KEY\" | ov config add cloud --api-key-stdin --activate",+ description: "Create and activate a Volcengine Cloud config.",+ },+ HelpItem {+ label: "ov config add self-managed --name local --url http://127.0.0.1:1933 --activate",+ description: "Create and activate a local self-managed config.",+ },+ ],+ arguments: &[],+ common_options: &[],+ advanced_options: &[],+ subcommands: &[+ HelpItem {+ label: "cloud",+ description: "Use the fixed Volcengine Cloud endpoint.",+ },+ HelpItem {+ label: "self-managed",+ description: "Use a local or hosted self-managed endpoint.",+ },+ ],+ next_steps: &[+ HelpItem {+ label: "ov config add cloud --help",+ description: "See cloud-specific flags.",+ },+ HelpItem {+ label: "ov config add self-managed --help",+ description: "See self-managed flags.",+ },+ ],+ },+ CommandHelpSpec {+ path: &["config", "add", "cloud"],+ purpose: "Create a Volcengine Cloud config without prompts.",+ usage: "ov config add cloud [--name <name>] (--api-key-stdin|--api-key-env <env>) [--account <account> --user <user>] [--activate] [--force]",+ examples: &[+ HelpItem {+ label: "printf '%s' \"$OV_KEY\" | ov config add cloud --name prod --api-key-stdin --activate",+ description: "Read the API key from stdin and make the config active.",+ },+ HelpItem {+ label: "ov config add cloud --api-key-env OV_KEY -o json",+ description: "Read the API key from an environment variable and print JSON.",+ },+ ],+ arguments: &[],+ common_options: &[+ HelpItem {+ label: "--name <name>",+ description: "Saved config name. Generated if omitted.",+ },+ HelpItem {+ label: "--api-key-stdin",+ description: "Read the API key from stdin.",+ },+ HelpItem {+ label: "--api-key-env <env>",+ description: "Read the API key from an environment variable.",+ },+ HelpItem {+ label: "--activate",+ description: "Also write the active ovcli.conf.",+ },+ HelpItem {+ label: "--force",+ description: "Replace an existing saved config.",+ },+ ],+ advanced_options: &[+ HelpItem {+ label: "--account <account>",+ description: "Optional account identity override.",+ },+ HelpItem {+ label: "--user <user>",+ description: "Optional user identity override.",+ },+ ],+ subcommands: &[],+ next_steps: &[+ HelpItem {+ label: "ov config validate",+ description: "Validate the active config.",+ },+ HelpItem {+ label: "ov config list",+ description: "Inspect saved configs.",+ },+ ],+ },+ CommandHelpSpec {+ path: &["config", "add", "self-managed"],+ purpose: "Create a self-managed config without prompts.",+ usage: "ov config add self-managed [--name <name>] [--url <url>] [--api-key-stdin|--api-key-env <env>] [--root-api-key-stdin|--root-api-key-env <env>] [--account <account>] [--user <user>] [--activate] [--force]",+ examples: &[+ HelpItem {+ label: "ov config add self-managed --name local --url http://127.0.0.1:1933 --activate",+ description: "Create a local no-key config.",+ },+ HelpItem {+ label: "ov config add self-managed --url https://ov.example.com --api-key-env OV_KEY --activate",+ description: "Create a hosted self-managed config with an API key.",+ },+ ],+ arguments: &[],+ common_options: &[+ HelpItem {+ label: "--name <name>",+ description: "Saved config name. Generated if omitted.",+ },+ HelpItem {+ label: "--url <url>",+ description: "Server URL. Defaults to http://127.0.0.1:1933.",+ },+ HelpItem {+ label: "--api-key-stdin / --api-key-env <env>",+ description: "Read a normal API key from stdin or an environment variable.",+ },+ HelpItem {+ label: "--root-api-key-stdin / --root-api-key-env <env>",+ description: "Read a root API key from stdin or an environment variable.",+ },+ HelpItem {+ label: "--activate",+ description: "Also write the active ovcli.conf.",+ },+ HelpItem {+ label: "--force",+ description: "Replace an existing saved config.",+ },+ ],+ advanced_options: &[+ HelpItem {+ label: "--account <account>",+ description: "Account identity. Required when only a root key is supplied.",+ },+ HelpItem {+ label: "--user <user>",+ description: "User identity. Required when only a root key is supplied.",+ },+ ],+ subcommands: &[],+ next_steps: &[+ HelpItem {+ label: "ov config validate",+ description: "Validate the active config.",+ },+ HelpItem {+ label: "ov config list",+ description: "Inspect saved configs.",+ },+ ],+ },+ CommandHelpSpec {+ path: &["config", "edit"],+ purpose: "Edit a saved CLI config without prompts.",+ usage: "ov config edit <name> [--new-name <name>] [--url <url>] [key options] [identity options] [--activate] [--force]",+ examples: &[+ HelpItem {+ label: "ov config edit prod --new-name production --activate",+ description: "Rename a saved config and make it active.",+ },+ HelpItem {+ label: "printf '%s' \"$OV_KEY\" | ov config edit prod --api-key-stdin --activate",+ description: "Replace the API key, validate, then activate.",+ },+ HelpItem {+ label: "ov config edit local --clear-api-key --activate",+ description: "Remove a normal API key from a saved config.",+ },+ ],+ arguments: &[HelpItem {+ label: "name",+ description: "Existing saved config name.",+ }],+ common_options: &[+ HelpItem {+ label: "--new-name <name>",+ description: "Rename the saved config.",+ },+ HelpItem {+ label: "--url <url>",+ description: "Replace the self-managed server URL.",+ },+ HelpItem {+ label: "--api-key-stdin / --api-key-env <env> / --clear-api-key",+ description: "Replace or clear the normal API key.",+ },+ HelpItem {+ label: "--root-api-key-stdin / --root-api-key-env <env> / --clear-root-api-key",+ description: "Replace or clear the root API key.",+ },+ HelpItem {+ label: "--activate",+ description: "Also make the edited config active.",+ },+ HelpItem {+ label: "--force",+ description: "Replace an existing target name when renaming.",+ },+ ],+ advanced_options: &[+ HelpItem {+ label: "--account <account>",+ description: "Replace account identity.",+ },+ HelpItem {+ label: "--user <user>",+ description: "Replace user identity.",+ },+ ],+ subcommands: &[],+ next_steps: &[+ HelpItem {+ label: "ov config validate",+ description: "Validate the active config.",+ },+ HelpItem {+ label: "ov config list",+ description: "Inspect saved configs.",+ },+ ],+ },+ CommandHelpSpec {+ path: &["config", "delete"],+ purpose: "Delete a saved CLI config without prompts.",+ usage: "ov config delete <name> [--force]",+ examples: &[+ HelpItem {+ label: "ov config delete old-local",+ description: "Delete a non-active saved config.",+ },+ HelpItem {+ label: "ov config delete missing -o json",+ description: "Return a JSON no-op if the config is already absent.",+ },+ ],+ arguments: &[HelpItem {+ label: "name",+ description: "Saved config name to delete.",+ }],+ common_options: &[HelpItem {+ label: "--force",+ description: "Reserved for future destructive delete behavior.",+ }],+ advanced_options: &[],+ subcommands: &[],+ next_steps: &[+ HelpItem {+ label: "ov config list",+ description: "Inspect remaining configs.",+ },+ HelpItem {+ label: "ov config switch <name>",+ description: "Switch away from an active config before deleting it.",+ },+ ],+ },CommandHelpSpec {path: &["language"],purpose: "Choose the OpenViking CLI display language.",@@ -2057,7 +2399,7 @@ fn help_item_line(item: &HelpItem) -> String {)}-fn localized_command_purpose<'a>(spec: &'a CommandHelpSpec, language: Language) -> &'a str {+fn localized_command_purpose(spec: &CommandHelpSpec, language: Language) -> &str {if language == Language::En {return spec.purpose;}@@ -2066,6 +2408,12 @@ fn localized_command_purpose<'a>(spec: &'a CommandHelpSpec, language: Language)["config", "show"] => "显示当前 CLI 配置,并隐藏敏感信息。",["config", "validate"] => "解析当前配置,并探测 OpenViking 服务器。",["config", "switch"] => "切换到已保存的 CLI 配置。",+ ["config", "list"] => "列出已保存的 CLI 配置,并标记当前配置。",+ ["config", "add"] => "不打开交互式向导,创建已保存的 CLI 配置。",+ ["config", "add", "cloud"] => "不打开交互式向导,创建火山引擎云配置。",+ ["config", "add", "self-managed"] => "不打开交互式向导,创建自托管配置。",+ ["config", "edit"] => "不打开交互式向导,编辑已保存的 CLI 配置。",+ ["config", "delete"] => "不打开交互式向导,删除已保存的 CLI 配置。",["health"] => "快速检查服务器是否可连接。",["status"] => "查看 OpenViking 服务器诊断状态。",["language"] => "选择 OpenViking CLI 显示语言。",@@ -2087,15 +2435,43 @@ fn localized_help_item_description<'a>("show" => "显示当前配置,并隐藏敏感信息。","validate" => "探测当前服务器和认证配置。","switch" => "切换当前已保存配置。",+ "list" => "列出已保存的配置。",+ "add" => "不打开提示,添加云端或自托管配置。",+ "edit" => "不打开提示,编辑已保存配置。",+ "delete" => "不打开提示,删除已保存配置。",+ "cloud" => "使用固定的火山引擎云端地址。",+ "self-managed" => "使用本地或远程自托管地址。","ov --help" => "查看所有命令。","ov health" => "快速健康检查。","ov status" => "查看详细后端状态。","ov config show" => "确认新的当前配置。","ov config switch" => "选择一个已保存配置并设为当前配置。",+ "ov config list" => "查看已保存配置。",+ "ov config list -o json" => "以 JSON 返回已保存配置,便于自动化。",+ "ov config add --help" => "创建新的已保存配置。",+ "ov config add cloud --help" => "查看云端配置专用参数。",+ "ov config add self-managed --help" => "查看自托管配置专用参数。",+ "ov config switch <name>" => "激活已保存的配置。","ov language" => "打开语言选择器。","ov language zh-CN" => "将显示语言切换为简体中文。","ov lang en" => "使用短别名切换为英文显示。","language" => "可选语言代码:en 或 zh-CN。",+ "name" => "已保存的配置名称。",+ "--name <name>" => "已保存配置名称。不提供则自动生成。",+ "--new-name <name>" => "重命名已保存配置。",+ "--url <url>" => "服务器地址。默认是 http://127.0.0.1:1933。",+ "--api-key-stdin" => "从 stdin 读取 API Key。",+ "--api-key-env <env>" => "从环境变量读取 API Key。",+ "--api-key-stdin / --api-key-env <env>" => "从 stdin 或环境变量读取普通 API Key。",+ "--api-key-stdin / --api-key-env <env> / --clear-api-key" => "替换或清除普通 API Key。",+ "--root-api-key-stdin / --root-api-key-env <env>" => {+ "从 stdin 或环境变量读取 root API Key。"+ }+ "--root-api-key-stdin / --root-api-key-env <env> / --clear-root-api-key" => {+ "替换或清除 root API Key。"+ }+ "--activate" => "同时写入当前 ovcli.conf。",+ "--force" => "替换已有的已保存配置。","-o, --output <table|json>" => "选择表格输出或机器可读 JSON。","-c, --compact <bool>" => "使用紧凑的表格或 JSON 输出。","--account <account>" => "覆盖本次命令的 X-OpenViking-Account。",@@ -2208,7 +2584,7 @@ fn localized_section_title(title: &str, language: Language) -> &str {}}-fn localized_badge<'a>(badge: &'a str, language: Language) -> &'a str {+fn localized_badge(badge: &str, language: Language) -> &str {match (language, badge) {(Language::ZhCn, "experimental") => "实验性",_ => badge,@@ -2249,6 +2625,9 @@ fn localized_command_description<'a>("config show" => "显示当前配置","config validate" => "验证当前配置","config switch" => "切换当前配置",+ "config add" => "非交互式添加配置",+ "config list" => "列出已保存配置",+ "config delete" => "删除已保存配置","health" => "快速检查服务器连接","status" => "查看系统状态","wait" => "等待异步任务完成",@@ -2281,6 +2660,9 @@ fn command_help_path(args: &[OsString]) -> Option<Vec<String>> {}let has_help_flag = tokens.iter().skip(1).any(|token| is_help_flag(token));+ if has_help_flag && let Some(path) = config_help_path(&tokens) {+ return Some(path);+ }let mut path = Vec::new();let mut i = 1;@@ -2329,6 +2711,79 @@ fn command_help_path(args: &[OsString]) -> Option<Vec<String>> {}}+fn config_help_path(tokens: &[String]) -> Option<Vec<String>> {+ let mut i = 1;+ while i < tokens.len() {+ let token = &tokens[i];+ if is_help_flag(token) {+ return None;+ }+ if token == "--sudo" || token == "--progress" || token == "--no-progress" || token == "-v" {+ i += 1;+ continue;+ }+ if consumes_value(token) {+ i += if token.contains('=') { 1 } else { 2 };+ continue;+ }+ if token.starts_with('-') {+ i += 1;+ continue;+ }++ if canonical_command_token(token) != "config" {+ return None;+ }++ let mut path = vec!["config".to_string()];+ i += 1;+ while i < tokens.len() {+ let token = &tokens[i];+ if is_help_flag(token) {+ return Some(path);+ }+ if consumes_value(token)+ || matches!(+ token.as_str(),+ "--name"+ | "--new-name"+ | "--url"+ | "--api-key-env"+ | "--root-api-key-env"+ | "--account"+ | "--user"+ | "--agent-id"+ )+ {+ i += if token.contains('=') { 1 } else { 2 };+ continue;+ }+ if token.starts_with('-') {+ i += 1;+ continue;+ }++ match path.as_slice() {+ [base] if base == "config" => match token.as_str() {+ "show" | "validate" | "switch" | "list" | "delete" | "edit" | "add" => {+ path.push(token.clone());+ }+ _ => return Some(path),+ },+ [base, add] if base == "config" && add == "add" => match token.as_str() {+ "cloud" | "self-managed" => path.push(token.clone()),+ _ => return Some(path),+ },+ _ => return Some(path),+ }+ i += 1;+ }+ return Some(path);+ }++ None+}+fn command_spec(path: &[String]) -> Option<&'static CommandHelpSpec> {COMMAND_HELP_SPECS.iter().find(|spec| {spec.path.len() == path.len()@@ -2580,16 +3035,64 @@ mod tests {os_args(&["ov", "config", "switch", "--help"]),os_args(&["ov", "config", "switch", "-h"]),os_args(&["ov", "config", "switch", "-help"]),+ os_args(&["ov", "config", "switch", "prod", "--help"]),] {let rendered = strip_ansi(&render_command_help_request(&args).expect("config switch help should render"),);- assert!(rendered.contains("ov config switch"));+ assert!(rendered.contains("ov config switch [name]"));assert!(rendered.contains("Switch the active CLI config"));assert!(!rendered.contains("profile"));}}+ #[test]+ fn renders_curated_config_agent_command_help() {+ let config = strip_ansi(+ &render_command_help_request(&os_args(&["ov", "config", "add", "--help"]))+ .expect("config add help should render"),+ );+ assert!(config.contains("ov config add <cloud|self-managed>"));+ assert!(config.contains("cloud"));+ assert!(config.contains("self-managed"));++ let cloud = strip_ansi(+ &render_command_help_request(&os_args(&["ov", "config", "add", "cloud", "--help"]))+ .expect("config add cloud help should render"),+ );+ assert!(cloud.contains("ov config add cloud"));+ assert!(cloud.contains("--api-key-stdin"));+ assert!(cloud.contains("--api-key-env <env>"));++ let self_managed = strip_ansi(+ &render_command_help_request(&os_args(&[+ "ov",+ "config",+ "add",+ "self-managed",+ "--help",+ ]))+ .expect("config add self-managed help should render"),+ );+ assert!(self_managed.contains("ov config add self-managed"));+ assert!(self_managed.contains("--root-api-key-stdin"));+ assert!(!self_managed.contains("--use-root-key-for-normal-commands"));++ let edit = strip_ansi(+ &render_command_help_request(&os_args(&["ov", "config", "edit", "prod", "--help"]))+ .expect("config edit help should render"),+ );+ assert!(edit.contains("ov config edit <name>"));+ assert!(edit.contains("--clear-api-key"));+ assert!(!edit.contains("--use-root-key-for-normal-commands"));++ let delete = strip_ansi(+ &render_command_help_request(&os_args(&["ov", "config", "delete", "prod", "--help"]))+ .expect("config delete help should render"),+ );+ assert!(delete.contains("ov config delete <name>"));+ }+#[test]fn renders_curated_group_help_for_config_and_task() {let config = strip_ansi(@@ -2600,6 +3103,9 @@ mod tests {assert!(config.contains("show"));assert!(config.contains("validate"));assert!(config.contains("switch"));+ assert!(config.contains("add"));+ assert!(config.contains("list"));+ assert!(config.contains("delete"));let task = strip_ansi(&render_command_help_request(&os_args(&["ov", "task", "--help"]))diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 3d094fe8f..759539cc6 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -2,6 +2,7 @@ mod base_client;mod client;mod commands;mod config;+mod config_agent;mod config_command_ui;mod config_wizard;mod error;@@ -89,17 +90,13 @@ impl CliContext {}pub fn get_client_with_timeout(&self, timeout_secs: Option<f64>) -> client::HttpClient {- let api_key = if self.sudo {- self.config.root_api_key.clone()- } else {- self.config.api_key.clone()- };+ let auth = self.config.effective_auth(self.sudo);client::HttpClient::new(&self.config.url,- api_key,+ auth.api_key,self.config.agent_id.clone(),- self.config.account.clone(),- self.config.user.clone(),+ auth.account,+ auth.user,timeout_secs.unwrap_or(self.config.timeout),self.profile.unwrap_or(self.config.profile),self.config.extra_headers.clone(),@@ -682,10 +679,10 @@ enum Commands {impl Commands {/// Returns true if this is an admin command that supports --sudofn is_admin_command(&self) -> bool {- match self {- Self::Admin { .. } | Self::System { .. } | Self::Reindex { .. } => true,- _ => false,- }+ matches!(+ self,+ Self::Admin { .. } | Self::System { .. } | Self::Reindex { .. }+ )}fn supports_upload_options(&self) -> bool {@@ -1021,7 +1018,14 @@ impl Commands {!matches!(self,Commands::Config {- action: None | Some(ConfigCommands::Switch),+ action: None+ | Some(+ ConfigCommands::Switch { .. }+ | ConfigCommands::Add { .. }+ | ConfigCommands::Edit(_)+ | ConfigCommands::Delete(_)+ | ConfigCommands::List,+ ),} | Commands::Version)}@@ -1034,7 +1038,139 @@ enum ConfigCommands {/// Validate configuration fileValidate,/// Switch between saved configs- Switch,+ Switch {+ /// Saved config name to activate. Omit to open the interactive selector.+ name: Option<String>,+ },+ /// List saved configs+ List,+ /// Delete a saved config+ Delete(ConfigDeleteArgs),+ /// Add a saved config without opening the interactive wizard+ Add {+ #[command(subcommand)]+ target: ConfigAddTarget,+ },+ /// Edit a saved config without opening the interactive wizard+ Edit(ConfigEditArgs),+}++#[derive(Subcommand)]+enum ConfigAddTarget {+ /// Add a Volcengine Cloud config+ Cloud(ConfigAddCloudArgs),+ /// Add a self-managed config+ SelfManaged(ConfigAddSelfManagedArgs),+}++#[derive(Args, Debug, Clone)]+struct ConfigAddCloudArgs {+ /// Saved config name. Agents should pass this for idempotent retries; generated when omitted.+ #[arg(long)]+ name: Option<String>,+ /// Read API key from stdin+ #[arg(long, conflicts_with = "api_key_env")]+ api_key_stdin: bool,+ /// Read API key from an environment variable+ #[arg(long, conflicts_with = "api_key_stdin")]+ api_key_env: Option<String>,+ /// Account identifier to send as X-OpenViking-Account+ #[arg(long)]+ account: Option<String>,+ /// User identifier to send as X-OpenViking-User+ #[arg(long)]+ user: Option<String>,+ /// Make the saved config active after validation+ #[arg(long)]+ activate: bool,+ /// Replace an existing saved config+ #[arg(long)]+ force: bool,+}++#[derive(Args, Debug, Clone)]+struct ConfigAddSelfManagedArgs {+ /// Saved config name. Agents should pass this for idempotent retries; generated when omitted.+ #[arg(long)]+ name: Option<String>,+ /// OpenViking server URL+ #[arg(long)]+ url: Option<String>,+ /// Read API key from stdin+ #[arg(long, conflicts_with_all = ["api_key_env", "root_api_key_stdin"])]+ api_key_stdin: bool,+ /// Read API key from an environment variable+ #[arg(long, conflicts_with = "api_key_stdin")]+ api_key_env: Option<String>,+ /// Read root API key from stdin+ #[arg(long, conflicts_with_all = ["root_api_key_env", "api_key_stdin"])]+ root_api_key_stdin: bool,+ /// Read root API key from an environment variable+ #[arg(long, conflicts_with = "root_api_key_stdin")]+ root_api_key_env: Option<String>,+ /// Account identifier to send as X-OpenViking-Account+ #[arg(long)]+ account: Option<String>,+ /// User identifier to send as X-OpenViking-User+ #[arg(long)]+ user: Option<String>,+ /// Make the saved config active after validation+ #[arg(long)]+ activate: bool,+ /// Replace an existing saved config+ #[arg(long)]+ force: bool,+}++#[derive(Args, Debug, Clone)]+struct ConfigEditArgs {+ /// Saved config name to edit+ name: String,+ /// Rename the saved config+ #[arg(long)]+ new_name: Option<String>,+ /// New server URL. Volcengine Cloud configs use a fixed URL.+ #[arg(long)]+ url: Option<String>,+ /// Read replacement API key from stdin+ #[arg(long, conflicts_with_all = ["api_key_env", "clear_api_key", "root_api_key_stdin"])]+ api_key_stdin: bool,+ /// Read replacement API key from an environment variable+ #[arg(long, conflicts_with_all = ["api_key_stdin", "clear_api_key"])]+ api_key_env: Option<String>,+ /// Remove the API key+ #[arg(long, conflicts_with_all = ["api_key_stdin", "api_key_env"])]+ clear_api_key: bool,+ /// Read replacement root API key from stdin+ #[arg(long, conflicts_with_all = ["root_api_key_env", "clear_root_api_key", "api_key_stdin"])]+ root_api_key_stdin: bool,+ /// Read replacement root API key from an environment variable+ #[arg(long, conflicts_with_all = ["root_api_key_stdin", "clear_root_api_key"])]+ root_api_key_env: Option<String>,+ /// Remove the root API key+ #[arg(long, conflicts_with_all = ["root_api_key_stdin", "root_api_key_env"])]+ clear_root_api_key: bool,+ /// Account identifier to send as X-OpenViking-Account+ #[arg(long)]+ account: Option<String>,+ /// User identifier to send as X-OpenViking-User+ #[arg(long)]+ user: Option<String>,+ /// Make the saved config active after validation+ #[arg(long)]+ activate: bool,+ /// Replace an existing saved config when renaming+ #[arg(long)]+ force: bool,+}++#[derive(Args, Debug, Clone)]+struct ConfigDeleteArgs {+ /// Saved config name to delete+ name: String,+ /// Delete even when the saved file cannot be parsed+ #[arg(long)]+ force: bool,}fn find_command_index(args: &[OsString]) -> Option<usize> {@@ -1088,14 +1224,13 @@ fn plain_help_misuse(args: &[OsString]) -> Option<PlainHelpMisuse> {if let Some(subcommand) = tokens.get(1).map(|token| canonical_plain_help_token(token)) {path.push(subcommand.to_string());}- if command == "task" && path.get(1).is_some_and(|token| token == "watch") {- if let Some(watch_subcommand) =+ if command == "task"+ && path.get(1).is_some_and(|token| token == "watch")+ && let Some(watch_subcommand) =tokens.get(2).map(|token| canonical_plain_help_token(token))- {- if watch_subcommand != "help" {- path.push(watch_subcommand.to_string());- }- }+ && watch_subcommand != "help"+ {+ path.push(watch_subcommand.to_string());}return Some(PlainHelpMisuse {help_command: prefixed_help_command(&path),@@ -1246,7 +1381,7 @@ fn pre_parse_requires_cli_config_file(args: &[OsString]) -> bool {};match command {- "config" => matches!(tokens.get(1).map(String::as_str), Some("show" | "validate")),+ "config" => config_command_requires_cli_config_file(&tokens),"language" | "version" => false,"task" => known_task_command_requires_config(&tokens),"admin" => tokens@@ -1270,6 +1405,23 @@ fn pre_parse_requires_cli_config_file(args: &[OsString]) -> bool {}}+fn config_command_requires_cli_config_file(tokens: &[String]) -> bool {+ matches!(tokens.get(1).map(String::as_str), Some("show" | "validate"))+}++fn is_config_agent_command_request(args: &[OsString]) -> bool {+ let tokens = command_tokens_for_config_gate(args);+ if tokens.first().map(String::as_str) != Some("config") {+ return false;+ }++ match tokens.get(1).map(String::as_str) {+ Some("add" | "edit" | "delete" | "list") => true,+ Some("switch") => tokens.get(2).is_some(),+ _ => false,+ }+}+fn command_tokens_for_config_gate(args: &[OsString]) -> Vec<String> {let mut tokens = Vec::new();let mut seen_command = false;@@ -1362,11 +1514,7 @@ fn known_task_command_requires_config(tokens: &[String]) -> bool {fn known_system_command_requires_config(tokens: &[String]) -> bool {match tokens.get(1).map(String::as_str) {Some("wait" | "status" | "health" | "consistency") => true,- Some("crypto") => match tokens.get(2).map(String::as_str) {- None => true,- Some("init-key") => true,- _ => false,- },+ Some("crypto") => matches!(tokens.get(2).map(String::as_str), None | Some("init-key")),_ => false,}}@@ -1559,7 +1707,10 @@ fn language_gate_action(has_saved_language: bool,is_interactive: bool,) -> LanguageGateAction {- if has_saved_language || is_language_command_request(args) {+ if has_saved_language+ || is_language_command_request(args)+ || is_config_agent_command_request(args)+ {LanguageGateAction::Continue} else if is_interactive {LanguageGateAction::Prompt@@ -2174,10 +2325,11 @@ async fn main() {#[cfg(test)]mod tests {use super::{- Cli, CliContext, Commands, LanguageGateAction, PrivacyCommands, UploadCliOptions,- first_command_token, is_language_command_request, language_command_can_run_picker,- language_gate_action, language_required_message, legacy_upload_option_error,- plain_help_misuse, pre_parse_requires_cli_config_file, preprocess_privacy_args,+ Cli, CliContext, Commands, ConfigAddTarget, ConfigCommands, LanguageGateAction,+ PrivacyCommands, UploadCliOptions, first_command_token, is_language_command_request,+ language_command_can_run_picker, language_gate_action, language_required_message,+ legacy_upload_option_error, plain_help_misuse, pre_parse_requires_cli_config_file,+ preprocess_privacy_args,};use crate::config::{Config, DEFAULT_SELF_MANAGED_URL};use crate::handlers;@@ -2222,13 +2374,112 @@ mod tests {let setup = Cli::try_parse_from(["ov", "config"]).expect("bare config should parse");let switch =Cli::try_parse_from(["ov", "config", "switch"]).expect("config switch should parse");+ let switch_named = Cli::try_parse_from(["ov", "config", "switch", "prod"])+ .expect("named config switch should parse");let version = Cli::try_parse_from(["ov", "version"]).expect("version should parse");assert!(!setup.command.requires_cli_config_file());assert!(!switch.command.requires_cli_config_file());+ assert!(!switch_named.command.requires_cli_config_file());assert!(!version.command.requires_cli_config_file());}+ #[test]+ fn config_agent_commands_parse_without_secret_value_flags() {+ let add_cloud = Cli::try_parse_from([+ "ov",+ "config",+ "add",+ "cloud",+ "--name",+ "prod",+ "--api-key-stdin",+ "--activate",+ ])+ .expect("cloud add should parse");+ let Commands::Config {+ action:+ Some(ConfigCommands::Add {+ target: ConfigAddTarget::Cloud(cloud),+ }),+ } = add_cloud.command+ else {+ panic!("expected cloud add command");+ };+ assert_eq!(cloud.name.as_deref(), Some("prod"));+ assert!(cloud.api_key_stdin);+ assert!(cloud.activate);++ let add_self_managed = Cli::try_parse_from([+ "ov",+ "config",+ "add",+ "self-managed",+ "--url",+ "https://ov.example.com",+ "--api-key-env",+ "OV_KEY",+ ])+ .expect("self-managed add should parse");+ let Commands::Config {+ action:+ Some(ConfigCommands::Add {+ target: ConfigAddTarget::SelfManaged(self_managed),+ }),+ } = add_self_managed.command+ else {+ panic!("expected self-managed add command");+ };+ assert_eq!(self_managed.url.as_deref(), Some("https://ov.example.com"));+ assert_eq!(self_managed.api_key_env.as_deref(), Some("OV_KEY"));++ let edit = Cli::try_parse_from([+ "ov",+ "config",+ "edit",+ "prod",+ "--clear-api-key",+ "--activate",+ ])+ .expect("config edit should parse");+ let Commands::Config {+ action: Some(ConfigCommands::Edit(edit)),+ } = edit.command+ else {+ panic!("expected edit command");+ };+ assert_eq!(edit.name, "prod");+ assert!(edit.clear_api_key);+ assert!(edit.activate);++ assert!(+ Cli::try_parse_from(["ov", "config", "add", "cloud", "--api-key", "secret"]).is_err(),+ "plain API key flag must stay rejected"+ );+ assert!(+ Cli::try_parse_from([+ "ov",+ "config",+ "add",+ "self-managed",+ "--use-root-key-for-normal-commands",+ ])+ .is_err(),+ "root-as-normal flag is obsolete and must stay rejected"+ );+ assert!(+ Cli::try_parse_from([+ "ov",+ "config",+ "edit",+ "prod",+ "--use-root-key-for-normal-commands",+ ])+ .is_err(),+ "root-as-normal edit flag is obsolete and must stay rejected"+ );+ }+#[test]fn pre_parse_config_gate_catches_incomplete_known_server_commands() {for args in [@@ -2383,6 +2634,11 @@ mod tests {&["ov", "task", "nope"],&["ov", "config"],&["ov", "config", "switch"],+ &["ov", "config", "switch", "prod"],+ &["ov", "config", "list"],+ &["ov", "config", "delete", "prod"],+ &["ov", "config", "add", "cloud", "--api-key-stdin"],+ &["ov", "config", "edit", "prod", "--activate"],&["ov", "config", "setup-cli"],&["ov", "version"],&["ov", "language", "en"],@@ -2607,6 +2863,29 @@ mod tests {);}+ #[test]+ fn language_gate_allows_config_agent_commands_without_saved_language() {+ for args in [+ &["ov", "config", "add", "cloud", "--api-key-stdin"][..],+ &["ov", "config", "add", "self-managed"],+ &["ov", "config", "edit", "prod", "--activate"],+ &["ov", "config", "delete", "prod"],+ &["ov", "config", "list"],+ &["ov", "config", "switch", "prod"],+ ] {+ assert_eq!(+ language_gate_action(&os_args(args), false, false),+ LanguageGateAction::Continue,+ "{args:?} should bypass first-run language selection"+ );+ }++ assert_eq!(+ language_gate_action(&os_args(&["ov", "config"]), false, false),+ LanguageGateAction::ExitNonInteractive+ );+ }+#[test]fn language_gate_message_points_to_explicit_language_commands() {let message = language_required_message();diff --git a/crates/ov_cli/src/status_ui.rs b/crates/ov_cli/src/status_ui.rsindex 46bc9e61a..fe2b8f6d5 100644--- a/crates/ov_cli/src/status_ui.rs+++ b/crates/ov_cli/src/status_ui.rs@@ -211,8 +211,10 @@ enum StatusFailureKind {impl StatusFailureKind {fn from_error(error: Option<&Error>) -> Self {match error {- Some(Error::Api(message)) if looks_like_auth_error(message) => Self::Authentication,- Some(Error::Api(_)) => Self::Api,+ Some(Error::Api { message, .. }) if looks_like_auth_error(message) => {+ Self::Authentication+ }+ Some(Error::Api { .. }) => Self::Api,_ => Self::Connection,}}@@ -884,7 +886,7 @@ mod tests {#[test]fn unreachable_status_distinguishes_auth_failures() {- let error = crate::error::Error::Api(+ let error = crate::error::Error::api("[AuthenticationError] API key invalid. Request ID: abc".to_string(),);let rendered =