Skip to content

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

feat: CLI sub-command optimization (#560)

MaojiaShengc242ad6699cc
diff --git a/Makefile b/Makefile
index 6f0ae1c47..55db08601 100644
--- a/Makefile
+++ b/Makefile
@@ -2,7 +2,6 @@
# Variables
PYTHON ?= python3
-PIP ?= $(PYTHON) -m pip
SETUP_PY := setup.py
AGFS_SERVER_DIR := third_party/agfs/agfs-server
OV_CLI_DIR := crates/ov_cli
@@ -42,12 +41,18 @@ help:
@echo " help - Show this help message"
check-pip:
- @$(PYTHON) -m pip --version > /dev/null 2>&1 || ( \
- echo "Error: pip not found for $(PYTHON)."; \
- echo "Try fixing your virtual environment by running:"; \
+ @if command -v uv > /dev/null 2>&1 && uv pip --help > /dev/null 2>&1; then \
+ echo " [OK] uv pip found"; \
+ elif $(PYTHON) -m pip --version > /dev/null 2>&1; then \
+ echo " [OK] pip found"; \
+ else \
+ echo "Error: Neither uv pip nor pip found for $(PYTHON)."; \
+ echo "Try fixing your environment by running:"; \
+ echo " uv sync # if using uv"; \
+ echo " or"; \
echo " $(PYTHON) -m ensurepip --upgrade"; \
- exit 1 \
- )
+ exit 1; \
+ fi
check-deps:
@echo "Checking dependencies..."
@@ -87,7 +92,13 @@ check-deps:
build: check-deps check-pip
@echo "Starting build process via setup.py..."
$(PYTHON) $(SETUP_PY) build_ext --inplace
- $(PIP) install -e .
+ @if command -v uv > /dev/null 2>&1 && uv pip --help > /dev/null 2>&1; then \
+ echo " [OK] uv pip found, use uv pip to install..."; \
+ uv pip install -e .; \
+ else \
+ echo " [OK] pip found, use pip to install..."; \
+ $(PYTHON) -m pip install -e .; \
+ fi
@echo "Build completed successfully."
clean:
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index ce3cf8a91..b23121950 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -307,6 +307,51 @@ impl HttpClient {
self.get("/api/v1/content/overview", &params).await
}
+ /// Download file as raw bytes
+ pub async fn get_bytes(&self, uri: &str) -> Result<Vec<u8>> {
+ let url = format!("{}/api/v1/content/download", self.base_url);
+ let params = vec![("uri".to_string(), uri.to_string())];
+
+ let response = self
+ .http
+ .get(&url)
+ .headers(self.build_headers())
+ .query(&params)
+ .send()
+ .await
+ .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;
+
+ let status = response.status();
+ if !status.is_success() {
+ // Try to parse error message as JSON
+ let json_result: Result<serde_json::Value> = response
+ .json()
+ .await
+ .map_err(|e| Error::Network(format!("Failed to parse error response: {}", e)));
+
+ let error_msg = match json_result {
+ 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(_) => format!("HTTP error {}", status),
+ };
+
+ return Err(Error::Api(error_msg));
+ }
+
+ response
+ .bytes()
+ .await
+ .map(|b| b.to_vec())
+ .map_err(|e| Error::Network(format!("Failed to read response bytes: {}", e)))
+ }
+
// ============ Filesystem Methods ============
pub async fn ls(&self, uri: &str, simple: bool, recursive: bool, output: &str, abs_limit: i32, show_all_hidden: bool, node_limit: i32) -> Result<serde_json::Value> {
diff --git a/crates/ov_cli/src/commands/content.rs b/crates/ov_cli/src/commands/content.rs
index 7c51f6de9..c1673f102 100644
--- a/crates/ov_cli/src/commands/content.rs
+++ b/crates/ov_cli/src/commands/content.rs
@@ -1,6 +1,9 @@
use crate::client::HttpClient;
use crate::error::Result;
use crate::output::OutputFormat;
+use std::fs::File;
+use std::io::Write;
+use std::path::Path;
pub async fn read(
client: &HttpClient,
@@ -34,3 +37,33 @@ pub async fn overview(
println!("{}", content);
Ok(())
}
+
+pub async fn get(
+ client: &HttpClient,
+ uri: &str,
+ local_path: &str,
+) -> Result<()> {
+ // Check if target path already exists
+ let path = Path::new(local_path);
+ if path.exists() {
+ return Err(crate::error::Error::Client(
+ format!("File already exists: {}", local_path)
+ ));
+ }
+
+ // Ensure parent directory exists
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+
+ // Download file
+ let bytes = client.get_bytes(uri).await?;
+
+ // Write to local file
+ let mut file = File::create(path)?;
+ file.write_all(&bytes)?;
+ file.flush()?;
+
+ println!("Downloaded {} bytes to {}", bytes.len(), local_path);
+ Ok(())
+}
diff --git a/crates/ov_cli/src/commands/system.rs b/crates/ov_cli/src/commands/system.rs
index 6f4b74c5c..eae7b35d8 100644
--- a/crates/ov_cli/src/commands/system.rs
+++ b/crates/ov_cli/src/commands/system.rs
@@ -34,19 +34,29 @@ pub async fn health(
client: &HttpClient,
output_format: OutputFormat,
compact: bool,
-) -> Result<()> {
+) -> Result<bool> {
let response: serde_json::Value = client.get("/health", &[]).await?;
- // For health check, if it's a simple status, just print it
- if let Some(status) = response.get("status").and_then(|v| v.as_str()) {
- if matches!(output_format, OutputFormat::Json) {
- output_success(&response, output_format, compact);
- } else {
- println!("{}", status);
- }
- } else {
+ // Extract the key fields
+ let healthy = response.get("healthy").and_then(|v| v.as_bool()).unwrap_or(false);
+ let _status = response.get("status").and_then(|v| v.as_str());
+ let version = response.get("version").and_then(|v| v.as_str());
+ let user_id = response.get("user_id").and_then(|v| v.as_str());
+
+ // For table output, print in a readable format
+ if matches!(output_format, OutputFormat::Table) || matches!(output_format, OutputFormat::Json) {
output_success(&response, output_format, compact);
+ } else {
+ // Simple text output
+ print!("healthy {}", if healthy { "true" } else { "false" });
+ if let Some(v) = version {
+ print!(" version {}", v);
+ }
+ if let Some(u) = user_id {
+ print!(" user_id {}", u);
+ }
+ println!();
}
- Ok(())
+ Ok(healthy)
}
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index eb98c45ce..49ffdd32f 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -261,6 +261,13 @@ enum Commands {
/// Viking URI
uri: String,
},
+ /// Download file to local path (supports binaries/images)
+ Get {
+ /// Viking URI
+ uri: String,
+ /// Local path (must not exist yet)
+ local_path: String,
+ },
/// Run semantic retrieval
Find {
/// Search query
@@ -606,6 +613,7 @@ async fn main() {
Commands::Read { uri } => handle_read(uri, ctx).await,
Commands::Abstract { uri } => handle_abstract(uri, ctx).await,
Commands::Overview { uri } => handle_overview(uri, ctx).await,
+ Commands::Get { uri, local_path } => handle_get(uri, local_path, ctx).await,
Commands::Find { query, uri, node_limit, threshold } => {
handle_find(query, uri, node_limit, threshold, ctx).await
}
@@ -772,7 +780,9 @@ async fn handle_system(cmd: SystemCommands, ctx: CliContext) -> Result<()> {
commands::system::status(&client, ctx.output_format, ctx.compact).await
}
SystemCommands::Health => {
- commands::system::health(&client, ctx.output_format, ctx.compact).await
+ let _ =
+ commands::system::health(&client, ctx.output_format, ctx.compact).await?;
+ Ok(())
}
}
}
@@ -913,6 +923,11 @@ async fn handle_overview(uri: String, ctx: CliContext) -> Result<()> {
commands::content::overview(&client, &uri, ctx.output_format, ctx.compact).await
}
+async fn handle_get(uri: String, local_path: String, ctx: CliContext) -> Result<()> {
+ let client = ctx.get_client();
+ commands::content::get(&client, &uri, &local_path).await
+}
+
async fn handle_find(
query: String,
uri: String,
@@ -1028,12 +1043,10 @@ async fn handle_glob(pattern: String, uri: String, node_limit: i32, ctx: CliCont
async fn handle_health(ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
- let system_status: serde_json::Value = client.get("/api/v1/observer/system", &[]).await?;
- let is_healthy = system_status.get("is_healthy").and_then(|v| v.as_bool()).unwrap_or(false);
- output::output_success(&serde_json::json!({ "healthy": is_healthy }), ctx.output_format, ctx.compact);
- if !is_healthy {
- std::process::exit(1);
- }
+
+ // Reuse the system health command
+ let _ = commands::system::health(&client, ctx.output_format, ctx.compact).await?;
+
Ok(())
}
diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.py
index f73e4e2b4..e227d2cc1 100644
--- a/openviking/server/routers/content.py
+++ b/openviking/server/routers/content.py
@@ -2,7 +2,10 @@
# SPDX-License-Identifier: Apache-2.0
"""Content endpoints for OpenViking HTTP Server."""
+from urllib.parse import quote
+
from fastapi import APIRouter, Depends, Query
+from fastapi.responses import Response as FastAPIResponse
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
@@ -45,3 +48,28 @@ async def overview(
service = get_service()
result = await service.fs.overview(uri, ctx=_ctx)
return Response(status="ok", result=result)
+
+
[email protected]("/download")
+async def download(
+ uri: str = Query(..., description="Viking URI"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Download file as raw bytes (for images, binaries, etc.)."""
+ service = get_service()
+ content = await service.fs.read_file_bytes(uri, ctx=_ctx)
+
+ # Try to get filename from stat
+ filename = "download"
+ try:
+ stat = await service.fs.stat(uri, ctx=_ctx)
+ if stat and "name" in stat:
+ filename = stat["name"]
+ except Exception:
+ pass
+ filename = quote(filename)
+ return FastAPIResponse(
+ content=content,
+ media_type="application/octet-stream",
+ headers={"Content-Disposition": f"attachment; filename*=UTF-8''{filename}"},
+ )
diff --git a/openviking/server/routers/system.py b/openviking/server/routers/system.py
index 7dcea6915..b10ca5916 100644
--- a/openviking/server/routers/system.py
+++ b/openviking/server/routers/system.py
@@ -8,12 +8,12 @@ from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
-from openviking.server.auth import get_request_context
+from openviking.server.auth import get_request_context, resolve_identity
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext
from openviking.server.models import Response
from openviking.storage.viking_fs import get_viking_fs
-from openviking_cli.utils.logger import get_logger
+from openviking_cli.utils import get_logger
logger = get_logger(__name__)
@@ -21,9 +21,43 @@ router = APIRouter()
@router.get("/health", tags=["system"])
-async def health_check():
+async def health_check(request: Request):
"""Health check endpoint (no authentication required)."""
- return {"status": "ok"}
+ from openviking import __version__
+
+ result = {"status": "ok", "healthy": True, "version": __version__}
+
+ # Try to get user identity if auth headers are present
+ try:
+ # Extract headers manually
+ x_api_key = request.headers.get("X-API-Key")
+ authorization = request.headers.get("Authorization")
+ x_openviking_user = request.headers.get("X-OpenViking-User")
+
+ # Check if we have auth or in dev mode
+ api_key_manager = getattr(request.app.state, "api_key_manager", None)
+ if api_key_manager is None:
+ # Dev mode - use default user
+ result["user_id"] = x_openviking_user or "default"
+ elif x_api_key or authorization:
+ # Try to resolve identity
+ try:
+ identity = await resolve_identity(
+ request,
+ x_api_key=x_api_key,
+ authorization=authorization,
+ x_openviking_account=request.headers.get("X-OpenViking-Account"),
+ x_openviking_user=x_openviking_user,
+ x_openviking_agent=request.headers.get("X-OpenViking-Agent"),
+ )
+ if identity and identity.user_id:
+ result["user_id"] = identity.user_id
+ except Exception:
+ pass
+ except Exception:
+ pass
+
+ return result
@router.get("/ready", tags=["system"])
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 5807e8f10..066c43282 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -180,3 +180,8 @@ class FSService:
"""File pattern matching."""
viking_fs = self._ensure_initialized()
return await viking_fs.glob(pattern, uri=uri, node_limit=node_limit, ctx=ctx)
+
+ async def read_file_bytes(self, uri: str, ctx: RequestContext) -> bytes:
+ """Read file as raw bytes."""
+ viking_fs = self._ensure_initialized()
+ return await viking_fs.read_file_bytes(uri, ctx=ctx)