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
fix(agfs): fix agfs binding-client import error (#458)
chuanbao66613a3b741886a
diff --git a/openviking/__init__.py b/openviking/__init__.pyindex 433f6ad9b..5d0c3e416 100644--- a/openviking/__init__.py+++ b/openviking/__init__.py@@ -26,7 +26,7 @@ except ImportError:__version__ = "0.0.0+unknown"try:- from pyagfs import AGFSClient+ from openviking.pyagfs import AGFSClientexcept ImportError:raise ImportError("pyagfs not found. Please install: pip install -e third_party/agfs/agfs-sdk/python"diff --git a/openviking/eval/recorder/recorder.py b/openviking/eval/recorder/recorder.pyindex be84fb4bb..c5869f1d8 100644--- a/openviking/eval/recorder/recorder.py+++ b/openviking/eval/recorder/recorder.py@@ -340,7 +340,7 @@ def create_recording_agfs_client(agfs_client: Any, record_file: Optional[str] =Usage:from openviking.eval.recorder import init_recorder, create_recording_agfs_client- from pyagfs import AGFSClient+ from openviking.pyagfs import AGFSClient# Initialize recorderinit_recorder(enabled=True)diff --git a/openviking/eval/recorder/recording_client.py b/openviking/eval/recorder/recording_client.pyindex c68981d64..7bd5abcdd 100644--- a/openviking/eval/recorder/recording_client.py+++ b/openviking/eval/recorder/recording_client.py@@ -25,7 +25,7 @@ class RecordingAGFSClient:to a file for later playback and performance analysis.Usage:- from pyagfs import AGFSClient+ from openviking.pyagfs import AGFSClientfrom openviking.eval.recorder.recording_client import RecordingAGFSClientbase_client = AGFSClient(api_base_url="http://localhost:1833")diff --git a/openviking/pyagfs/__init__.py b/openviking/pyagfs/__init__.pynew file mode 100644index 000000000..7d8b48fc0--- /dev/null+++ b/openviking/pyagfs/__init__.py@@ -0,0 +1,38 @@+"""AGFS Python SDK - Client library for AGFS Server API"""++__version__ = "0.1.7"++from .client import AGFSClient, FileHandle+from .exceptions import (+ AGFSClientError,+ AGFSConnectionError,+ AGFSHTTPError,+ AGFSNotSupportedError,+ AGFSTimeoutError,+)+from .helpers import cp, download, upload++# Binding client depends on a native shared library (libagfsbinding.so/dylib/dll).+# Make it optional so the pure-HTTP AGFSClient remains usable when the native+# library is not installed (e.g. Docker images without CGO build).+try:+ from .binding_client import AGFSBindingClient+ from .binding_client import FileHandle as BindingFileHandle+except (ImportError, OSError):+ AGFSBindingClient = None+ BindingFileHandle = None++__all__ = [+ "AGFSClient",+ "AGFSBindingClient",+ "FileHandle",+ "BindingFileHandle",+ "AGFSClientError",+ "AGFSConnectionError",+ "AGFSTimeoutError",+ "AGFSHTTPError",+ "AGFSNotSupportedError",+ "cp",+ "upload",+ "download",+]diff --git a/openviking/pyagfs/binding_client.py b/openviking/pyagfs/binding_client.pynew file mode 100644index 000000000..3ba5254db--- /dev/null+++ b/openviking/pyagfs/binding_client.py@@ -0,0 +1,603 @@+"""AGFS Python Binding Client - Direct binding to AGFS Server implementation"""++import ctypes+import json+import os+import platform+from pathlib import Path+from typing import Any, BinaryIO, Dict, Iterator, List, Optional, Union++from .exceptions import AGFSClientError, AGFSNotSupportedError+++def _find_library() -> str:+ """Find the AGFS binding shared library."""+ system = platform.system()++ if system == "Darwin":+ lib_name = "libagfsbinding.dylib"+ elif system == "Linux":+ lib_name = "libagfsbinding.so"+ elif system == "Windows":+ lib_name = "libagfsbinding.dll"+ else:+ raise AGFSClientError(f"Unsupported platform: {system}")++ search_paths = [+ Path(__file__).parent / "lib" / lib_name,+ Path(__file__).parent.parent / "lib" / lib_name,+ Path(__file__).parent.parent.parent / "lib" / lib_name,+ Path("/usr/local/lib") / lib_name,+ Path("/usr/lib") / lib_name,+ Path(os.environ.get("AGFS_LIB_PATH", "")) / lib_name+ if os.environ.get("AGFS_LIB_PATH")+ else None,+ ]++ for path in search_paths:+ if path and path.exists():+ return str(path)++ raise AGFSClientError(+ f"Could not find {lib_name}. Please set AGFS_LIB_PATH environment variable "+ f"or install the library to /usr/local/lib"+ )+++class BindingLib:+ """Wrapper for the AGFS binding shared library."""++ _instance = None++ def __new__(cls):+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ cls._instance._load_library()+ return cls._instance++ def _load_library(self):+ lib_path = _find_library()+ self.lib = ctypes.CDLL(lib_path)+ self._setup_functions()++ def _setup_functions(self):+ self.lib.AGFS_NewClient.argtypes = []+ self.lib.AGFS_NewClient.restype = ctypes.c_int64++ self.lib.AGFS_FreeClient.argtypes = [ctypes.c_int64]+ self.lib.AGFS_FreeClient.restype = None++ self.lib.AGFS_GetLastError.argtypes = [ctypes.c_int64]+ self.lib.AGFS_GetLastError.restype = ctypes.c_char_p++ self.lib.AGFS_FreeString.argtypes = [ctypes.c_char_p]+ self.lib.AGFS_FreeString.restype = None++ self.lib.AGFS_Health.argtypes = [ctypes.c_int64]+ self.lib.AGFS_Health.restype = ctypes.c_int++ self.lib.AGFS_GetCapabilities.argtypes = [ctypes.c_int64]+ self.lib.AGFS_GetCapabilities.restype = ctypes.c_char_p++ self.lib.AGFS_Ls.argtypes = [ctypes.c_int64, ctypes.c_char_p]+ self.lib.AGFS_Ls.restype = ctypes.c_char_p++ self.lib.AGFS_Read.argtypes = [+ ctypes.c_int64,+ ctypes.c_char_p,+ ctypes.c_int64,+ ctypes.c_int64,+ ctypes.POINTER(ctypes.c_char_p),+ ctypes.POINTER(ctypes.c_int64),+ ]+ self.lib.AGFS_Read.restype = ctypes.c_int64++ self.lib.AGFS_Write.argtypes = [+ ctypes.c_int64,+ ctypes.c_char_p,+ ctypes.c_void_p,+ ctypes.c_int64,+ ]+ self.lib.AGFS_Write.restype = ctypes.c_char_p++ self.lib.AGFS_Create.argtypes = [ctypes.c_int64, ctypes.c_char_p]+ self.lib.AGFS_Create.restype = ctypes.c_char_p++ self.lib.AGFS_Mkdir.argtypes = [ctypes.c_int64, ctypes.c_char_p, ctypes.c_uint]+ self.lib.AGFS_Mkdir.restype = ctypes.c_char_p++ self.lib.AGFS_Rm.argtypes = [ctypes.c_int64, ctypes.c_char_p, ctypes.c_int]+ self.lib.AGFS_Rm.restype = ctypes.c_char_p++ self.lib.AGFS_Stat.argtypes = [ctypes.c_int64, ctypes.c_char_p]+ self.lib.AGFS_Stat.restype = ctypes.c_char_p++ self.lib.AGFS_Mv.argtypes = [ctypes.c_int64, ctypes.c_char_p, ctypes.c_char_p]+ self.lib.AGFS_Mv.restype = ctypes.c_char_p++ self.lib.AGFS_Chmod.argtypes = [ctypes.c_int64, ctypes.c_char_p, ctypes.c_uint]+ self.lib.AGFS_Chmod.restype = ctypes.c_char_p++ self.lib.AGFS_Touch.argtypes = [ctypes.c_int64, ctypes.c_char_p]+ self.lib.AGFS_Touch.restype = ctypes.c_char_p++ self.lib.AGFS_Mounts.argtypes = [ctypes.c_int64]+ self.lib.AGFS_Mounts.restype = ctypes.c_char_p++ self.lib.AGFS_Mount.argtypes = [+ ctypes.c_int64,+ ctypes.c_char_p,+ ctypes.c_char_p,+ ctypes.c_char_p,+ ]+ self.lib.AGFS_Mount.restype = ctypes.c_char_p++ self.lib.AGFS_Unmount.argtypes = [ctypes.c_int64, ctypes.c_char_p]+ self.lib.AGFS_Unmount.restype = ctypes.c_char_p++ self.lib.AGFS_LoadPlugin.argtypes = [ctypes.c_int64, ctypes.c_char_p]+ self.lib.AGFS_LoadPlugin.restype = ctypes.c_char_p++ self.lib.AGFS_UnloadPlugin.argtypes = [ctypes.c_int64, ctypes.c_char_p]+ self.lib.AGFS_UnloadPlugin.restype = ctypes.c_char_p++ self.lib.AGFS_ListPlugins.argtypes = [ctypes.c_int64]+ self.lib.AGFS_ListPlugins.restype = ctypes.c_char_p++ self.lib.AGFS_OpenHandle.argtypes = [+ ctypes.c_int64,+ ctypes.c_char_p,+ ctypes.c_int,+ ctypes.c_uint,+ ctypes.c_int,+ ]+ self.lib.AGFS_OpenHandle.restype = ctypes.c_int64++ self.lib.AGFS_CloseHandle.argtypes = [ctypes.c_int64]+ self.lib.AGFS_CloseHandle.restype = ctypes.c_char_p++ self.lib.AGFS_HandleRead.argtypes = [+ ctypes.c_int64,+ ctypes.c_int64,+ ctypes.c_int64,+ ctypes.c_int,+ ]+ self.lib.AGFS_HandleRead.restype = ctypes.c_char_p++ self.lib.AGFS_HandleWrite.argtypes = [+ ctypes.c_int64,+ ctypes.c_void_p,+ ctypes.c_int64,+ ctypes.c_int64,+ ctypes.c_int,+ ]+ self.lib.AGFS_HandleWrite.restype = ctypes.c_char_p++ self.lib.AGFS_HandleSeek.argtypes = [ctypes.c_int64, ctypes.c_int64, ctypes.c_int]+ self.lib.AGFS_HandleSeek.restype = ctypes.c_char_p++ self.lib.AGFS_HandleSync.argtypes = [ctypes.c_int64]+ self.lib.AGFS_HandleSync.restype = ctypes.c_char_p++ self.lib.AGFS_HandleStat.argtypes = [ctypes.c_int64]+ self.lib.AGFS_HandleStat.restype = ctypes.c_char_p++ self.lib.AGFS_ListHandles.argtypes = [ctypes.c_int64]+ self.lib.AGFS_ListHandles.restype = ctypes.c_char_p++ self.lib.AGFS_GetHandleInfo.argtypes = [ctypes.c_int64]+ self.lib.AGFS_GetHandleInfo.restype = ctypes.c_char_p+++class AGFSBindingClient:+ """Client for interacting with AGFS using Python binding (no HTTP server required).++ This client directly uses the AGFS server implementation through a shared library,+ providing better performance than the HTTP client by avoiding network overhead.++ The interface is compatible with the HTTP client (AGFSClient), allowing easy+ switching between implementations.+ """++ def __init__(self, config_path: Optional[str] = None):+ """+ Initialize AGFS binding client.++ Args:+ config_path: Optional path to configuration file (not used in binding mode).+ """+ self._lib = BindingLib()+ self._client_id = self._lib.lib.AGFS_NewClient()+ if self._client_id <= 0:+ raise AGFSClientError("Failed to create AGFS client")++ def __del__(self):+ if hasattr(self, "_client_id") and self._client_id > 0:+ try:+ self._lib.lib.AGFS_FreeClient(self._client_id)+ except Exception:+ pass++ def _parse_response(self, result: bytes) -> Dict[str, Any]:+ """Parse JSON response from the library."""+ if isinstance(result, bytes):+ result = result.decode("utf-8")+ data = json.loads(result)++ if "error_id" in data and data["error_id"] != 0:+ error_msg = self._lib.lib.AGFS_GetLastError(data["error_id"])+ if isinstance(error_msg, bytes):+ error_msg = error_msg.decode("utf-8")+ raise AGFSClientError(error_msg if error_msg else "Unknown error")++ return data++ def health(self) -> Dict[str, Any]:+ """Check client health."""+ result = self._lib.lib.AGFS_Health(self._client_id)+ return {"status": "healthy" if result == 1 else "unhealthy"}++ def get_capabilities(self) -> Dict[str, Any]:+ """Get client capabilities."""+ result = self._lib.lib.AGFS_GetCapabilities(self._client_id)+ return self._parse_response(result)++ def ls(self, path: str = "/") -> List[Dict[str, Any]]:+ """List directory contents."""+ result = self._lib.lib.AGFS_Ls(self._client_id, path.encode("utf-8"))+ data = self._parse_response(result)+ return data.get("files", [])++ def read(self, path: str, offset: int = 0, size: int = -1, stream: bool = False):+ return self.cat(path, offset, size, stream)++ def cat(self, path: str, offset: int = 0, size: int = -1, stream: bool = False):+ """Read file content with optional offset and size."""+ if stream:+ raise AGFSNotSupportedError("Streaming not supported in binding mode")++ result_ptr = ctypes.c_char_p()+ size_ptr = ctypes.c_int64()++ error_id = self._lib.lib.AGFS_Read(+ self._client_id,+ path.encode("utf-8"),+ ctypes.c_int64(offset),+ ctypes.c_int64(size),+ ctypes.byref(result_ptr),+ ctypes.byref(size_ptr),+ )++ if error_id < 0:+ error_msg = self._lib.lib.AGFS_GetLastError(error_id)+ if isinstance(error_msg, bytes):+ error_msg = error_msg.decode("utf-8")+ raise AGFSClientError(error_msg if error_msg else "Unknown error")++ if result_ptr:+ data = ctypes.string_at(result_ptr, size_ptr.value)+ return data++ return b""++ def write(+ self, path: str, data: Union[bytes, Iterator[bytes], BinaryIO], max_retries: int = 3+ ) -> str:+ """Write data to file."""+ if not isinstance(data, bytes):+ if hasattr(data, "read"):+ data = data.read()+ else:+ data = b"".join(data)++ result = self._lib.lib.AGFS_Write(+ self._client_id, path.encode("utf-8"), data, ctypes.c_int64(len(data))+ )+ resp = self._parse_response(result)+ return resp.get("message", "OK")++ def create(self, path: str) -> Dict[str, Any]:+ """Create a new file."""+ result = self._lib.lib.AGFS_Create(self._client_id, path.encode("utf-8"))+ return self._parse_response(result)++ def mkdir(self, path: str, mode: str = "755") -> Dict[str, Any]:+ """Create a directory."""+ mode_int = int(mode, 8)+ result = self._lib.lib.AGFS_Mkdir(+ self._client_id, path.encode("utf-8"), ctypes.c_uint(mode_int)+ )+ return self._parse_response(result)++ def rm(self, path: str, recursive: bool = False) -> Dict[str, Any]:+ """Remove a file or directory."""+ result = self._lib.lib.AGFS_Rm(self._client_id, path.encode("utf-8"), 1 if recursive else 0)+ return self._parse_response(result)++ def stat(self, path: str) -> Dict[str, Any]:+ """Get file/directory information."""+ result = self._lib.lib.AGFS_Stat(self._client_id, path.encode("utf-8"))+ return self._parse_response(result)++ def mv(self, old_path: str, new_path: str) -> Dict[str, Any]:+ """Rename/move a file or directory."""+ result = self._lib.lib.AGFS_Mv(+ self._client_id, old_path.encode("utf-8"), new_path.encode("utf-8")+ )+ return self._parse_response(result)++ def chmod(self, path: str, mode: int) -> Dict[str, Any]:+ """Change file permissions."""+ result = self._lib.lib.AGFS_Chmod(+ self._client_id, path.encode("utf-8"), ctypes.c_uint(mode)+ )+ return self._parse_response(result)++ def touch(self, path: str) -> Dict[str, Any]:+ """Touch a file."""+ result = self._lib.lib.AGFS_Touch(self._client_id, path.encode("utf-8"))+ return self._parse_response(result)++ def mounts(self) -> List[Dict[str, Any]]:+ """List all mounted plugins."""+ result = self._lib.lib.AGFS_Mounts(self._client_id)+ data = self._parse_response(result)+ return data.get("mounts", [])++ def mount(self, fstype: str, path: str, config: Dict[str, Any]) -> Dict[str, Any]:+ """Mount a plugin dynamically."""+ config_json = json.dumps(config)+ result = self._lib.lib.AGFS_Mount(+ self._client_id,+ fstype.encode("utf-8"),+ path.encode("utf-8"),+ config_json.encode("utf-8"),+ )+ return self._parse_response(result)++ def unmount(self, path: str) -> Dict[str, Any]:+ """Unmount a plugin."""+ result = self._lib.lib.AGFS_Unmount(self._client_id, path.encode("utf-8"))+ return self._parse_response(result)++ def load_plugin(self, library_path: str) -> Dict[str, Any]:+ """Load an external plugin."""+ result = self._lib.lib.AGFS_LoadPlugin(self._client_id, library_path.encode("utf-8"))+ return self._parse_response(result)++ def unload_plugin(self, library_path: str) -> Dict[str, Any]:+ """Unload an external plugin."""+ result = self._lib.lib.AGFS_UnloadPlugin(self._client_id, library_path.encode("utf-8"))+ return self._parse_response(result)++ def list_plugins(self) -> List[str]:+ """List all loaded external plugins."""+ result = self._lib.lib.AGFS_ListPlugins(self._client_id)+ data = self._parse_response(result)+ return data.get("loaded_plugins", [])++ def get_plugins_info(self) -> List[dict]:+ """Get detailed information about all loaded plugins."""+ return self.list_plugins()++ def grep(+ self,+ path: str,+ pattern: str,+ recursive: bool = False,+ case_insensitive: bool = False,+ stream: bool = False,+ ):+ """Search for a pattern in files."""+ raise AGFSNotSupportedError("Grep not supported in binding mode")++ def digest(self, path: str, algorithm: str = "xxh3") -> Dict[str, Any]:+ """Calculate the digest of a file."""+ raise AGFSNotSupportedError("Digest not supported in binding mode")++ def open_handle(+ self, path: str, flags: int = 0, mode: int = 0o644, lease: int = 60+ ) -> "FileHandle":+ """Open a file handle for stateful operations."""+ handle_id = self._lib.lib.AGFS_OpenHandle(+ self._client_id, path.encode("utf-8"), flags, ctypes.c_uint(mode), lease+ )++ if handle_id < 0:+ raise AGFSClientError("Failed to open handle")++ return FileHandle(self, handle_id, path, flags)++ def list_handles(self) -> List[Dict[str, Any]]:+ """List all active file handles."""+ result = self._lib.lib.AGFS_ListHandles(self._client_id)+ data = self._parse_response(result)+ return data.get("handles", [])++ def get_handle_info(self, handle_id: int) -> Dict[str, Any]:+ """Get information about a specific handle."""+ result = self._lib.lib.AGFS_GetHandleInfo(ctypes.c_int64(handle_id))+ return self._parse_response(result)++ def close_handle(self, handle_id: int) -> Dict[str, Any]:+ """Close a file handle."""+ result = self._lib.lib.AGFS_CloseHandle(ctypes.c_int64(handle_id))+ return self._parse_response(result)++ def handle_read(self, handle_id: int, size: int = -1, offset: Optional[int] = None) -> bytes:+ """Read from a file handle."""+ has_offset = 1 if offset is not None else 0+ offset_val = offset if offset is not None else 0++ result = self._lib.lib.AGFS_HandleRead(+ ctypes.c_int64(handle_id), ctypes.c_int64(size), ctypes.c_int64(offset_val), has_offset+ )++ if isinstance(result, bytes):+ return result++ data = json.loads(result.decode("utf-8") if isinstance(result, bytes) else result)+ if "error_id" in data and data["error_id"] != 0:+ error_msg = self._lib.lib.AGFS_GetLastError(data["error_id"])+ if isinstance(error_msg, bytes):+ error_msg = error_msg.decode("utf-8")+ raise AGFSClientError(error_msg if error_msg else "Unknown error")++ return result if isinstance(result, bytes) else result.encode("utf-8")++ def handle_write(self, handle_id: int, data: bytes, offset: Optional[int] = None) -> int:+ """Write to a file handle."""+ has_offset = 1 if offset is not None else 0+ offset_val = offset if offset is not None else 0++ result = self._lib.lib.AGFS_HandleWrite(+ ctypes.c_int64(handle_id),+ data,+ ctypes.c_int64(len(data)),+ ctypes.c_int64(offset_val),+ has_offset,+ )+ resp = self._parse_response(result)+ return resp.get("bytes_written", 0)++ def handle_seek(self, handle_id: int, offset: int, whence: int = 0) -> int:+ """Seek within a file handle."""+ result = self._lib.lib.AGFS_HandleSeek(+ ctypes.c_int64(handle_id), ctypes.c_int64(offset), whence+ )+ data = self._parse_response(result)+ return data.get("position", 0)++ def handle_sync(self, handle_id: int) -> Dict[str, Any]:+ """Sync a file handle."""+ result = self._lib.lib.AGFS_HandleSync(ctypes.c_int64(handle_id))+ return self._parse_response(result)++ def handle_stat(self, handle_id: int) -> Dict[str, Any]:+ """Get file info via handle."""+ result = self._lib.lib.AGFS_HandleStat(ctypes.c_int64(handle_id))+ return self._parse_response(result)++ def renew_handle(self, handle_id: int, lease: int = 60) -> Dict[str, Any]:+ """Renew the lease on a file handle."""+ return {"message": "lease renewed", "lease": lease}+++class FileHandle:+ """A file handle for stateful file operations.++ Supports context manager protocol for automatic cleanup.+ """++ O_RDONLY = 0+ O_WRONLY = 1+ O_RDWR = 2+ O_APPEND = 8+ O_CREATE = 16+ O_EXCL = 32+ O_TRUNC = 64++ SEEK_SET = 0+ SEEK_CUR = 1+ SEEK_END = 2++ def __init__(self, client: AGFSBindingClient, handle_id: int, path: str, flags: int):+ self._client = client+ self._handle_id = handle_id+ self._path = path+ self._flags = flags+ self._closed = False++ @property+ def handle_id(self) -> int:+ """The handle ID."""+ return self._handle_id++ @property+ def path(self) -> str:+ """The file path."""+ return self._path++ @property+ def flags(self) -> int:+ """The open flags (numeric)."""+ return self._flags++ @property+ def closed(self) -> bool:+ """Whether the handle is closed."""+ return self._closed++ def read(self, size: int = -1) -> bytes:+ """Read from current position."""+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_read(self._handle_id, size)++ def read_at(self, size: int, offset: int) -> bytes:+ """Read at specific offset (pread)."""+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_read(self._handle_id, size, offset)++ def write(self, data: bytes) -> int:+ """Write at current position."""+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_write(self._handle_id, data)++ def write_at(self, data: bytes, offset: int) -> int:+ """Write at specific offset (pwrite)."""+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_write(self._handle_id, data, offset)++ def seek(self, offset: int, whence: int = 0) -> int:+ """Seek to position."""+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_seek(self._handle_id, offset, whence)++ def tell(self) -> int:+ """Get current position."""+ return self.seek(0, self.SEEK_CUR)++ def sync(self) -> None:+ """Flush data to storage."""+ if self._closed:+ raise AGFSClientError("Handle is closed")+ self._client.handle_sync(self._handle_id)++ def stat(self) -> Dict[str, Any]:+ """Get file info."""+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_stat(self._handle_id)++ def info(self) -> Dict[str, Any]:+ """Get handle info."""+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.get_handle_info(self._handle_id)++ def renew(self, lease: int = 60) -> Dict[str, Any]:+ """Renew the handle lease."""+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.renew_handle(self._handle_id, lease)++ def close(self) -> None:+ """Close the handle."""+ if not self._closed:+ self._client.close_handle(self._handle_id)+ self._closed = True++ def __enter__(self) -> "FileHandle":+ return self++ def __exit__(self, exc_type, exc_val, exc_tb) -> None:+ self.close()++ def __repr__(self) -> str:+ status = "closed" if self._closed else "open"+ return f"FileHandle(id={self._handle_id}, path={self._path}, flags={self._flags}, {status})"diff --git a/openviking/pyagfs/client.py b/openviking/pyagfs/client.pynew file mode 100644index 000000000..d42817c5c--- /dev/null+++ b/openviking/pyagfs/client.py@@ -0,0 +1,1004 @@+"""AGFS Server API Client"""++import time+from typing import Any, BinaryIO, Dict, Iterator, List, Optional, Union++import requests+from requests.exceptions import ConnectionError, Timeout++from .exceptions import AGFSClientError, AGFSHTTPError, AGFSNotSupportedError+++class AGFSClient:+ """Client for interacting with AGFS (Plugin-based File System) Server API"""++ def __init__(self, api_base_url="http://localhost:8080", timeout=10):+ """+ Initialize AGFS client.++ Args:+ api_base_url: API base URL. Can be either full URL with "/api/v1" or just the base.+ If "/api/v1" is not present, it will be automatically appended.+ e.g., "http://localhost:8080" or "http://localhost:8080/api/v1"+ timeout: Request timeout in seconds (default: 10)+ """+ api_base_url = api_base_url.rstrip("/")+ # Auto-append /api/v1 if not present+ if not api_base_url.endswith("/api/v1"):+ api_base_url = api_base_url + "/api/v1"+ self.api_base = api_base_url+ self.session = requests.Session()+ self.timeout = timeout++ def _handle_request_error(self, e: Exception, operation: str = "request") -> None:+ """Convert request exceptions to user-friendly error messages"""+ if isinstance(e, ConnectionError):+ # Extract host and port from the error message+ url_parts = self.api_base.split("://")+ if len(url_parts) > 1:+ host_port = url_parts[1].split("/")[0]+ else:+ host_port = "server"+ raise AGFSClientError(f"Connection refused - server not running at {host_port}")+ elif isinstance(e, Timeout):+ raise AGFSClientError(f"Request timeout after {self.timeout}s")+ elif isinstance(e, requests.exceptions.HTTPError):+ # Extract useful error information from response+ if hasattr(e, "response") and e.response is not None:+ status_code = e.response.status_code++ # Special handling for 501 Not Implemented - always raise typed error+ if status_code == 501:+ try:+ error_data = e.response.json()+ error_msg = error_data.get("error", "Operation not supported")+ except (ValueError, KeyError, TypeError):+ error_msg = "Operation not supported"+ raise AGFSNotSupportedError(error_msg)++ # Try to get error message from JSON response first+ error_msg = None+ try:+ error_data = e.response.json()+ error_msg = error_data.get("error", "")+ except (ValueError, KeyError, TypeError):+ pass++ # Always use AGFSHTTPError to preserve status_code+ if error_msg:+ raise AGFSHTTPError(error_msg, status_code)+ elif status_code == 404:+ raise AGFSHTTPError("No such file or directory", status_code)+ elif status_code == 403:+ raise AGFSHTTPError("Permission denied", status_code)+ elif status_code == 409:+ raise AGFSHTTPError("Resource already exists", status_code)+ elif status_code == 500:+ raise AGFSHTTPError("Internal server error", status_code)+ elif status_code == 502:+ raise AGFSHTTPError("Bad Gateway - backend service unavailable", status_code)+ else:+ raise AGFSHTTPError(f"HTTP error {status_code}", status_code)+ else:+ raise AGFSHTTPError("HTTP error", None)+ else:+ # For other exceptions, re-raise with simplified message+ raise AGFSClientError(str(e))++ def health(self) -> Dict[str, Any]:+ """Check server health"""+ response = self.session.get(f"{self.api_base}/health", timeout=self.timeout)+ response.raise_for_status()+ return response.json()++ def get_capabilities(self) -> Dict[str, Any]:+ """Get server capabilities++ Returns:+ Dict containing 'version' and 'features' list.+ e.g., {'version': '1.4.0', 'features': ['handlefs', 'grep', ...]}+ """+ try:+ response = self.session.get(f"{self.api_base}/capabilities", timeout=self.timeout)++ # If capabilities endpoint doesn't exist (older server), return empty capabilities+ if response.status_code == 404:+ return {"version": "unknown", "features": []}++ response.raise_for_status()+ return response.json()+ except Exception as e:+ # If capabilities check fails, treat it as unknown/empty rather than error+ # unless it's a connection error+ if isinstance(e, ConnectionError):+ self._handle_request_error(e)+ return {"version": "unknown", "features": []}++ def ls(self, path: str = "/") -> List[Dict[str, Any]]:+ """List directory contents"""+ try:+ response = self.session.get(+ f"{self.api_base}/directories", params={"path": path}, timeout=self.timeout+ )+ response.raise_for_status()+ data = response.json()+ files = data.get("files")+ return files if files is not None else []+ except Exception as e:+ self._handle_request_error(e)++ def read(self, path: str, offset: int = 0, size: int = -1, stream: bool = False):+ return self.cat(path, offset, size, stream)++ def cat(self, path: str, offset: int = 0, size: int = -1, stream: bool = False):+ """Read file content with optional offset and size++ Args:+ path: File path+ offset: Starting position (default: 0)+ size: Number of bytes to read (default: -1, read all)+ stream: Enable streaming mode for continuous reads (default: False)++ Returns:+ If stream=False: bytes content+ If stream=True: Response object for iteration+ """+ try:+ params = {"path": path}++ if stream:+ params["stream"] = "true"+ # Streaming mode - return response object for iteration+ response = self.session.get(+ f"{self.api_base}/files",+ params=params,+ stream=True,+ timeout=None, # No timeout for streaming+ )+ response.raise_for_status()+ return response+ else:+ # Normal mode - return content+ if offset > 0:+ params["offset"] = str(offset)+ if size >= 0:+ params["size"] = str(size)++ response = self.session.get(+ f"{self.api_base}/files", params=params, timeout=self.timeout+ )+ response.raise_for_status()+ return response.content+ except Exception as e:+ self._handle_request_error(e)++ def write(+ self, path: str, data: Union[bytes, Iterator[bytes], BinaryIO], max_retries: int = 3+ ) -> str:+ """Write data to file and return the response message++ Args:+ path: Path to write the file+ data: File content as bytes, iterator of bytes, or file-like object+ max_retries: Maximum number of retry attempts (default: 3)++ Returns:+ Response message from server+ """+ # Calculate timeout based on file size (if known)+ # For streaming data, use a larger default timeout+ if isinstance(data, bytes):+ data_size_mb = len(data) / (1024 * 1024)+ write_timeout = max(10, min(300, int(data_size_mb * 1 + 10)))+ else:+ # For streaming/unknown size, use no timeout+ write_timeout = None++ last_error = None++ for attempt in range(max_retries + 1):+ try:+ response = self.session.put(+ f"{self.api_base}/files",+ params={"path": path},+ data=data, # requests supports bytes, iterator, or file-like object+ timeout=write_timeout,+ )+ response.raise_for_status()+ result = response.json()++ # If we succeeded after retrying, let user know+ if attempt > 0:+ print(f"✓ Upload succeeded after {attempt} retry(ies)")++ return result.get("message", "OK")++ except (ConnectionError, Timeout) as e:+ # Network errors and timeouts are retryable+ last_error = e++ if attempt < max_retries:+ # Exponential backoff: 1s, 2s, 4s+ wait_time = 2**attempt+ print(+ f"⚠ Upload failed (attempt {attempt + 1}/{max_retries + 1}): {type(e).__name__}"+ )+ print(f" Retrying in {wait_time} seconds...")+ time.sleep(wait_time)+ else:+ # Last attempt failed+ print(f"✗ Upload failed after {max_retries + 1} attempts")+ self._handle_request_error(e)++ except requests.exceptions.HTTPError as e:+ # Check if it's a server error (5xx) which might be retryable+ if hasattr(e, "response") and e.response is not None:+ status_code = e.response.status_code++ # Only retry specific server errors that indicate temporary issues+ # 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout+ # Do NOT retry 500 Internal Server Error (usually indicates business logic errors)+ retryable_5xx = [502, 503, 504]++ if status_code in retryable_5xx:+ last_error = e++ if attempt < max_retries:+ wait_time = 2**attempt+ print(+ f"⚠ Server error {status_code} (attempt {attempt + 1}/{max_retries + 1})"+ )+ print(f" Retrying in {wait_time} seconds...")+ time.sleep(wait_time)+ else:+ print(f"✗ Upload failed after {max_retries + 1} attempts")+ self._handle_request_error(e)+ else:+ # 500 and other errors (including 4xx) are not retryable+ # They usually indicate business logic errors or client mistakes+ self._handle_request_error(e)+ else:+ self._handle_request_error(e)++ except Exception as e:+ # Other exceptions are not retryable+ self._handle_request_error(e)++ # Should not reach here, but just in case+ if last_error:+ self._handle_request_error(last_error)++ def create(self, path: str) -> Dict[str, Any]:+ """Create a new file"""+ try:+ response = self.session.post(+ f"{self.api_base}/files", params={"path": path}, timeout=self.timeout+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def mkdir(self, path: str, mode: str = "755") -> Dict[str, Any]:+ """Create a directory"""+ try:+ response = self.session.post(+ f"{self.api_base}/directories",+ params={"path": path, "mode": mode},+ timeout=self.timeout,+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def rm(self, path: str, recursive: bool = False, force: bool = True) -> Dict[str, Any]:+ """Remove a file or directory.++ Args:+ path: Path to remove.+ recursive: Remove directories recursively.+ force: If True (default), ignore nonexistent files (like rm -f). Idempotent by default.+ """+ try:+ params = {"path": path}+ if recursive:+ params["recursive"] = "true"+ response = self.session.delete(+ f"{self.api_base}/files",+ params=params,+ timeout=self.timeout,+ )+ response.raise_for_status()+ return response.json()+ except requests.exceptions.HTTPError as e:+ if force and e.response is not None and e.response.status_code == 404:+ return {"message": "deleted"}+ self._handle_request_error(e)+ except Exception as e:+ self._handle_request_error(e)++ def stat(self, path: str) -> Dict[str, Any]:+ """Get file/directory information"""+ try:+ response = self.session.get(+ f"{self.api_base}/stat", params={"path": path}, timeout=self.timeout+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def mv(self, old_path: str, new_path: str) -> Dict[str, Any]:+ """Rename/move a file or directory"""+ try:+ response = self.session.post(+ f"{self.api_base}/rename",+ params={"path": old_path},+ json={"newPath": new_path},+ timeout=self.timeout,+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def chmod(self, path: str, mode: int) -> Dict[str, Any]:+ """Change file permissions"""+ try:+ response = self.session.post(+ f"{self.api_base}/chmod",+ params={"path": path},+ json={"mode": mode},+ timeout=self.timeout,+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def touch(self, path: str) -> Dict[str, Any]:+ """Touch a file (update timestamp by writing empty content)"""+ try:+ response = self.session.post(+ f"{self.api_base}/touch", params={"path": path}, timeout=self.timeout+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def mounts(self) -> List[Dict[str, Any]]:+ """List all mounted plugins"""+ try:+ response = self.session.get(f"{self.api_base}/mounts", timeout=self.timeout)+ response.raise_for_status()+ data = response.json()+ return data.get("mounts", [])+ except Exception as e:+ self._handle_request_error(e)++ def mount(self, fstype: str, path: str, config: Dict[str, Any]) -> Dict[str, Any]:+ """Mount a plugin dynamically++ Args:+ fstype: Filesystem type (e.g., 'sqlfs', 's3fs', 'memfs')+ path: Mount path+ config: Plugin configuration as dictionary++ Returns:+ Response with message+ """+ try:+ response = self.session.post(+ f"{self.api_base}/mount",+ json={"fstype": fstype, "path": path, "config": config},+ timeout=self.timeout,+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def unmount(self, path: str) -> Dict[str, Any]:+ """Unmount a plugin"""+ try:+ response = self.session.post(+ f"{self.api_base}/unmount", json={"path": path}, timeout=self.timeout+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def load_plugin(self, library_path: str) -> Dict[str, Any]:+ """Load an external plugin from a shared library or HTTP(S) URL++ Args:+ library_path: Path to the shared library (.so/.dylib/.dll) or HTTP(S) URL++ Returns:+ Response with message and plugin name+ """+ try:+ response = self.session.post(+ f"{self.api_base}/plugins/load",+ json={"library_path": library_path},+ timeout=self.timeout,+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def unload_plugin(self, library_path: str) -> Dict[str, Any]:+ """Unload an external plugin++ Args:+ library_path: Path to the shared library++ Returns:+ Response with message+ """+ try:+ response = self.session.post(+ f"{self.api_base}/plugins/unload",+ json={"library_path": library_path},+ timeout=self.timeout,+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def list_plugins(self) -> List[str]:+ """List all loaded external plugins++ Returns:+ List of plugin library paths+ """+ try:+ response = self.session.get(f"{self.api_base}/plugins", timeout=self.timeout)+ response.raise_for_status()+ data = response.json()++ # Support both old and new API formats+ if "loaded_plugins" in data:+ # Old format+ return data.get("loaded_plugins", [])+ elif "plugins" in data:+ # New format - extract library paths from external plugins only+ plugins = data.get("plugins", [])+ return [+ p.get("library_path", "")+ for p in plugins+ if p.get("is_external", False) and p.get("library_path")+ ]+ else:+ return []+ except Exception as e:+ self._handle_request_error(e)++ def get_plugins_info(self) -> List[dict]:+ """Get detailed information about all loaded plugins++ Returns:+ List of plugin info dictionaries with keys:+ - name: Plugin name+ - library_path: Path to plugin library (for external plugins)+ - is_external: Whether this is an external plugin+ - mounted_paths: List of mount point information+ - config_params: List of configuration parameters (name, type, required, default, description)+ """+ try:+ response = self.session.get(f"{self.api_base}/plugins", timeout=self.timeout)+ response.raise_for_status()+ data = response.json()+ return data.get("plugins", [])+ except Exception as e:+ self._handle_request_error(e)++ def grep(+ self,+ path: str,+ pattern: str,+ recursive: bool = False,+ case_insensitive: bool = False,+ stream: bool = False,+ node_limit: Optional[int] = None,+ ):+ """Search for a pattern in files using regular expressions++ Args:+ path: Path to file or directory to search+ pattern: Regular expression pattern to search for+ recursive: Whether to search recursively in directories (default: False)+ case_insensitive: Whether to perform case-insensitive matching (default: False)+ stream: Whether to stream results as NDJSON (default: False)+ node_limit: Maximum number of results to return (default: None)++ Returns:+ If stream=False: Dict with 'matches' (list of match objects) and 'count'+ If stream=True: Iterator yielding match dicts and a final summary dict++ Example (non-stream):+ >>> result = client.grep("/local/test-grep", "error", recursive=True)+ >>> print(result['count'])+ 2++ Example (stream):+ >>> for item in client.grep("/local/test-grep", "error", recursive=True, stream=True):+ ... if item.get('type') == 'summary':+ ... print(f"Total: {item['count']}")+ ... else:+ ... print(f"{item['file']}:{item['line']}: {item['content']}")+ """+ try:+ json_payload = {+ "path": path,+ "pattern": pattern,+ "recursive": recursive,+ "case_insensitive": case_insensitive,+ "stream": stream,+ }+ if node_limit is not None:+ json_payload["node_limit"] = node_limit+ response = self.session.post(+ f"{self.api_base}/grep",+ json=json_payload,+ timeout=None if stream else self.timeout,+ stream=stream,+ )+ response.raise_for_status()++ if stream:+ # Return iterator for streaming results+ return self._parse_ndjson_stream(response)+ else:+ # Return complete result+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def _parse_ndjson_stream(self, response):+ """Parse NDJSON streaming response line by line"""+ import json++ for line in response.iter_lines():+ if line:+ try:+ yield json.loads(line)+ except json.JSONDecodeError:+ # Skip malformed lines+ continue++ def digest(self, path: str, algorithm: str = "xxh3") -> Dict[str, Any]:+ """Calculate the digest of a file using specified algorithm++ Args:+ path: Path to the file+ algorithm: Hash algorithm to use - "xxh3" or "md5" (default: "xxh3")++ Returns:+ Dict with 'algorithm', 'path', and 'digest' keys++ Example:+ >>> result = client.digest("/local/file.txt", "xxh3")+ >>> print(result['digest'])+ abc123def456...++ >>> result = client.digest("/local/file.txt", "md5")+ >>> print(result['digest'])+ 5d41402abc4b2a76b9719d911017c592+ """+ try:+ response = self.session.post(+ f"{self.api_base}/digest",+ json={"algorithm": algorithm, "path": path},+ timeout=self.timeout,+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ # ==================== HandleFS API ====================+ # These APIs provide POSIX-like file handle operations for+ # filesystems that support stateful file access (e.g., seek, pread/pwrite)++ def open_handle(+ self, path: str, flags: int = 0, mode: int = 0o644, lease: int = 60+ ) -> "FileHandle":+ """Open a file handle for stateful operations++ Args:+ path: Path to the file+ flags: Open flags (0=O_RDONLY, 1=O_WRONLY, 2=O_RDWR, can OR with O_APPEND=8, O_CREATE=16, O_EXCL=32, O_TRUNC=64)+ mode: File mode for creation (default: 0644)+ lease: Lease duration in seconds (default: 60)++ Returns:+ FileHandle object for performing operations++ Example:+ >>> with client.open_handle("/memfs/file.txt", flags=2) as fh:+ ... data = fh.read(100)+ ... fh.seek(0)+ ... fh.write(b"Hello")+ """+ try:+ response = self.session.post(+ f"{self.api_base}/handles/open",+ params={"path": path, "flags": str(flags), "mode": str(mode), "lease": str(lease)},+ timeout=self.timeout,+ )+ response.raise_for_status()+ data = response.json()+ return FileHandle(self, data["handle_id"], path, data.get("flags", ""))+ except Exception as e:+ self._handle_request_error(e)++ def list_handles(self) -> List[Dict[str, Any]]:+ """List all active file handles++ Returns:+ List of handle info dicts with keys: handle_id, path, flags, lease, expires_at, created_at, last_access+ """+ try:+ response = self.session.get(f"{self.api_base}/handles", timeout=self.timeout)+ response.raise_for_status()+ data = response.json()+ return data.get("handles", [])+ except Exception as e:+ self._handle_request_error(e)++ def get_handle_info(self, handle_id: int) -> Dict[str, Any]:+ """Get information about a specific handle++ Args:+ handle_id: The handle ID (int64)++ Returns:+ Handle info dict+ """+ try:+ response = self.session.get(+ f"{self.api_base}/handles/{handle_id}", timeout=self.timeout+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def close_handle(self, handle_id: int) -> Dict[str, Any]:+ """Close a file handle++ Args:+ handle_id: The handle ID (int64) to close++ Returns:+ Response with message+ """+ try:+ response = self.session.delete(+ f"{self.api_base}/handles/{handle_id}", timeout=self.timeout+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def handle_read(self, handle_id: int, size: int = -1, offset: Optional[int] = None) -> bytes:+ """Read from a file handle++ Args:+ handle_id: The handle ID (int64)+ size: Number of bytes to read (default: -1, read all)+ offset: If specified, read at this offset (pread), otherwise read at current position++ Returns:+ bytes content+ """+ try:+ params = {"size": str(size)}+ if offset is not None:+ params["offset"] = str(offset)+ response = self.session.get(+ f"{self.api_base}/handles/{handle_id}/read", params=params, timeout=self.timeout+ )+ response.raise_for_status()+ return response.content+ except Exception as e:+ self._handle_request_error(e)++ def handle_write(self, handle_id: int, data: bytes, offset: Optional[int] = None) -> int:+ """Write to a file handle++ Args:+ handle_id: The handle ID (int64)+ data: Data to write+ offset: If specified, write at this offset (pwrite), otherwise write at current position++ Returns:+ Number of bytes written+ """+ try:+ params = {}+ if offset is not None:+ params["offset"] = str(offset)+ response = self.session.put(+ f"{self.api_base}/handles/{handle_id}/write",+ params=params,+ data=data,+ timeout=self.timeout,+ )+ response.raise_for_status()+ result = response.json()+ return result.get("bytes_written", 0)+ except Exception as e:+ self._handle_request_error(e)++ def handle_seek(self, handle_id: int, offset: int, whence: int = 0) -> int:+ """Seek within a file handle++ Args:+ handle_id: The handle ID (int64)+ offset: Offset to seek to+ whence: 0=SEEK_SET, 1=SEEK_CUR, 2=SEEK_END++ Returns:+ New position+ """+ try:+ response = self.session.post(+ f"{self.api_base}/handles/{handle_id}/seek",+ params={"offset": str(offset), "whence": str(whence)},+ timeout=self.timeout,+ )+ response.raise_for_status()+ result = response.json()+ return result.get("position", 0)+ except Exception as e:+ self._handle_request_error(e)++ def handle_sync(self, handle_id: int) -> Dict[str, Any]:+ """Sync a file handle (flush to storage)++ Args:+ handle_id: The handle ID (int64)++ Returns:+ Response with message+ """+ try:+ response = self.session.post(+ f"{self.api_base}/handles/{handle_id}/sync", timeout=self.timeout+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def handle_stat(self, handle_id: int) -> Dict[str, Any]:+ """Get file info via handle++ Args:+ handle_id: The handle ID (int64)++ Returns:+ File info dict+ """+ try:+ response = self.session.get(+ f"{self.api_base}/handles/{handle_id}/stat", timeout=self.timeout+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)++ def renew_handle(self, handle_id: int, lease: int = 60) -> Dict[str, Any]:+ """Renew the lease on a file handle++ Args:+ handle_id: The handle ID (int64)+ lease: New lease duration in seconds++ Returns:+ Response with new expires_at+ """+ try:+ response = self.session.post(+ f"{self.api_base}/handles/{handle_id}/renew",+ params={"lease": str(lease)},+ timeout=self.timeout,+ )+ response.raise_for_status()+ return response.json()+ except Exception as e:+ self._handle_request_error(e)+++class FileHandle:+ """A file handle for stateful file operations++ Supports context manager protocol for automatic cleanup.++ Example:+ >>> with client.open_handle("/memfs/file.txt", flags=2) as fh:+ ... fh.write(b"Hello World")+ ... fh.seek(0)+ ... print(fh.read())+ """++ # Open flag constants+ O_RDONLY = 0+ O_WRONLY = 1+ O_RDWR = 2+ O_APPEND = 8+ O_CREATE = 16+ O_EXCL = 32+ O_TRUNC = 64++ # Seek whence constants+ SEEK_SET = 0+ SEEK_CUR = 1+ SEEK_END = 2++ def __init__(self, client: AGFSClient, handle_id: int, path: str, flags: int):+ self._client = client+ self._handle_id = handle_id+ self._path = path+ self._flags = flags+ self._closed = False++ @property+ def handle_id(self) -> int:+ """The handle ID (int64)"""+ return self._handle_id++ @property+ def path(self) -> str:+ """The file path"""+ return self._path++ @property+ def flags(self) -> int:+ """The open flags (numeric)"""+ return self._flags++ @property+ def closed(self) -> bool:+ """Whether the handle is closed"""+ return self._closed++ def read(self, size: int = -1) -> bytes:+ """Read from current position++ Args:+ size: Number of bytes to read (default: -1, read all)++ Returns:+ bytes content+ """+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_read(self._handle_id, size)++ def read_at(self, size: int, offset: int) -> bytes:+ """Read at specific offset (pread)++ Args:+ size: Number of bytes to read+ offset: Offset to read from++ Returns:+ bytes content+ """+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_read(self._handle_id, size, offset)++ def write(self, data: bytes) -> int:+ """Write at current position++ Args:+ data: Data to write++ Returns:+ Number of bytes written+ """+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_write(self._handle_id, data)++ def write_at(self, data: bytes, offset: int) -> int:+ """Write at specific offset (pwrite)++ Args:+ data: Data to write+ offset: Offset to write at++ Returns:+ Number of bytes written+ """+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_write(self._handle_id, data, offset)++ def seek(self, offset: int, whence: int = 0) -> int:+ """Seek to position++ Args:+ offset: Offset to seek to+ whence: SEEK_SET(0), SEEK_CUR(1), or SEEK_END(2)++ Returns:+ New position+ """+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_seek(self._handle_id, offset, whence)++ def tell(self) -> int:+ """Get current position++ Returns:+ Current position+ """+ return self.seek(0, self.SEEK_CUR)++ def sync(self) -> None:+ """Flush data to storage"""+ if self._closed:+ raise AGFSClientError("Handle is closed")+ self._client.handle_sync(self._handle_id)++ def stat(self) -> Dict[str, Any]:+ """Get file info++ Returns:+ File info dict+ """+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.handle_stat(self._handle_id)++ def info(self) -> Dict[str, Any]:+ """Get handle info++ Returns:+ Handle info dict+ """+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.get_handle_info(self._handle_id)++ def renew(self, lease: int = 60) -> Dict[str, Any]:+ """Renew the handle lease++ Args:+ lease: New lease duration in seconds++ Returns:+ Response with new expires_at+ """+ if self._closed:+ raise AGFSClientError("Handle is closed")+ return self._client.renew_handle(self._handle_id, lease)++ def close(self) -> None:+ """Close the handle"""+ if not self._closed:+ self._client.close_handle(self._handle_id)+ self._closed = True++ def __enter__(self) -> "FileHandle":+ return self++ def __exit__(self, exc_type, exc_val, exc_tb) -> None:+ self.close()++ def __repr__(self) -> str:+ status = "closed" if self._closed else "open"+ return f"FileHandle(id={self._handle_id}, path={self._path}, flags={self._flags}, {status})"diff --git a/openviking/pyagfs/exceptions.py b/openviking/pyagfs/exceptions.pynew file mode 100644index 000000000..7247215c9--- /dev/null+++ b/openviking/pyagfs/exceptions.py@@ -0,0 +1,33 @@+"""Exception classes for pyagfs"""+++class AGFSClientError(Exception):+ """Base exception for AGFS client errors"""++ pass+++class AGFSConnectionError(AGFSClientError):+ """Connection related errors"""++ pass+++class AGFSTimeoutError(AGFSClientError):+ """Timeout errors"""++ pass+++class AGFSHTTPError(AGFSClientError):+ """HTTP related errors"""++ def __init__(self, message, status_code=None):+ super().__init__(message)+ self.status_code = status_code+++class AGFSNotSupportedError(AGFSClientError):+ """Operation not supported by the server or filesystem (HTTP 501)"""++ passdiff --git a/openviking/pyagfs/helpers.py b/openviking/pyagfs/helpers.pynew file mode 100644index 000000000..19881f27e--- /dev/null+++ b/openviking/pyagfs/helpers.py@@ -0,0 +1,291 @@+"""Helper functions for common file operations in AGFS.++This module provides high-level helper functions for common operations:+- cp: Copy files/directories within AGFS+- upload: Upload files/directories from local filesystem to AGFS+- download: Download files/directories from AGFS to local filesystem+"""++from pathlib import Path+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from .client import AGFSClient+++def cp(+ client: "AGFSClient", src: str, dst: str, recursive: bool = False, stream: bool = False+) -> None:+ """Copy a file or directory within AGFS.++ Args:+ client: AGFSClient instance+ src: Source path in AGFS+ dst: Destination path in AGFS+ recursive: If True, copy directories recursively+ stream: If True, use streaming for large files (memory efficient)++ Raises:+ AGFSClientError: If source doesn't exist or operation fails++ Examples:+ >>> client = AGFSClient("http://localhost:8080")+ >>> cp(client, "/file.txt", "/backup/file.txt") # Copy file+ >>> cp(client, "/dir", "/backup/dir", recursive=True) # Copy directory+ """+ # Check if source exists and get its type+ src_info = client.stat(src)+ is_dir = src_info.get("isDir", False)++ if is_dir:+ if not recursive:+ raise ValueError(f"Cannot copy directory '{src}' without recursive=True")+ _copy_directory(client, src, dst, stream)+ else:+ _copy_file(client, src, dst, stream)+++def upload(+ client: "AGFSClient",+ local_path: str,+ remote_path: str,+ recursive: bool = False,+ stream: bool = False,+) -> None:+ """Upload a file or directory from local filesystem to AGFS.++ Args:+ client: AGFSClient instance+ local_path: Path to local file or directory+ remote_path: Destination path in AGFS+ recursive: If True, upload directories recursively+ stream: If True, use streaming for large files (memory efficient)++ Raises:+ FileNotFoundError: If local path doesn't exist+ AGFSClientError: If upload fails++ Examples:+ >>> client = AGFSClient("http://localhost:8080")+ >>> upload(client, "/tmp/file.txt", "/remote/file.txt") # Upload file+ >>> upload(client, "/tmp/data", "/remote/data", recursive=True) # Upload directory+ """+ local = Path(local_path)++ if not local.exists():+ raise FileNotFoundError(f"Local path does not exist: {local_path}")++ if local.is_dir():+ if not recursive:+ raise ValueError(f"Cannot upload directory '{local_path}' without recursive=True")+ _upload_directory(client, local, remote_path, stream)+ else:+ _upload_file(client, local, remote_path, stream)+++def download(+ client: "AGFSClient",+ remote_path: str,+ local_path: str,+ recursive: bool = False,+ stream: bool = False,+) -> None:+ """Download a file or directory from AGFS to local filesystem.++ Args:+ client: AGFSClient instance+ remote_path: Path in AGFS+ local_path: Destination path on local filesystem+ recursive: If True, download directories recursively+ stream: If True, use streaming for large files (memory efficient)++ Raises:+ AGFSClientError: If remote path doesn't exist or download fails++ Examples:+ >>> client = AGFSClient("http://localhost:8080")+ >>> download(client, "/remote/file.txt", "/tmp/file.txt") # Download file+ >>> download(client, "/remote/data", "/tmp/data", recursive=True) # Download directory+ """+ # Check if remote path exists and get its type+ remote_info = client.stat(remote_path)+ is_dir = remote_info.get("isDir", False)++ if is_dir:+ if not recursive:+ raise ValueError(f"Cannot download directory '{remote_path}' without recursive=True")+ _download_directory(client, remote_path, Path(local_path), stream)+ else:+ _download_file(client, remote_path, Path(local_path), stream)+++# Internal helper functions+++def _copy_file(client: "AGFSClient", src: str, dst: str, stream: bool) -> None:+ """Copy a single file within AGFS."""+ # Ensure parent directory exists+ _ensure_remote_parent_dir(client, dst)++ if stream:+ # Stream the file content for memory efficiency+ response = client.cat(src, stream=True)+ # Read and write in chunks+ chunk_size = 8192+ chunks = []+ for chunk in response.iter_content(chunk_size=chunk_size):+ chunks.append(chunk)+ data = b"".join(chunks)+ client.write(dst, data)+ else:+ # Read entire file and write+ data = client.cat(src)+ client.write(dst, data)+++def _copy_directory(client: "AGFSClient", src: str, dst: str, stream: bool) -> None:+ """Recursively copy a directory within AGFS."""+ # Create destination directory+ try:+ client.mkdir(dst)+ except Exception:+ # Directory might already exist, continue+ pass++ # List source directory contents+ items = client.ls(src)++ for item in items:+ item_name = item["name"]+ src_path = f"{src.rstrip('/')}/{item_name}"+ dst_path = f"{dst.rstrip('/')}/{item_name}"++ if item.get("isDir", False):+ # Recursively copy subdirectory+ _copy_directory(client, src_path, dst_path, stream)+ else:+ # Copy file+ _copy_file(client, src_path, dst_path, stream)+++def _upload_file(client: "AGFSClient", local_file: Path, remote_path: str, stream: bool) -> None:+ """Upload a single file to AGFS."""+ # Ensure parent directory exists in AGFS+ _ensure_remote_parent_dir(client, remote_path)++ if stream:+ # Read file in chunks for memory efficiency+ chunk_size = 8192+ chunks = []+ with open(local_file, "rb") as f:+ while True:+ chunk = f.read(chunk_size)+ if not chunk:+ break+ chunks.append(chunk)+ data = b"".join(chunks)+ client.write(remote_path, data)+ else:+ # Read entire file+ with open(local_file, "rb") as f:+ data = f.read()+ client.write(remote_path, data)+++def _upload_directory(+ client: "AGFSClient", local_dir: Path, remote_path: str, stream: bool+) -> None:+ """Recursively upload a directory to AGFS."""+ # Create remote directory+ try:+ client.mkdir(remote_path)+ except Exception:+ # Directory might already exist, continue+ pass++ # Walk through local directory+ for item in local_dir.iterdir():+ remote_item_path = f"{remote_path.rstrip('/')}/{item.name}"++ if item.is_dir():+ # Recursively upload subdirectory+ _upload_directory(client, item, remote_item_path, stream)+ else:+ # Upload file+ _upload_file(client, item, remote_item_path, stream)+++def _download_file(client: "AGFSClient", remote_path: str, local_file: Path, stream: bool) -> None:+ """Download a single file from AGFS."""+ # Ensure parent directory exists locally+ local_file.parent.mkdir(parents=True, exist_ok=True)++ if stream:+ # Stream the file content+ response = client.cat(remote_path, stream=True)+ with open(local_file, "wb") as f:+ for chunk in response.iter_content(chunk_size=8192):+ f.write(chunk)+ else:+ # Read entire file+ data = client.cat(remote_path)+ with open(local_file, "wb") as f:+ f.write(data)+++def _download_directory(+ client: "AGFSClient", remote_path: str, local_dir: Path, stream: bool+) -> None:+ """Recursively download a directory from AGFS."""+ # Create local directory+ local_dir.mkdir(parents=True, exist_ok=True)++ # List remote directory contents+ items = client.ls(remote_path)++ for item in items:+ item_name = item["name"]+ remote_item_path = f"{remote_path.rstrip('/')}/{item_name}"+ local_item_path = local_dir / item_name++ if item.get("isDir", False):+ # Recursively download subdirectory+ _download_directory(client, remote_item_path, local_item_path, stream)+ else:+ # Download file+ _download_file(client, remote_item_path, local_item_path, stream)+++def _ensure_remote_parent_dir(client: "AGFSClient", path: str) -> None:+ """Ensure the parent directory exists for a remote path."""+ parent = "/".join(path.rstrip("/").split("/")[:-1])+ if parent and parent != "/":+ # Try to create parent directory (and its parents)+ _ensure_remote_dir_recursive(client, parent)+++def _ensure_remote_dir_recursive(client: "AGFSClient", path: str) -> None:+ """Recursively ensure a directory exists in AGFS."""+ if not path or path == "/":+ return++ # Check if directory already exists+ try:+ info = client.stat(path)+ if info.get("isDir", False):+ return # Directory exists+ except Exception:+ # Directory doesn't exist, need to create it+ pass++ # Ensure parent exists first+ parent = "/".join(path.rstrip("/").split("/")[:-1])+ if parent and parent != "/":+ _ensure_remote_dir_recursive(client, parent)++ # Create this directory+ try:+ client.mkdir(path)+ except Exception:+ # Might already exist due to race condition, ignore+ passdiff --git a/openviking/server/api_keys.py b/openviking/server/api_keys.pyindex 4064baa21..8ee62e758 100644--- a/openviking/server/api_keys.py+++ b/openviking/server/api_keys.py@@ -9,8 +9,7 @@ from dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom typing import Dict, Optional-from pyagfs import AGFSClient-+from openviking.pyagfs import AGFSClientfrom openviking.server.identity import ResolvedIdentity, Rolefrom openviking_cli.exceptions import (AlreadyExistsError,diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.pyindex 51bbeb87f..97b9297ff 100644--- a/openviking/server/routers/filesystem.py+++ b/openviking/server/routers/filesystem.py@@ -5,9 +5,9 @@from typing import Optionalfrom fastapi import APIRouter, Depends, Query-from pyagfs.exceptions import AGFSClientErrorfrom pydantic import BaseModel+from openviking.pyagfs.exceptions import AGFSClientErrorfrom openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_servicefrom openviking.server.identity import RequestContextdiff --git a/openviking/storage/queuefs/named_queue.py b/openviking/storage/queuefs/named_queue.pyindex ca0e9b297..ad79202b0 100644--- a/openviking/storage/queuefs/named_queue.py+++ b/openviking/storage/queuefs/named_queue.py@@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Unionfrom openviking_cli.utils.logger import get_loggerif TYPE_CHECKING:- from pyagfs import AGFSClient+ from openviking.pyagfs import AGFSClientlogger = get_logger(__name__)diff --git a/openviking/storage/transaction/path_lock.py b/openviking/storage/transaction/path_lock.pyindex c4f959b67..1a2ad7b0d 100644--- a/openviking/storage/transaction/path_lock.py+++ b/openviking/storage/transaction/path_lock.py@@ -10,8 +10,7 @@ Lock protocol: viking://resources/.../.path.ovlock file exists = lockedimport asynciofrom typing import List, Optional-from pyagfs import AGFSClient-+from openviking.pyagfs import AGFSClientfrom openviking.storage.transaction.transaction_record import TransactionRecordfrom openviking_cli.utils.logger import get_loggerdiff --git a/openviking/storage/transaction/transaction_manager.py b/openviking/storage/transaction/transaction_manager.pyindex 80f261619..da76cde7d 100644--- a/openviking/storage/transaction/transaction_manager.py+++ b/openviking/storage/transaction/transaction_manager.py@@ -11,8 +11,7 @@ import threadingimport timefrom typing import Any, Dict, Optional-from pyagfs import AGFSClient-+from openviking.pyagfs import AGFSClientfrom openviking.storage.transaction.path_lock import PathLockfrom openviking.storage.transaction.transaction_record import (TransactionRecord,diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.pyindex 06b69b1ed..873d5bd2f 100644--- a/openviking/storage/viking_fs.py+++ b/openviking/storage/viking_fs.py@@ -22,8 +22,7 @@ from datetime import datetimefrom pathlib import PurePathfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Union-from pyagfs.exceptions import AGFSHTTPError-+from openviking.pyagfs.exceptions import AGFSHTTPErrorfrom openviking.server.identity import RequestContext, Rolefrom openviking.utils.time_utils import format_simplified, get_current_timestamp, parse_iso_datetimefrom openviking_cli.exceptions import NotFoundErrordiff --git a/openviking/utils/agfs_utils.py b/openviking/utils/agfs_utils.pyindex 535f86d54..511cf2d04 100644--- a/openviking/utils/agfs_utils.py+++ b/openviking/utils/agfs_utils.py@@ -30,7 +30,7 @@ def create_agfs_client(agfs_config: Any) -> Any:if mode == "binding-client":# Import binding client if mode is binding-client- from pyagfs import AGFSBindingClient+ from openviking.pyagfs import AGFSBindingClientif AGFSBindingClient is None:raise ImportError(@@ -47,7 +47,7 @@ def create_agfs_client(agfs_config: Any) -> Any:# Check if binding library existstry:- from pyagfs.binding_client import _find_library+ from openviking.pyagfs.binding_client import _find_libraryactual_lib_path = _find_library()except Exception:@@ -56,7 +56,7 @@ def create_agfs_client(agfs_config: Any) -> Any:)client = AGFSBindingClient()- logger.debug(f"[AGFSUtils] Created AGFSBindingClient (lib_path={actual_lib_path})")+ logger.info(f"[AGFSUtils] Created AGFSBindingClient (lib_path={actual_lib_path})")# Automatically mount backend for binding clientmount_agfs_backend(client, agfs_config)@@ -64,7 +64,7 @@ def create_agfs_client(agfs_config: Any) -> Any:return clientelse:# Default to http-client- from pyagfs import AGFSClient+ from openviking.pyagfs import AGFSClienturl = getattr(agfs_config, "url", "http://localhost:8080")timeout = getattr(agfs_config, "timeout", 10)@@ -81,9 +81,8 @@ def mount_agfs_backend(agfs: Any, agfs_config: Any) -> None:agfs: AGFS client instance (HTTP or Binding).agfs_config: AGFS configuration object containing backend settings."""- from pyagfs import AGFSBindingClient-from openviking.agfs_manager import AGFSManager+ from openviking.pyagfs import AGFSBindingClient# Only binding-client needs manual mounting. HTTP server handles its own mounting.if AGFSBindingClient is None or not isinstance(agfs, AGFSBindingClient):diff --git a/openviking_cli/utils/config/agfs_config.py b/openviking_cli/utils/config/agfs_config.pyindex 2f2df7c81..8e3061fef 100644--- a/openviking_cli/utils/config/agfs_config.py+++ b/openviking_cli/utils/config/agfs_config.py@@ -85,7 +85,7 @@ class AGFSConfig(BaseModel):)mode: str = Field(- default="http-client",+ default="binding-client",description="AGFS client mode: 'http-client' | 'binding-client'",)diff --git a/pyproject.toml b/pyproject.tomlindex 84067240f..610364ac6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -46,7 +46,6 @@ dependencies = ["apscheduler>=3.11.0","volcengine>=1.0.216","volcengine-python-sdk[ark]>=5.0.3",- "pyagfs","fastapi>=0.128.0","uvicorn>=0.39.0","xxhash>=3.0.0",diff --git a/setup.py b/setup.pyindex 17e1e5846..9f116d3b6 100644--- a/setup.py+++ b/setup.py@@ -312,9 +312,9 @@ class CMakeBuildExtension(build_ext):setup(- install_requires=[- f"pyagfs @ file://localhost/{os.path.abspath('third_party/agfs/agfs-sdk/python')}"- ],+ # install_requires=[+ # f"pyagfs @ file://localhost/{os.path.abspath('third_party/agfs/agfs-sdk/python')}"+ # ],ext_modules=[Extension(name="openviking.storage.vectordb.engine",