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: add Rust CLI implementation [very fast] (#162)
Zayn Jarvis44032c93f705
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 4049f53d0..7f20c045c 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -43,6 +43,8 @@ permissions:jobs:build:+ # Skip this workflow for CLI releases (tags starting with cli-)+ if: "!startsWith(github.event.release.tag_name, 'cli-')"uses: ./.github/workflows/_build.ymlwith:os_json: ${{ inputs.os_json || '["ubuntu-latest", "macos-latest", "macos-15-intel", "windows-latest"]' }}diff --git a/.github/workflows/rust-cli.yml b/.github/workflows/rust-cli.ymlnew file mode 100644index 000000000..800f6b245--- /dev/null+++ b/.github/workflows/rust-cli.yml@@ -0,0 +1,193 @@+name: Rust CLI Build++on:+ workflow_call:+ push:+ branches: [ main, feat/rust-cli ]+ paths:+ - 'crates/**'+ - 'Cargo.toml'+ - '.github/workflows/rust-cli.yml'+ tags:+ - 'cli-*' # Trigger release on tags starting with cli-+ pull_request:+ branches: [ main ]+ paths:+ - 'crates/**'+ - 'Cargo.toml'+ - '.github/workflows/rust-cli.yml'++jobs:+ build:+ name: Build ${{ matrix.target }}+ runs-on: ${{ matrix.os }}+ strategy:+ fail-fast: false+ matrix:+ include:+ - os: ubuntu-latest+ target: x86_64-unknown-linux-gnu+ artifact_name: ov-linux-x86_64+ - os: ubuntu-latest+ target: aarch64-unknown-linux-gnu+ artifact_name: ov-linux-aarch64+ - os: macos-latest+ target: x86_64-apple-darwin+ artifact_name: ov-macos-x86_64+ - os: macos-latest+ target: aarch64-apple-darwin+ artifact_name: ov-macos-aarch64+ - os: windows-latest+ target: x86_64-pc-windows-msvc+ artifact_name: ov-windows-x86_64.exe++ steps:+ - uses: actions/checkout@v4++ - name: Install Rust+ uses: dtolnay/rust-toolchain@v1+ with:+ toolchain: stable+ targets: ${{ matrix.target }}++ - name: Install system dependencies (Linux)+ if: runner.os == 'Linux'+ run: |+ sudo apt-get update+ sudo apt-get install -y pkg-config libssl-dev++ - name: Install cross-compilation tools (Linux ARM64)+ if: matrix.target == 'aarch64-unknown-linux-gnu'+ run: |+ sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu+ echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> $GITHUB_ENV+ echo "CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc" >> $GITHUB_ENV+ echo "CXX_aarch64_unknown_linux_gnu=aarch64-linux-gnu-g++" >> $GITHUB_ENV++ - name: Cache Cargo registry and index+ uses: actions/cache@v4+ with:+ path: |+ ~/.cargo/registry/index+ ~/.cargo/registry/cache+ ~/.cargo/git/db+ key: ${{ runner.os }}-cargo-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}+ restore-keys: |+ ${{ runner.os }}-cargo-${{ matrix.target }}-+ ${{ runner.os }}-cargo-++ - name: Cache build artifacts+ uses: actions/cache@v4+ with:+ path: target+ key: ${{ runner.os }}-target-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}-${{ hashFiles('crates/**/*.rs') }}+ restore-keys: |+ ${{ runner.os }}-target-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}-+ ${{ runner.os }}-target-${{ matrix.target }}-++ - name: Build CLI+ run: cargo build --release --target ${{ matrix.target }} -p openviking-cli++ - name: Create compressed artifacts+ shell: bash+ run: |+ mkdir -p artifacts+ cd target/${{ matrix.target }}/release++ if [[ "${{ matrix.os }}" == "windows-latest" ]]; then+ # Windows: create zip+ 7z a ../../../artifacts/${{ matrix.artifact_name }}.zip ov.exe+ cd ../../../artifacts+ # Use PowerShell to get hash in correct format+ powershell -Command "(Get-FileHash -Algorithm SHA256 '${{ matrix.artifact_name }}.zip').Hash.ToLower() + ' ${{ matrix.artifact_name }}.zip'" > ${{ matrix.artifact_name }}.zip.sha256+ else+ # Unix: create tar.gz+ tar czf ../../../artifacts/${{ matrix.artifact_name }}.tar.gz ov+ cd ../../../artifacts+ # shasum format: <hash> <filename>+ shasum -a 256 ${{ matrix.artifact_name }}.tar.gz > ${{ matrix.artifact_name }}.tar.gz.sha256+ fi++ - name: Verify checksum format+ shell: bash+ run: |+ echo "Contents of checksum file:"+ cat artifacts/*.sha256+ echo ""+ echo "Verifying checksum locally:"+ cd artifacts+ if [[ "${{ matrix.os }}" == "windows-latest" ]]; then+ sha256sum -c *.sha256 || shasum -a 256 -c *.sha256 || echo "Checksum verification skipped on Windows"+ else+ shasum -a 256 -c *.sha256+ fi++ - name: Upload artifacts+ uses: actions/upload-artifact@v4+ with:+ name: ${{ matrix.artifact_name }}+ path: artifacts/*++ release:+ name: Create GitHub Release+ runs-on: ubuntu-latest+ needs: build+ if: startsWith(github.ref, 'refs/tags/cli-')+ permissions:+ contents: write+ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Get version from tag+ id: get_version+ run: echo "version=${GITHUB_REF#refs/tags/cli-}" >> $GITHUB_OUTPUT++ - name: Download all artifacts+ uses: actions/download-artifact@v4+ with:+ path: artifacts++ - name: Display artifact structure+ run: ls -R artifacts/++ - name: Create GitHub Release+ uses: softprops/action-gh-release@v2+ with:+ name: CLI v${{ steps.get_version.outputs.version }}+ body: |+ # OpenViking CLI v${{ steps.get_version.outputs.version }}++ ## Installation++ ### Quick Install (macOS/Linux)+ ```bash+ curl -fsSL https://raw.githubusercontent.com/${{ github.repository }}/refs/tags/cli-${{ steps.get_version.outputs.version }}/crates/openviking-cli/install.sh | bash+ ```++ ### Manual Installation+ Download the appropriate binary for your platform below, extract it, and add it to your PATH.++ The CLI command is simply `ov`:+ ```bash+ # After extraction+ chmod +x ov # Unix only+ mv ov /usr/local/bin/ # or any directory in your PATH++ # Verify installation+ ov --version+ ```++ ### Checksums+ SHA256 checksums are provided for each binary for verification.++ ## Changes+ See the [commit history](https://github.com/${{ github.repository }}/commits/cli-${{ steps.get_version.outputs.version }}) for details.+ files: |+ artifacts/**/*.tar.gz+ artifacts/**/*.zip+ artifacts/**/*.sha256+ draft: false+ prerelease: ${{ contains(steps.get_version.outputs.version, 'alpha') || contains(steps.get_version.outputs.version, 'beta') || contains(steps.get_version.outputs.version, 'rc') }}+ env:+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\ No newline at end of filediff --git a/.gitignore b/.gitignoreindex e628f0f12..21f50bfa0 100644--- a/.gitignore+++ b/.gitignore@@ -26,6 +26,12 @@ MANIFESTopenviking.egg-info/data/+# Rust+Cargo.lock+target/+**/*.rs.bk+*.pdb+# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.diff --git a/Cargo.toml b/Cargo.tomlnew file mode 100644index 000000000..a08b6a5f5--- /dev/null+++ b/Cargo.toml@@ -0,0 +1,8 @@+[workspace]+members = ["crates/openviking-cli"]+resolver = "2"++[profile.release]+opt-level = 3+lto = true+strip = truediff --git a/README.md b/README.mdindex 8680b324c..161650eab 100644--- a/README.md+++ b/README.md@@ -65,6 +65,8 @@ Before starting with OpenViking, please ensure your environment meets the follow### 1. Installation+#### Python Package+```bashpip install openviking```diff --git a/crates/openviking-cli/Cargo.toml b/crates/openviking-cli/Cargo.tomlnew file mode 100644index 000000000..547aff5ae--- /dev/null+++ b/crates/openviking-cli/Cargo.toml@@ -0,0 +1,24 @@+[package]+name = "openviking-cli"+version = "0.1.0"+edition = "2021"+authors = ["OpenViking Contributors"]+description = "CLI client for OpenViking"+license = "MIT"++[[bin]]+name = "ov"+path = "src/main.rs"++[dependencies]+clap = { version = "4.5", features = ["derive", "env"] }+reqwest = { version = "0.12", features = ["json", "multipart", "rustls-tls"], default-features = false }+serde = { version = "1.0", features = ["derive"] }+serde_json = { version = "1.0", features = ["preserve_order"] }+tokio = { version = "1.38", features = ["full"] }+colored = "2.1"+dirs = "5.0"+anyhow = "1.0"+mime_guess = "2.0"+thiserror = "1.0"+unicode-width = "0.1"diff --git a/crates/openviking-cli/install.sh b/crates/openviking-cli/install.shnew file mode 100755index 000000000..539502a5b--- /dev/null+++ b/crates/openviking-cli/install.sh@@ -0,0 +1,177 @@+#!/bin/bash+set -e++# OpenViking CLI Installer+# Usage: curl -fsSL https://raw.githubusercontent.com/<OWNER>/<REPO>/refs/tags/<TAG>/crates/openviking-cli/install.sh | bash+# Example: curl -fsSL https://raw.githubusercontent.com/volcengine/openviking/refs/tags/cli-0.1.0/crates/openviking-cli/install.sh | bash+# Skip checksum: curl -fsSL ... | SKIP_CHECKSUM=1 bash+# Custom repo: REPO=owner/repo curl -fsSL ... | bash++REPO="${REPO:-volcengine/openviking}"+BINARY_NAME="ov"+INSTALL_DIR="/usr/local/bin"+SKIP_CHECKSUM="${SKIP_CHECKSUM:-0}"++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+NC='\033[0m' # No Color++info() { echo -e "${GREEN}[INFO]${NC} $1"; }+warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }+error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }++# Detect platform and architecture+detect_platform() {+ case "$(uname -s)" in+ Linux*)+ OS="linux"+ ;;+ Darwin*)+ OS="macos"+ ;;+ CYGWIN*|MINGW*|MSYS*)+ OS="windows"+ ;;+ *)+ error "Unsupported operating system: $(uname -s)"+ ;;+ esac++ case "$(uname -m)" in+ x86_64|amd64)+ ARCH="x86_64"+ ;;+ arm64|aarch64)+ ARCH="aarch64"+ ;;+ *)+ error "Unsupported architecture: $(uname -m)"+ ;;+ esac++ ARTIFACT_NAME="${BINARY_NAME}-${OS}-${ARCH}"+ if [[ "$OS" == "windows" ]]; then+ ARTIFACT_NAME="${ARTIFACT_NAME}.exe"+ ARCHIVE_EXT="zip"+ else+ ARCHIVE_EXT="tar.gz"+ fi+}++# Get latest release info+get_latest_release() {+ info "Getting latest release information..."+ LATEST_RELEASE=$(curl -s "https://api.github.com/repos/${REPO}/releases/latest")+ TAG_NAME=$(echo "$LATEST_RELEASE" | grep '"tag_name"' | sed -E 's/.*"tag_name": "([^"]+)".*/\1/')++ if [[ -z "$TAG_NAME" ]]; then+ error "Could not determine latest release version"+ fi++ info "Latest version: $TAG_NAME"+ DOWNLOAD_URL="https://github.com/${REPO}/releases/download/${TAG_NAME}/${ARTIFACT_NAME}.${ARCHIVE_EXT}"+ CHECKSUM_URL="https://github.com/${REPO}/releases/download/${TAG_NAME}/${ARTIFACT_NAME}.${ARCHIVE_EXT}.sha256"+}++# Download and extract binary+download_binary() {+ info "Downloading ${ARTIFACT_NAME}.${ARCHIVE_EXT}..."+ TEMP_DIR=$(mktemp -d)+ ARCHIVE_FILE="$TEMP_DIR/${ARTIFACT_NAME}.${ARCHIVE_EXT}"+ CHECKSUM_FILE="$TEMP_DIR/${ARTIFACT_NAME}.${ARCHIVE_EXT}.sha256"++ # Download archive+ if ! curl -sSL -o "$ARCHIVE_FILE" "$DOWNLOAD_URL"; then+ error "Failed to download from $DOWNLOAD_URL"+ fi++ # Download and verify checksum+ if [[ "$SKIP_CHECKSUM" == "1" ]]; then+ warn "Skipping checksum verification (SKIP_CHECKSUM=1)"+ elif ! curl -sSL -o "$CHECKSUM_FILE" "$CHECKSUM_URL"; then+ warn "Could not download checksum file, skipping verification"+ elif grep -q "Not Found" "$CHECKSUM_FILE" 2>/dev/null; then+ warn "Checksum file not available in release, skipping verification"+ else+ info "Verifying checksum..."+ if command -v sha256sum >/dev/null; then+ (cd "$TEMP_DIR" && sha256sum -c "${ARTIFACT_NAME}.${ARCHIVE_EXT}.sha256") || error "Checksum verification failed"+ elif command -v shasum >/dev/null; then+ (cd "$TEMP_DIR" && shasum -a 256 -c "${ARTIFACT_NAME}.${ARCHIVE_EXT}.sha256") || error "Checksum verification failed"+ else+ warn "No checksum utility found, skipping verification"+ fi+ fi++ # Extract archive+ info "Extracting archive..."+ if [[ "$ARCHIVE_EXT" == "tar.gz" ]]; then+ tar -xzf "$ARCHIVE_FILE" -C "$TEMP_DIR" || error "Failed to extract archive"+ elif [[ "$ARCHIVE_EXT" == "zip" ]]; then+ unzip -q "$ARCHIVE_FILE" -d "$TEMP_DIR" || error "Failed to extract archive"+ fi++ TEMP_FILE="$TEMP_DIR/$BINARY_NAME"+ if [[ "$OS" == "windows" ]]; then+ TEMP_FILE="${TEMP_FILE}.exe"+ fi++ if [[ ! -f "$TEMP_FILE" ]]; then+ error "Binary not found after extraction: $TEMP_FILE"+ fi++ info "Download and extraction successful"+}++# Install binary+install_binary() {+ info "Installing to $INSTALL_DIR/$BINARY_NAME..."++ # Check if install directory exists and is writable+ if [[ ! -d "$INSTALL_DIR" ]]; then+ error "Install directory $INSTALL_DIR does not exist"+ fi++ # Try to install+ if [[ -w "$INSTALL_DIR" ]]; then+ cp "$TEMP_FILE" "$INSTALL_DIR/$BINARY_NAME"+ else+ info "Requesting sudo privileges for installation..."+ sudo cp "$TEMP_FILE" "$INSTALL_DIR/$BINARY_NAME"+ sudo chmod +x "$INSTALL_DIR/$BINARY_NAME"+ fi++ # Make executable+ chmod +x "$INSTALL_DIR/$BINARY_NAME" 2>/dev/null || sudo chmod +x "$INSTALL_DIR/$BINARY_NAME"++ # Cleanup+ rm -rf "$TEMP_DIR"+}++# Verify installation+verify_installation() {+ info "Verifying installation..."+ if command -v "$BINARY_NAME" >/dev/null; then+ VERSION=$($BINARY_NAME --version)+ info "Successfully installed: $VERSION"+ info "Run '$BINARY_NAME --help' to get started"+ else+ error "Installation failed - $BINARY_NAME not found in PATH"+ fi+}++main() {+ info "OpenViking CLI Installer"+ detect_platform+ info "Detected platform: $OS ($ARCH)"+ get_latest_release+ download_binary+ install_binary+ verify_installation+ info "Installation complete! 🎉"+}++# Run main function+main "$@"\ No newline at end of filediff --git a/crates/openviking-cli/src/client.rs b/crates/openviking-cli/src/client.rsnew file mode 100644index 000000000..53dc3b7be--- /dev/null+++ b/crates/openviking-cli/src/client.rs@@ -0,0 +1,380 @@+use reqwest::{Client as ReqwestClient, StatusCode};+use serde::de::DeserializeOwned;+use serde_json::Value;++use crate::error::{Error, Result};++/// High-level HTTP client for OpenViking API+#[derive(Clone)]+pub struct HttpClient {+ http: ReqwestClient,+ base_url: String,+ api_key: Option<String>,+}++impl HttpClient {+ /// Create a new HTTP client+ pub fn new(base_url: impl Into<String>, api_key: Option<String>) -> Self {+ let http = ReqwestClient::builder()+ .timeout(std::time::Duration::from_secs(60))+ .build()+ .expect("Failed to build HTTP client");++ Self {+ http,+ base_url: base_url.into().trim_end_matches('/').to_string(),+ api_key,+ }+ }++ fn build_headers(&self) -> reqwest::header::HeaderMap {+ let mut headers = reqwest::header::HeaderMap::new();+ headers.insert(+ reqwest::header::CONTENT_TYPE,+ reqwest::header::HeaderValue::from_static("application/json"),+ );+ if let Some(api_key) = &self.api_key {+ if let Ok(value) = reqwest::header::HeaderValue::from_str(api_key) {+ headers.insert("X-API-Key", value);+ }+ }+ headers+ }++ /// Make a GET request+ pub async fn get<T: DeserializeOwned>(+ &self,+ path: &str,+ params: &[(String, String)],+ ) -> Result<T> {+ let url = format!("{}{}", self.base_url, path);+ let response = self+ .http+ .get(&url)+ .headers(self.build_headers())+ .query(params)+ .send()+ .await+ .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;++ self.handle_response(response).await+ }++ /// Make a POST request+ pub async fn post<B: serde::Serialize, T: DeserializeOwned>(+ &self,+ path: &str,+ body: &B,+ ) -> Result<T> {+ let url = format!("{}{}", self.base_url, path);+ let response = self+ .http+ .post(&url)+ .headers(self.build_headers())+ .json(body)+ .send()+ .await+ .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;++ self.handle_response(response).await+ }++ /// Make a DELETE request+ pub async fn delete<T: DeserializeOwned>(+ &self,+ path: &str,+ params: &[(String, String)],+ ) -> Result<T> {+ let url = format!("{}{}", self.base_url, path);+ let response = self+ .http+ .delete(&url)+ .headers(self.build_headers())+ .query(params)+ .send()+ .await+ .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;++ self.handle_response(response).await+ }++ /// Make a DELETE request with a JSON body+ pub async fn delete_with_body<B: serde::Serialize, T: DeserializeOwned>(+ &self,+ path: &str,+ body: &B,+ ) -> Result<T> {+ let url = format!("{}{}", self.base_url, path);+ let response = self+ .http+ .delete(&url)+ .headers(self.build_headers())+ .json(body)+ .send()+ .await+ .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;++ self.handle_response(response).await+ }++ async fn handle_response<T: DeserializeOwned>(+ &self,+ response: reqwest::Response,+ ) -> Result<T> {+ let status = response.status();++ // Handle empty response (204 No Content, etc.)+ if status == StatusCode::NO_CONTENT || status == StatusCode::ACCEPTED {+ return serde_json::from_value(Value::Null)+ .map_err(|e| Error::Parse(format!("Failed to parse empty response: {}", e)));+ }++ let json: Value = response+ .json()+ .await+ .map_err(|e| Error::Network(format!("Failed to parse JSON response: {}", e)))?;++ // Handle HTTP errors+ if !status.is_success() {+ let error_msg = 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));+ return Err(Error::Api(error_msg));+ }++ // Handle API errors (status == success but body has error)+ 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(format!("[{}] {}", code, message)));+ }+ }++ // Extract result from wrapped response or use the whole response+ let result = if let Some(result) = json.get("result") {+ result.clone()+ } else {+ json+ };++ serde_json::from_value(result)+ .map_err(|e| Error::Parse(format!("Failed to deserialize response: {}", e)))+ }++ // ============ Content Methods ============++ pub async fn read(&self, uri: &str) -> Result<String> {+ let params = vec![("uri".to_string(), uri.to_string())];+ self.get("/api/v1/content/read", ¶ms).await+ }++ pub async fn abstract_content(&self, uri: &str) -> Result<String> {+ let params = vec![("uri".to_string(), uri.to_string())];+ self.get("/api/v1/content/abstract", ¶ms).await+ }++ pub async fn overview(&self, uri: &str) -> Result<String> {+ let params = vec![("uri".to_string(), uri.to_string())];+ self.get("/api/v1/content/overview", ¶ms).await+ }++ // ============ Filesystem Methods ============++ pub async fn ls(&self, uri: &str, simple: bool, recursive: bool) -> Result<serde_json::Value> {+ let params = vec![+ ("uri".to_string(), uri.to_string()),+ ("simple".to_string(), simple.to_string()),+ ("recursive".to_string(), recursive.to_string()),+ ];+ self.get("/api/v1/fs/ls", ¶ms).await+ }++ pub async fn tree(&self, uri: &str) -> Result<serde_json::Value> {+ let params = vec![("uri".to_string(), uri.to_string())];+ self.get("/api/v1/fs/tree", ¶ms).await+ }++ pub async fn mkdir(&self, uri: &str) -> Result<()> {+ let body = serde_json::json!({ "uri": uri });+ let _: serde_json::Value = self.post("/api/v1/fs/mkdir", &body).await?;+ Ok(())+ }++ pub async fn rm(&self, uri: &str, recursive: bool) -> Result<()> {+ let params = vec![+ ("uri".to_string(), uri.to_string()),+ ("recursive".to_string(), recursive.to_string()),+ ];+ let _: serde_json::Value = self.delete("/api/v1/fs", ¶ms).await?;+ Ok(())+ }++ pub async fn mv(&self, from_uri: &str, to_uri: &str) -> Result<()> {+ let body = serde_json::json!({+ "from_uri": from_uri,+ "to_uri": to_uri,+ });+ let _: serde_json::Value = self.post("/api/v1/fs/mv", &body).await?;+ Ok(())+ }++ pub async fn stat(&self, uri: &str) -> Result<serde_json::Value> {+ let params = vec![("uri".to_string(), uri.to_string())];+ self.get("/api/v1/fs/stat", ¶ms).await+ }++ // ============ Search Methods ============++ pub async fn find(+ &self,+ query: String,+ uri: String,+ limit: i32,+ threshold: Option<f64>,+ ) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "query": query,+ "target_uri": uri,+ "limit": limit,+ "score_threshold": threshold,+ });+ self.post("/api/v1/search/find", &body).await+ }++ pub async fn search(+ &self,+ query: String,+ uri: String,+ session_id: Option<String>,+ limit: i32,+ threshold: Option<f64>,+ ) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "query": query,+ "target_uri": uri,+ "session_id": session_id,+ "limit": limit,+ "score_threshold": threshold,+ });+ self.post("/api/v1/search/search", &body).await+ }++ pub async fn grep(&self, uri: &str, pattern: &str, ignore_case: bool) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "uri": uri,+ "pattern": pattern,+ "case_insensitive": ignore_case,+ });+ self.post("/api/v1/search/grep", &body).await+ }++ pub async fn glob(&self, pattern: &str, uri: &str) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "pattern": pattern,+ "uri": uri,+ });+ self.post("/api/v1/search/glob", &body).await+ }++ // ============ Resource Methods ============++ pub async fn add_resource(+ &self,+ path: &str,+ target: Option<String>,+ reason: &str,+ instruction: &str,+ wait: bool,+ timeout: Option<f64>,+ ) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "path": path,+ "target": target,+ "reason": reason,+ "instruction": instruction,+ "wait": wait,+ "timeout": timeout,+ });+ self.post("/api/v1/resources", &body).await+ }++ pub async fn add_skill(+ &self,+ data: &str,+ wait: bool,+ timeout: Option<f64>,+ ) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "data": data,+ "wait": wait,+ "timeout": timeout,+ });+ self.post("/api/v1/skills", &body).await+ }++ // ============ Relation Methods ============++ pub async fn relations(&self, uri: &str) -> Result<serde_json::Value> {+ let params = vec![("uri".to_string(), uri.to_string())];+ self.get("/api/v1/relations", ¶ms).await+ }++ pub async fn link(+ &self,+ from_uri: &str,+ to_uris: &[String],+ reason: &str,+ ) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "from_uri": from_uri,+ "to_uris": to_uris,+ "reason": reason,+ });+ self.post("/api/v1/relations/link", &body).await+ }++ pub async fn unlink(&self, from_uri: &str, to_uri: &str) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "from_uri": from_uri,+ "to_uri": to_uri,+ });+ self.delete_with_body("/api/v1/relations/link", &body).await+ }++ // ============ Pack Methods ============++ pub async fn export_ovpack(&self, uri: &str, to: &str) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "uri": uri,+ "to": to,+ });+ self.post("/api/v1/pack/export", &body).await+ }++ pub async fn import_ovpack(+ &self,+ file_path: &str,+ parent: &str,+ force: bool,+ vectorize: bool,+ ) -> Result<serde_json::Value> {+ let body = serde_json::json!({+ "file_path": file_path,+ "parent": parent,+ "force": force,+ "vectorize": vectorize,+ });+ self.post("/api/v1/pack/import", &body).await+ }+}diff --git a/crates/openviking-cli/src/commands/content.rs b/crates/openviking-cli/src/commands/content.rsnew file mode 100644index 000000000..f275efaea--- /dev/null+++ b/crates/openviking-cli/src/commands/content.rs@@ -0,0 +1,33 @@+use crate::client::HttpClient;+use crate::error::Result;+use crate::output::OutputFormat;++pub async fn read(+ client: &HttpClient,+ uri: &str,+ _output_format: OutputFormat,+) -> Result<()> {+ let content = client.read(uri).await?;+ println!("{}", content);+ Ok(())+}++pub async fn abstract_content(+ client: &HttpClient,+ uri: &str,+ _output_format: OutputFormat,+) -> Result<()> {+ let content = client.abstract_content(uri).await?;+ println!("{}", content);+ Ok(())+}++pub async fn overview(+ client: &HttpClient,+ uri: &str,+ _output_format: OutputFormat,+) -> Result<()> {+ let content = client.overview(uri).await?;+ println!("{}", content);+ Ok(())+}diff --git a/crates/openviking-cli/src/commands/filesystem.rs b/crates/openviking-cli/src/commands/filesystem.rsnew file mode 100644index 000000000..05a769cb9--- /dev/null+++ b/crates/openviking-cli/src/commands/filesystem.rs@@ -0,0 +1,67 @@+use crate::client::HttpClient;+use crate::error::Result;+use crate::output::{output_success, OutputFormat};++pub async fn ls(+ client: &HttpClient,+ uri: &str,+ simple: bool,+ recursive: bool,+ output_format: OutputFormat,+) -> Result<()> {+ let result = client.ls(uri, simple, recursive).await?;+ output_success(&result, output_format, false);+ Ok(())+}++pub async fn tree(+ client: &HttpClient,+ uri: &str,+ output_format: OutputFormat,+) -> Result<()> {+ let result = client.tree(uri).await?;+ output_success(&result, output_format, false);+ Ok(())+}++pub async fn mkdir(+ client: &HttpClient,+ uri: &str,+ _output_format: OutputFormat,+) -> Result<()> {+ client.mkdir(uri).await?;+ println!("Directory created: {}", uri);+ Ok(())+}++pub async fn rm(+ client: &HttpClient,+ uri: &str,+ recursive: bool,+ _output_format: OutputFormat,+) -> Result<()> {+ client.rm(uri, recursive).await?;+ println!("Removed: {}", uri);+ Ok(())+}++pub async fn mv(+ client: &HttpClient,+ from_uri: &str,+ to_uri: &str,+ _output_format: OutputFormat,+) -> Result<()> {+ client.mv(from_uri, to_uri).await?;+ println!("Moved: {} -> {}", from_uri, to_uri);+ Ok(())+}++pub async fn stat(+ client: &HttpClient,+ uri: &str,+ output_format: OutputFormat,+) -> Result<()> {+ let result = client.stat(uri).await?;+ output_success(&result, output_format, false);+ Ok(())+}diff --git a/crates/openviking-cli/src/commands/mod.rs b/crates/openviking-cli/src/commands/mod.rsnew file mode 100644index 000000000..9979b34a2--- /dev/null+++ b/crates/openviking-cli/src/commands/mod.rs@@ -0,0 +1,9 @@+pub mod content;+pub mod search;+pub mod filesystem;+pub mod observer;+pub mod session;+pub mod system;+pub mod resources;+pub mod relations;+pub mod pack;diff --git a/crates/openviking-cli/src/commands/observer.rs b/crates/openviking-cli/src/commands/observer.rsnew file mode 100644index 000000000..2863b5090--- /dev/null+++ b/crates/openviking-cli/src/commands/observer.rs@@ -0,0 +1,39 @@+use crate::client::HttpClient;+use crate::error::Result;+use crate::output::{output_success, OutputFormat};++pub async fn queue(+ client: &HttpClient,+ output_format: OutputFormat,+) -> Result<()> {+ let response: serde_json::Value = client.get("/api/v1/observer/queue", &[]).await?;+ output_success(&response, output_format, false);+ Ok(())+}++pub async fn vikingdb(+ client: &HttpClient,+ output_format: OutputFormat,+) -> Result<()> {+ let response: serde_json::Value = client.get("/api/v1/observer/vikingdb", &[]).await?;+ output_success(&response, output_format, false);+ Ok(())+}++pub async fn vlm(+ client: &HttpClient,+ output_format: OutputFormat,+) -> Result<()> {+ let response: serde_json::Value = client.get("/api/v1/observer/vlm", &[]).await?;+ output_success(&response, output_format, false);+ Ok(())+}++pub async fn system(+ client: &HttpClient,+ output_format: OutputFormat,+) -> Result<()> {+ let response: serde_json::Value = client.get("/api/v1/observer/system", &[]).await?;+ output_success(&response, output_format, false);+ Ok(())+}diff --git a/crates/openviking-cli/src/commands/pack.rs b/crates/openviking-cli/src/commands/pack.rsnew file mode 100644index 000000000..68db4c27a--- /dev/null+++ b/crates/openviking-cli/src/commands/pack.rs@@ -0,0 +1,30 @@+use crate::client::HttpClient;+use crate::error::Result;+use crate::output::{output_success, OutputFormat};++pub async fn export(+ client: &HttpClient,+ uri: &str,+ to: &str,+ format: OutputFormat,+) -> Result<()> {+ let result = client.export_ovpack(uri, to).await?;+ output_success(&result, format, false);+ Ok(())+}++pub async fn import(+ client: &HttpClient,+ file_path: &str,+ target: &str,+ force: bool,+ no_vectorize: bool,+ format: OutputFormat,+) -> Result<()> {+ let vectorize = !no_vectorize;+ let result = client+ .import_ovpack(file_path, target, force, vectorize)+ .await?;+ output_success(&result, format, false);+ Ok(())+}diff --git a/crates/openviking-cli/src/commands/relations.rs b/crates/openviking-cli/src/commands/relations.rsnew file mode 100644index 000000000..c988d1675--- /dev/null+++ b/crates/openviking-cli/src/commands/relations.rs@@ -0,0 +1,54 @@+use crate::client::HttpClient;+use crate::error::Result;+use crate::output::{output_success, OutputFormat};++pub async fn list_relations(+ client: &HttpClient,+ uri: &str,+ format: OutputFormat,+) -> Result<()> {+ let result = client.relations(uri).await?;+ output_success(&result, format, false);+ Ok(())+}++pub async fn link(+ client: &HttpClient,+ from_uri: &str,+ to_uris: &Vec<String>,+ reason: &str,+ format: OutputFormat,+) -> Result<()> {+ let result = client.link(from_uri, to_uris, reason).await?;+ // If the server returns null/empty, show a confirmation summary+ if result.is_null() {+ let summary = serde_json::json!({+ "from": from_uri,+ "to": to_uris,+ "reason": reason,+ });+ output_success(&summary, format, false);+ } else {+ output_success(&result, format, false);+ }+ Ok(())+}++pub async fn unlink(+ client: &HttpClient,+ from_uri: &str,+ to_uri: &str,+ format: OutputFormat,+) -> Result<()> {+ let result = client.unlink(from_uri, to_uri).await?;+ if result.is_null() {+ let summary = serde_json::json!({+ "from": from_uri,+ "to": to_uri,+ });+ output_success(&summary, format, false);+ } else {+ output_success(&result, format, false);+ }+ Ok(())+}diff --git a/crates/openviking-cli/src/commands/resources.rs b/crates/openviking-cli/src/commands/resources.rsnew file mode 100644index 000000000..221b4fcd5--- /dev/null+++ b/crates/openviking-cli/src/commands/resources.rs@@ -0,0 +1,32 @@+use crate::client::HttpClient;+use crate::error::Result;+use crate::output::{output_success, OutputFormat};++pub async fn add_resource(+ client: &HttpClient,+ path: &str,+ to: Option<String>,+ reason: String,+ instruction: String,+ wait: bool,+ timeout: Option<f64>,+ format: OutputFormat,+) -> Result<()> {+ let result = client+ .add_resource(path, to, &reason, &instruction, wait, timeout)+ .await?;+ output_success(&result, format, false);+ Ok(())+}++pub async fn add_skill(+ client: &HttpClient,+ data: &str,+ wait: bool,+ timeout: Option<f64>,+ format: OutputFormat,+) -> Result<()> {+ let result = client.add_skill(data, wait, timeout).await?;+ output_success(&result, format, false);+ Ok(())+}diff --git a/crates/openviking-cli/src/commands/search.rs b/crates/openviking-cli/src/commands/search.rsnew file mode 100644index 000000000..218265268--- /dev/null+++ b/crates/openviking-cli/src/commands/search.rs@@ -0,0 +1,53 @@+use crate::client::HttpClient;+use crate::error::Result;+use crate::output::{output_success, OutputFormat};++pub async fn find(+ client: &HttpClient,+ query: &str,+ uri: &str,+ limit: i32,+ threshold: Option<f64>,+ output_format: OutputFormat,+) -> Result<()> {+ let result = client.find(query.to_string(), uri.to_string(), limit, threshold).await?;+ output_success(&result, output_format, false);+ Ok(())+}++pub async fn search(+ client: &HttpClient,+ query: &str,+ uri: &str,+ session_id: Option<String>,+ limit: i32,+ threshold: Option<f64>,+ output_format: OutputFormat,+) -> Result<()> {+ let result = client.search(query.to_string(), uri.to_string(), session_id, limit, threshold).await?;+ output_success(&result, output_format, false);+ Ok(())+}++pub async fn grep(+ client: &HttpClient,+ uri: &str,+ pattern: &str,+ ignore_case: bool,+ output_format: OutputFormat,+) -> Result<()> {+ let result = client.grep(uri, pattern, ignore_case).await?;+ output_success(&result, output_format, false);+ Ok(())+}++pub async fn glob(+ client: &HttpClient,+ pattern: &str,+ uri: &str,+ output_format: OutputFormat,+) -> Result<()> {+ let result = client.glob(pattern, uri).await?;+ output_success(&result, output_format, false);+ Ok(())+}diff --git a/crates/openviking-cli/src/commands/session.rs b/crates/openviking-cli/src/commands/session.rsnew file mode 100644index 000000000..617e1829d--- /dev/null+++ b/crates/openviking-cli/src/commands/session.rs@@ -0,0 +1,88 @@+use crate::client::HttpClient;+use crate::error::Result;+use crate::output::{output_success, OutputFormat};+use serde_json::json;++pub async fn new_session(+ client: &HttpClient,+ output_format: OutputFormat,+) -> Result<()> {+ let response: serde_json::Value = client.post("/api/v1/sessions", &json!({})).await?;+ output_success(&response, output_format, false);+ Ok(())+}++pub async fn list_sessions(+ client: &HttpClient,+ output_format: OutputFormat,+) -> Result<()> {+ let response: serde_json::Value = client.get("/api/v1/sessions", &[]).await?;+ output_success(&response, output_format, false);+ Ok(())+}++pub async fn get_session(+ client: &HttpClient,+ session_id: &str,+ output_format: OutputFormat,+) -> Result<()> {+ let path = format!("/api/v1/sessions/{}", url_encode(session_id));+ let response: serde_json::Value = client.get(&path, &[]).await?;+ output_success(&response, output_format, false);+ Ok(())+}++pub async fn delete_session(+ client: &HttpClient,+ session_id: &str,+ output_format: OutputFormat,+) -> Result<()> {+ let path = format!("/api/v1/sessions/{}", url_encode(session_id));+ let response: serde_json::Value = client.delete(&path, &[]).await?;++ // Return session_id in result if empty (similar to Python implementation)+ let result = if response.is_null() || response.as_object().map(|o| o.is_empty()).unwrap_or(false) {+ json!({"session_id": session_id})+ } else {+ response+ };++ output_success(&result, output_format, false);+ Ok(())+}++pub async fn add_message(+ client: &HttpClient,+ session_id: &str,+ role: &str,+ content: &str,+ output_format: OutputFormat,+) -> Result<()> {+ let path = format!("/api/v1/sessions/{}/messages", url_encode(session_id));+ let body = json!({+ "role": role,+ "content": content+ });++ let response: serde_json::Value = client.post(&path, &body).await?;+ output_success(&response, output_format, false);+ Ok(())+}++pub async fn commit_session(+ client: &HttpClient,+ session_id: &str,+ output_format: OutputFormat,+) -> Result<()> {+ let path = format!("/api/v1/sessions/{}/commit", url_encode(session_id));+ let response: serde_json::Value = client.post(&path, &json!({})).await?;+ output_success(&response, output_format, false);+ Ok(())+}++fn url_encode(s: &str) -> String {+ // Simple URL encoding for session IDs+ s.replace('/', "%2F")+ .replace(':', "%3A")+ .replace(' ', "%20")+}diff --git a/crates/openviking-cli/src/commands/system.rs b/crates/openviking-cli/src/commands/system.rsnew file mode 100644index 000000000..6cc546028--- /dev/null+++ b/crates/openviking-cli/src/commands/system.rs@@ -0,0 +1,49 @@+use crate::client::HttpClient;+use crate::error::Result;+use crate::output::{output_success, OutputFormat};+use serde_json::json;++pub async fn wait(+ client: &HttpClient,+ timeout: Option<f64>,+ output_format: OutputFormat,+) -> Result<()> {+ let path = if let Some(t) = timeout {+ format!("/api/v1/system/wait?timeout={}", t)+ } else {+ "/api/v1/system/wait".to_string()+ };++ let response: serde_json::Value = client.post(&path, &json!({})).await?;+ output_success(&response, output_format, false);+ Ok(())+}++pub async fn status(+ client: &HttpClient,+ output_format: OutputFormat,+) -> Result<()> {+ let response: serde_json::Value = client.get("/api/v1/system/status", &[]).await?;+ output_success(&response, output_format, false);+ Ok(())+}++pub async fn health(+ client: &HttpClient,+ output_format: OutputFormat,+) -> Result<()> {+ let response: serde_json::Value = client.get("/api/v1/system/health", &[]).await?;++ // For health check, if it's a simple boolean, just print it+ if let Some(healthy) = response.get("healthy").and_then(|v| v.as_bool()) {+ if matches!(output_format, OutputFormat::Json) {+ output_success(&response, output_format, false);+ } else {+ println!("{}", healthy);+ }+ } else {+ output_success(&response, output_format, false);+ }++ Ok(())+}diff --git a/crates/openviking-cli/src/config.rs b/crates/openviking-cli/src/config.rsnew file mode 100644index 000000000..363b39a8a--- /dev/null+++ b/crates/openviking-cli/src/config.rs@@ -0,0 +1,76 @@+use serde::{Deserialize, Serialize};+use std::path::PathBuf;++use crate::error::{Error, Result};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Config {+ #[serde(default = "default_url")]+ pub url: String,+ pub api_key: Option<String>,+ pub user: Option<String>,+ #[serde(default = "default_output_format")]+ pub output: String,+}++fn default_url() -> String {+ "http://localhost:1933".to_string()+}++fn default_output_format() -> String {+ "table".to_string()+}++impl Default for Config {+ fn default() -> Self {+ Self {+ url: "http://localhost:1933".to_string(),+ api_key: None,+ user: None,+ output: "table".to_string(),+ }+ }+}++impl Config {+ /// Load config from default location or create default+ pub fn load() -> Result<Self> {+ Self::load_default()+ }++ pub fn load_default() -> Result<Self> {+ let config_path = default_config_path()?;+ if config_path.exists() {+ Self::from_file(&config_path.to_string_lossy())+ } else {+ Ok(Self::default())+ }+ }++ pub fn from_file(path: &str) -> Result<Self> {+ let content = std::fs::read_to_string(path)+ .map_err(|e| Error::Config(format!("Failed to read config file: {}", e)))?;+ let config: Config = serde_json::from_str(&content)+ .map_err(|e| Error::Config(format!("Failed to parse config file: {}", e)))?;+ Ok(config)+ }++ pub fn save_default(&self) -> Result<()> {+ let config_path = default_config_path()?;+ if let Some(parent) = config_path.parent() {+ std::fs::create_dir_all(parent)+ .map_err(|e| Error::Config(format!("Failed to create config directory: {}", e)))?;+ }+ let content = serde_json::to_string_pretty(self)+ .map_err(|e| Error::Config(format!("Failed to serialize config: {}", e)))?;+ std::fs::write(&config_path, content)+ .map_err(|e| Error::Config(format!("Failed to write config file: {}", e)))?;+ Ok(())+ }+}++pub fn default_config_path() -> Result<PathBuf> {+ let home = dirs::home_dir()+ .ok_or_else(|| Error::Config("Could not determine home directory".to_string()))?;+ Ok(home.join(".openviking").join("ovcli.conf"))+}diff --git a/crates/openviking-cli/src/error.rs b/crates/openviking-cli/src/error.rsnew file mode 100644index 000000000..bdbdd9d48--- /dev/null+++ b/crates/openviking-cli/src/error.rs@@ -0,0 +1,100 @@+use thiserror::Error;++#[derive(Error, Debug)]+pub enum Error {+ #[error("Configuration error: {0}")]+ Config(String),++ #[error("Network error: {0}")]+ Network(String),++ #[error("API error: {0}")]+ Api(String),++ #[error("Client error: {0}")]+ Client(String),++ #[error("Parse error: {0}")]+ Parse(String),++ #[error("Output error: {0}")]+ Output(String),++ #[error("IO error: {0}")]+ Io(#[from] std::io::Error),++ #[error("Serialization error: {0}")]+ Serialization(#[from] serde_json::Error),+}++pub type Result<T> = std::result::Result<T, Error>;++/// CLI-specific error type for command handlers+#[derive(Error, Debug)]+#[error("{message}")]+pub struct CliError {+ pub message: String,+ pub code: String,+ pub exit_code: i32,+}++impl CliError {+ pub fn new(message: impl Into<String>) -> Self {+ Self {+ message: message.into(),+ code: "CLI_ERROR".to_string(),+ exit_code: 1,+ }+ }++ pub fn config(message: impl Into<String>) -> Self {+ Self {+ message: message.into(),+ code: "CLI_CONFIG".to_string(),+ exit_code: 2,+ }+ }++ pub fn network(message: impl Into<String>) -> Self {+ Self {+ message: message.into(),+ code: "CONNECTION_ERROR".to_string(),+ exit_code: 3,+ }+ }+}++impl From<Error> for CliError {+ fn from(err: Error) -> Self {+ match err {+ Error::Config(msg) => CliError::config(msg),+ Error::Network(msg) => CliError::network(msg),+ Error::Api(msg) => CliError::new(format!("API error: {}", msg)),+ Error::Client(msg) => CliError::new(format!("Client error: {}", msg)),+ Error::Parse(msg) => CliError::new(format!("Parse error: {}", msg)),+ Error::Output(msg) => CliError::new(format!("Output error: {}", msg)),+ Error::Io(e) => CliError::new(format!("IO error: {}", e)),+ Error::Serialization(e) => CliError::new(format!("Serialization error: {}", e)),+ }+ }+}++impl From<reqwest::Error> for CliError {+ fn from(err: reqwest::Error) -> Self {+ if err.is_connect() || err.is_timeout() {+ CliError::network(format!(+ "Failed to connect to OpenViking server. \+ Check the url in ovcli.conf and ensure the server is running. ({ })",+ err+ ))+ } else {+ CliError::new(format!("HTTP error: {}", err))+ }+ }+}++impl From<serde_json::Error> for CliError {+ fn from(err: serde_json::Error) -> Self {+ CliError::new(format!("JSON error: {}", err))+ }+}diff --git a/crates/openviking-cli/src/main.rs b/crates/openviking-cli/src/main.rsnew file mode 100644index 000000000..8986f343f--- /dev/null+++ b/crates/openviking-cli/src/main.rs@@ -0,0 +1,655 @@+mod client;+mod commands;+mod config;+mod error;+mod output;++use clap::{Parser, Subcommand};+use config::Config;+use error::{Error, Result};+use output::OutputFormat;++/// CLI context shared across commands+#[derive(Debug, Clone)]+pub struct CliContext {+ pub config: Config,+ pub output_format: OutputFormat,+}++impl CliContext {+ pub fn new(output_format: OutputFormat) -> Result<Self> {+ let config = Config::load()?;+ Ok(Self {+ config,+ output_format,+ })+ }++ pub fn get_client(&self) -> client::HttpClient {+ client::HttpClient::new(&self.config.url, self.config.api_key.clone())+ }+}++#[derive(Parser)]+#[command(name = "openviking")]+#[command(about = "OpenViking - An Agent-native context database")]+#[command(version = env!("CARGO_PKG_VERSION"))]+#[command(arg_required_else_help = true)]+struct Cli {+ /// Output format+ #[arg(short, long, value_enum, default_value = "table")]+ output: OutputFormat,++ /// Output compact JSON with {ok, result} wrapper (for scripts)+ #[arg(long)]+ json: bool,++ #[command(subcommand)]+ command: Commands,+}++#[derive(Subcommand)]+enum Commands {+ /// Add resources into OpenViking+ AddResource {+ /// Local path or URL to import+ path: String,+ /// Target URI+ #[arg(long)]+ to: Option<String>,+ /// Reason for import+ #[arg(long, default_value = "")]+ reason: String,+ /// Additional instruction+ #[arg(long, default_value = "")]+ instruction: String,+ /// Wait until processing is complete+ #[arg(long)]+ wait: bool,+ /// Wait timeout in seconds+ #[arg(long)]+ timeout: Option<f64>,+ },+ /// Add a skill into OpenViking+ AddSkill {+ /// Skill directory, SKILL.md, or raw content+ data: String,+ /// Wait until processing is complete+ #[arg(long)]+ wait: bool,+ /// Wait timeout in seconds+ #[arg(long)]+ timeout: Option<f64>,+ },+ /// List relations of a resource+ Relations {+ /// Viking URI+ uri: String,+ },+ /// Create relation links from one URI to one or more targets+ Link {+ /// Source URI+ from_uri: String,+ /// One or more target URIs+ to_uris: Vec<String>,+ /// Reason for linking+ #[arg(long, default_value = "")]+ reason: String,+ },+ /// Remove a relation link+ Unlink {+ /// Source URI+ from_uri: String,+ /// Target URI to unlink+ to_uri: String,+ },+ /// Export context as .ovpack+ Export {+ /// Source URI+ uri: String,+ /// Output .ovpack file path+ to: String,+ },+ /// Import .ovpack into target URI+ Import {+ /// Input .ovpack file path+ file_path: String,+ /// Target parent URI+ target_uri: String,+ /// Overwrite when conflicts exist+ #[arg(long)]+ force: bool,+ /// Disable vectorization after import+ #[arg(long)]+ no_vectorize: bool,+ },+ /// System utility commands+ System {+ #[command(subcommand)]+ action: SystemCommands,+ },+ /// Observer status commands+ Observer {+ #[command(subcommand)]+ action: ObserverCommands,+ },+ /// Session management commands+ Session {+ #[command(subcommand)]+ action: SessionCommands,+ },+ /// List directory contents+ #[command(alias = "list")]+ Ls {+ /// Viking URI to list (default: viking://)+ #[arg(default_value = "viking://")]+ uri: String,+ /// Simple path output (just paths, no table)+ #[arg(short, long)]+ simple: bool,+ /// List all subdirectories recursively+ #[arg(short, long)]+ recursive: bool,+ },+ /// Get directory tree+ Tree {+ /// Viking URI to get tree for+ uri: String,+ },+ /// Create directory+ Mkdir {+ /// Directory URI to create+ uri: String,+ },+ /// Remove resource+ #[command(alias = "del", alias = "delete")]+ Rm {+ /// Viking URI to remove+ uri: String,+ /// Remove recursively+ #[arg(short, long)]+ recursive: bool,+ },+ /// Move or rename resource+ #[command(alias = "rename")]+ Mv {+ /// Source URI+ from_uri: String,+ /// Target URI+ to_uri: String,+ },+ /// Get resource metadata+ Stat {+ /// Viking URI to get metadata for+ uri: String,+ },+ /// Read file content (L2)+ Read {+ /// Viking URI+ uri: String,+ },+ /// Read abstract content (L0)+ Abstract {+ /// Viking URI+ uri: String,+ },+ /// Read overview content (L1)+ Overview {+ /// Viking URI+ uri: String,+ },+ /// Run semantic retrieval+ Find {+ /// Search query+ query: String,+ /// Target URI+ #[arg(short, long, default_value = "")]+ uri: String,+ /// Maximum number of results+ #[arg(short = 'n', long, default_value = "10")]+ limit: i32,+ /// Score threshold+ #[arg(short, long)]+ threshold: Option<f64>,+ },+ /// Run context-aware retrieval+ Search {+ /// Search query+ query: String,+ /// Target URI+ #[arg(short, long, default_value = "")]+ uri: String,+ /// Session ID for context-aware search+ #[arg(long)]+ session_id: Option<String>,+ /// Maximum number of results+ #[arg(short = 'n', long, default_value = "10")]+ limit: i32,+ /// Score threshold+ #[arg(short, long)]+ threshold: Option<f64>,+ },+ /// Run content pattern search+ Grep {+ /// Target URI+ uri: String,+ /// Search pattern+ pattern: String,+ /// Case insensitive+ #[arg(short, long)]+ ignore_case: bool,+ },+ /// Run file glob pattern search+ Glob {+ /// Glob pattern+ pattern: String,+ /// Search root URI+ #[arg(short, long, default_value = "viking://")]+ uri: String,+ },+ /// Configuration management+ Config {+ #[command(subcommand)]+ action: ConfigCommands,+ },+ /// Show CLI version+ Version,+}++#[derive(Subcommand)]+enum SystemCommands {+ /// Wait for queued async processing to complete+ Wait {+ /// Wait timeout in seconds+ #[arg(long)]+ timeout: Option<f64>,+ },+ /// Show component status+ Status,+ /// Quick health check+ Health,+}++#[derive(Subcommand)]+enum ObserverCommands {+ /// Get queue status+ Queue,+ /// Get VikingDB status+ Vikingdb,+ /// Get VLM status+ Vlm,+ /// Get overall system status+ System,+}++#[derive(Subcommand)]+enum SessionCommands {+ /// Create a new session+ New,+ /// List sessions+ List,+ /// Get session details+ Get {+ /// Session ID+ session_id: String,+ },+ /// Delete a session+ Delete {+ /// Session ID+ session_id: String,+ },+ /// Add one message to a session+ AddMessage {+ /// Session ID+ session_id: String,+ /// Message role, e.g. user/assistant+ #[arg(long)]+ role: String,+ /// Message content+ #[arg(long)]+ content: String,+ },+ /// Commit a session (archive messages and extract memories)+ Commit {+ /// Session ID+ session_id: String,+ },+}++#[derive(Subcommand)]+enum ConfigCommands {+ /// Show current configuration+ Show,+ /// Validate configuration file+ Validate,+}++#[tokio::main]+async fn main() {+ let cli = Cli::parse();++ // --json flag overrides output format+ let output_format = if cli.json {+ OutputFormat::Json+ } else {+ cli.output+ };++ let ctx = match CliContext::new(output_format) {+ Ok(ctx) => ctx,+ Err(e) => {+ eprintln!("Error: {}", e);+ std::process::exit(2);+ }+ };++ let result = match cli.command {+ Commands::AddResource { path, to, reason, instruction, wait, timeout } => {+ handle_add_resource(path, to, reason, instruction, wait, timeout, ctx).await+ }+ Commands::AddSkill { data, wait, timeout } => {+ handle_add_skill(data, wait, timeout, ctx).await+ }+ Commands::Relations { uri } => {+ handle_relations(uri, ctx).await+ }+ Commands::Link { from_uri, to_uris, reason } => {+ handle_link(from_uri, to_uris, reason, ctx).await+ }+ Commands::Unlink { from_uri, to_uri } => {+ handle_unlink(from_uri, to_uri, ctx).await+ }+ Commands::Export { uri, to } => {+ handle_export(uri, to, ctx).await+ }+ Commands::Import { file_path, target_uri, force, no_vectorize } => {+ handle_import(file_path, target_uri, force, no_vectorize, ctx).await+ }+ Commands::System { action } => handle_system(action, ctx).await,+ Commands::Observer { action } => handle_observer(action, ctx).await,+ Commands::Session { action } => handle_session(action, ctx).await,+ Commands::Ls { uri, simple, recursive } => {+ handle_ls(uri, simple, recursive, ctx).await+ }+ Commands::Tree { uri } => {+ handle_tree(uri, ctx).await+ }+ Commands::Mkdir { uri } => {+ handle_mkdir(uri, ctx).await+ }+ Commands::Rm { uri, recursive } => {+ handle_rm(uri, recursive, ctx).await+ }+ Commands::Mv { from_uri, to_uri } => {+ handle_mv(from_uri, to_uri, ctx).await+ }+ Commands::Stat { uri } => {+ handle_stat(uri, ctx).await+ }+ Commands::Config { action } => handle_config(action, ctx).await,+ Commands::Version => {+ println!("{}", env!("CARGO_PKG_VERSION"));+ Ok(())+ }+ Commands::Read { uri } => handle_read(uri, ctx).await,+ Commands::Abstract { uri } => handle_abstract(uri, ctx).await,+ Commands::Overview { uri } => handle_overview(uri, ctx).await,+ Commands::Find { query, uri, limit, threshold } => {+ handle_find(query, uri, limit, threshold, ctx).await+ }+ Commands::Search { query, uri, session_id, limit, threshold } => {+ handle_search(query, uri, session_id, limit, threshold, ctx).await+ }+ Commands::Grep { uri, pattern, ignore_case } => {+ handle_grep(uri, pattern, ignore_case, ctx).await+ }+ Commands::Glob { pattern, uri } => {+ handle_glob(pattern, uri, ctx).await+ }+ };++ if let Err(e) = result {+ eprintln!("Error: {}", e);+ std::process::exit(1);+ }+}++async fn handle_add_resource(+ path: String,+ to: Option<String>,+ reason: String,+ instruction: String,+ wait: bool,+ timeout: Option<f64>,+ ctx: CliContext,+) -> Result<()> {+ let client = ctx.get_client();+ commands::resources::add_resource(+ &client, &path, to, reason, instruction, wait, timeout, ctx.output_format+ ).await+}++async fn handle_add_skill(+ data: String,+ wait: bool,+ timeout: Option<f64>,+ ctx: CliContext,+) -> Result<()> {+ let client = ctx.get_client();+ commands::resources::add_skill(+ &client, &data, wait, timeout, ctx.output_format+ ).await+}++async fn handle_relations(uri: String, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::relations::list_relations(&client, &uri, ctx.output_format+ ).await+}++async fn handle_link(+ from_uri: String,+ to_uris: Vec<String>,+ reason: String,+ ctx: CliContext,+) -> Result<()> {+ let client = ctx.get_client();+ commands::relations::link(+ &client, &from_uri, &to_uris, &reason, ctx.output_format+ ).await+}++async fn handle_unlink(+ from_uri: String,+ to_uri: String,+ ctx: CliContext,+) -> Result<()> {+ let client = ctx.get_client();+ commands::relations::unlink(+ &client, &from_uri, &to_uri, ctx.output_format+ ).await+}++async fn handle_export(uri: String, to: String, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::pack::export(&client, &uri, &to, ctx.output_format+ ).await+}++async fn handle_import(+ file_path: String,+ target_uri: String,+ force: bool,+ no_vectorize: bool,+ ctx: CliContext,+) -> Result<()> {+ let client = ctx.get_client();+ commands::pack::import(+ &client, &file_path, &target_uri, force, no_vectorize, ctx.output_format+ ).await+}++async fn handle_system(cmd: SystemCommands, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ match cmd {+ SystemCommands::Wait { timeout } => {+ commands::system::wait(&client, timeout, ctx.output_format).await+ }+ SystemCommands::Status => {+ commands::system::status(&client, ctx.output_format).await+ }+ SystemCommands::Health => {+ commands::system::health(&client, ctx.output_format).await+ }+ }+}++async fn handle_observer(cmd: ObserverCommands, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ match cmd {+ ObserverCommands::Queue => {+ commands::observer::queue(&client, ctx.output_format).await+ }+ ObserverCommands::Vikingdb => {+ commands::observer::vikingdb(&client, ctx.output_format).await+ }+ ObserverCommands::Vlm => {+ commands::observer::vlm(&client, ctx.output_format).await+ }+ ObserverCommands::System => {+ commands::observer::system(&client, ctx.output_format).await+ }+ }+}++async fn handle_session(cmd: SessionCommands, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ match cmd {+ SessionCommands::New => {+ commands::session::new_session(&client, ctx.output_format).await+ }+ SessionCommands::List => {+ commands::session::list_sessions(&client, ctx.output_format).await+ }+ SessionCommands::Get { session_id } => {+ commands::session::get_session(&client, &session_id, ctx.output_format+ ).await+ }+ SessionCommands::Delete { session_id } => {+ commands::session::delete_session(&client, &session_id, ctx.output_format+ ).await+ }+ SessionCommands::AddMessage { session_id, role, content } => {+ commands::session::add_message(+ &client, &session_id, &role, &content, ctx.output_format+ ).await+ }+ SessionCommands::Commit { session_id } => {+ commands::session::commit_session(&client, &session_id, ctx.output_format+ ).await+ }+ }+}++async fn handle_config(cmd: ConfigCommands, _ctx: CliContext) -> Result<()> {+ match cmd {+ ConfigCommands::Show => {+ let config = Config::load()?;+ output::output_success(+ &serde_json::to_value(config).unwrap(),+ output::OutputFormat::Json,+ true+ );+ Ok(())+ }+ ConfigCommands::Validate => {+ match Config::load() {+ Ok(_) => {+ println!("Configuration is valid");+ Ok(())+ }+ Err(e) => {+ Err(Error::Config(e.to_string()))+ }+ }+ }+ }+}++async fn handle_read(uri: String, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::content::read(&client, &uri, ctx.output_format).await+}++async fn handle_abstract(uri: String, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::content::abstract_content(&client, &uri, ctx.output_format).await+}++async fn handle_overview(uri: String, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::content::overview(&client, &uri, ctx.output_format).await+}++async fn handle_find(+ query: String,+ uri: String,+ limit: i32,+ threshold: Option<f64>,+ ctx: CliContext,+) -> Result<()> {+ let client = ctx.get_client();+ commands::search::find(&client, &query, &uri, limit, threshold, ctx.output_format).await+}++async fn handle_search(+ query: String,+ uri: String,+ session_id: Option<String>,+ limit: i32,+ threshold: Option<f64>,+ ctx: CliContext,+) -> Result<()> {+ let client = ctx.get_client();+ commands::search::search(&client, &query, &uri, session_id, limit, threshold, ctx.output_format).await+}++async fn handle_ls(uri: String, simple: bool, recursive: bool, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::filesystem::ls(&client, &uri, simple, recursive, ctx.output_format).await+}++async fn handle_tree(uri: String, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::filesystem::tree(&client, &uri, ctx.output_format).await+}++async fn handle_mkdir(uri: String, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::filesystem::mkdir(&client, &uri, ctx.output_format).await+}++async fn handle_rm(uri: String, recursive: bool, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::filesystem::rm(&client, &uri, recursive, ctx.output_format).await+}++async fn handle_mv(from_uri: String, to_uri: String, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::filesystem::mv(&client, &from_uri, &to_uri, ctx.output_format).await+}++async fn handle_stat(uri: String, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::filesystem::stat(&client, &uri, ctx.output_format).await+}++async fn handle_grep(uri: String, pattern: String, ignore_case: bool, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::search::grep(&client, &uri, &pattern, ignore_case, ctx.output_format).await+}++async fn handle_glob(pattern: String, uri: String, ctx: CliContext) -> Result<()> {+ let client = ctx.get_client();+ commands::search::glob(&client, &pattern, &uri, ctx.output_format).await+}diff --git a/crates/openviking-cli/src/output.rs b/crates/openviking-cli/src/output.rsnew file mode 100644index 000000000..86724e34c--- /dev/null+++ b/crates/openviking-cli/src/output.rs@@ -0,0 +1,316 @@+use serde::Serialize;+use serde_json::json;+use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};++#[derive(Debug, Clone, Copy, PartialEq)]+pub enum OutputFormat {+ Table,+ Json,+}++impl From<&str> for OutputFormat {+ fn from(s: &str) -> Self {+ match s {+ "json" => OutputFormat::Json,+ _ => OutputFormat::Table,+ }+ }+}++pub fn output_success<T: Serialize>(result: T, format: OutputFormat, json_output: bool) {+ if json_output || matches!(format, OutputFormat::Json) {+ println!("{}", json!({ "ok": true, "result": result }));+ } else {+ print_table(result);+ }+}++#[allow(dead_code)]+pub fn output_error(code: &str, message: &str, format: OutputFormat, json_output: bool) {+ if json_output || matches!(format, OutputFormat::Json) {+ eprintln!(+ "{}",+ json!({+ "ok": false,+ "error": {+ "code": code,+ "message": message+ }+ })+ );+ } else {+ eprintln!("ERROR[{}]: {}", code, message);+ }+}++fn print_table<T: Serialize>(result: T) {+ // Convert to json Value for processing+ let value = match serde_json::to_value(&result) {+ Ok(v) => v,+ Err(_) => {+ println!("{}", serde_json::to_string_pretty(&result).unwrap_or_default());+ return;+ }+ };++ // Handle string result+ if let Some(s) = value.as_str() {+ println!("{}", s);+ return;+ }++ // Handle array of objects+ if let Some(items) = value.as_array() {+ if !items.is_empty() {+ if let Some(table) = format_array_to_table(items) {+ println!("{}", table);+ return;+ }+ } else {+ println!("(empty)");+ return;+ }+ }++ // Handle object+ if let Some(obj) = value.as_object() {+ if !obj.is_empty() {+ // Calculate max key width+ let max_key_width = obj.keys()+ .map(|k| k.width())+ .max()+ .unwrap_or(0)+ .min(120);++ let mut output = String::new();+ for (k, v) in obj {+ let is_uri = k == "uri";+ let formatted_value = format_value(v);+ let (content, _) = truncate_string(&formatted_value, is_uri, 120);+ let padded_key = pad_cell(k, max_key_width, false);+ output.push_str(&format!("{} {}\n", padded_key, content));+ }+ println!("{}", output);+ return;+ }+ }++ // Default: JSON output+ println!("{}", serde_json::to_string_pretty(&result).unwrap_or_default());+}++struct ColumnInfo {+ max_width: usize, // Max width for alignment (capped at 120)+ is_numeric: bool, // True if all values in column are numeric+ is_uri_column: bool, // True if column name is "uri"+}++fn format_array_to_table(items: &Vec<serde_json::Value>) -> Option<String> {+ if items.is_empty() {+ return None;+ }++ // Check if all items are objects+ if !items.iter().all(|i| i.is_object()) {+ // Handle list of primitives+ let mut output = String::new();+ for item in items {+ let (content, _) = truncate_string(&format_value(item), false, 120);+ output.push_str(&format!("{}\n", content));+ }+ return Some(output);+ }++ // Collect all unique keys+ let mut keys: Vec<String> = Vec::new();+ let mut key_set = std::collections::HashSet::new();++ for item in items {+ if let Some(obj) = item.as_object() {+ for k in obj.keys() {+ if key_set.insert(k.clone()) {+ keys.push(k.clone());+ }+ }+ }+ }++ if keys.is_empty() {+ return None;+ }++ // First pass: analyze columns+ let mut column_info: Vec<ColumnInfo> = Vec::new();++ for key in &keys {+ let is_uri_column = key == "uri";+ let mut is_numeric = true;+ let mut max_width = key.width(); // Start with header width++ for item in items {+ if let Some(obj) = item.as_object() {+ if let Some(value) = obj.get(key) {+ let formatted = format_value(value);+ let display_width = formatted.width();++ // Update max_width (capped at 120 for alignment calculation)+ max_width = max_width.max(display_width.min(120));++ // Check if numeric+ if is_numeric && !is_numeric_value(value) {+ is_numeric = false;+ }+ }+ }+ }++ column_info.push(ColumnInfo {+ max_width,+ is_numeric,+ is_uri_column,+ });+ }++ // Second pass: format rows+ let mut output = String::new();++ // Header row+ let header_cells: Vec<String> = keys.iter()+ .enumerate()+ .map(|(i, k)| pad_cell(k, column_info[i].max_width, false))+ .collect();+ output.push_str(&header_cells.join(" "));+ output.push('\n');++ // Data rows+ for item in items {+ if let Some(obj) = item.as_object() {+ let row_cells: Vec<String> = keys.iter()+ .enumerate()+ .map(|(i, k)| {+ let info = &column_info[i];+ let value = obj.get(k)+ .map(|v| format_value(v))+ .unwrap_or_default();++ let (content, skip_padding) = truncate_string(+ &value,+ info.is_uri_column,+ info.max_width+ );++ if skip_padding {+ // Long URI, output as-is without padding+ content+ } else {+ // Normal cell, apply padding and alignment+ pad_cell(&content, info.max_width, info.is_numeric)+ }+ })+ .collect();++ output.push_str(&row_cells.join(" "));+ output.push('\n');+ }+ }++ Some(output)+}++fn format_value(v: &serde_json::Value) -> String {+ match v {+ serde_json::Value::String(s) => s.clone(),+ serde_json::Value::Number(n) => n.to_string(),+ serde_json::Value::Bool(b) => b.to_string(),+ serde_json::Value::Null => "null".to_string(),+ _ => v.to_string(),+ }+}++fn pad_cell(content: &str, width: usize, align_right: bool) -> String {+ let display_width = content.width();++ if display_width >= width {+ return content.to_string();+ }++ let padding_needed = width - display_width;+ if align_right {+ format!("{}{}", " ".repeat(padding_needed), content)+ } else {+ format!("{}{}", content, " ".repeat(padding_needed))+ }+}++fn is_numeric_value(v: &serde_json::Value) -> bool {+ match v {+ serde_json::Value::Number(_) => true,+ serde_json::Value::String(s) => s.parse::<f64>().is_ok(),+ _ => false,+ }+}++fn truncate_string(s: &str, is_uri: bool, max_width: usize) -> (String, bool) {+ const MAX_LEN: usize = 120;+ let display_width = s.width();++ // URI columns: don't truncate if exceeds threshold+ if is_uri && display_width > max_width {+ return (s.to_string(), true); // true = skip padding+ }++ // Normal truncation - truncate by display width+ if display_width > MAX_LEN {+ let mut current_width = 0;+ let mut truncated = String::new();+ for ch in s.chars() {+ let ch_width = ch.width().unwrap_or(0);+ if current_width + ch_width > MAX_LEN - 3 {+ break;+ }+ current_width += ch_width;+ truncated.push(ch);+ }+ (format!("{}...", truncated), false)+ } else {+ (s.to_string(), false)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn test_object_formatting_with_alignment() {+ // Test object with keys of different lengths+ let obj = json!({+ "id": "123",+ "name": "Test Resource",+ "uri": "viking://resources/test",+ "type": "document"+ });++ // This should not panic and should produce aligned output+ // We can't easily capture stdout, but at least verify it doesn't crash+ print_table(obj);+ }++ #[test]+ fn test_object_with_long_uri() {+ // Test that long URIs are handled correctly+ let obj = json!({+ "id": "456",+ "uri": "viking://resources/very/long/path/that/exceeds/normal/width/limits/and/should/not/be/truncated/because/it/is/a/uri"+ });++ print_table(obj);+ }++ #[test]+ fn test_empty_object() {+ let obj = json!({});+ print_table(obj);+ }+}