Skip to content

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

fix(cli): preserve structured API errors (#3379)

Qin Haojiefd098cfd65ec
diff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rs
index 101969254..bb592a9aa 100644
--- a/crates/ov_cli/src/base_client.rs
+++ b/crates/ov_cli/src/base_client.rs
@@ -69,13 +69,13 @@ fn zip_entry_name(relative_path: &Path) -> Result<String> {
Ok(normalize_zip_entry_name(name))
}
-pub fn api_error_from_envelope(json: &Value, status: StatusCode) -> String {
+pub fn api_error_from_envelope(json: &Value, status: StatusCode) -> Error {
let error_code = json
.get("error")
.and_then(|e| e.get("code"))
.and_then(|c| c.as_str());
- let error_msg = json
- .get("error")
+ let error = json.get("error");
+ let error_msg = error
.and_then(|e| e.get("message"))
.and_then(|m| m.as_str())
.map(|s| s.to_string())
@@ -84,11 +84,34 @@ pub fn api_error_from_envelope(json: &Value, status: StatusCode) -> String {
.and_then(|d| d.as_str())
.map(|s| s.to_string())
})
- .unwrap_or_else(|| format!("HTTP error {}", status));
+ .unwrap_or_else(|| {
+ if json.is_null() {
+ format!("HTTP error {}", status)
+ } else {
+ json.to_string()
+ }
+ });
+ let details = error.and_then(|e| e.get("details")).cloned();
+
+ Error::api_response(
+ error_code.map(str::to_string),
+ error_msg,
+ details,
+ status.as_u16(),
+ )
+}
- match error_code {
- Some(code) => format!("[{}] {}", code, error_msg),
- None => error_msg,
+pub(crate) fn api_error_from_body(body: &[u8], status: StatusCode) -> Error {
+ match serde_json::from_slice(body) {
+ Ok(json) => api_error_from_envelope(&json, status),
+ Err(_) => Error::api_with_status(
+ format!(
+ "HTTP error {}\n\nRaw response body:\n{}",
+ status,
+ String::from_utf8_lossy(body)
+ ),
+ status.as_u16(),
+ ),
}
}
@@ -280,7 +303,7 @@ impl BaseClient {
let response = request
.send()
.await
- .map_err(|e| Error::Network(format!("{}: {}", error_context, e)))?;
+ .map_err(|e| Error::from_reqwest(error_context, e))?;
if !Self::is_gateway_token_challenge(&response) {
return Ok(response);
}
@@ -295,7 +318,7 @@ impl BaseClient {
.header(GATEWAY_TOKEN_HEADER, gateway_token)
.send()
.await
- .map_err(|e| Error::Network(format!("{}: {}", error_context, e)))
+ .map_err(|e| Error::from_reqwest(error_context, e))
}
async fn headers_for_uncloneable_request(&self) -> Result<reqwest::header::HeaderMap> {
@@ -310,7 +333,7 @@ impl BaseClient {
.headers(headers.clone())
.send()
.await
- .map_err(|e| Error::Network(format!("Gateway detection request failed: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Gateway detection request failed", e))?;
if Self::is_gateway_token_challenge(&response) {
if let Ok(value) = reqwest::header::HeaderValue::from_str(gateway_token) {
headers.insert(GATEWAY_TOKEN_HEADER, value);
@@ -333,40 +356,26 @@ impl BaseClient {
let bytes = response
.bytes()
.await
- .map_err(|e| Error::Network(format!("Failed to read response body: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to read response body", e))?;
+
+ if !status.is_success() {
+ return Err(api_error_from_body(&bytes, status));
+ }
let json: Value = match serde_json::from_slice(&bytes) {
Ok(json) => json,
Err(e) => {
let body_str = String::from_utf8_lossy(&bytes);
- return Err(Error::Network(format!(
+ return Err(Error::Parse(format!(
"Failed to parse JSON response: {}\n\nRaw response body:\n{}",
e, body_str
)));
}
};
- if !status.is_success() {
- return Err(Error::api_with_status(
- api_error_from_envelope(&json, status),
- status.as_u16(),
- ));
- }
-
if let Some(error) = json.get("error") {
if !error.is_null() {
- let code = error
- .get("code")
- .and_then(|c| c.as_str())
- .unwrap_or("UNKNOWN");
- let message = error
- .get("message")
- .and_then(|m| m.as_str())
- .unwrap_or("Unknown error");
- return Err(Error::api_with_status(
- format!("[{}] {}", code, message),
- status.as_u16(),
- ));
+ return Err(api_error_from_envelope(&json, status));
}
}
@@ -388,7 +397,7 @@ impl BaseClient {
ReqwestClient::builder()
.timeout(timeout)
.build()
- .map_err(|e| Error::Network(format!("Failed to build HTTP client: {}", e)))
+ .map_err(|e| Error::from_reqwest("Failed to build HTTP client", e))
}
pub(crate) fn create_client_with_connect_timeout(
@@ -400,7 +409,7 @@ impl BaseClient {
.connect_timeout(connect_timeout)
.timeout(timeout)
.build()
- .map_err(|e| Error::Network(format!("Failed to build HTTP client: {}", e)))
+ .map_err(|e| Error::from_reqwest("Failed to build HTTP client", e))
}
pub async fn get<T: DeserializeOwned + 'static>(
@@ -559,6 +568,9 @@ impl BaseClient {
mod tests {
use super::*;
use serde_json::json;
+ use std::time::Duration;
+ use tokio::io::AsyncWriteExt;
+ use tokio::net::TcpListener;
#[test]
fn unwrap_success_envelope_preserves_profile_for_value_results() {
@@ -589,6 +601,70 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn request_timeout_is_not_reported_as_network_failure() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let _connection = listener.accept().await.unwrap();
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ });
+
+ let client = BaseClient::new(
+ format!("http://{address}"),
+ None,
+ None,
+ None,
+ None,
+ 0.02,
+ false,
+ None,
+ );
+ let error = client
+ .get::<Value>("/slow", &[])
+ .await
+ .expect_err("slow response should time out");
+
+ assert!(matches!(error, Error::Timeout(_)));
+ }
+
+ #[tokio::test]
+ async fn plain_text_http_error_preserves_status() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let (mut connection, _) = listener.accept().await.unwrap();
+ connection
+ .write_all(
+ b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 20\r\n\r\nupstream unavailable",
+ )
+ .await
+ .unwrap();
+ });
+
+ let client = BaseClient::new(
+ format!("http://{address}"),
+ None,
+ None,
+ None,
+ None,
+ 1.0,
+ false,
+ None,
+ );
+ let error = client.get::<Value>("/", &[]).await.unwrap_err();
+
+ assert_eq!(error.code(), "UNAVAILABLE");
+ assert!(matches!(
+ error,
+ Error::Api {
+ status: Some(503),
+ message,
+ ..
+ } if message.contains("upstream unavailable")
+ ));
+ }
+
#[test]
fn unwrap_success_envelope_drops_null_profile_for_value_results() {
let body = json!({
@@ -734,7 +810,7 @@ impl<'a> FileUploader<'a> {
ignore_dirs: Option<&str>,
) -> Result<NamedTempFile> {
if !dir_path.is_dir() {
- return Err(Error::Network(format!(
+ return Err(Error::InvalidPath(format!(
"Path {} is not a directory",
dir_path.display()
)));
@@ -774,7 +850,7 @@ impl<'a> FileUploader<'a> {
ignore_dirs: Option<&str>,
) -> Result<NamedTempFile> {
if !dir_path.is_dir() {
- return Err(Error::Network(format!(
+ return Err(Error::InvalidPath(format!(
"Path {} is not a directory",
dir_path.display()
)));
@@ -882,7 +958,7 @@ impl<'a> FileUploader<'a> {
let part = part
.mime_str("application/octet-stream")
- .map_err(|e| Error::Network(format!("Failed to set mime type: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to set mime type", e))?;
let mut form = reqwest::multipart::Form::new().part("file", part);
if let Some(upload_mode) = &self.upload_mode {
@@ -904,7 +980,7 @@ impl<'a> FileUploader<'a> {
.multipart(form)
.send()
.await
- .map_err(|e| Error::Network(format!("File upload failed: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("File upload failed", e))?;
let result: Value = self.client.handle_response(response).await?;
result
@@ -950,7 +1026,7 @@ impl<'a> FileUploader<'a> {
let part = part
.mime_str("application/octet-stream")
- .map_err(|e| Error::Network(format!("Failed to set mime type: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to set mime type", e))?;
let mut form = reqwest::multipart::Form::new().part("file", part);
if let Some(upload_mode) = &self.upload_mode {
@@ -972,7 +1048,7 @@ impl<'a> FileUploader<'a> {
.multipart(form)
.send()
.await
- .map_err(|e| Error::Network(format!("File upload failed: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("File upload failed", e))?;
pb.finish_with_message("Upload complete");
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 143585acb..45427d9aa 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -396,34 +396,16 @@ impl HttpClient {
let bytes = response
.bytes()
.await
- .map_err(|e| Error::Network(format!("Failed to read error response: {}", e)))?;
-
- let error_msg = match serde_json::from_slice::<serde_json::Value>(&bytes) {
- Ok(json) => json
- .get("error")
- .and_then(|e| e.get("message"))
- .and_then(|m| m.as_str())
- .map(|s| s.to_string())
- .or_else(|| {
- json.get("detail")
- .and_then(|d| d.as_str())
- .map(|s| s.to_string())
- })
- .unwrap_or_else(|| format!("HTTP error {}", status)),
- Err(_) => {
- let body_str = String::from_utf8_lossy(&bytes);
- format!("HTTP error {}\n\nRaw response body:\n{}", status, body_str)
- }
- };
+ .map_err(|e| Error::from_reqwest("Failed to read error response", e))?;
- return Err(Error::api(error_msg));
+ return Err(crate::base_client::api_error_from_body(&bytes, status));
}
response
.bytes()
.await
.map(|b| b.to_vec())
- .map_err(|e| Error::Network(format!("Failed to read response bytes: {}", e)))
+ .map_err(|e| Error::from_reqwest("Failed to read response bytes", e))
}
// ============ Filesystem Methods ============
@@ -1164,33 +1146,15 @@ impl HttpClient {
let bytes = response
.bytes()
.await
- .map_err(|e| Error::Network(format!("Failed to read error response: {}", e)))?;
-
- let error_msg = match serde_json::from_slice::<serde_json::Value>(&bytes) {
- Ok(json) => json
- .get("error")
- .and_then(|e| e.get("message"))
- .and_then(|m| m.as_str())
- .map(|s| s.to_string())
- .or_else(|| {
- json.get("detail")
- .and_then(|d| d.as_str())
- .map(|s| s.to_string())
- })
- .unwrap_or_else(|| format!("HTTP error {}", status)),
- Err(_) => {
- let body_str = String::from_utf8_lossy(&bytes);
- format!("HTTP error {}\n\nRaw response body:\n{}", status, body_str)
- }
- };
+ .map_err(|e| Error::from_reqwest("Failed to read error response", e))?;
- return Err(Error::api(error_msg));
+ return Err(crate::base_client::api_error_from_body(&bytes, status));
}
let bytes = response
.bytes()
.await
- .map_err(|e| Error::Network(format!("Failed to read response bytes: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to read response bytes", e))?;
let to_path = Path::new(to);
let final_path = if to_path.is_dir() {
@@ -1694,7 +1658,7 @@ impl HttpClient {
let bytes = response
.bytes()
.await
- .map_err(|e| Error::Network(format!("Failed to read blob bytes: {}", e)))?
+ .map_err(|e| Error::from_reqwest("Failed to read blob bytes", e))?
.to_vec();
return Ok(SnapshotShowResult::Blob { oid, size, bytes });
}
@@ -1702,30 +1666,26 @@ impl HttpClient {
let bytes = response
.bytes()
.await
- .map_err(|e| Error::Network(format!("Failed to read response body: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to read response body", e))?;
+
+ if !status.is_success() {
+ return Err(crate::base_client::api_error_from_body(&bytes, status));
+ }
+
let json: Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(e) => {
let body_str = String::from_utf8_lossy(&bytes);
- return Err(Error::Network(format!(
+ return Err(Error::Parse(format!(
"Failed to parse JSON response: {}\n\nRaw response body:\n{}",
e, body_str
)));
}
};
- if !status.is_success() {
- return Err(Error::api_with_status(
- crate::base_client::api_error_from_envelope(&json, status),
- status.as_u16(),
- ));
- }
if let Some(error) = json.get("error") {
if !error.is_null() {
- return Err(Error::api_with_status(
- crate::base_client::api_error_from_envelope(&json, status),
- status.as_u16(),
- ));
+ return Err(crate::base_client::api_error_from_envelope(&json, status));
}
}
@@ -2034,10 +1994,16 @@ mod tests {
}
});
- assert_eq!(
- api_error_from_envelope(&body, StatusCode::INTERNAL_SERVER_ERROR),
- "[PROCESSING_ERROR] Parse error: boom"
- );
+ let error = api_error_from_envelope(&body, StatusCode::INTERNAL_SERVER_ERROR);
+ assert!(matches!(
+ error,
+ crate::error::Error::Api {
+ code: Some(code),
+ message,
+ status: Some(500),
+ ..
+ } if code == "PROCESSING_ERROR" && message == "Parse error: boom"
+ ));
}
#[test]
diff --git a/crates/ov_cli/src/commands/chat.rs b/crates/ov_cli/src/commands/chat.rs
index 36293dfc6..28ed4b89f 100644
--- a/crates/ov_cli/src/commands/chat.rs
+++ b/crates/ov_cli/src/commands/chat.rs
@@ -18,6 +18,7 @@ use termimad::MadSkin;
use unicode_width::UnicodeWidthStr;
use uuid::Uuid;
+use crate::base_client::api_error_from_body;
use crate::config::Config;
use crate::i18n::{Language, copy};
use crate::theme;
@@ -164,7 +165,7 @@ impl ChatCommand {
let client = Client::builder()
.timeout(Duration::from_secs(300))
.build()
- .map_err(|e| Error::Network(format!("Failed to create HTTP client: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to create HTTP client", e))?;
let config = Config::load()?;
let endpoint = self.resolve_endpoint_from_config(&config);
@@ -425,18 +426,21 @@ impl ChatCommand {
let response = req_builder
.send()
.await
- .map_err(|e| Error::Network(format!("Failed to send request: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to send request", e))?;
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)));
+ let body = response
+ .bytes()
+ .await
+ .map_err(|e| Error::from_reqwest("Failed to read error response", e))?;
+ return Err(api_error_from_body(&body, status));
}
let chat_response: ChatResponse = response
.json()
.await
- .map_err(|e| Error::Parse(format!("Failed to parse response: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to parse response", e))?;
// Print events if any
self.print_events(&chat_response.events);
@@ -470,12 +474,15 @@ impl ChatCommand {
let response = req_builder
.send()
.await
- .map_err(|e| Error::Network(format!("Failed to send request: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to send request", e))?;
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)));
+ let body = response
+ .bytes()
+ .await
+ .map_err(|e| Error::from_reqwest("Failed to read error response", e))?;
+ return Err(api_error_from_body(&body, status));
}
// Process the SSE stream
@@ -487,7 +494,7 @@ impl ChatCommand {
while let Some(chunk) = response
.chunk()
.await
- .map_err(|e| Error::Network(format!("Stream error: {}", e)))?
+ .map_err(|e| Error::from_reqwest("Stream error", e))?
{
let chunk_str = String::from_utf8_lossy(&chunk);
buffer.push_str(&chunk_str);
@@ -688,18 +695,21 @@ impl ChatCommand {
let response = req_builder
.send()
.await
- .map_err(|e| Error::Network(format!("Failed to send request: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to send request", e))?;
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)));
+ let body = response
+ .bytes()
+ .await
+ .map_err(|e| Error::from_reqwest("Failed to read error response", e))?;
+ return Err(api_error_from_body(&body, status));
}
let chat_response: ChatResponse = response
.json()
.await
- .map_err(|e| Error::Parse(format!("Failed to parse response: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to parse response", e))?;
// Save session ID
if session_id.is_none() {
@@ -745,12 +755,15 @@ impl ChatCommand {
let response = req_builder
.send()
.await
- .map_err(|e| Error::Network(format!("Failed to send request: {}", e)))?;
+ .map_err(|e| Error::from_reqwest("Failed to send request", e))?;
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)));
+ let body = response
+ .bytes()
+ .await
+ .map_err(|e| Error::from_reqwest("Failed to read error response", e))?;
+ return Err(api_error_from_body(&body, status));
}
let response_session_id = response
@@ -771,7 +784,7 @@ impl ChatCommand {
while let Some(chunk) = response
.chunk()
.await
- .map_err(|e| Error::Network(format!("Stream error: {}", e)))?
+ .map_err(|e| Error::from_reqwest("Stream error", e))?
{
let chunk_str = String::from_utf8_lossy(&chunk);
buffer.push_str(&chunk_str);
diff --git a/crates/ov_cli/src/config_agent.rs b/crates/ov_cli/src/config_agent.rs
index 4e83d1e7e..edefe9f30 100644
--- a/crates/ov_cli/src/config_agent.rs
+++ b/crates/ov_cli/src/config_agent.rs
@@ -918,15 +918,15 @@ fn validate_optional_actor_peer_id(actor_peer_id: Option<&str>) -> AgentResult<(
}
fn validation_error(kind: ConfigKind, error: Error) -> AgentError {
+ if error.code() == "UNAUTHENTICATED" {
+ if let Error::Api { message, .. } = error {
+ return AgentError::auth(message);
+ }
+ }
+
match error {
- Error::Api { message, .. } => AgentError::auth(format!(
- "{} {message}",
- match kind {
- ConfigKind::OpenVikingService => "Check the API key.",
- ConfigKind::Custom => "Check the API key, account, and user.",
- }
- )),
- Error::Network(message) => AgentError::validation(format!(
+ Error::Api { message, .. } => AgentError::validation(message),
+ Error::Network(message) | Error::Timeout(message) => AgentError::validation(format!(
"{} {message}",
match kind {
ConfigKind::OpenVikingService => "Could not reach OpenViking Service.",
diff --git a/crates/ov_cli/src/config_command_ui.rs b/crates/ov_cli/src/config_command_ui.rs
index fee08d1ef..97e630e0c 100644
--- a/crates/ov_cli/src/config_command_ui.rs
+++ b/crates/ov_cli/src/config_command_ui.rs
@@ -5,7 +5,6 @@ use crate::{
config::{Config, display_config_home},
config_wizard::ConfigKind,
error::Error,
- error_classifier::looks_like_auth_error,
i18n::{Language, copy},
theme,
};
@@ -405,6 +404,7 @@ fn unknown_value(value: &str) -> String {
#[derive(Debug, Clone, Copy)]
enum ValidationFailureKind {
Network,
+ Timeout,
Auth,
Unhealthy,
Other,
@@ -415,7 +415,8 @@ 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::Timeout(_) => Self::Timeout,
+ error @ Error::Api { .. } if error.code() == "UNAUTHENTICATED" => Self::Auth,
_ => Self::Other,
}
}
@@ -423,6 +424,7 @@ impl ValidationFailureKind {
fn server_check(self, language: Language) -> String {
match self {
Self::Network => fail_value(copy(language, "unreachable", "无法连接")),
+ Self::Timeout => fail_value(copy(language, "timed out", "超时")),
Self::Auth | Self::Unhealthy => ok_value(copy(language, "reachable", "可连接")),
Self::Other => warn_value(unknown(language)),
}
@@ -431,7 +433,7 @@ impl ValidationFailureKind {
fn auth_check(self, language: Language) -> String {
match self {
Self::Auth => fail_value(copy(language, "rejected", "被拒绝")),
- Self::Network => warn_value(copy(language, "not checked", "未检查")),
+ Self::Network | Self::Timeout => warn_value(copy(language, "not checked", "未检查")),
Self::Unhealthy => ok_value(copy(language, "accepted", "已通过")),
Self::Other => warn_value(unknown(language)),
}
@@ -440,7 +442,9 @@ impl ValidationFailureKind {
fn health_check(self, language: Language) -> String {
match self {
Self::Unhealthy => fail_value(copy(language, "unhealthy", "不健康")),
- Self::Network | Self::Auth => warn_value(copy(language, "not checked", "未检查")),
+ Self::Network | Self::Timeout | Self::Auth => {
+ warn_value(copy(language, "not checked", "未检查"))
+ }
Self::Other => warn_value(unknown(language)),
}
}
@@ -449,12 +453,16 @@ impl ValidationFailureKind {
match language {
Language::En => match self {
Self::Network => "Could not reach the configured OpenViking server.",
+ Self::Timeout => {
+ "OpenViking did not respond before the configured timeout expired."
+ }
Self::Auth => "OpenViking rejected the API key for this config.",
Self::Unhealthy => "OpenViking is reachable but reported an unhealthy state.",
Self::Other => "The active config could not be validated.",
},
Language::ZhCn => match self {
Self::Network => "无法连接已配置的 OpenViking 服务器。",
+ Self::Timeout => "OpenViking 未在配置的超时时间内响应。",
Self::Auth => "OpenViking 拒绝了这个配置的 API Key。",
Self::Unhealthy => "服务器可连接,但健康状态异常。",
Self::Other => "当前配置验证失败。",
diff --git a/crates/ov_cli/src/config_wizard/store.rs b/crates/ov_cli/src/config_wizard/store.rs
index cbadbbf95..922fe6fcf 100644
--- a/crates/ov_cli/src/config_wizard/store.rs
+++ b/crates/ov_cli/src/config_wizard/store.rs
@@ -614,7 +614,17 @@ async fn detect_api_key_role(client: &BaseClient) -> Result<ApiKeyRole> {
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::Api {
+ code,
+ message,
+ details,
+ status,
+ }) => Err(Error::Api {
+ code,
+ message,
+ details,
+ status,
+ }),
Err(error) => Err(error),
}
}
@@ -665,24 +675,13 @@ pub(crate) fn validation_error_copy(kind: ConfigKind, error: &Error) -> String {
"Cannot reach the server. Check the URL and your network connection.".to_string()
}
},
- Error::Api {
- status: Some(401 | 403),
- ..
- } => "API key was rejected. Check your API key.".to_string(),
- Error::Api {
- status: Some(404), ..
- } => {
- "Server responded but the API endpoint was not found. Check the server URL.".to_string()
- }
- Error::Api {
- status: Some(status),
- ..
- } => {
- format!("Server returned HTTP {status}. Check the server configuration.")
+ Error::Timeout(_) => {
+ "Connection timed out. Increase the request timeout or check the server.".to_string()
}
- Error::Api { .. } => {
- "Server returned an error during validation. Check the server logs.".to_string()
+ error @ Error::Api { .. } if error.code() == "UNAUTHENTICATED" => {
+ "API key was rejected. Check your API key.".to_string()
}
+ Error::Api { message, .. } => message.clone(),
Error::Config(msg) => msg.clone(),
_ => match kind {
ConfigKind::OpenVikingService => {
@@ -706,20 +705,11 @@ pub(crate) fn validation_error_copy_zh(kind: ConfigKind, error: &Error) -> Strin
}
ConfigKind::Custom => "无法连接服务器。请检查 URL 和网络连接。".to_string(),
},
- Error::Api {
- status: Some(401 | 403),
- ..
- } => "API Key 被拒绝。请检查 API Key。".to_string(),
- Error::Api {
- status: Some(404), ..
- } => "服务器响应了,但 API 端点未找到。请检查服务器 URL。".to_string(),
- Error::Api {
- status: Some(status),
- ..
- } => {
- format!("服务器返回 HTTP {status}。请检查服务器配置。")
+ Error::Timeout(_) => "连接超时。请提高请求超时时间或检查服务器状态。".to_string(),
+ error @ Error::Api { .. } if error.code() == "UNAUTHENTICATED" => {
+ "API Key 被拒绝。请检查 API Key。".to_string()
}
- Error::Api { .. } => "服务器验证时返回错误。请检查服务器日志。".to_string(),
+ Error::Api { message, .. } => message.clone(),
Error::Config(msg) => msg.clone(),
_ => match kind {
ConfigKind::OpenVikingService => "验证失败。请检查 API Key 后重试。".to_string(),
@@ -779,7 +769,7 @@ mod tests {
ApiKeyRole, ConfigDraft, ConfigKind, ConfigStore, OPENVIKING_SERVICE_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,
+ validate_candidate_config_with_role, validate_config_name,
};
use crate::config::Config;
use std::fs;
@@ -1135,28 +1125,6 @@ mod tests {
assert!(!admin_probe_regular_key_status(500));
}
- #[test]
- fn validation_error_copy_hides_raw_backend_details() {
- let error = crate::error::Error::api(
- "[AuthenticationError] invalid key. Request ID: 02177930089909800000000000000000ffff"
- .to_string(),
- );
-
- let cloud = validation_error_copy(ConfigKind::OpenVikingService, &error);
- let custom = validation_error_copy(ConfigKind::Custom, &error);
-
- assert_eq!(
- cloud,
- "Server returned an error during validation. Check the server logs."
- );
- assert_eq!(
- custom,
- "Server returned an error during validation. Check the server logs."
- );
- assert!(!cloud.contains("Request ID"));
- assert!(!custom.contains("AuthenticationError"));
- }
-
#[test]
fn edit_active_config_updates_active_config_and_saved_config() {
let dir = unique_dir("edit-active");
diff --git a/crates/ov_cli/src/error.rs b/crates/ov_cli/src/error.rs
index a73950278..d449d60a3 100644
--- a/crates/ov_cli/src/error.rs
+++ b/crates/ov_cli/src/error.rs
@@ -1,3 +1,4 @@
+use serde_json::Value;
use thiserror::Error;
#[derive(Error, Debug)]
@@ -14,9 +15,14 @@ pub enum Error {
#[error("Network error: {0}")]
Network(String),
+ #[error("Request timeout: {0}")]
+ Timeout(String),
+
#[error("API error: {message}")]
Api {
+ code: Option<String>,
message: String,
+ details: Option<Value>,
status: Option<u16>,
},
@@ -48,17 +54,80 @@ pub enum Error {
impl Error {
pub fn api(message: impl Into<String>) -> Self {
Self::Api {
+ code: None,
message: message.into(),
+ details: None,
status: None,
}
}
pub fn api_with_status(message: impl Into<String>, status: u16) -> Self {
Self::Api {
+ code: None,
+ message: message.into(),
+ details: None,
+ status: Some(status),
+ }
+ }
+
+ pub fn api_response(
+ code: Option<String>,
+ message: impl Into<String>,
+ details: Option<Value>,
+ status: u16,
+ ) -> Self {
+ Self::Api {
+ code,
message: message.into(),
+ details,
status: Some(status),
}
}
+
+ pub(crate) fn from_reqwest(context: &str, error: reqwest::Error) -> Self {
+ if error.is_timeout() {
+ Self::Timeout(format!("{context}: request timed out: {error}"))
+ } else if error.is_decode() {
+ Self::Parse(format!("{context}: {error}"))
+ } else if error.is_builder() {
+ Self::Client(format!("{context}: {error}"))
+ } else {
+ Self::Network(format!("{context}: {error}"))
+ }
+ }
+
+ pub(crate) fn code(&self) -> &str {
+ match self {
+ Self::MissingConfig | Self::Config(_) => "FAILED_PRECONDITION",
+ Self::Language(_) | Self::Client(_) | Self::InvalidPath(_) => "INVALID_ARGUMENT",
+ Self::Network(_) => "UNAVAILABLE",
+ Self::Timeout(_) => "DEADLINE_EXCEEDED",
+ Self::Api { code, status, .. } => code
+ .as_deref()
+ .unwrap_or_else(|| code_from_http_status(*status)),
+ Self::Parse(_)
+ | Self::Output(_)
+ | Self::Io(_)
+ | Self::Serialization(_)
+ | Self::Zip(_)
+ | Self::AlreadyReported => "INTERNAL",
+ }
+ }
+}
+
+fn code_from_http_status(status: Option<u16>) -> &'static str {
+ match status {
+ Some(400 | 422) => "INVALID_ARGUMENT",
+ Some(401) => "UNAUTHENTICATED",
+ Some(403) => "PERMISSION_DENIED",
+ Some(404) => "NOT_FOUND",
+ Some(409) => "CONFLICT",
+ Some(412) => "FAILED_PRECONDITION",
+ Some(429) => "RESOURCE_EXHAUSTED",
+ Some(502 | 503) => "UNAVAILABLE",
+ Some(504) => "DEADLINE_EXCEEDED",
+ _ => "INTERNAL",
+ }
}
pub type Result<T> = std::result::Result<T, Error>;
diff --git a/crates/ov_cli/src/error_classifier.rs b/crates/ov_cli/src/error_classifier.rs
deleted file mode 100644
index b108a911f..000000000
--- a/crates/ov_cli/src/error_classifier.rs
+++ /dev/null
@@ -1,195 +0,0 @@
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) struct MissingTrustedIdentityFields {
- pub(crate) account: bool,
- pub(crate) user: bool,
-}
-
-pub(crate) fn missing_trusted_identity_fields(
- message: &str,
-) -> Option<MissingTrustedIdentityFields> {
- let lower = message.to_ascii_lowercase();
- let describes_missing_value = lower.contains("must include")
- || lower.contains("requires")
- || lower.contains("required")
- || lower.contains("missing");
- let mentions_trusted_identity = lower.contains("trusted")
- && (lower.contains("x-openviking-account")
- || lower.contains("x-openviking-user")
- || lower.contains("account_id")
- || lower.contains("user_id"));
- if !describes_missing_value || !mentions_trusted_identity {
- return None;
- }
-
- let fields = MissingTrustedIdentityFields {
- account: lower.contains("x-openviking-account") || lower.contains("account_id"),
- user: lower.contains("x-openviking-user") || lower.contains("user_id"),
- };
- (fields.account || fields.user).then_some(fields)
-}
-
-pub(crate) fn looks_like_missing_api_key_error(message: &str) -> bool {
- let lower = message.to_ascii_lowercase();
- lower.contains("missing api key") || lower.contains("api key header required")
-}
-
-pub(crate) fn looks_like_auth_error(message: &str) -> bool {
- let lower = message.to_ascii_lowercase();
- lower.contains("api key")
- || lower.contains("unauthorized")
- || lower.contains("forbidden")
- || lower.contains("authentication")
- || lower.contains("trusted openviking chat requires")
- || lower.contains("trusted mode requests must include")
- || lower
- .split(|ch: char| !ch.is_ascii_alphanumeric())
- .any(|token| token == "auth")
-}
-
-pub(crate) fn looks_like_gateway_dev_boundary_error(message: &str) -> bool {
- let lower = message.to_ascii_lowercase();
- lower.contains("dev auth can only be used when gateway and openviking server are localhost")
- || (lower.contains("auth_mode changed to dev")
- && lower.contains("gateway")
- && lower.contains("openviking server"))
-}
-
-pub(crate) fn looks_like_gateway_standalone_proxy_error(message: &str) -> bool {
- let lower = message.to_ascii_lowercase();
- lower.contains("openviking upstream is not configured")
- || (lower.contains("vikingbot gateway proxy")
- && lower.contains("no available openviking server"))
-}
-
-/// Detect the kernel's pydantic `extra="forbid"` rejection — e.g.
-/// "body.tags: Extra inputs are not permitted" — and return the offending field
-/// name. This usually means the target OpenViking instance is on a different
-/// version than the CLI (the field is missing, renamed, or removed), so callers
-/// can surface a version-mismatch hint instead of the raw API error.
-pub(crate) fn extra_forbidden_field(message: &str) -> Option<String> {
- if !message.contains("Extra inputs are not permitted") {
- return None;
- }
- // The kernel reports the location as `body.<field>: Extra inputs ...`.
- let after = message.split("body.").nth(1)?;
- let field = after
- .split(|ch: char| ch == ':' || ch.is_whitespace())
- .next()?
- .trim();
- if field.is_empty() {
- None
- } else {
- Some(field.to_string())
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::{
- extra_forbidden_field, looks_like_auth_error, looks_like_gateway_dev_boundary_error,
- looks_like_gateway_standalone_proxy_error, looks_like_missing_api_key_error,
- missing_trusted_identity_fields,
- };
-
- #[test]
- fn extracts_extra_forbidden_field() {
- assert_eq!(
- extra_forbidden_field(
- "[INVALID_ARGUMENT] Invalid request parameters: body.tags: Extra inputs are not permitted."
- ),
- Some("tags".to_string())
- );
- assert_eq!(
- extra_forbidden_field("body.args: Extra inputs are not permitted"),
- Some("args".to_string())
- );
- }
-
- #[test]
- fn ignores_non_extra_forbidden_errors() {
- assert_eq!(extra_forbidden_field("API key is invalid"), None);
- assert_eq!(extra_forbidden_field("body.query: Field required"), None);
- }
-
- #[test]
- fn detects_auth_errors() {
- for message in [
- "API key is invalid",
- "request was unauthorized",
- "forbidden",
- "authentication failed",
- "auth failed",
- "Trusted OpenViking chat requires X-OpenViking-Account and X-OpenViking-User.",
- "Trusted mode requests must include X-OpenViking-Account.",
- ] {
- assert!(looks_like_auth_error(message), "{message}");
- }
- }
-
- #[test]
- fn extracts_missing_trusted_identity_fields() {
- let both = missing_trusted_identity_fields(
- "Trusted mode requests must include X-OpenViking-Account or explicit account_id in the URL and X-OpenViking-User or explicit user_id in the URL.",
- )
- .expect("trusted identity fields");
- assert!(both.account);
- assert!(both.user);
-
- let user =
- missing_trusted_identity_fields("Trusted OpenViking chat requires X-OpenViking-User.")
- .expect("trusted user field");
- assert!(!user.account);
- assert!(user.user);
-
- let wrapped = missing_trusted_identity_fields(
- "Request failed (401 Unauthorized): {\"detail\":\"Trusted request is missing account_id and user_id\"}",
- )
- .expect("wrapped trusted identity fields");
- assert!(wrapped.account);
- assert!(wrapped.user);
-
- assert!(missing_trusted_identity_fields("API key is invalid").is_none());
- }
-
- #[test]
- fn detects_missing_api_key_without_matching_invalid_keys() {
- for message in [
- "Missing API Key when resolving identity.",
- "Missing API Key in trusted mode with Root API Key enabled.",
- "OpenViking API key header required",
- ] {
- assert!(looks_like_missing_api_key_error(message), "{message}");
- }
- assert!(!looks_like_missing_api_key_error("API key is invalid"));
- }
-
- #[test]
- fn avoids_auth_substring_false_positives() {
- for message in ["author not found", "authority unavailable"] {
- assert!(!looks_like_auth_error(message), "{message}");
- }
- }
-
- #[test]
- fn detects_gateway_dev_boundary_errors() {
- for message in [
- "Request failed (403 Forbidden): {\"detail\":\"OpenViking dev auth can only be used when gateway and OpenViking server are localhost\"}",
- "Request failed (403 Forbidden): {\"detail\":\"OpenViking server auth_mode changed to dev, but dev auth can only be used when gateway and OpenViking server are localhost\"}",
- ] {
- assert!(looks_like_gateway_dev_boundary_error(message), "{message}");
- }
- }
-
- #[test]
- fn detects_gateway_standalone_proxy_errors() {
- for message in [
- "OpenViking upstream is not configured",
- "VikingBot gateway proxy is active, but no available OpenViking server is configured",
- ] {
- assert!(
- looks_like_gateway_standalone_proxy_error(message),
- "{message}"
- );
- }
- }
-}
diff --git a/crates/ov_cli/src/error_ui.rs b/crates/ov_cli/src/error_ui.rs
index 44a65cf85..4b70c6c9f 100644
--- a/crates/ov_cli/src/error_ui.rs
+++ b/crates/ov_cli/src/error_ui.rs
@@ -1,16 +1,13 @@
use std::ffi::OsString;
use colored::Colorize;
+use serde_json::{Map, Value};
use unicode_width::UnicodeWidthStr;
use crate::{
error::Error,
- error_classifier::{
- MissingTrustedIdentityFields, extra_forbidden_field, looks_like_auth_error,
- looks_like_gateway_dev_boundary_error, looks_like_gateway_standalone_proxy_error,
- looks_like_missing_api_key_error, missing_trusted_identity_fields,
- },
i18n::{Language, copy},
+ output::OutputFormat,
terminal_ui::{fit_to_display_width, truncate_to_display_width},
theme,
};
@@ -86,6 +83,42 @@ pub(crate) fn print_report(report: &ErrorReport, verbose: bool) {
eprint!("{}", render_report(report, verbose));
}
+pub(crate) fn print_runtime_error(
+ command: &str,
+ error: &Error,
+ format: OutputFormat,
+ compact: bool,
+ verbose: bool,
+) {
+ if matches!(format, OutputFormat::Json) {
+ eprintln!("{}", render_json_error(error, compact));
+ } else {
+ print_report(&report_for_runtime_error(command, error), verbose);
+ }
+}
+
+fn render_json_error(error: &Error, compact: bool) -> String {
+ let (message, details): (String, Option<&Value>) = match error {
+ Error::Api {
+ message, details, ..
+ } => (message.clone(), details.as_ref()),
+ _ => (error.to_string(), None),
+ };
+
+ let mut body = Map::new();
+ body.insert("code".to_string(), Value::String(error.code().to_string()));
+ body.insert("message".to_string(), Value::String(message));
+ if let Some(details) = details {
+ body.insert("details".to_string(), details.clone());
+ }
+ let envelope = serde_json::json!({"ok": false, "error": body});
+ if compact {
+ envelope.to_string()
+ } else {
+ serde_json::to_string_pretty(&envelope).unwrap_or_else(|_| envelope.to_string())
+ }
+}
+
pub(crate) fn report_for_clap_error(args: &[OsString], clap_output: &str) -> ErrorReport {
let language = Language::current();
let command = display_command(args);
@@ -194,16 +227,6 @@ pub(crate) fn report_for_plain_help_error(
)])
}
-fn is_client_auth_error(status: Option<u16>, message: &str) -> bool {
- if matches!(status, Some(code) if (500..600).contains(&code)) {
- return false;
- }
- if message.contains("Upstream model ") {
- return false;
- }
- looks_like_auth_error(message)
-}
-
pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &Error) -> ErrorReport {
let language = Language::current();
let command = command.into();
@@ -230,6 +253,20 @@ pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &Error
ErrorAction::new("ov language en", copy(language, "Use English", "使用英文")),
ErrorAction::new("ov language zh-CN", copy(language, "Use Simplified Chinese", "使用简体中文")),
]),
+ Error::Timeout(message) => ErrorReport::new(
+ copy(language, "Request Timeout", "请求超时"),
+ copy(
+ language,
+ "OpenViking did not respond before the configured timeout expired.",
+ "OpenViking 未在配置的超时时间内响应。",
+ ),
+ )
+ .with_command(command)
+ .with_detail(message)
+ .with_actions(vec![
+ ErrorAction::new("ov config", copy(language, "Increase the request timeout", "提高请求超时时间")),
+ ErrorAction::new("ov config show", copy(language, "Show the active config", "查看当前配置")),
+ ]),
Error::Network(message) => ErrorReport::new(
copy(language, "Connection Error", "连接错误"),
copy(
@@ -245,159 +282,26 @@ pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &Error
ErrorAction::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_gateway_dev_boundary_error(message) => {
- ErrorReport::new(
- copy(language, "Gateway Safety Check", "Gateway 安全校验失败"),
- copy(
- language,
- "OpenViking is in dev mode. VikingBot gateway and OpenViking server must both listen on localhost.",
- "OpenViking 当前是 dev 模式,VikingBot gateway 和 OpenViking server 必须都监听 localhost。",
- ),
- )
- .with_command(command)
- .with_detail(message)
- .with_actions(vec![
- ErrorAction::new(
- "ov config",
- copy(
- language,
- "Set bot.gateway.host to 127.0.0.1, or configure server.root_api_key",
- "将 bot.gateway.host 改为 127.0.0.1,或配置 server.root_api_key",
- ),
- ),
- ErrorAction::new(
- "ov health",
- copy(language, "Check the active endpoint", "检查当前端点"),
- ),
- ])
- }
- Error::Api { message, .. } if looks_like_gateway_standalone_proxy_error(message) => {
- ErrorReport::new(
- copy(language, "VikingBot Gateway Proxy", "VikingBot Gateway Proxy 不可用"),
- copy(
- language,
- "The active config is using VikingBot gateway proxy, but the gateway has no available OpenViking server. Standalone gateway mode can only serve ov chat.",
- "当前配置正在使用 VikingBot gateway proxy,但 gateway 没有可用的 OpenViking server。standalone gateway 模式只能使用 ov chat,其他 ov CLI 请求无法转发。",
- ),
- )
- .with_command(command)
- .with_detail(message)
- .with_actions(vec![
- ErrorAction::new(
- "ov chat",
- copy(language, "Chat with standalone VikingBot", "使用 standalone VikingBot 对话"),
- ),
- ErrorAction::new(
- "ov config",
- copy(
- language,
- "Point url to OpenViking server or fix bot.ov_server",
- "将 url 指向 OpenViking server,或修复 bot.ov_server",
- ),
- ),
- ErrorAction::new(
- "ov health",
- copy(language, "Check the active endpoint", "检查当前端点"),
- ),
- ])
- }
- Error::Api { message, .. } if missing_trusted_identity_fields(message).is_some() => {
- let fields = missing_trusted_identity_fields(message).expect("matched above");
- let names = trusted_identity_field_names(fields, language);
- ErrorReport::new(
- copy(
- language,
- "OpenViking Identity Missing",
- "OpenViking 身份配置缺失",
- ),
- trusted_identity_error_message(fields, language),
- )
- .with_command(command)
- .with_detail(message)
- .with_actions(vec![
- ErrorAction::new(
- "ov config",
- match language {
- Language::En => format!("Configure {names} in ovcli.conf"),
- Language::ZhCn => format!("在 ovcli.conf 中配置 {names}"),
- },
- ),
- ErrorAction::new(
- "ov config show",
- copy(language, "Show the active config", "查看当前配置"),
- ),
- ])
- }
- Error::Api { message, .. } if looks_like_missing_api_key_error(message) => {
- let trusted = message
- .to_ascii_lowercase()
- .contains("trusted mode");
- ErrorReport::new(
- copy(
- language,
- "OpenViking API Key Missing",
- "OpenViking API Key 未配置",
- ),
- missing_api_key_error_message(language, trusted),
- )
- .with_command(command)
- .with_detail(message)
- .with_actions(vec![
- ErrorAction::new(
- "ov config",
- copy(
- language,
- "Configure api_key in ovcli.conf",
- "在 ovcli.conf 中配置 api_key",
- ),
- ),
- ErrorAction::new(
- "ov config show",
- copy(language, "Show the active config", "查看当前配置"),
- ),
- ])
- }
- Error::Api { message, status } if is_client_auth_error(*status, message) => ErrorReport::new(
+ Error::Api { message, .. } if error.code() == "UNAUTHENTICATED" => ErrorReport::new(
copy(language, "Authentication Error", "认证错误"),
- copy(language, "OpenViking rejected the API key for the active config.", "OpenViking 拒绝了当前配置的 API Key。"),
+ api_error_message(error.code(), message),
)
.with_command(command)
- .with_detail(message)
.with_actions(vec![
ErrorAction::new("ov config", copy(language, "Edit this config", "编辑这个配置")),
ErrorAction::new("ov config switch", copy(language, "Use another config", "使用其他配置")),
]),
- Error::Api { message, .. } if extra_forbidden_field(message).is_some() => {
- let field = extra_forbidden_field(message).unwrap_or_default();
- ErrorReport::new(
+ Error::Api { message, details, .. } => {
+ let mut report = ErrorReport::new(
copy(language, "OpenViking API Error", "OpenViking API 错误"),
- match language {
- Language::En => format!(
- "OpenViking rejected an unsupported field \"{field}\". This instance's version likely does not match your CLI (the field may be missing, renamed, or removed)."
- ),
- Language::ZhCn => format!(
- "OpenViking 拒绝了不支持的字段 \"{field}\":该实例版本可能与当前 CLI 不匹配(字段可能缺失、改名或已被移除)。"
- ),
- },
+ api_error_message(error.code(), message),
)
- .with_command(command)
- .with_detail(message)
- .with_actions(vec![
- ErrorAction::new("ov health", copy(language, "Check the instance version", "查看实例版本")),
- ErrorAction::new("ov config validate", copy(language, "Check the active config", "检查当前配置")),
- ErrorAction::new("ov status", copy(language, "Check OpenViking status", "查看 OpenViking 状态")),
- ])
+ .with_command(command);
+ if let Some(details) = details {
+ report = report.with_detail(details.to_string());
+ }
+ report
}
- Error::Api { message, .. } => ErrorReport::new(
- copy(language, "OpenViking API Error", "OpenViking API 错误"),
- api_error_message(language, message),
- )
- .with_command(command)
- .with_detail(message)
- .with_actions(vec![
- ErrorAction::new("ov config validate", copy(language, "Check the active config", "检查当前配置")),
- ErrorAction::new("ov status", copy(language, "Check OpenViking status", "查看 OpenViking 状态")),
- ]),
Error::Client(message) => ErrorReport::new(
copy(language, "Command Error", "命令错误"),
sentence_case_error(message),
@@ -433,50 +337,6 @@ pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &Error
}
}
-fn trusted_identity_field_names(
- fields: MissingTrustedIdentityFields,
- language: Language,
-) -> &'static str {
- match (fields.account, fields.user) {
- (true, true) => copy(language, "account and user", "account 和 user"),
- (true, false) => "account",
- (false, true) => "user",
- (false, false) => unreachable!("at least one identity field is required"),
- }
-}
-
-fn trusted_identity_error_message(
- fields: MissingTrustedIdentityFields,
- language: Language,
-) -> String {
- let names = trusted_identity_field_names(fields, language);
- match language {
- Language::En => format!(
- "OpenViking server is using trusted mode. The active ovcli.conf is missing {names}, so the request identity cannot be determined. Configure {names} in ovcli.conf."
- ),
- Language::ZhCn => format!(
- "OpenViking server 使用 trusted 模式。当前 ovcli.conf 缺少 {names},无法确定请求身份。请在 ovcli.conf 中配置 {names}。"
- ),
- }
-}
-
-fn missing_api_key_error_message(language: Language, trusted: bool) -> &'static str {
- match (language, trusted) {
- (Language::En, true) => {
- "OpenViking server is using trusted mode with a Root API Key. The active ovcli.conf did not provide that key. Configure api_key with the server's Root API Key."
- }
- (Language::ZhCn, true) => {
- "OpenViking server 使用 trusted 模式,并启用了 Root API Key。当前 ovcli.conf 未提供该 key。请将 api_key 配置为该 server 的 Root API Key。"
- }
- (Language::En, false) => {
- "The current request did not provide an OpenViking API Key. Configure api_key in ovcli.conf: use a User/Admin API Key for api_key mode, or a Root API Key for trusted mode."
- }
- (Language::ZhCn, false) => {
- "当前请求未提供 OpenViking API Key。请在 ovcli.conf 中配置 api_key:api_key 模式使用 User/Admin API Key,trusted 模式使用 Root API Key。"
- }
- }
-}
-
fn config_error_actions(message: &str, language: Language) -> Vec<ErrorAction> {
if is_config_file_load_error(message) {
return vec![ErrorAction::new(
@@ -681,96 +541,12 @@ fn is_contextual_top_level_command(command: &str) -> bool {
)
}
-fn api_error_message(language: Language, raw: &str) -> String {
- let Some(summary) = summarize_api_error(raw) else {
- return copy(
- language,
- "OpenViking returned an error for this request.",
- "OpenViking 返回了请求错误。",
- )
- .to_string();
- };
-
- match language {
- Language::En => format!("OpenViking returned an error: {summary}"),
- Language::ZhCn => format!("OpenViking 返回了请求错误:{summary}"),
- }
-}
-
-fn summarize_api_error(raw: &str) -> Option<String> {
- let raw = raw.trim();
- if raw.is_empty() {
- return None;
- }
-
- if let Some(summary) = summarize_json_api_error(raw) {
- return Some(summary);
- }
-
- let cleaned = strip_request_id(raw);
- let cleaned = cleaned.trim();
- if cleaned.is_empty() {
- return None;
- }
-
- if let Some((code, message)) = bracketed_error(cleaned) {
- return Some(format_summary(Some(code), message));
- }
-
- Some(ensure_sentence(
- cleaned.lines().next().unwrap_or(cleaned).trim(),
- ))
-}
-
-fn summarize_json_api_error(raw: &str) -> Option<String> {
- let value: serde_json::Value = serde_json::from_str(raw).ok()?;
- let error = value.get("error").unwrap_or(&value);
- let code = error
- .get("code")
- .and_then(serde_json::Value::as_str)
- .filter(|value| !value.trim().is_empty());
- let message = error
- .get("message")
- .and_then(serde_json::Value::as_str)
- .or_else(|| error.get("detail").and_then(serde_json::Value::as_str))
- .filter(|value| !value.trim().is_empty())?;
- Some(format_summary(code, message))
-}
-
-fn bracketed_error(value: &str) -> Option<(&str, &str)> {
- let rest = value.strip_prefix('[')?;
- let end = rest.find(']')?;
- let code = rest[..end].trim();
- let message = rest[end + 1..].trim();
- if code.is_empty() || message.is_empty() {
- return None;
- }
- Some((code, message))
-}
-
-fn format_summary(code: Option<&str>, message: &str) -> String {
- let message = ensure_sentence(strip_request_id(message).trim());
- match code {
- Some(code) => format!("{code}: {message}"),
- None => message,
- }
-}
-
-fn strip_request_id(value: &str) -> &str {
- for marker in ["Request ID:", "Request Id:", "request ID:", "request id:"] {
- if let Some(index) = value.find(marker) {
- return value[..index].trim_end();
- }
- }
- value
-}
-
-fn ensure_sentence(value: &str) -> String {
- let value = value.trim().trim_end_matches('.').trim();
- if value.is_empty() {
- return "OpenViking returned an error.".to_string();
+fn api_error_message(code: &str, message: &str) -> String {
+ if message.is_empty() {
+ format!("[{code}] OpenViking returned an error")
+ } else {
+ format!("[{code}] {message}")
}
- format!("{value}.")
}
pub(crate) fn render_report(report: &ErrorReport, verbose: bool) -> String {
@@ -950,13 +726,12 @@ fn detail_line(language: Language, detail: &str) -> String {
}
fn render_card_line(line: &str, inner_width: usize) -> String {
- let line = truncate_to_display_width(line, inner_width);
let width = line.width();
let padding = inner_width.saturating_sub(width);
format!(
"{} {}{} {}",
theme::error("│"),
- theme::body(&line),
+ theme::body(line),
" ".repeat(padding),
theme::error("│")
)
@@ -972,7 +747,7 @@ fn wrap_text(text: &str, width: usize) -> Vec<String> {
for word in text.split_whitespace() {
if current.is_empty() && word.width() > width {
- lines.push(truncate_to_display_width(word, width));
+ lines.push(word.to_string());
continue;
}
@@ -1168,11 +943,10 @@ fn help_command_from_usage(usage: &str) -> Option<String> {
#[cfg(test)]
mod tests {
use super::{
- CARD_WIDTH, ErrorAction, ErrorReport, missing_api_key_error_message, render_report,
+ CARD_WIDTH, ErrorAction, ErrorReport, render_json_error, render_report,
render_report_with_width, report_for_clap_error, report_for_runtime_error,
- trusted_identity_error_message,
};
- use crate::{error::Error, error_classifier::MissingTrustedIdentityFields, i18n::Language};
+ use crate::error::Error;
use std::ffi::OsString;
use unicode_width::UnicodeWidthStr;
@@ -1292,184 +1066,33 @@ Usage: ov config [OPTIONS] [COMMAND]
}
#[test]
- fn runtime_api_error_hides_raw_detail_by_default() {
- let error = Error::api(
- "[AuthenticationError] API key invalid. Request ID: 02177930089909800000000000000000"
- .to_string(),
- );
- let report = report_for_runtime_error("ov status", &error);
- let normal = strip_ansi(&render_report(&report, false));
- let verbose = strip_ansi(&render_report(&report, true));
-
- assert!(normal.contains("Authentication Error"));
- assert!(normal.contains("OpenViking rejected the API key"));
- assert!(normal.contains("ov config"));
- assert!(!normal.contains("Request ID"));
- assert!(!normal.contains("AuthenticationError"));
-
- assert!(verbose.contains("Detail:"));
- assert!(verbose.contains("Request ID"));
- }
-
- #[test]
- fn trusted_identity_error_names_missing_ovcli_fields() {
- let error = Error::api(
- "[INVALID_ARGUMENT] Trusted mode requests must include X-OpenViking-Account or explicit account_id in the URL and X-OpenViking-User or explicit user_id in the URL."
- .to_string(),
- );
- let report = report_for_runtime_error("ov ls viking://", &error);
- let normal = strip_ansi(&render_report(&report, false));
-
- assert!(normal.contains("OpenViking Identity Missing"));
- assert!(normal.contains("trusted mode"));
- assert!(normal.contains("ovcli.conf"));
- assert!(normal.contains("account and user"));
- assert!(!normal.contains("rejected the API key"));
- }
-
- #[test]
- fn missing_api_key_error_is_not_reported_as_rejected_key() {
- let error = Error::api(
- "[UNAUTHENTICATED] Missing API Key in trusted mode with Root API Key enabled."
- .to_string(),
- );
- let report = report_for_runtime_error("ov ls viking://", &error);
- let normal = strip_ansi(&render_report(&report, false));
-
- assert!(normal.contains("OpenViking API Key Missing"));
- assert!(normal.contains("trusted mode"));
- assert!(normal.contains("Root API Key"));
- assert!(normal.contains("ovcli.conf"));
- assert!(!normal.contains("rejected the API key"));
- }
-
- #[test]
- fn trusted_identity_and_missing_key_have_chinese_guidance() {
- let identity = trusted_identity_error_message(
- MissingTrustedIdentityFields {
- account: true,
- user: true,
- },
- Language::ZhCn,
- );
- assert!(identity.contains("OpenViking server 使用 trusted 模式"));
- assert!(identity.contains("ovcli.conf 缺少 account 和 user"));
- assert!(identity.contains("配置 account 和 user"));
-
- let api_key = missing_api_key_error_message(Language::ZhCn, true);
- assert!(api_key.contains("trusted 模式"));
- assert!(api_key.contains("Root API Key"));
- assert!(api_key.contains("ovcli.conf"));
- assert!(api_key.contains("api_key"));
- }
-
- #[test]
- fn gateway_dev_boundary_error_is_not_reported_as_api_key_rejection() {
- let error = Error::api(
- "Request failed (403 Forbidden): {\"detail\":\"OpenViking server auth_mode changed to dev, but dev auth can only be used when gateway and OpenViking server are localhost\"}"
- .to_string(),
- );
- let report = report_for_runtime_error("ov ls viking://", &error);
- let normal = strip_ansi(&render_report(&report, false));
-
- assert!(normal.contains("Gateway Safety Check"));
- assert!(normal.contains("OpenViking is in dev mode"));
- assert!(normal.contains("bot.gateway.host"));
- assert!(!normal.contains("OpenViking rejected the API key"));
- }
-
- #[test]
- fn remote_resource_auth_failure_wrapped_as_5xx_is_not_api_key_error() {
- let error = Error::api_with_status(
- "HTTP request failed: authentication error (401). Check your credentials or permissions. URL: https://example.com/private"
- .to_string(),
- 500,
- );
- let report =
- report_for_runtime_error("ov add-resource https://example.com/private", &error);
- let normal = strip_ansi(&render_report(&report, false));
-
- assert!(normal.contains("OpenViking API Error"));
- assert!(!normal.contains("Authentication Error"));
- assert!(!normal.contains("OpenViking rejected the API key"));
- }
-
- #[test]
- fn gateway_standalone_proxy_error_explains_missing_openviking_server() {
- let error = Error::api(
- "VikingBot gateway proxy is active, but no available OpenViking server is configured"
- .to_string(),
- );
- let report = report_for_runtime_error("ov ls viking://", &error);
- let normal = strip_ansi(&render_report(&report, false));
-
- assert!(normal.contains("VikingBot Gateway Proxy"));
- assert!(normal.contains("no available") || normal.contains("没有可用"));
- assert!(normal.contains("OpenViking server"));
- assert!(normal.contains("serve ov chat") || normal.contains("只能使用 ov chat"));
- assert!(normal.contains("ov chat"));
- assert!(!normal.contains("OpenViking rejected the API key"));
- }
-
- #[test]
- fn server_401_is_still_api_key_error() {
- let error = Error::api_with_status("API key invalid".to_string(), 401);
- let report = report_for_runtime_error("ov status", &error);
- let normal = strip_ansi(&render_report(&report, false));
-
- assert!(normal.contains("Authentication Error"));
- assert!(normal.contains("OpenViking rejected the API key"));
- }
-
- #[test]
- fn upstream_model_auth_error_is_not_cli_api_key_error() {
- let error = Error::api_with_status(
- "[UNAUTHENTICATED] Upstream model authentication failed: invalid api key".to_string(),
- 401,
+ fn structured_api_errors_are_not_reclassified_from_message_text() {
+ let error = Error::api_response(
+ Some("FAILED_PRECONDITION".to_string()),
+ "Apply permission at https://open.feishu.cn/app/auth?token=abc",
+ Some(serde_json::json!({"feishu_code": 99991672})),
+ 412,
);
- let report = report_for_runtime_error("ov find hello", &error);
- let normal = strip_ansi(&render_report(&report, false));
- let verbose = strip_ansi(&render_report(&report, true));
-
- assert!(normal.contains("OpenViking API Error"));
- assert!(!normal.contains("Authentication Error"));
- assert!(!normal.contains("OpenViking rejected the API key"));
-
- assert!(verbose.contains("Detail:"));
- assert!(verbose.contains("Upstream model authentication failed"));
- }
- #[test]
- fn runtime_api_error_shows_sanitized_detail_by_default() {
- let error = Error::api(
- "[InvalidRequest] resource not found. Request ID: 02177930089909800000000000000000"
- .to_string(),
- );
- let report = report_for_runtime_error("ov read viking://missing", &error);
- let normal = strip_ansi(&render_report(&report, false));
- let verbose = strip_ansi(&render_report(&report, true));
-
- assert!(normal.contains("OpenViking API Error"));
- assert!(normal.contains("InvalidRequest: resource not found."));
- assert!(!normal.contains("Request ID"));
- assert!(!normal.contains("02177930089909800000000000000000"));
+ let report = report_for_runtime_error("ov add-resource", &error);
+ let rendered = strip_ansi(&render_report(&report, false));
+ assert!(rendered.contains("OpenViking API Error"));
+ assert!(rendered.contains("[FAILED_PRECONDITION]"));
+ assert!(!rendered.contains("Authentication Error"));
- assert!(verbose.contains("Detail:"));
- assert!(verbose.contains("Request ID"));
+ let json: serde_json::Value =
+ serde_json::from_str(&render_json_error(&error, true)).unwrap();
+ assert_eq!(json["error"]["code"], "FAILED_PRECONDITION");
+ assert_eq!(json["error"]["details"]["feishu_code"], 99991672);
}
#[test]
- fn runtime_api_error_summarizes_json_error_envelope() {
- let error = Error::api(
- r#"{"error":{"code":"PermissionDenied","message":"root key required","request_id":"abc"}}"#
- .to_string(),
- );
- let report = report_for_runtime_error("ov admin list-users --sudo", &error);
- let normal = strip_ansi(&render_report(&report, false));
+ fn local_runtime_json_error_always_has_code() {
+ let error = Error::Config("Failed to parse config file".to_string());
+ let json: serde_json::Value =
+ serde_json::from_str(&render_json_error(&error, true)).unwrap();
- assert!(normal.contains("PermissionDenied: root key required."));
- assert!(!normal.contains("request_id"));
- assert!(!normal.contains("abc"));
+ assert_eq!(json["error"]["code"], "FAILED_PRECONDITION");
}
#[test]
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 634ea908b..021b7c502 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -7,7 +7,6 @@ mod config_agent;
mod config_command_ui;
mod config_wizard;
mod error;
-mod error_classifier;
mod error_ui;
mod handlers;
mod health_ui;
@@ -2402,6 +2401,22 @@ fn preprocess_cli_args(args: Vec<OsString>) -> Vec<OsString> {
preprocess_privacy_args(args)
}
+fn pre_parse_output_options(args: &[OsString]) -> (OutputFormat, bool) {
+ let Ok(matches) = Cli::command()
+ .ignore_errors(true)
+ .try_get_matches_from(args)
+ else {
+ return (OutputFormat::Table, true);
+ };
+ (
+ matches
+ .get_one::<OutputFormat>("output")
+ .copied()
+ .unwrap_or(OutputFormat::Table),
+ matches.get_one::<bool>("compact").copied().unwrap_or(true),
+ )
+}
+
fn preprocess_privacy_args(args: Vec<OsString>) -> Vec<OsString> {
let args = preprocess_privacy_get_shortcut(args);
preprocess_privacy_upsert_key_flags(args)
@@ -2530,12 +2545,18 @@ fn language_command_can_run_picker(has_language_value: bool, is_interactive: boo
async fn main() {
let args = preprocess_cli_args(std::env::args_os().collect());
let command_display = error_ui::display_command(&args);
+ let (pre_parse_output_format, pre_parse_compact) = pre_parse_output_options(&args);
match ensure_language_selected_before_command(&args).await {
Ok(true) => {}
Ok(false) => return,
Err(e) => {
- let report = error_ui::report_for_runtime_error(&command_display, &e);
- error_ui::print_report(&report, false);
+ error_ui::print_runtime_error(
+ &command_display,
+ &e,
+ pre_parse_output_format,
+ pre_parse_compact,
+ false,
+ );
std::process::exit(2);
}
}
@@ -2558,8 +2579,13 @@ async fn main() {
match Config::load_required() {
Ok(config) => Some(config),
Err(e) => {
- let report = error_ui::report_for_runtime_error(&command_display, &e);
- error_ui::print_report(&report, false);
+ error_ui::print_runtime_error(
+ &command_display,
+ &e,
+ pre_parse_output_format,
+ pre_parse_compact,
+ false,
+ );
std::process::exit(2);
}
}
@@ -2640,8 +2666,13 @@ async fn main() {
std::process::exit(2);
}
if let Err(e) = handlers::handle_language(language.clone()).await {
- let report = error_ui::report_for_runtime_error(&command_display, &e);
- error_ui::print_report(&report, cli.verbose);
+ error_ui::print_runtime_error(
+ &command_display,
+ &e,
+ output_format,
+ compact,
+ cli.verbose,
+ );
std::process::exit(2);
}
return;
@@ -2658,8 +2689,13 @@ async fn main() {
let config = match config_result {
Ok(config) => config,
Err(e) => {
- let report = error_ui::report_for_runtime_error(&command_display, &e);
- error_ui::print_report(&report, cli.verbose);
+ error_ui::print_runtime_error(
+ &command_display,
+ &e,
+ output_format,
+ compact,
+ cli.verbose,
+ );
std::process::exit(2);
}
};
@@ -3209,8 +3245,13 @@ async fn main() {
if let Err(e) = result {
if !matches!(e, Error::AlreadyReported) {
- let report = error_ui::report_for_runtime_error(&command_display, &e);
- error_ui::print_report(&report, verbose_errors);
+ error_ui::print_runtime_error(
+ &command_display,
+ &e,
+ output_format,
+ compact,
+ verbose_errors,
+ );
}
std::process::exit(1);
}
@@ -3223,7 +3264,8 @@ mod tests {
PrivacyCommands, SkillCommands, UploadCliOptions, find_command_index, 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_cli_args, preprocess_privacy_args,
+ pre_parse_output_options, pre_parse_requires_cli_config_file, preprocess_cli_args,
+ preprocess_privacy_args,
};
use crate::config::{Config, DEFAULT_CUSTOM_URL};
use crate::output::OutputFormat;
@@ -3254,6 +3296,17 @@ mod tests {
assert_eq!(cli.actor_peer_id.as_deref(), Some("peer-a"));
}
+ #[test]
+ fn pre_parse_output_options_preserve_json_config_errors() {
+ for args in [
+ os_args(&["ov", "ls", "--output", "json", "--compact=false"]),
+ os_args(&["ov", "ls", "-ojson"]),
+ os_args(&["ov", "ls", "-o=json"]),
+ ] {
+ assert_eq!(pre_parse_output_options(&args).0, OutputFormat::Json);
+ }
+ }
+
#[test]
fn cli_parses_find_context_type() {
let cli =
diff --git a/crates/ov_cli/src/status_ui.rs b/crates/ov_cli/src/status_ui.rs
index 3984be3fc..5bc21f553 100644
--- a/crates/ov_cli/src/status_ui.rs
+++ b/crates/ov_cli/src/status_ui.rs
@@ -6,7 +6,6 @@ use crate::{
config::{Config, display_config_home},
config_wizard::{ConfigKind, ConfigStore},
error::{Error, Result},
- error_classifier::looks_like_auth_error,
i18n::{Language, copy},
theme,
};
@@ -205,16 +204,18 @@ pub(crate) fn render_unreachable_status(
enum StatusFailureKind {
Authentication,
Api,
+ Timeout,
Connection,
}
impl StatusFailureKind {
fn from_error(error: Option<&Error>) -> Self {
match error {
- Some(Error::Api { message, .. }) if looks_like_auth_error(message) => {
+ Some(error @ Error::Api { .. }) if error.code() == "UNAUTHENTICATED" => {
Self::Authentication
}
Some(Error::Api { .. }) => Self::Api,
+ Some(Error::Timeout(_)) => Self::Timeout,
_ => Self::Connection,
}
}
@@ -223,6 +224,7 @@ impl StatusFailureKind {
match self {
Self::Authentication => copy(language, "Authentication failed", "认证失败"),
Self::Api => copy(language, "Server error", "服务器错误"),
+ Self::Timeout => copy(language, "Timed out", "请求超时"),
Self::Connection => copy(language, "Unreachable", "无法连接"),
}
}
@@ -235,6 +237,11 @@ impl StatusFailureKind {
"OpenViking returned an API error",
"OpenViking 返回 API 错误",
),
+ Self::Timeout => copy(
+ language,
+ "Server did not respond before the configured timeout",
+ "服务器未在配置的超时时间内响应",
+ ),
Self::Connection => copy(language, "Cannot reach server", "无法连接服务器"),
}
}
@@ -269,6 +276,20 @@ impl StatusFailureKind {
copy(language, "Run a quick health check", "快速健康检查"),
),
],
+ Self::Timeout => vec![
+ (
+ "ov config",
+ copy(language, "Increase the request timeout", "提高请求超时时间"),
+ ),
+ (
+ "ov config show",
+ copy(language, "Show the active config", "查看当前配置"),
+ ),
+ (
+ "ov health",
+ copy(language, "Run a quick health check", "快速健康检查"),
+ ),
+ ],
Self::Connection => vec![
(
"ov config validate",
@@ -886,8 +907,11 @@ mod tests {
#[test]
fn unreachable_status_distinguishes_auth_failures() {
- let error = crate::error::Error::api(
- "[AuthenticationError] API key invalid. Request ID: abc".to_string(),
+ let error = crate::error::Error::api_response(
+ Some("UNAUTHENTICATED".to_string()),
+ "API key invalid",
+ None,
+ 401,
);
let rendered =
super::render_unreachable_status(&sample_config(), Some("local"), 2, Some(&error));
@@ -896,7 +920,7 @@ mod tests {
assert!(rendered.contains("Status Authentication failed"));
assert!(rendered.contains("Issue API key rejected"));
assert!(rendered.contains("ov config Edit the active API key"));
- assert!(!rendered.contains("Request ID"));
+ assert!(!rendered.contains("API key invalid"));
}
#[test]
diff --git a/openviking/parse/accessors/feishu_accessor.py b/openviking/parse/accessors/feishu_accessor.py
index b5af7042e..d8951a10b 100644
--- a/openviking/parse/accessors/feishu_accessor.py
+++ b/openviking/parse/accessors/feishu_accessor.py
@@ -30,6 +30,7 @@ logger = get_logger(__name__)
_FEISHU_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\(feishu://image/([^)]+)\)")
_FEISHU_DOCUMENT_FORBIDDEN = 1770032
+_FEISHU_BITABLE_PERMISSION_REQUIRED = 99991672
def _title_as_filename(title: str) -> str:
@@ -79,15 +80,21 @@ def _raise_from_lark_response(
msg,
http_status,
)
- raise OpenVikingError(
- f"Feishu {operation} failed: code={code}, msg={msg}",
- code=(
+ if code == _FEISHU_BITABLE_PERMISSION_REQUIRED:
+ public_code = "FAILED_PRECONDITION"
+ message = (
+ "Feishu application is missing required Bitable permissions: "
+ f"code={code}, msg={msg}"
+ )
+ else:
+ public_code = (
"PERMISSION_DENIED"
- if code == _FEISHU_DOCUMENT_FORBIDDEN or "forbidden" in msg.lower()
+ if code == _FEISHU_DOCUMENT_FORBIDDEN
else error_code_from_http_status(http_status)
- ),
- details=details,
- )
+ )
+ message = f"Feishu {operation} failed: code={code}, msg={msg}"
+
+ raise OpenVikingError(message, code=public_code, details=details)
@dataclass
diff --git a/openviking/server/error_mapping.py b/openviking/server/error_mapping.py
index d969f0ece..6c10b1370 100644
--- a/openviking/server/error_mapping.py
+++ b/openviking/server/error_mapping.py
@@ -21,6 +21,7 @@ from openviking.pyagfs.exceptions import (
AGFSNetworkError,
AGFSNotADirectoryError,
AGFSNotFoundError,
+ AGFSNotSupportedError,
AGFSPermissionDeniedError,
AGFSPluginError,
AGFSSerializationError,
@@ -38,6 +39,7 @@ from openviking_cli.exceptions import (
OpenVikingError,
PermissionDeniedError,
UnavailableError,
+ UnimplementedError,
)
_KNOWN_HTTP_STATUS_CODES = frozenset(HTTP_STATUS_TO_ERROR_CODE)
@@ -502,6 +504,8 @@ def map_exception(
return PermissionDeniedError(str(exc), resource=resource)
if isinstance(exc, AGFSAlreadyExistsError):
return ConflictError(str(exc), resource=resource)
+ if isinstance(exc, AGFSNotSupportedError):
+ return UnimplementedError(str(exc), details=_resource_details(resource))
if isinstance(exc, AGFSInvalidPathError):
message = str(exc)
return InvalidURIError(resource or message, message)
diff --git a/tests/parse/test_feishu_errors.py b/tests/parse/test_feishu_errors.py
index 2f705ff24..9cae0cb78 100644
--- a/tests/parse/test_feishu_errors.py
+++ b/tests/parse/test_feishu_errors.py
@@ -49,6 +49,22 @@ def test_maps_feishu_forbidden_to_permission_denied_and_keeps_details():
assert exc.details["resource"] == "doc_token"
+def test_maps_missing_bitable_scope_without_parsing_message():
+ response = _fake_response(
+ code=99991672,
+ msg="opaque provider message",
+ http_status=400,
+ )
+
+ exc = _raised_error(response, operation="list bitable tables")
+
+ assert exc.code == "FAILED_PRECONDITION"
+ assert exc.message == (
+ "Feishu application is missing required Bitable permissions: "
+ "code=99991672, msg=opaque provider message"
+ )
+
+
@pytest.mark.parametrize(
("http_status", "error_code"),
[
diff --git a/tests/server/test_error_mapping.py b/tests/server/test_error_mapping.py
index 7129cf60e..840f18158 100644
--- a/tests/server/test_error_mapping.py
+++ b/tests/server/test_error_mapping.py
@@ -7,6 +7,7 @@ from openviking.pyagfs.exceptions import (
AGFSClientError,
AGFSHTTPError,
AGFSIsADirectoryError,
+ AGFSNotSupportedError,
GitConcurrentCommitError,
)
from openviking.server.error_mapping import map_exception
@@ -88,6 +89,13 @@ def test_agfs_is_directory_maps_to_structured_invalid_argument():
}
+def test_agfs_not_supported_maps_to_unimplemented():
+ mapped = map_exception(AGFSNotSupportedError("git feature disabled"))
+
+ assert mapped is not None
+ assert mapped.code == "UNIMPLEMENTED"
+
+
def test_value_error_invalid_uri_maps_to_invalid_uri():
mapped = map_exception(ValueError("invalid viking URI: missing path"), resource="viking://")