Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
Feat: CLI optimization (#389)
MaojiaShenge4b1ffed10d3
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex be9c68709..937719b06 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -369,13 +369,13 @@ impl HttpClient {&self,query: String,uri: String,- limit: i32,+ node_limit: i32,threshold: Option<f64>,) -> Result<serde_json::Value> {let body = serde_json::json!({"query": query,"target_uri": uri,- "limit": limit,+ "limit": node_limit,"score_threshold": threshold,});self.post("/api/v1/search/find", &body).await@@ -386,28 +386,30 @@ impl HttpClient {query: String,uri: String,session_id: Option<String>,- limit: i32,+ node_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,+ "limit": node_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> {+ pub async fn grep(&self, uri: &str, pattern: &str, ignore_case: bool, node_limit: i32) -> Result<serde_json::Value> {let body = serde_json::json!({"uri": uri,"pattern": pattern,"case_insensitive": ignore_case,+ "node_limit": node_limit,});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,diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rsindex 45a4d00b7..ef68a17f4 100644--- a/crates/ov_cli/src/commands/search.rs+++ b/crates/ov_cli/src/commands/search.rs@@ -6,12 +6,12 @@ pub async fn find(client: &HttpClient,query: &str,uri: &str,- limit: i32,+ node_limit: i32,threshold: Option<f64>,output_format: OutputFormat,compact: bool,) -> Result<()> {- let result = client.find(query.to_string(), uri.to_string(), limit, threshold).await?;+ let result = client.find(query.to_string(), uri.to_string(), node_limit, threshold).await?;output_success(&result, output_format, compact);Ok(())}@@ -21,12 +21,12 @@ pub async fn search(query: &str,uri: &str,session_id: Option<String>,- limit: i32,+ node_limit: i32,threshold: Option<f64>,output_format: OutputFormat,compact: bool,) -> Result<()> {- let result = client.search(query.to_string(), uri.to_string(), session_id, limit, threshold).await?;+ let result = client.search(query.to_string(), uri.to_string(), session_id, node_limit, threshold).await?;output_success(&result, output_format, compact);Ok(())}@@ -36,14 +36,16 @@ pub async fn grep(uri: &str,pattern: &str,ignore_case: bool,+ node_limit: i32,output_format: OutputFormat,compact: bool,) -> Result<()> {- let result = client.grep(uri, pattern, ignore_case).await?;+ let result = client.grep(uri, pattern, ignore_case, node_limit).await?;output_success(&result, output_format, compact);Ok(())}+pub async fn glob(client: &HttpClient,pattern: &str,diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex affb78bfa..93b55461a 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -195,7 +195,7 @@ enum Commands {#[arg(short, long)]all: bool,/// Maximum number of nodes to list- #[arg(long = "node-limit", short = 'n', default_value = "256")]+ #[arg(long = "node-limit", short = 'n', alias = "limit", default_value = "256")]node_limit: i32,},/// Get directory tree@@ -209,7 +209,7 @@ enum Commands {#[arg(short, long)]all: bool,/// Maximum number of nodes to list- #[arg(long = "node-limit", short = 'n', default_value = "256")]+ #[arg(long = "node-limit", short = 'n', alias = "limit", default_value = "256")]node_limit: i32,/// Maximum depth level to traverse (default: 3)#[arg(short = 'L', long = "level-limit", default_value = "3")]@@ -265,8 +265,8 @@ enum Commands {#[arg(short, long, default_value = "")]uri: String,/// Maximum number of results- #[arg(short = 'n', long, default_value = "10")]- limit: i32,+ #[arg(short = 'n', long = "node-limit", alias = "limit", default_value = "10")]+ node_limit: i32,/// Score threshold#[arg(short, long)]threshold: Option<f64>,@@ -282,8 +282,8 @@ enum Commands {#[arg(long)]session_id: Option<String>,/// Maximum number of results- #[arg(short = 'n', long, default_value = "10")]- limit: i32,+ #[arg(short = 'n', long = "node-limit", alias = "limit", default_value = "10")]+ node_limit: i32,/// Score threshold#[arg(short, long)]threshold: Option<f64>,@@ -298,6 +298,9 @@ enum Commands {/// Case insensitive#[arg(short, long)]ignore_case: bool,+ /// Maximum number of results+ #[arg(short = 'n', long = "node-limit", alias = "limit", default_value = "256")]+ node_limit: i32,},/// Run file glob pattern searchGlob {@@ -562,15 +565,16 @@ async fn main() {Commands::Read { uri } => handle_read(uri, ctx).await,Commands::Abstract { uri } => handle_abstract(uri, ctx).await,Commands::Overview { uri } => handle_overview(uri, ctx).await,- Commands::Find { query, uri, limit, threshold } => {- handle_find(query, uri, limit, threshold, ctx).await+ Commands::Find { query, uri, node_limit, threshold } => {+ handle_find(query, uri, node_limit, threshold, ctx).await}- Commands::Search { query, uri, session_id, limit, threshold } => {- handle_search(query, uri, session_id, limit, threshold, ctx).await+ Commands::Search { query, uri, session_id, node_limit, threshold } => {+ handle_search(query, uri, session_id, node_limit, threshold, ctx).await}- Commands::Grep { uri, pattern, ignore_case } => {- handle_grep(uri, pattern, ignore_case, ctx).await+ Commands::Grep { uri, pattern, ignore_case, node_limit } => {+ handle_grep(uri, pattern, ignore_case, node_limit, ctx).await}+Commands::Glob { pattern, uri } => {handle_glob(pattern, uri, ctx).await}@@ -860,24 +864,24 @@ async fn handle_overview(uri: String, ctx: CliContext) -> Result<()> {async fn handle_find(query: String,uri: String,- limit: i32,+ node_limit: i32,threshold: Option<f64>,ctx: CliContext,) -> Result<()> {let client = ctx.get_client();- commands::search::find(&client, &query, &uri, limit, threshold, ctx.output_format, ctx.compact).await+ commands::search::find(&client, &query, &uri, node_limit, threshold, ctx.output_format, ctx.compact).await}async fn handle_search(query: String,uri: String,session_id: Option<String>,- limit: i32,+ node_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, ctx.compact).await+ commands::search::search(&client, &query, &uri, session_id, node_limit, threshold, ctx.output_format, ctx.compact).await}/// Print command with specified parameters for debugging@@ -938,11 +942,12 @@ async fn handle_stat(uri: String, ctx: CliContext) -> Result<()> {commands::filesystem::stat(&client, &uri, ctx.output_format, ctx.compact).await}-async fn handle_grep(uri: String, pattern: String, ignore_case: bool, ctx: CliContext) -> Result<()> {+async fn handle_grep(uri: String, pattern: String, ignore_case: bool, node_limit: i32, ctx: CliContext) -> Result<()> {let client = ctx.get_client();- commands::search::grep(&client, &uri, &pattern, ignore_case, ctx.output_format, ctx.compact).await+ commands::search::grep(&client, &uri, &pattern, ignore_case, node_limit, ctx.output_format, ctx.compact).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, ctx.compact).awaitdiff --git a/docs/design/server_client/prompt.md b/docs/design/server_client/prompt.mddeleted file mode 100644index 758d3c08f..000000000--- a/docs/design/server_client/prompt.md+++ /dev/null@@ -1,1244 +0,0 @@-# OpenViking Server/CLI 实现任务 Prompt--本文档包含各任务的 Agent Prompt,用于指导实现。-------## T1: Service 层抽取--### 目标-从 `async_client.py` 抽取业务逻辑到独立的 Service 层,使业务逻辑与传输层解耦。--### 背景-当前 `openviking/async_client.py` 包含了所有业务逻辑,需要将其抽取到 `openviking/service/` 目录下,便于 HTTP Server 和 CLI 复用。--### 任务详情--1. **创建 Service 层目录结构**:-```-openviking/service/-├── __init__.py-├── core.py # OpenVikingService 主类-├── fs_service.py # 文件系统操作-├── resource_service.py # 资源导入、技能添加-├── search_service.py # 语义搜索-├── session_service.py # 会话管理-├── relation_service.py # 关联管理-├── pack_service.py # 导入导出-└── debug_service.py # 调试服务-```--2. **抽取业务逻辑**:--- `FSService`: ls, tree, stat, mkdir, rm, mv, read, abstract, overview, grep, glob-- `ResourceService`: add_resource, add_skill, wait_processed-- `SearchService`: find, search-- `SessionService`: session, sessions, add_message, commit-- `RelationService`: link, unlink, relations-- `DebugService`: observer (ObserverService)-- `PackService`: export_ovpack, import_ovpack--3. **创建 OpenVikingService 主类**:-- 组合所有子 Service-- 管理 VikingFS、VectorIndex 等基础设施-- 提供统一的初始化和关闭方法--4. **修改 async_client.py**:-- 改为调用 Service 层-- 保持现有 API 不变(兼容层)--### 验收标准-- 现有单元测试全部通过-- `async_client.py` API 保持不变-- Service 层可独立使用--### 参考文件-- `openviking/async_client.py` - 现有实现-- `openviking/storage/viking_fs.py` - VikingFS 实现-- `design/server-cli-design.md` - 设计文档 4.1 节-------## T2: HTTP Server 实现--### 目标-基于 FastAPI 实现 HTTP Server,提供 RESTful API。--### 背景-参考 `design/server-cli-design.md` 第七节 HTTP API 设计。--### 任务详情--1. **创建 Server 目录结构**:-```-openviking/server/-├── __init__.py-├── app.py # FastAPI 应用入口-├── bootstrap.py # 服务启动器-├── config.py # 服务器配置-├── auth.py # API Key 认证-├── dependencies.py # 依赖注入-├── models.py # 响应模型、错误码-└── routers/- ├── __init__.py- ├── resources.py # /api/v1/resources- ├── filesystem.py # /api/v1/fs- ├── content.py # /api/v1/content- ├── search.py # /api/v1/search- ├── relations.py # /api/v1/relations- ├── sessions.py # /api/v1/sessions- ├── pack.py # /api/v1/pack- ├── system.py # /api/v1/system, /health- └── debug.py # /api/v1/debug-```--2. **实现统一响应格式**(参考设计文档 5.2 节):-```python-class Response(BaseModel):- status: str # "ok" | "error"- result: Optional[Any] = None- error: Optional[ErrorInfo] = None- time: float = 0.0- usage: Optional[UsageInfo] = None-```--3. **实现 API Key 认证**:-- 支持 `X-API-Key` header-- 支持 `Authorization: Bearer` header--4. **实现所有 API 端点**(参考设计文档 7.3 节):-- 资源管理: POST /api/v1/resources, POST /api/v1/skills-- 文件系统: GET /api/v1/fs/ls, GET /api/v1/fs/tree, etc.-- 内容读取: GET /api/v1/content/read, /abstract, /overview-- 搜索: POST /api/v1/search/find, /search, /grep, /glob-- 关联: POST /api/v1/relations/link, DELETE /api/v1/relations/link-- 会话: POST/GET/DELETE /api/v1/sessions-- 导入导出: POST /api/v1/pack/export, /import-- 系统: GET /health, GET /api/v1/system/status-- 调试: GET /api/v1/debug/status, GET /api/v1/debug/health--5. **实现服务启动器** (bootstrap.py):-- 加载配置文件 `ov.conf`(通过 `--config` 参数或 `OPENVIKING_CONFIG_FILE` 环境变量指定)-- 初始化 OpenVikingService-- 启动 uvicorn 服务器--### 验收标准-```bash-# 启动服务-openviking serve --config ./ov.conf --port 8000--# 验证 API-curl http://localhost:8000/health-curl -X POST http://localhost:8000/api/v1/resources \- -H "X-API-Key: test" -d '{"path": "./docs"}'-curl "http://localhost:8000/api/v1/fs/ls?uri=viking://" \- -H "X-API-Key: test"-```--### 依赖-- T1 (Service 层) 必须先完成--### 参考文件-- `design/server-cli-design.md` - 第七节-- `openviking/service/` - Service 层(T1 产出)-------## T3: CLI 基础框架--### 目标-使用 Typer 实现 CLI 核心命令。--### 背景-参考 `design/server-cli-design.md` 第六节 CLI 设计。--### 任务详情--1. **创建 CLI 目录结构**:-```-openviking/cli/-├── __init__.py-├── main.py # CLI 入口-├── output.py # 输出格式化(JSON/Table/Plain)-└── config.py # 配置管理(读取环境变量、配置文件)-```--2. **更新 pyproject.toml**:-```toml-[project.scripts]-openviking = "openviking_cli.cli.main:app"--[project.optional-dependencies]-cli = [- "typer>=0.9.0",- "rich>=13.0.0",-]-```--3. **实现核心命令**:-```bash-# 服务管理-openviking serve [--config <file>] [--port 1933] [--host 0.0.0.0]--# 调试命令-openviking status # 系统整体状态(包含 queue/vikingdb/vlm 组件状态)-openviking health # 快速健康检查--# 资源导入-openviking add-resource <path> [--to <uri>] [--wait] [--timeout N]--# 文件系统操作-openviking ls <uri> [--simple] [--recursive]--# 内容读取-openviking read <uri>-openviking abstract <uri>-openviking overview <uri>--# 搜索-openviking find <query> [<uri>] [--limit N] [--threshold F]-```--4. **实现配置管理**:-- CLI 连接信息通过 `ovcli.conf` 配置文件管理(url/api_key/user)-- 配置文件路径通过 `OPENVIKING_CLI_CONFIG_FILE` 环境变量指定-- 命令行参数(`--config`、`--host`、`--port`)优先于配置文件-- 不使用 `--url`、`--api-key` 等全局命令行选项--5. **实现输出格式化**:-- 支持 `--output json` 输出 JSON-- 默认使用 Rich 美化输出--### 验收标准-```bash-openviking --help-openviking serve --config ./ov.conf --port 1933-openviking add-resource ./docs/ --wait-openviking ls viking://resources/-openviking find "how to use"-```--### 依赖-- T1 (Service 层) 必须先完成--### 参考文件-- `design/server-cli-design.md` - 第六节-- `openviking/service/` - Service 层(T1 产出)-------## T4: Python SDK--### 目标-实现 HTTPClient,支持通过 HTTP 连接远程 Server。--### 背景-参考 `design/server-cli-design.md` 3.1 节分层架构和 6.2 节 Python SDK。--### 任务详情--1. **创建 Client 目录结构**:-```-openviking/client/-├── __init__.py-├── base.py # 客户端基类接口-├── local.py # LocalClient(直接调用 Service)-└── http.py # HTTPClient(HTTP 调用 Server)-```--2. **定义客户端接口** (base.py):-```python-class BaseClient(ABC):- @abstractmethod- async def ls(self, uri: str, simple: bool = False, recursive: bool = False) -> Response: ...- @abstractmethod- async def find(self, query: str, target_uri: str = "viking://", limit: int = 10) -> Response: ...- # ... 所有方法-```--3. **实现 HTTPClient** (http.py):-- 使用 httpx 进行 HTTP 调用-- 实现所有 API 端点的客户端方法-- 处理认证(API Key)-- 处理错误响应,转换为异常-- 实现 debug 方法(get_status, is_healthy):-```python-def get_status(self) -> SystemStatus:- """Get system status (same as LocalClient)."""- response = self._get("/api/v1/debug/status")- return SystemStatus(**response["result"])--def is_healthy(self) -> bool:- """Quick health check (same as LocalClient)."""- response = self._get("/api/v1/debug/health")- return response["healthy"]-```--4. **实现 LocalClient** (local.py):-- 直接调用 OpenVikingService-- 包装返回值为统一的 Response 格式--5. **修改 OpenViking 类**:-```python-class OpenViking:- def __init__(- self,- path: Optional[str] = None, # 嵌入式模式- url: Optional[str] = None, # HTTP 模式- api_key: Optional[str] = None,- user: Optional[str] = None,- ):- if url:- self._client = HTTPClient(url, api_key)- else:- self._client = LocalClient(path)-```--### 验收标准-```python-# HTTP 模式-client = OpenViking(url="http://localhost:8000", api_key="test")-results = client.find("how to use")--# 嵌入式模式(保持兼容)-client = OpenViking(path="./data")-results = client.find("how to use")-```--### 依赖-- T2 (HTTP Server) 必须先完成--### 参考文件-- `design/server-cli-design.md` - 3.1 节、6.2 节-- `openviking/server/` - HTTP Server(T2 产出)-------## T5: CLI 完整命令--### 目标-补全所有 CLI 命令。--### 背景-参考 `design/server-cli-design.md` 6.1 节命令列表。--### 任务详情--1. **会话管理命令**:-```bash-openviking session new [--user <name>]-openviking session list-openviking session get <id>-openviking session commit <id>-openviking session delete <id>-```--2. **文件系统命令**:-```bash-openviking tree <uri>-openviking stat <uri>-openviking mkdir <uri>-openviking rm <uri> [--recursive]-openviking mv <from> <to>-```--3. **搜索命令**:-```bash-openviking search <query> [<uri>] [--session-id ID] [--limit N]-openviking grep <uri> <pattern> [-i]-openviking glob <pattern> [<uri>]-```--4. **关联命令**:-```bash-openviking link <from> <to>... [--reason TEXT]-openviking unlink <from> <to>-openviking relations <uri>-```--5. **导入导出命令**:-```bash-openviking export <uri> <file.ovpack>-openviking import <file.ovpack> <uri> [--force] [--no-vectorize]-```--6. **配置命令**:-```bash-openviking config show-openviking config init-```--7. **工具命令**:-```bash-openviking wait [--timeout N]-openviking add-skill <file> [--wait]-```--### 验收标准-```bash-openviking --help # 显示所有命令-openviking session new --user alice-openviking session list-openviking export viking://resources/docs/ ./backup.ovpack-openviking config show-```--### 依赖-- T3 (CLI 基础框架) 必须先完成--### 参考文件-- `design/server-cli-design.md` - 6.1 节-- `openviking/cli/main.py` - CLI 基础框架(T3 产出)-------## T6: 集成测试--### 目标-编写端到端集成测试,验证 CLI、Server、Python SDK 的完整工作流程。--### 背景-参考 `design/server-cli-design.md` 8.5 节验证方案。--### 任务详情--1. **创建测试文件**:-```-tests/integration/-├── test_cli.py # CLI 命令测试-├── test_server.py # HTTP Server 测试-└── test_http_client.py # Python SDK 测试-```--2. **CLI 测试** (test_cli.py):-```python-def test_serve_command():- """测试 serve 命令启动服务"""- ...--def test_add_resource_command():- """测试 add-resource 命令"""- ...--def test_ls_command():- """测试 ls 命令"""- ...--def test_find_command():- """测试 find 命令"""- ...--def test_session_commands():- """测试 session 子命令"""- ...-```--3. **Server 测试** (test_server.py):-```python-async def server():- """启动测试服务器"""- ...--async def test_health_endpoint(server):- """测试 /health 端点"""- ...--async def test_resources_api(server):- """测试资源 API"""- ...--async def test_search_api(server):- """测试搜索 API"""- ...--async def test_auth_required(server):- """测试认证"""- ...-```--4. **Python SDK 测试** (test_http_client.py):-```python-async def test_http_client_find():- """测试 HTTP 客户端 find 方法"""- ...--async def test_http_client_session():- """测试 HTTP 客户端会话管理"""- ...--async def test_http_client_error_handling():- """测试错误处理"""- ...-```--5. **端到端工作流测试**:-```python-async def test_full_workflow():- """完整工作流测试"""- # 1. 启动 Server- # 2. 使用 Python SDK 连接- # 3. 添加资源- # 4. 搜索- # 5. 会话管理- # 6. 导出/导入- ...-```--### 验收标准-- 所有集成测试通过-- 覆盖主要使用场景-- 测试报告显示覆盖率--### 依赖-- T4 (Python SDK) 必须先完成-- T5 (CLI 完整命令) 必须先完成--### 参考文件-- `tests/` - 现有测试结构-- `tests/conftest.py` - pytest 配置-------## T7: 文档更新--### 目标-更新用户文档,包括 README、API 文档、CHANGELOG。--### 背景-参考 `design/server-cli-design.md` 6.3 节使用指南。--### 任务详情--1. **更新 README.md**:-- 添加 CLI 安装和使用说明-- 添加 Server 部署说明-- 添加 HTTP API 使用示例-- 更新架构图--2. **生成 OpenAPI 文档**:-- FastAPI 自动生成 `/docs` 和 `/redoc`-- 确保所有端点有完整的描述和示例--3. **更新 CHANGELOG.md**:-- 记录新增的 CLI 功能-- 记录新增的 HTTP API-- 记录 SDK 的 HTTP 模式支持--4. **添加使用示例**:-```markdown-## CLI 使用--### 启动服务-\`\`\`bash-openviking serve --config ./ov.conf --port 8000-\`\`\`--### 添加资源-\`\`\`bash-openviking add-resource ./docs/ --wait-\`\`\`--### 语义搜索-\`\`\`bash-openviking find "how to configure"-\`\`\`--## HTTP API 使用--### 健康检查-\`\`\`bash-curl http://localhost:8000/health-\`\`\`--### 搜索-\`\`\`bash-curl -X POST http://localhost:8000/api/v1/search/find \- -H "X-API-Key: your-key" \- -H "Content-Type: application/json" \- -d '{"query": "how to configure", "limit": 10}'-\`\`\`--## Python SDK (HTTP 模式)--\`\`\`python-from openviking import OpenViking--client = OpenViking(url="http://localhost:8000", api_key="your-key")-results = client.find("how to configure")-\`\`\`-```--### 验收标准-- README 包含完整的 CLI/Server/API 使用说明-- OpenAPI 文档可访问且完整-- CHANGELOG 记录所有变更--### 依赖-- T6 (集成测试) 必须先完成--### 参考文件-- `design/server-cli-design.md` - 6.3 节-- `README.md` - 现有文档-------## T8: Docker 部署--### 目标-提供 Docker 镜像和 docker-compose 配置,简化部署流程。--### 背景-Docker 是现代应用部署的标准方式,降低用户部署门槛。--### 任务详情--1. **创建 Dockerfile**:-```dockerfile-FROM python:3.11-slim--WORKDIR /app--# 安装依赖-COPY pyproject.toml .-RUN pip install .--# 复制代码-COPY openviking/ openviking/--# 暴露端口-EXPOSE 8000--# 启动命令-CMD ["openviking", "serve", "--host", "0.0.0.0", "--port", "8000"]-```--2. **创建 docker-compose.yml**:-```yaml-version: '3.8'--services:- openviking:- build: .- ports:- - "8000:8000"- volumes:- - openviking-data:/data- - ./ov.conf:/etc/openviking/ov.conf- environment:- - OPENVIKING_CONFIG_FILE=/etc/openviking/ov.conf- - OPENAI_API_KEY=${OPENAI_API_KEY}- restart: unless-stopped--volumes:- openviking-data:-```--3. **创建 .dockerignore**:-```-.git-.venv-__pycache__-*.pyc-.pytest_cache-.mypy_cache-tests/-docs/-*.md-```--4. **多阶段构建优化**(可选):-- 使用多阶段构建减小镜像体积-- 分离构建依赖和运行依赖--5. **发布到 Docker Hub / GitHub Container Registry**:-- 配置 GitHub Actions 自动构建和发布-- 支持多架构(amd64, arm64)--### 验收标准-```bash-# 构建镜像-docker build -t openviking .--# 运行容器-docker run -p 8000:8000 -e OPENAI_API_KEY=xxx openviking--# 使用 docker-compose-docker-compose up -d--# 验证服务-curl http://localhost:8000/health-```--### 依赖-- T2 (HTTP Server) 必须先完成--### 参考文件-- `pyproject.toml` - 依赖配置-- `openviking/server/` - Server 实现-------## T9: MCP Server 实现--### 目标-实现 Model Context Protocol (MCP) 服务端,让 Claude 等 AI 可以直接调用 OpenViking。--### 背景-MCP 是 Anthropic 推出的标准协议,允许 AI 模型与外部工具交互。实现 MCP Server 可以让 OpenViking 无缝集成到 Claude Desktop、Cursor 等支持 MCP 的应用中。--### 任务详情--1. **创建 MCP Server 目录结构**:-```-openviking/mcp/-├── __init__.py-├── server.py # MCP Server 主入口-├── tools.py # Tool 定义-└── resources.py # Resource 定义-```--2. **定义 MCP Tools**:-```python-# 核心 Tools-tools = [- {- "name": "openviking_find",- "description": "Semantic search in OpenViking context database",- "inputSchema": {- "type": "object",- "properties": {- "query": {"type": "string", "description": "Search query"},- "uri": {"type": "string", "description": "Target URI scope"},- "limit": {"type": "integer", "description": "Max results"}- },- "required": ["query"]- }- },- {- "name": "openviking_read",- "description": "Read content from OpenViking",- "inputSchema": {- "type": "object",- "properties": {- "uri": {"type": "string", "description": "Resource URI"}- },- "required": ["uri"]- }- },- {- "name": "openviking_ls",- "description": "List directory contents in OpenViking",- "inputSchema": {- "type": "object",- "properties": {- "uri": {"type": "string", "description": "Directory URI"}- },- "required": ["uri"]- }- },- # ... 更多 tools-]-```--3. **实现 MCP Server**:-```python-from mcp.server import Server-from mcp.types import Tool, TextContent--server = Server("openviking")-[email protected]_tools()-async def list_tools() -> list[Tool]:- return tools-[email protected]_tool()-async def call_tool(name: str, arguments: dict) -> list[TextContent]:- if name == "openviking_find":- result = await client.find(arguments["query"], ...)- return [TextContent(type="text", text=json.dumps(result))]- # ... 处理其他 tools-```--4. **支持 stdio 和 SSE 传输**:-- stdio: 用于 Claude Desktop 等本地应用-- SSE: 用于 Web 应用--5. **配置文件示例** (claude_desktop_config.json):-```json-{- "mcpServers": {- "openviking": {- "command": "openviking",- "args": ["mcp", "--path", "/path/to/data"]- }- }-}-```--6. **添加 CLI 命令**:-```bash-openviking mcp [--path <dir>] [--transport stdio|sse]-```--### 验收标准-- MCP Server 可以通过 stdio 启动-- Claude Desktop 可以成功连接并调用 tools-- 所有核心功能(find, read, ls, abstract, overview)可通过 MCP 调用--### 依赖-- T1 (Service 层) 必须先完成-- 建议 T3 (CLI 基础框架) 先完成--### 参考文件-- [MCP Specification](https://spec.modelcontextprotocol.io/)-- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)-- `openviking/service/` - Service 层-------## T10: TypeScript SDK--### 目标-基于 HTTP API 实现 TypeScript/JavaScript 客户端 SDK。--### 背景-TypeScript/JavaScript 是 Web 开发的主流语言,覆盖前端和 Node.js 后端开发者。--### 任务详情--1. **创建项目结构**:-```-openviking-js/-├── package.json-├── tsconfig.json-├── src/-│ ├── index.ts # 主入口-│ ├── client.ts # OpenViking 客户端-│ ├── types.ts # 类型定义-│ └── errors.ts # 错误类-├── tests/-│ └── client.test.ts-└── README.md-```--2. **实现客户端类**:-```typescript-// src/client.ts-export interface OpenVikingConfig {- url: string;- apiKey: string;- user?: string;- agent?: string;-}--export class OpenViking {- private config: OpenVikingConfig;-- constructor(config: OpenVikingConfig) {- this.config = config;- }-- async find(query: string, options?: FindOptions): Promise<SearchResult> {- const response = await fetch(`${this.config.url}/api/v1/search/find`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-API-Key': this.config.apiKey,- },- body: JSON.stringify({ query, ...options }),- });- return this.handleResponse(response);- }-- async ls(uri: string, options?: LsOptions): Promise<LsResult> { ... }- async read(uri: string): Promise<ReadResult> { ... }- async abstract(uri: string): Promise<ReadResult> { ... }- async overview(uri: string): Promise<ReadResult> { ... }- // ... 其他方法-}-```--3. **类型定义**:-```typescript-// src/types.ts-export interface Response<T> {- status: 'ok' | 'error';- result?: T;- error?: ErrorInfo;- time: number;-}--export interface SearchResult {- items: SearchItem[];- query: string;- total: number;-}--export interface SearchItem {- uri: string;- score: number;- content: string;- abstract?: string;-}--// ... 其他类型-```--4. **错误处理**:-```typescript-// src/errors.ts-export class OpenVikingError extends Error {- code: string;- details?: Record<string, unknown>;-- constructor(code: string, message: string, details?: Record<string, unknown>) {- super(message);- this.code = code;- this.details = details;- }-}--export class NotFoundError extends OpenVikingError {}-export class InvalidURIError extends OpenVikingError {}-// ... 其他错误类-```--5. **发布配置**:-```json-// package.json-{- "name": "@openviking/sdk",- "version": "1.0.0",- "main": "dist/index.js",- "types": "dist/index.d.ts",- "scripts": {- "build": "tsc",- "test": "jest"- }-}-```--### 验收标准-```typescript-import { OpenViking } from '@openviking/sdk';--const client = new OpenViking({- url: 'http://localhost:8000',- apiKey: 'your-api-key',-});--// 搜索-const results = await client.find('how to configure');-console.log(results.items);--// 读取-const content = await client.read('viking://resources/doc.md');-console.log(content);-```--### 依赖-- T2 (HTTP Server) 必须先完成--### 参考文件-- `design/server-cli-design.md` - 7.3 节 API 端点-- `openviking/server/models.py` - 响应模型定义-------## T11: Golang SDK--### 目标-基于 HTTP API 实现 Golang 客户端 SDK。--### 背景-Go 是云原生和基础设施领域的主流语言,覆盖 Kubernetes 生态和后端开发者。--### 任务详情--1. **创建项目结构**:-```-openviking-go/-├── go.mod-├── go.sum-├── client.go # 主客户端-├── types.go # 类型定义-├── errors.go # 错误定义-├── client_test.go # 测试-└── README.md-```--2. **实现客户端**:-```go-// client.go-package openviking--import (- "bytes"- "encoding/json"- "net/http"-)--type Config struct {- URL string- APIKey string- User string- Agent string-}--type Client struct {- config Config- httpClient *http.Client-}--func NewClient(config Config) *Client {- return &Client{- config: config,- httpClient: &http.Client{},- }-}--func (c *Client) Find(query string, opts *FindOptions) (*SearchResult, error) {- body := map[string]interface{}{- "query": query,- }- if opts != nil {- if opts.URI != "" {- body["uri"] = opts.URI- }- if opts.Limit > 0 {- body["limit"] = opts.Limit- }- }-- resp, err := c.post("/api/v1/search/find", body)- if err != nil {- return nil, err- }-- var result SearchResult- if err := json.Unmarshal(resp.Result, &result); err != nil {- return nil, err- }- return &result, nil-}--func (c *Client) Ls(uri string, opts *LsOptions) (*LsResult, error) { ... }-func (c *Client) Read(uri string) (*ReadResult, error) { ... }-func (c *Client) Abstract(uri string) (*ReadResult, error) { ... }-func (c *Client) Overview(uri string) (*ReadResult, error) { ... }-// ... 其他方法-```--3. **类型定义**:-```go-// types.go-package openviking--import "encoding/json"--type Response struct {- Status string `json:"status"`- Result json.RawMessage `json:"result,omitempty"`- Error *ErrorInfo `json:"error,omitempty"`- Time float64 `json:"time"`-}--type ErrorInfo struct {- Code string `json:"code"`- Message string `json:"message"`- Details map[string]interface{} `json:"details,omitempty"`-}--type SearchResult struct {- Items []SearchItem `json:"items"`- Query string `json:"query"`- Total int `json:"total"`-}--type SearchItem struct {- URI string `json:"uri"`- Score float64 `json:"score"`- Content string `json:"content"`- Abstract string `json:"abstract,omitempty"`-}--type FindOptions struct {- URI string- Limit int- Threshold float64-}--// ... 其他类型-```--4. **错误处理**:-```go-// errors.go-package openviking--import "fmt"--type OpenVikingError struct {- Code string- Message string- Details map[string]interface{}-}--func (e *OpenVikingError) Error() string {- return fmt.Sprintf("[%s] %s", e.Code, e.Message)-}--var (- ErrNotFound = &OpenVikingError{Code: "NOT_FOUND"}- ErrInvalidURI = &OpenVikingError{Code: "INVALID_URI"}- ErrUnavailable = &OpenVikingError{Code: "UNAVAILABLE"}- // ... 其他错误-)-```--5. **HTTP 请求封装**:-```go-func (c *Client) post(path string, body interface{}) (*Response, error) {- jsonBody, err := json.Marshal(body)- if err != nil {- return nil, err- }-- req, err := http.NewRequest("POST", c.config.URL+path, bytes.NewBuffer(jsonBody))- if err != nil {- return nil, err- }-- req.Header.Set("Content-Type", "application/json")- req.Header.Set("X-API-Key", c.config.APIKey)-- resp, err := c.httpClient.Do(req)- if err != nil {- return nil, err- }- defer resp.Body.Close()-- var response Response- if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {- return nil, err- }-- if response.Status == "error" {- return nil, &OpenVikingError{- Code: response.Error.Code,- Message: response.Error.Message,- Details: response.Error.Details,- }- }-- return &response, nil-}-```--### 验收标准-```go-package main--import (- "fmt"- "github.com/openviking/openviking-go"-)--func main() {- client := openviking.NewClient(openviking.Config{- URL: "http://localhost:8000",- APIKey: "your-api-key",- })-- // 搜索- results, err := client.Find("how to configure", &openviking.FindOptions{- Limit: 10,- })- if err != nil {- panic(err)- }- for _, item := range results.Items {- fmt.Printf("%s: %.2f\n", item.URI, item.Score)- }-- // 读取- content, err := client.Read("viking://resources/doc.md")- if err != nil {- panic(err)- }- fmt.Println(content.Content)-}-```--### 依赖-- T2 (HTTP Server) 必须先完成--### 参考文件-- `design/server-cli-design.md` - 7.3 节 API 端点-- `openviking/server/models.py` - 响应模型定义-------## 附录:异常类定义--所有任务共用的异常类定义,应在 T1 中创建 `openviking/exceptions.py`:--```python-class OpenVikingError(Exception):- """Base exception for all OpenViking errors."""- def __init__(self, code: str, message: str, details: dict = None):- self.code = code- self.message = message- self.details = details or {}- super().__init__(f"[{code}] {message}")--# 参数错误-class InvalidArgumentError(OpenVikingError): pass-class InvalidURIError(InvalidArgumentError): pass--# 资源错误-class NotFoundError(OpenVikingError): pass-class AlreadyExistsError(OpenVikingError): pass--# 认证/权限错误-class UnauthenticatedError(OpenVikingError): pass-class PermissionDeniedError(OpenVikingError): pass--# 服务错误-class UnavailableError(OpenVikingError): pass-class InternalError(OpenVikingError): pass-class DeadlineExceededError(OpenVikingError): pass--# 业务错误-class ProcessingError(OpenVikingError): pass-class EmbeddingFailedError(OpenVikingError): pass-class SessionExpiredError(OpenVikingError): pass-```-------## 附录:错误码映射--```python-ERROR_CODE_TO_HTTP_STATUS = {- "OK": 200,- "INVALID_ARGUMENT": 400,- "INVALID_URI": 400,- "NOT_FOUND": 404,- "ALREADY_EXISTS": 409,- "PERMISSION_DENIED": 403,- "UNAUTHENTICATED": 401,- "RESOURCE_EXHAUSTED": 429,- "FAILED_PRECONDITION": 412,- "ABORTED": 409,- "DEADLINE_EXCEEDED": 504,- "UNAVAILABLE": 503,- "INTERNAL": 500,- "UNIMPLEMENTED": 501,- "PROCESSING": 202,- "EMBEDDING_FAILED": 500,- "VLM_FAILED": 500,- "SESSION_EXPIRED": 410,-}-```diff --git a/docs/design/server_client/server-cli-design.md b/docs/design/server_client/server-cli-design.mddeleted file mode 100644index 91b3426d2..000000000--- a/docs/design/server_client/server-cli-design.md+++ /dev/null@@ -1,1564 +0,0 @@-# OpenViking Server/CLI 模式技术方案--## 一、背景与目标--### 1.1 当前架构--OpenViking 目前主要以 Python SDK 形式提供服务,支持两种部署模式:-- **Embedded 模式**:自动启动本地 AGFS 子进程和 VikingVectorIndex(单例)-- **Service 模式**:连接远程 AGFS 和 VectorDB 服务(非单例)--### 1.2 现有问题--| 问题 | 描述 |-|------|------|-| 缺少统一 CLI | 无法通过命令行管理 OpenViking |-| 服务分散 | AGFS 和 VectorDB 需要分别启动 |-| 无 HTTP API | 核心功能没有 HTTP API 暴露 |-| 部署复杂 | 生产环境需要手动协调多个服务 |--### 1.3 目标--1. **CLI 模式**:提供完整的命令行工具-2. **Server 模式**:提供统一的 HTTP API 服务-3. **保持兼容**:现有 SDK 使用方式不变-------## 二、竞品分析与最佳实践--### 2.1 竞品对比--| 产品 | CLI 设计 | Server 模式 | API 风格 | 部署模式 |-|------|----------|-------------|----------|----------|-| **Chroma** | `chroma run/db/login` | 内置 FastAPI | RESTful | in-memory/persistent/client-server |-| **Qdrant** | 无独立 CLI | 独立服务 | RESTful + gRPC | standalone/distributed |-| **Milvus** | `milvus_cli` 交互式 | 独立服务 | RESTful + gRPC | lite/standalone/distributed |-| **Mem0** | 无 CLI | Platform + OSS | RESTful | managed/self-hosted |-| **LlamaIndex** | 无统一 CLI | 微服务架构 | RESTful | self-hosted |--### 2.2 Chroma 设计参考--Chroma 的 CLI 设计简洁实用:-```bash-chroma run --path <directory> # 启动服务器-chroma db create <name> # 创建数据库-chroma login # 认证登录-chroma browse # 浏览数据-```--**借鉴点**:-- 三种运行模式(in-memory/persistent/client-server)-- 简洁的命令结构-- 环境变量配置支持--### 2.3 Qdrant API 设计参考--Qdrant 的 REST API 采用资源层级结构:-```-POST /collections/{collection_name}/points/search-GET /collections/{collection_name}/points/{id}-PUT /collections/{collection_name}/points-```--**借鉴点**:-- 资源层级 URL 设计-- POST 用于复杂查询(请求体包含向量和过滤条件)-- 完善的过滤 DSL-- 一致性级别控制--### 2.4 Milvus CLI 设计参考--Milvus CLI 采用模块化架构:-```-milvus_cli/-├── Connection.py # 连接管理-├── Collection.py # 集合操作-├── Database.py # 数据库管理-├── Index.py # 索引管理-├── Partition.py # 分区管理-├── Data.py # 数据操作-├── Role.py # 角色管理-└── User.py # 用户管理-```--**借鉴点**:-- 模块化命令组织-- 交互式 CLI 支持-- 完整的 RBAC 支持--### 2.5 Mem0 架构参考--Mem0 的双部署模式:-- **Platform API**:托管服务,API Key 认证-- **OSS SDK**:自托管,直接调用--**借鉴点**:-- 统一的搜索管道(Platform 和 OSS 共用)-- 复杂的过滤 DSL(AND/OR 逻辑)-- 用户隔离(user_id scoping)--### 2.6 Redis/MySQL 客户端设计参考--Redis 和 MySQL 的客户端设计模式:-- **Server 独立运行**:Server 作为独立进程启动,不依赖 Client-- **Client 仅连接**:Client 只负责连接 Server,不负责启动或管理 Server-- **配置分离**:Server 配置和 Client 配置分开管理--```python-# Redis 示例-import redis-r = redis.Redis(host='localhost', port=6379) # 仅连接,不启动 Server-r.set('foo', 'bar')--# MySQL 示例-import mysql.connector-conn = mysql.connector.connect(host='localhost', user='root') # 仅连接-```--**借鉴点**:-- Client 无需 `initialize()` 方法-- 连接参数通过构造函数传入-- Server 生命周期独立于 Client--### 2.7 响应格式与错误处理最佳实践--#### Qdrant 响应格式-```json-{- "status": "ok",- "time": 0.123,- "result": {...},- "usage": {"cpu": 100, "vector_io_read": 40}-}-```-- 统一的 `status/time/result` 包装-- 可选的 `usage` 字段用于资源监控-- 错误通过 HTTP 状态码 + 消息字符串返回--#### Milvus 错误码-```python-# 数字错误码 + 消息-(code=1, message="UnexpectedError...")-(code=2, message="Connection timeout...")-(code=2200, message="Retry exhausted...")-```-- 基于 gRPC 的数字错误码-- 包含 `code`, `message`, `reason` 三元组--#### gRPC 标准状态码(业界标准)-| 码 | 名称 | HTTP | 说明 |-|----|------|------|------|-| 0 | OK | 200 | 成功 |-| 3 | INVALID_ARGUMENT | 400 | 参数无效 |-| 5 | NOT_FOUND | 404 | 资源不存在 |-| 7 | PERMISSION_DENIED | 403 | 权限不足 |-| 13 | INTERNAL | 500 | 内部错误 |-| 14 | UNAVAILABLE | 503 | 服务不可用 |-| 16 | UNAUTHENTICATED | 401 | 未认证 |--**借鉴点**:-- gRPC 17 种标准状态码覆盖所有常见场景-- 明确的 HTTP 状态码映射-- 可重试 vs 不可重试错误分类--### 2.8 最佳实践总结--| 方面 | 最佳实践 | 来源 |-|------|----------|------|-| **CLI 结构** | 动词-名词命令(`run`, `db create`) | Chroma |-| **API 路由** | 资源层级(`/collections/{name}/points`) | Qdrant |-| **认证** | API Key + 可选 JWT | Qdrant, Mem0 |-| **部署模式** | 三层(embedded/standalone/distributed) | Milvus |-| **过滤系统** | JSON DSL(AND/OR/比较操作符) | Mem0, Qdrant |-| **模块化** | 按资源类型组织命令 | Milvus |-| **Client 设计** | 仅连接,不管理 Server 生命周期 | Redis, MySQL |-| **响应格式** | `{status, time, result}` 统一包装 | Qdrant |-| **错误码** | gRPC 标准状态码(字符串形式) | gRPC, Milvus |-| **HTTP 映射** | 错误码到 HTTP 状态码的标准映射 | gRPC |--### 2.9 参考资料--- [Chroma Documentation](https://docs.trychroma.com/) - CLI 设计参考-- [Qdrant API Reference](https://api.qdrant.tech/) - REST API 设计参考-- [Milvus CLI](https://github.com/zilliztech/milvus_cli) - 模块化 CLI 参考-- [Mem0 Documentation](https://docs.mem0.ai/) - 双部署模式参考-- [LlamaIndex Architecture](https://developers.llamaindex.ai/python/cloud/self_hosting/architecture/) - 微服务架构参考-- [gRPC Status Codes](https://grpc.github.io/grpc/core/md_doc_statuscodes.html) - 标准错误码定义-- [gRPC HTTP Mapping](https://grpc.github.io/grpc/core/md_doc_http-grpc-status-mapping.html) - HTTP 状态码映射-- [Qdrant Common Errors](https://qdrant.tech/documentation/guides/common-errors/) - 错误处理参考-- [Chroma Troubleshooting](https://docs.trychroma.com/troubleshooting) - 异常类设计参考-------## 三、架构设计--### 3.0 接口定位--OpenViking 提供三种接口,面向不同使用场景:--| 接口 | 使用者 | 场景 | 特点 |-|------|--------|------|------|-| **Python SDK** | Agent 开发者 | Agent 代码中调用 | 对象化 API,支持异步,client 实例维护状态 |-| **Bash CLI** | Agent / 运维人员 | Agent subprocess 调用、运维脚本 | 非交互式,通过 ovcli.conf 配置文件管理连接状态 |-| **HTTP API** | 任意语言客户端 | 跨语言集成、微服务调用 | RESTful,无状态,每次请求带身份信息 |--**选型建议**:-- **Agent 开发**:优先使用 Python SDK,可以维护 client 实例状态-- **Agent 调用外部工具**:使用 Bash CLI,通过 ovcli.conf 配置文件传递连接和身份信息-- **非 Python 环境**:使用 HTTP API--### 3.1 分层架构--```-┌─────────────────────────────────────────────────────────────┐-│ CLI Layer │-│ openviking <command> [options] │-└─────────────────────────────────────────────────────────────┘- │- ▼-┌─────────────────────────────────────────────────────────────┐-│ Client Layer │-│ ┌─────────────────┐ ┌─────────────────┐ │-│ │ LocalClient │ │ HTTPClient │ │-│ │ (直接调用Service)│ │ (HTTP调用Server)│ │-│ └─────────────────┘ └─────────────────┘ │-└─────────────────────────────────────────────────────────────┘- │- ▼-┌─────────────────────────────────────────────────────────────┐-│ Service Layer │-│ ┌─────────────────────────────────────────────────────────┐│-│ │ OpenVikingService ││-│ │ - ResourceService (资源解析、向量化) ││-│ │ - SearchService (语义搜索) ││-│ │ - SessionService (会话管理) ││-│ │ - FSService (文件系统操作) ││-│ │ - DebugService (调试服务) ││-│ └─────────────────────────────────────────────────────────┘│-└─────────────────────────────────────────────────────────────┘- │- ▼-┌─────────────────────────────────────────────────────────────┐-│ Infrastructure Layer │-│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │-│ │ VikingFS │ │ VikingDB │ │ AGFS │ │-│ └─────────────┘ └─────────────┘ └─────────────┘ │-└─────────────────────────────────────────────────────────────┘-```--### 3.2 部署模式--#### 选型决策--**为什么支持多种部署模式**:--1. **嵌入式模式**:降低入门门槛,开发者无需部署服务即可使用-2. **独立服务模式**:支持团队共享、多 Agent 并发访问-3. **混合模式**:灵活组合,适应不同基础设施环境--**参考业界实践**:-- Chroma:in-memory / persistent / client-server 三种模式-- Milvus:lite / standalone / distributed 三种模式-- SQLite:嵌入式 vs PostgreSQL/MySQL 独立服务--| 模式 | 说明 | 适用场景 |-|------|------|----------|-| **嵌入式** | SDK 自动启动本地 AGFS + VectorDB | 本地开发、单机部署 |-| **独立服务** | 通过 CLI 启动 Server,SDK/CLI 通过 HTTP 连接 | 团队共享、生产环境 |-| **混合模式** | 本地 Server + 远程 AGFS/VectorDB | 分布式部署 |--```-嵌入式模式:-┌─────────────────────────────────────┐-│ Python Process │-│ ┌─────────┐ ┌─────────┐ │-│ │ SDK │──│ Service │ │-│ └─────────┘ └────┬────┘ │-│ │ │-│ ┌─────────┐ ┌────┴────┐ │-│ │ AGFS │ │ VectorDB│ │-│ └─────────┘ └─────────┘ │-└─────────────────────────────────────┘--独立服务模式:-┌─────────────┐ ┌─────────────────────────────────────┐-│ CLI / SDK │─HTTP─│ OpenViking Server │-│ (Client) │ │ ┌─────────┐ ┌─────────┐ │-└─────────────┘ │ │ Service │──│ AGFS │ │- │ └────┬────┘ └─────────┘ │- │ │ │- │ ┌────┴────┐ │- │ │ VectorDB│ │- │ └─────────┘ │- └─────────────────────────────────────┘-```--### 3.3 身份与隔离--支持多租户场景,首先通过 account_id 区分不同的应用租户,然后允许通过 `user` 和 `agent` 实现租户内的身份隔离:--用户或智能体身份标识详见 `from openviking_cli.session.user_id import UserIdentifier`--| 参数 | 说明 | 默认值 |-|------|------|------|-| `account_id` | 租户账号标识,区分不同的租户,租户内 user 和 agent id 空间隔离,也就是保证租户之间数据隔离 | `default` |-| `user_id` | 用户身份标识,用户在租户内的唯一标识符 | `default` |-| `agent_id` | 智能体身份标识,智能体或应用在租户内的唯一标识符 | `default` |--> 举例说明,如果一个团队部署一个 OpenViking 上下文数据库,让团队成员共享一部分上下文资料,但各自保留独立的记忆数据,团队使用统一的 account_id,每个成员使用不同的 user_id 来区分,成员使用不同的应用(如 OpenCode, OpenClaw 等)则使用不同的 agent_id 来区分。-> 一般情况下,`account_id` 不会出现在 viking:// uri 中,因为每个租户的用户数据都是隔离的,不需要在 uri 中指定租户。---### 3.4 配置管理--#### Server 配置--服务端配置统一使用 JSON 配置文件,通过 `--config` 或 `OPENVIKING_CONFIG_FILE` 环境变量指定(与 `OpenVikingConfig` 共用同一个文件):--```json-{- "server": {- "host": "0.0.0.0",- "port": 1933,- "api_key": "your-api-key"- },- "storage": {- "path": "~/.openviking/data"- },- "embedding": {- "dense": {- "provider": "openai",- "model": "text-embedding-3-small"- }- },- "vlm": {- "provider": "openai",- "model": "gpt-4o"- }-}-```--#### Client 配置--客户端 SDK 通过构造函数参数配置:--```python-# 构造函数参数-client = SyncHTTPClient(url="http://localhost:1933", api_key="your-api-key")-```--SDK 构造函数只接受 `url`、`api_key`、`path` 参数。不支持 `config` 参数,也不支持 `vectordb_url`/`agfs_url` 参数。--#### CLI 配置--CLI 通过 `ovcli.conf` 配置文件管理连接信息,不使用 `--url`、`--api-key` 等全局命令行选项:--```json-{- "url": "http://localhost:1933",- "api_key": "sk-xxx",- "output": "table"-}-```--配置文件路径通过 `OPENVIKING_CLI_CONFIG_FILE` 环境变量指定。--#### 环境变量--只保留 2 个环境变量:--| 环境变量 | 说明 | 示例 |-|----------|------|------|-| `OPENVIKING_CONFIG_FILE` | ov.conf 配置文件路径(SDK 嵌入式 + Server) | `~/.openviking/ov.conf` |-| `OPENVIKING_CLI_CONFIG_FILE` | ovcli.conf 配置文件路径(CLI 连接配置) | `~/.openviking/ovcli.conf` |--不再使用单字段环境变量(`OPENVIKING_URL`、`OPENVIKING_API_KEY`、`OPENVIKING_HOST`、`OPENVIKING_PORT`、`OPENVIKING_PATH`、`OPENVIKING_VECTORDB_URL`、`OPENVIKING_AGFS_URL` 均已移除)。--#### 配置文件--系统使用 2 个配置文件:--| 配置文件 | 用途 | 环境变量 |-|----------|------|----------|-| `ov.conf` | SDK 嵌入式模式 + Server 配置 | `OPENVIKING_CONFIG_FILE` |-| `ovcli.conf` | CLI 连接配置(url/api_key/user) | `OPENVIKING_CLI_CONFIG_FILE` |--#### 配置优先级--从高到低:-1. 构造函数参数(SDK)/ 命令行参数(`--config`、`--host`、`--port`)-2. 配置文件(`ov.conf` 或 `ovcli.conf`)-------## 四、模块设计--### 4.1 模块职责--| 模块 | 职责 | 依赖 |-|------|------|------|-| **service/** | 核心业务逻辑,与传输层无关 | Infrastructure Layer |-| **server/** | HTTP API 服务,调用 Service 层 | service/ |-| **cli/** | 命令行工具,调用 Client 层 | client/ |-| **client/** | 客户端抽象,支持本地和 HTTP 两种模式 | service/ 或 HTTP |--**设计原则**:-- **Service 层独立**:业务逻辑不依赖传输层(HTTP/CLI),便于测试和复用-- **Client 层抽象**:LocalClient 和 HTTPClient 实现相同接口,上层无感知-- **CLI 薄层**:CLI 只负责参数解析和输出格式化,业务逻辑在 Service 层--### 4.2 目录结构--```-openviking/-├── service/ # Service 层(业务逻辑)-│ ├── __init__.py-│ ├── core.py # OpenVikingService-│ ├── fs_service.py # 文件系统操作-│ ├── resource_service.py # 资源导入、技能添加-│ ├── search_service.py # 语义搜索-│ ├── session_service.py # 会话管理-│ ├── relation_service.py # 关联管理-│ ├── pack_service.py # 导入导出-│ └── debug_service.py # 调试服务-│-├── server/ # HTTP Server-│ ├── __init__.py-│ ├── app.py # FastAPI 应用-│ ├── bootstrap.py # 服务启动器-│ ├── config.py # 服务器配置-│ ├── dependencies.py # 依赖注入-│ └── routers/-│ ├── resources.py # /api/v1/resources-│ ├── filesystem.py # /api/v1/fs-│ ├── content.py # /api/v1/content-│ ├── search.py # /api/v1/search-│ ├── relations.py # /api/v1/relations-│ ├── sessions.py # /api/v1/sessions-│ └── debug.py # /api/v1/debug-│-├── cli/ # CLI 模块-│ ├── __init__.py-│ ├── main.py # CLI 入口-│ └── output.py # 输出格式化(JSON/table/脚本模式)-│-├── client/ # Client 层-│ ├── __init__.py-│ ├── local.py # LocalClient-│ └── http.py # HTTPClient-│-├── async_client.py # 兼容层-└── sync_client.py # 兼容层-```--### 4.3 pyproject.toml--```toml-[project.scripts]-openviking = "openviking_cli.cli.main:app"-```--### 4.4 新增依赖--```toml-dependencies = [- # ... 现有依赖- # argparse is used for CLI (part of Python stdlib, no extra dependency needed)- "rich>=13.0.0", # CLI 美化输出-]-```-------## 五、接口设计--### 5.1 核心方法定义--| 方法 | 参数 | 说明 |-|------|------|------|-| `add_resource` | `path, target, wait, timeout` | 导入资源 |-| `add_skill` | `data, wait` | 添加技能 |-| `ls` | `uri, simple, recursive` | 列出目录 |-| `tree` | `uri` | 目录树 |-| `stat` | `uri` | 状态信息 |-| `mkdir` | `uri` | 创建目录 |-| `rm` | `uri, recursive` | 删除 |-| `mv` | `from_uri, to_uri` | 移动 |-| `read` | `uri` | 读取完整内容 (L2) |-| `abstract` | `uri` | 读取摘要 (L0) |-| `overview` | `uri` | 读取概览 (L1) |-| `find` | `query, target_uri, limit, threshold` | 语义搜索 |-| `search` | `query, target_uri, session, limit` | 带上下文搜索 |-| `grep` | `uri, pattern, case_insensitive` | 内容搜索 |-| `glob` | `pattern, uri` | 模式匹配 |-| `link` | `from_uri, uris, reason` | 创建关联 |-| `unlink` | `from_uri, uri` | 删除关联 |-| `relations` | `uri` | 查看关联 |-| `export_ovpack` | `uri, to` | 导出 |-| `import_ovpack` | `file, target, force, vectorize` | 导入 |-| `session` | `user` | 创建/获取 Session 对象 |-| `sessions` | - | 获取所有 Session 对象列表 |-| `wait_processed` | `timeout` | 等待处理完成 |-| `get_status` | - | 获取系统状态(包含 queue/vikingdb/vlm 组件状态) |-| `is_healthy` | - | 快速健康检查 |--**Session 对象方法:**--| 方法 | 参数 | 说明 |-|------|------|------|-| `add_message` | `role, content` | 添加消息 |-| `commit` | - | 提交会话(归档消息、提取记忆) |-| `delete` | - | 删除会话 |--### 5.2 统一返回值格式--参考 Qdrant 的响应格式设计,采用 `{status, time, result}` 统一包装:--**成功响应**:-```json-{- "status": "ok",- "result": {...},- "time": 0.123,- "usage": { // 可选,用于监控- "tokens": 100,- "vectors_scanned": 1000- }-}-```--**错误响应**:-```json-{- "status": "error",- "error": {- "code": "NOT_FOUND", // gRPC 风格错误码- "message": "Resource not found: viking://...",- "details": {...} // 可选,额外错误信息- },- "time": 0.05-}-```--**Python 数据模型**:-```python-@dataclass-class Response:- status: str # "ok" | "error"- result: Optional[Any] = None- error: Optional[ErrorInfo] = None- time: float = 0.0- usage: Optional[UsageInfo] = None--@dataclass-class ErrorInfo:- code: str # NOT_FOUND, INVALID_URI, ...- message: str- details: Optional[dict] = None--@dataclass-class UsageInfo:- tokens: Optional[int] = None- vectors_scanned: Optional[int] = None-```--### 5.3 各方法返回值--**ls / tree**-```json-{- "status": "ok",- "result": {- "entries": [- {"name": "doc.md", "type": "file", "uri": "viking://resources/doc.md", "size": 1024},- {"name": "images/", "type": "dir", "uri": "viking://resources/images/", "children_count": 5}- ]- },- "time": 0.05-}-```--**find / search**-```json-{- "status": "ok",- "result": {- "items": [- {- "uri": "viking://resources/doc.md",- "score": 0.92,- "content": "...",- "abstract": "...",- "metadata": {"type": "markdown", "scope": "resources"}- }- ],- "query": "how to use openviking",- "total": 10- },- "time": 0.15,- "usage": {"vectors_scanned": 1000}-}-```--**read / abstract / overview**-```json-{- "status": "ok",- "result": {- "uri": "viking://resources/doc.md",- "content": "...",- "level": "L2"- },- "time": 0.02-}-```--**stat**-```json-{- "status": "ok",- "result": {- "uri": "viking://resources/doc.md",- "type": "file",- "size": 1024,- "created_at": "2024-01-01T00:00:00Z",- "updated_at": "2024-01-02T00:00:00Z",- "has_abstract": true,- "has_overview": true,- "vectorized": true- },- "time": 0.01-}-```--**add_resource**-```json-{- "status": "ok",- "result": {- "uri": "viking://resources/my-docs/",- "files_count": 10,- "processing_status": "processing",- "queue": {- "vectorize": {"processed": 5, "total": 10, "failed": 0}- }- },- "time": 0.5-}-```--**session**(Python CLI 返回 Session 对象,HTTP API 返回 JSON)-```python-# Python CLI-session = client.session()-session.id # "session-abc123"-session.user # "alice"-session.created_at # datetime-session.message_count # 10-session.compressed # False--# HTTP API 返回-{- "status": "ok",- "result": {- "session_id": "session-abc123",- "user": "alice",- "created_at": "2024-01-01T00:00:00Z",- "message_count": 10,- "compressed": false- },- "time": 0.02-}-```--**错误示例**-```json-{- "status": "error",- "error": {- "code": "NOT_FOUND",- "message": "Resource not found: viking://resources/nonexistent/"- },- "time": 0.01-}-```--```json-{- "status": "error",- "error": {- "code": "INVALID_URI",- "message": "Invalid URI format: 'invalid-uri'",- "details": {- "expected": "viking://<scope>/<path>",- "received": "invalid-uri"- }- },- "time": 0.001-}-```--**debug/status**-```json-{- "status": "ok",- "result": {- "is_healthy": true,- "components": {- "queue": {"name": "queue", "is_healthy": true, "has_errors": false, "details": {...}},- "vikingdb": {"name": "vikingdb", "is_healthy": true, "has_errors": false, "details": {...}},- "vlm": {"name": "vlm", "is_healthy": true, "has_errors": false, "details": {...}}- },- "errors": []- },- "time": 0.05-}-```--**debug/health**-```json-{- "healthy": true-}-```--### 5.4 错误处理--基于 gRPC 标准状态码,结合 OpenViking 业务场景定制。--#### 通用错误码(基于 gRPC 标准)--| 错误码 | HTTP 状态 | 说明 | 适用场景 |-|--------|-----------|------|----------|-| `OK` | 200 | 成功 | 所有成功操作 |-| `INVALID_ARGUMENT` | 400 | 参数无效 | URI 格式错误、参数缺失、类型错误 |-| `NOT_FOUND` | 404 | 资源不存在 | URI 指向的资源不存在 |-| `ALREADY_EXISTS` | 409 | 资源已存在 | 创建重复资源、重复导入 |-| `PERMISSION_DENIED` | 403 | 权限不足 | API Key 无权限、用户隔离 |-| `UNAUTHENTICATED` | 401 | 未认证 | API Key 缺失或无效 |-| `RESOURCE_EXHAUSTED` | 429 | 资源耗尽 | 配额超限、速率限制 |-| `FAILED_PRECONDITION` | 412 | 前置条件失败 | 资源未就绪、依赖缺失 |-| `ABORTED` | 409 | 操作中止 | 并发冲突、事务失败 |-| `DEADLINE_EXCEEDED` | 504 | 超时 | 处理超时、等待超时 |-| `UNAVAILABLE` | 503 | 服务不可用 | AGFS/VectorDB 不可用 |-| `INTERNAL` | 500 | 内部错误 | 未预期的服务端错误 |-| `UNIMPLEMENTED` | 501 | 未实现 | 功能未实现 |--#### OpenViking 特定错误码--| 错误码 | HTTP 状态 | 说明 | 适用场景 |-|--------|-----------|------|----------|-| `INVALID_URI` | 400 | URI 格式无效 | `viking://` 协议解析失败 |-| `PROCESSING` | 202 | 处理中 | 资源正在处理,尚未就绪 |-| `EMBEDDING_FAILED` | 500 | 向量化失败 | Embedding API 调用失败 |-| `VLM_FAILED` | 500 | VLM 调用失败 | 摘要/概览生成失败 |-| `SESSION_EXPIRED` | 410 | 会话过期 | 会话已被删除或过期 |--#### Python 异常类--参考 Chroma 的特定异常类设计,异常类与错误码一一对应:--```python-# openviking/exceptions.py--class OpenVikingError(Exception):- """Base exception for all OpenViking errors."""- def __init__(self, code: str, message: str, details: dict = None):- self.code = code- self.message = message- self.details = details or {}- super().__init__(f"[{code}] {message}")--# 参数错误-class InvalidArgumentError(OpenVikingError): pass-class InvalidURIError(InvalidArgumentError): pass--# 资源错误-class NotFoundError(OpenVikingError): pass-class AlreadyExistsError(OpenVikingError): pass--# 认证/权限错误-class UnauthenticatedError(OpenVikingError): pass-class PermissionDeniedError(OpenVikingError): pass--# 服务错误-class UnavailableError(OpenVikingError): pass-class InternalError(OpenVikingError): pass-class DeadlineExceededError(OpenVikingError): pass--# 业务错误-class ProcessingError(OpenVikingError): pass-class EmbeddingFailedError(OpenVikingError): pass-class SessionExpiredError(OpenVikingError): pass-```--**错误码到异常的映射**:-```python-ERROR_CODE_TO_EXCEPTION = {- "INVALID_ARGUMENT": InvalidArgumentError,- "INVALID_URI": InvalidURIError,- "NOT_FOUND": NotFoundError,- "ALREADY_EXISTS": AlreadyExistsError,- "UNAUTHENTICATED": UnauthenticatedError,- "PERMISSION_DENIED": PermissionDeniedError,- "UNAVAILABLE": UnavailableError,- "INTERNAL": InternalError,- "DEADLINE_EXCEEDED": DeadlineExceededError,- "PROCESSING": ProcessingError,- "EMBEDDING_FAILED": EmbeddingFailedError,- "SESSION_EXPIRED": SessionExpiredError,-}--def raise_for_error(response: dict):- """Convert error response to exception."""- if response.get("status") == "error":- error = response["error"]- exc_class = ERROR_CODE_TO_EXCEPTION.get(error["code"], OpenVikingError)- raise exc_class(error["code"], error["message"], error.get("details", {}))-```-------## 六、CLI 实现--### 6.1 Bash CLI--#### 模式选型:非交互式 CLI--**选型决策**:采用非交互式 CLI。--**为什么选择非交互式**:--1. **Agent 调用场景**:Agent 通过 subprocess 调用 CLI,非交互式更自然-2. **无状态设计**:每次调用独立,避免状态污染和并发冲突-3. **易于集成**:可以直接在 shell 脚本、CI/CD 中使用-4. **参考业界实践**:kubectl、aws cli、gh cli 都是非交互式设计--#### 多 Agent 场景--OpenViking 支持多 user、多 agent,CLI 需要处理多进程并发场景:--```-┌─────────────────────────────────────────────────────────────┐-│ OpenViking Server │-│ │-│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │-│ │ user:alice│ │ user:bob │ │ user:carol│ │-│ │ agent:a1 │ │ agent:b1 │ │ agent:c1 │ │-│ └──────────┘ └──────────┘ └──────────┘ │-└─────────────────────────────────────────────────────────────┘- ▲ ▲ ▲- │ │ │- ┌────┴────┐ ┌────┴────┐ ┌────┴────┐- │ Agent A │ │ Agent B │ │ Agent C │- │ (进程1) │ │ (进程2) │ │ (进程3) │- └─────────┘ └─────────┘ └─────────┘-```--多个 Agent 进程可能同时运行,各自有不同的 user/agent 身份。各进程通过各自的 `ovcli.conf` 配置文件管理连接信息和身份(详见 3.4 配置管理)。--#### 使用示例--**Agent 调用场景**:-```bash-# CLI 连接信息通过 ovcli.conf 配置文件管理-# 配置文件路径通过 OPENVIKING_CLI_CONFIG_FILE 环境变量指定-export OPENVIKING_CLI_CONFIG_FILE=~/.openviking/ovcli.conf--# ovcli.conf 内容示例:-# {-# "url": "http://localhost:1933",-# "api_key": "sk-xxx",-# "output": "table"-# }--# 后续 CLI 调用自动读取 ovcli.conf,无需重复指定-openviking find "how to use openviking"-openviking ls viking://resources/-openviking read viking://resources/doc.md-```--#### 设计原则--1. **与接口一致**:命令名、参数与接口定义保持一致-2. **体现核心特性**:突出文件系统范式、分层上下文、语义搜索、会话管理-3. **简洁直观**:常用操作简单,复杂操作通过子命令组织--#### 命令列表--```bash-# 服务管理-openviking serve [--config <file>] [--port 1933] [--host 0.0.0.0]-openviking status--# 资源导入-openviking add-resource <path> [--to <uri>] [--wait] [--timeout N]-openviking add-skill <file> [--wait]--# 文件系统操作-openviking ls <uri> [--simple] [--recursive]-openviking tree <uri>-openviking stat <uri>-openviking mkdir <uri>-openviking rm <uri> [--recursive]-openviking mv <from> <to>--# 内容读取-openviking read <uri>-openviking abstract <uri>-openviking overview <uri>--# 搜索-openviking find <query> [<uri>] [--limit N] [--threshold F]-openviking search <query> [<uri>] [--session-id ID] [--limit N]-openviking grep <uri> <pattern> [-i]-openviking glob <pattern> [<uri>]--# 关联管理-openviking link <from> <to>... [--reason TEXT]-openviking unlink <from> <to>-openviking relations <uri>--# 会话管理-openviking session new [--user <name>]-openviking session list-openviking session get <id>-openviking session commit <id>--# 导入导出-openviking export <uri> <file.ovpack>-openviking import <file.ovpack> <uri> [--force] [--no-vectorize]--# 工具命令-openviking wait [--timeout N]-openviking config show-openviking config init--# 调试命令-openviking status # 系统整体状态(包含 queue/vikingdb/vlm 组件状态)-openviking health # 快速健康检查-```--#### 命令分组说明--| 命令组 | 体现特性 | 说明 |-|--------|----------|------|-| `add-resource/add-skill` | 自动处理 | 导入后自动解析、分层、向量化 |-| `ls/tree/stat/mkdir/rm/mv` | 文件系统范式 | 像操作文件一样管理上下文 |-| `read/abstract/overview` | 分层上下文 | L0/L1/L2 按需加载 |-| `find/search` | 目录递归检索 | 语义搜索 + 目录定位 |-| `session *` | 会话管理 | 自动压缩、记忆提取 |-| `status/health` | 调试诊断 | 系统状态查询、健康检查 |--#### 实现 (使用 argparse)--```python-# openviking/__main__.py-import argparse-import sys---def main():- """Main CLI entry point."""- parser = argparse.ArgumentParser(- description="OpenViking - An Agent-native context database",- formatter_class=argparse.ArgumentDefaultsHelpFormatter,- )- subparsers = parser.add_subparsers(dest="command", help="Available commands")-- # serve command- serve_parser = subparsers.add_parser("serve", help="Start OpenViking HTTP Server")- serve_parser.add_argument("--config", type=str, default=None, help="Config file path (ov.conf)")- serve_parser.add_argument("--host", type=str, default=None, help="Host to bind to")- serve_parser.add_argument("--port", type=int, default=None, help="Port to bind to")-- args = parser.parse_args()-- if args.command == "serve":- from openviking.server.bootstrap import main as serve_main- serve_main()- else:- parser.print_help()- sys.exit(1)-```-------### 6.2 Python SDK--#### 使用方式--```python-from openviking import OpenViking--# 嵌入式模式-client = OpenViking(path="./data")--# HTTP 模式-client = OpenViking(url="http://localhost:1933", api_key="xxx")-```--#### 完整示例--```python-from openviking import OpenViking--# 连接-client = OpenViking(url="http://localhost:1933", api_key="xxx")--# 导入资源-result = client.add_resource("./docs/", target="viking://resources/my-docs/", wait=True)-print(f"导入完成: {result.data.uri}, 文件数: {result.data.files_count}")--# 分层读取-abstract = client.abstract("viking://resources/my-docs/") # L0-overview = client.overview("viking://resources/my-docs/") # L1-content = client.read("viking://resources/my-docs/README.md") # L2--# 语义搜索-results = client.find("how to configure", target_uri="viking://resources/my-docs/", limit=10)-for r in results.data.results:- print(f"{r.uri}: {r.score:.2f}")--# 会话管理(OOP 模式)-session = client.session()-session.add_message("user", "What is OpenViking?")-results = client.search("What is OpenViking?", session=session)--# Session 操作-session.compress()-memories = session.extract()--# 获取所有 session-all_sessions = client.sessions()-```--#### 实现方式--```python-class Session:- """Session 对象,封装会话操作"""- def __init__(self, client, session_id: str, user: UserIdentifier):- self._client = client- self.id = session_id- self.user = user-- def add_message(self, role: str, content: str):- """添加消息"""- ...-- def compress(self):- """压缩会话"""- ...-- def extract(self):- """提取记忆"""- ...--class OpenViking:- def __init__(- self,- path: Optional[str] = None,- url: Optional[str] = None,- api_key: Optional[str] = None,- user: Optional[str] = None,- user: Optional[UserIdentifier] = None- ):- if url:- self._backend = HTTPBackend(url, api_key)- else:- self._backend = LocalBackend(path)- self._user = user--- def session(self, user: UserIdentifier = None) -> Session:- """创建或获取 Session 对象"""- ...-- def sessions(self) -> List[Session]:- """获取所有 Session 对象"""- ...-```--### 6.3 使用指南--#### 安装--```bash-pip install openviking-```--#### 配置文件--详见 3.4 配置管理中的配置文件定义。--#### viking:// 目录结构--```-viking://-├── resources/ # 外部资源(文档、代码等)-├── user/-│ └── memories/ # 用户记忆-├── agent/-│ ├── memories/ # Agent 记忆-│ ├── skills/ # Agent 技能-│ └── instructions/ # Agent 指令-└── session/ # 会话数据-```--#### 分层上下文--| 层级 | 方法 | 说明 | 适用场景 |-|------|------|------|----------|-| L0 | `abstract()` | 一句话摘要 | 快速浏览、列表展示 |-| L1 | `overview()` | 核心信息 | 初步了解、决策参考 |-| L2 | `read()` | 完整内容 | 详细阅读、代码执行 |-------## 七、HTTP API 实现--### 7.1 设计原则--**选型决策**:--1. **RESTful 风格**:资源层级 URL,标准 HTTP 方法- - 参考 Qdrant API 设计:`/collections/{name}/points`- - 便于理解和使用,符合开发者习惯--2. **POST 用于复杂查询**:搜索等操作使用 POST,请求体包含查询参数- - 原因:GET 的 URL 长度有限制,复杂查询参数(如向量、过滤条件)不适合放 URL- - 参考:Qdrant、Elasticsearch 都采用 POST 进行搜索--3. **统一响应格式**:所有 API 返回 `{status, time, result}` 结构- - 参考 Qdrant 响应格式- - 便于客户端统一处理--**为什么不用 GraphQL**:-- OpenViking 的查询模式相对固定,不需要 GraphQL 的灵活性-- RESTful 更简单,学习成本低-- 便于缓存和调试--### 7.2 认证机制--采用 API Key 认证:--```-X-API-Key: your-api-key-# 或-Authorization: Bearer your-api-key-```--**认证策略**:-- `/health` 端点:永远不需要认证(用于负载均衡器健康检查)-- 其他 API 端点:- - 如果 `config.api_key` 为 `None`(默认)→ 跳过认证(本地开发模式)- - 如果 `config.api_key` 有值 → 验证请求中的 Key--**配置方式**:-```json-// ~/.openviking/ov.conf-{- "server": {- "api_key": "your-secret-key" // 设置后启用认证,不设置则跳过认证- }-}-```--### 7.3 API 端点设计--所有 API 响应格式遵循 5.2 统一返回值格式,具体返回值结构见 5.3 各方法返回值。--#### 资源管理 `/api/v1/resources`-```-POST /api/v1/resources # add_resource- Body: {"path": "...", "target": "...", "wait": false}--POST /api/v1/skills # add_skill- Body: {"data": {...}}-```--#### 文件系统 `/api/v1/fs`-```-GET /api/v1/fs/ls?uri=viking:// # ls-GET /api/v1/fs/tree?uri=viking:// # tree-GET /api/v1/fs/stat?uri=viking://... # stat-POST /api/v1/fs/mkdir # mkdir- Body: {"uri": "viking://..."}--DELETE /api/v1/fs?uri=viking://...&recursive=false # rm-POST /api/v1/fs/mv # mv- Body: {"from": "...", "to": "..."}-```--#### 内容读取 `/api/v1/content`-```-GET /api/v1/content/read?uri=viking://... # read (L2)-GET /api/v1/content/abstract?uri=viking://... # abstract (L0)-GET /api/v1/content/overview?uri=viking://... # overview (L1)-```--#### 搜索 `/api/v1/search`-```-POST /api/v1/search/find # find- Body: {"query": "...", "uri": "viking://", "limit": 10}--POST /api/v1/search/search # search (with session)- Body: {"query": "...", "uri": "...", "session_id": "..."}--POST /api/v1/search/grep # grep- Body: {"uri": "...", "pattern": "...", "case_insensitive": false}--POST /api/v1/search/glob # glob- Body: {"pattern": "**/*.md", "uri": "viking://"}-```--#### 关联 `/api/v1/relations`-```-POST /api/v1/relations/link # link- Body: {"from": "...", "to": "...", "reason": "..."}--DELETE /api/v1/relations/link # unlink- Body: {"from": "...", "to": "..."}--GET /api/v1/relations?uri=viking://... # relations-```--#### 会话 `/api/v1/sessions`-```-POST /api/v1/sessions # session new- Body: {"user": "alice"}--GET /api/v1/sessions # session list-GET /api/v1/sessions/{id} # session get-DELETE /api/v1/sessions/{id} # session delete--POST /api/v1/sessions/{id}/commit # session commit-POST /api/v1/sessions/{id}/messages # add message- Body: {"role": "user", "content": "..."}-```--#### 导入导出 `/api/v1/pack`-```-POST /api/v1/pack/export # export- Body: {"uri": "...", "file": "..."}--POST /api/v1/pack/import # import- Body: {"file": "...", "uri": "...", "force": false}-```--#### 系统 `/api/v1/system`-```-GET /health # 健康检查-GET /api/v1/system/status # 系统状态-POST /api/v1/system/wait # wait_processed- Body: {"timeout": 60}-```--#### 调试 `/api/v1/debug`-```-GET /api/v1/debug/status # 系统整体状态(包含 queue/vikingdb/vlm 组件状态)-GET /api/v1/debug/health # 快速健康检查(返回 bool)-```--### 7.4 Server 实现--```python-# openviking/server/app.py-from fastapi import FastAPI, Depends-from openviking.server.auth import verify_api_key-from openviking.server.routers import resources, filesystem, content, search, sessions, debug--app = FastAPI(- title="OpenViking API",- description="Context Database for AI Agents",- version="1.0.0"-)--# 注册路由-app.include_router(resources.router, prefix="/api/v1/resources", dependencies=[Depends(verify_api_key)])-app.include_router(filesystem.router, prefix="/api/v1/fs", dependencies=[Depends(verify_api_key)])-app.include_router(content.router, prefix="/api/v1/content", dependencies=[Depends(verify_api_key)])-app.include_router(search.router, prefix="/api/v1/search", dependencies=[Depends(verify_api_key)])-app.include_router(sessions.router, prefix="/api/v1/sessions", dependencies=[Depends(verify_api_key)])-app.include_router(debug.router, prefix="/api/v1/debug", dependencies=[Depends(verify_api_key)])-[email protected]("/health")-async def health():- return {"status": "healthy"}-```-------## 八、实现任务拆解--### 8.1 任务概览--| 任务 | 描述 | 依赖 | 优先级 | 状态 | 适合社区开发者 |-|------|------|------|--------|------|---------------|-| T1 | Service 层抽取 | - | P0 | Done | |-| T2 | HTTP Server | T1 | P1 | Done | |-| T3 | CLI 基础框架 | T1 | P1 | | |-| T4 | Python SDK | T2 | P2 | Done | |-| T5 | CLI 完整命令 | T3 | P2 | | |-| T6 | 集成测试 | T4, T5 | P3 | | |-| T7 | 文档更新 | T6 | P3 | | |-| T8 | Docker 部署 | T2 | P1 | | ✅ |-| T9 | MCP Server | T1 | P1 | | ✅ |-| T10 | TypeScript SDK | T2 | P2 | | ✅ |-| T11 | Golang SDK | T2 | P2 | | ✅ |--### 8.2 依赖关系--```-T1 (Service层)- ├── T2 (Server) ──┬── T4 (Python SDK) ──┐- │ ├── T8 (Docker) │- │ ├── T10 (TS SDK) ├── T6 (测试) ── T7 (文档)- │ └── T11 (Go SDK) │- │ │- ├── T3 (CLI基础) ── T5 (CLI完整) ────────┘- │- └── T9 (MCP Server)-```--### 8.3 任务详情--#### T1: Service 层抽取(P0)--**目标**:从 `async_client.py` 抽取业务逻辑到独立的 Service 层--**交付物**:-- `openviking/service/core.py` - OpenVikingService-- `openviking/service/resource_service.py` - 资源导入、技能添加-- `openviking/service/search_service.py` - 语义搜索-- `openviking/service/session_service.py` - 会话管理-- `openviking/service/fs_service.py` - 文件系统操作--**验收标准**:-- 现有单元测试全部通过-- `async_client.py` 作为兼容层,API 不变-------#### T2: HTTP Server(P1)--**目标**:实现 FastAPI HTTP Server--**交付物**:-- `openviking/server/app.py` - FastAPI 应用-- `openviking/server/bootstrap.py` - 服务启动器-- `openviking/server/auth.py` - API Key 认证-- `openviking/server/routers/*.py` - 所有 API 路由-- `openviking/server/models.py` - 统一响应模型--**验收标准**:-```bash-# 启动服务-openviking serve --config ./ov.conf --port 1933--# 验证 API-curl http://localhost:1933/health-curl -X POST http://localhost:1933/api/v1/resources \- -H "X-API-Key: test" -d '{"path": "./docs"}'-curl http://localhost:1933/api/v1/fs/ls?uri=viking://-```-------#### T3: CLI 基础框架(P1)--**目标**:实现 CLI 核心命令--**交付物**:-- `openviking/cli/main.py` - CLI 入口-- `openviking/cli/output.py` - 输出格式化-- 核心命令:`serve`, `ls`, `find`, `read`, `abstract`, `overview`, `add-resource`--**验收标准**:-```bash-openviking serve --config ./ov.conf --port 1933-openviking add-resource ./docs/ --wait-openviking ls viking://resources/-openviking find "how to use"-```-------#### T4: Python SDK(P2)--**目标**:支持通过 HTTP 连接远程 Server--**交付物**:-- `openviking/client/http.py` - HTTPClient-- `openviking/client/local.py` - LocalClient(重构)-- 修改 `async_client.py` 支持 `server_url` 参数--**验收标准**:-```python-# HTTP 模式-client = OpenViking(url="http://localhost:1933", api_key="test")-results = client.find("how to use")-```-------#### T5: CLI 完整命令(P2)--**目标**:补全所有 CLI 命令--**交付物**:-- 会话命令:`session new/list/get/compress/extract`-- 文件系统命令:`tree`, `stat`, `mkdir`, `rm`, `mv`-- 搜索命令:`search`, `grep`, `glob`-- 关联命令:`link`, `unlink`, `relations`-- 导入导出:`export`, `import`-- 配置命令:`config show/init`-- 工具命令:`wait`, `status`--**验收标准**:-```bash-openviking --help # 显示所有命令-openviking session new --user alice-openviking export viking://resources/docs/ ./backup.ovpack-```-------#### T6: 集成测试(P3)--**目标**:端到端测试--**交付物**:-- `tests/integration/test_cli.py`-- `tests/integration/test_server.py`-- `tests/integration/test_http_client.py`--**验收标准**:-- 所有集成测试通过-- 覆盖主要使用场景-------#### T7: 文档更新(P3)--**目标**:更新用户文档--**交付物**:-- README.md 更新(CLI 和 Server 使用说明)-- OpenAPI 文档(自动生成)-- CHANGELOG.md 更新-------#### T8: Docker 部署(P1)--**目标**:提供 Docker 镜像和 docker-compose 配置--**交付物**:-- `Dockerfile` - 多阶段构建-- `docker-compose.yml` - 本地部署配置-- `.dockerignore` - 忽略文件-- GitHub Actions 自动构建发布--**验收标准**:-```bash-docker build -t openviking .-docker run -p 1933:1933 -e OPENAI_API_KEY=xxx openviking-curl http://localhost:1933/health-```-------#### T9: MCP Server(P1)--**目标**:实现 Model Context Protocol 服务端,让 Claude 等 AI 可直接调用--**交付物**:-- `openviking/mcp/server.py` - MCP Server 主入口-- `openviking/mcp/tools.py` - Tool 定义(find, read, ls, abstract, overview)-- CLI 命令:`openviking mcp [--path <dir>]`--**验收标准**:-- Claude Desktop 可成功连接并调用 tools-- 支持 stdio 传输-------#### T10: TypeScript SDK(P2)--**目标**:基于 HTTP API 实现 TypeScript/JavaScript 客户端--**交付物**:-- `openviking-js/` - 独立 npm 包-- 完整类型定义-- 错误处理-- README 和示例--**验收标准**:-```typescript-import { OpenViking } from '@openviking/sdk';-const client = new OpenViking({ url: 'http://localhost:1933', apiKey: 'xxx' });-const results = await client.find('how to configure');-```-------#### T11: Golang SDK(P2)--**目标**:基于 HTTP API 实现 Golang 客户端--**交付物**:-- `openviking-go/` - 独立 Go 模块-- 完整类型定义-- 错误处理-- README 和示例--**验收标准**:-```go-client := openviking.NewClient(openviking.Config{URL: "http://localhost:1933", APIKey: "xxx"})-results, _ := client.Find("how to configure", nil)-```--### 8.4 关键文件--| 文件 | 操作 | 说明 |-|------|------|------|-| `pyproject.toml` | 修改 | 添加依赖和入口点 |-| `openviking/exceptions.py` | 新增 | 异常类定义 |-| `openviking/cli/main.py` | 新增 | CLI 入口 |-| `openviking/server/app.py` | 新增 | FastAPI 应用入口 |-| `openviking/server/auth.py` | 新增 | API Key 认证 |-| `openviking/server/models.py` | 新增 | 响应模型、错误码定义 |-| `openviking/server/routers/*.py` | 新增 | API 路由 |-| `openviking/client/http.py` | 新增 | HTTP 客户端 |-| `openviking/async_client.py` | 修改 | 支持 HTTP 模式 |--### 8.5 验证方案--#### Bash CLI 验证-```bash-openviking config init-openviking serve --port 1933-openviking add-resource ./docs/ --wait-openviking ls viking://-openviking find "how to use"-```--#### HTTP API 验证-```bash-curl http://localhost:1933/health-curl -X POST http://localhost:1933/api/v1/resources \- -H "X-API-Key: xxx" -d '{"path": "./docs"}'-curl "http://localhost:1933/api/v1/fs/ls?uri=viking://" \- -H "X-API-Key: xxx"-```--#### Python CLI 验证-```python-from openviking import OpenViking-client = OpenViking(url="http://localhost:1933", api_key="xxx")-result = client.find("how to use")-print(result)-```diff --git a/openviking/__main__.py b/openviking/__main__.pydeleted file mode 100644index 68a6e891f..000000000--- a/openviking/__main__.py+++ /dev/null@@ -1,14 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Main entry point for `python -m openviking`."""--from openviking_cli.cli.main import app---def main() -> None:- """Run the OpenViking CLI."""- app()---if __name__ == "__main__":- main()diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.pyindex d4bc369d2..51bbeb87f 100644--- a/openviking/server/routers/filesystem.py+++ b/openviking/server/routers/filesystem.py@@ -2,6 +2,8 @@# SPDX-License-Identifier: Apache-2.0"""Filesystem endpoints for OpenViking HTTP Server."""+from typing import Optional+from fastapi import APIRouter, Depends, Queryfrom pyagfs.exceptions import AGFSClientErrorfrom pydantic import BaseModel@@ -24,10 +26,12 @@ async def ls(abs_limit: int = Query(256, description="Abstract limit (only for agent output)"),show_all_hidden: bool = Query(False, description="List all hidden files, like -a"),node_limit: int = Query(1000, description="Maximum number of nodes to list"),+ limit: Optional[int] = Query(None, description="Alias for node_limit"),_ctx: RequestContext = Depends(get_request_context),):"""List directory contents."""service = get_service()+ actual_node_limit = limit if limit is not None else node_limitresult = await service.fs.ls(uri,ctx=_ctx,@@ -36,7 +40,7 @@ async def ls(output=output,abs_limit=abs_limit,show_all_hidden=show_all_hidden,- node_limit=node_limit,+ node_limit=actual_node_limit,)return Response(status="ok", result=result)@@ -48,18 +52,20 @@ async def tree(abs_limit: int = Query(256, description="Abstract limit (only for agent output)"),show_all_hidden: bool = Query(False, description="List all hidden files, like -a"),node_limit: int = Query(1000, description="Maximum number of nodes to list"),+ limit: Optional[int] = Query(None, description="Alias for node_limit"),level_limit: int = Query(3, description="Maximum depth level to traverse"),_ctx: RequestContext = Depends(get_request_context),):"""Get directory tree."""service = get_service()+ actual_node_limit = limit if limit is not None else node_limitresult = await service.fs.tree(uri,ctx=_ctx,output=output,abs_limit=abs_limit,show_all_hidden=show_all_hidden,- node_limit=node_limit,+ node_limit=actual_node_limit,level_limit=level_limit,)return Response(status="ok", result=result)diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.pyindex 299d93b2c..f7b0591b3 100644--- a/openviking/server/routers/search.py+++ b/openviking/server/routers/search.py@@ -21,6 +21,7 @@ class FindRequest(BaseModel):query: strtarget_uri: str = ""limit: int = 10+ node_limit: Optional[int] = Nonescore_threshold: Optional[float] = Nonefilter: Optional[Dict[str, Any]] = None@@ -32,6 +33,7 @@ class SearchRequest(BaseModel):target_uri: str = ""session_id: Optional[str] = Nonelimit: int = 10+ node_limit: Optional[int] = Nonescore_threshold: Optional[float] = Nonefilter: Optional[Dict[str, Any]] = None@@ -42,6 +44,7 @@ class GrepRequest(BaseModel):uri: strpattern: strcase_insensitive: bool = False+ node_limit: Optional[int] = Noneclass GlobRequest(BaseModel):@@ -58,11 +61,12 @@ async def find():"""Semantic search without session context."""service = get_service()+ actual_limit = request.node_limit if request.node_limit is not None else request.limitresult = await service.search.find(query=request.query,ctx=_ctx,target_uri=request.target_uri,- limit=request.limit,+ limit=actual_limit,score_threshold=request.score_threshold,filter=request.filter,)@@ -86,12 +90,13 @@ async def search(session = service.sessions.session(_ctx, request.session_id)await session.load()+ actual_limit = request.node_limit if request.node_limit is not None else request.limitresult = await service.search.search(query=request.query,ctx=_ctx,target_uri=request.target_uri,session=session,- limit=request.limit,+ limit=actual_limit,score_threshold=request.score_threshold,filter=request.filter,)@@ -113,6 +118,7 @@ async def grep(request.pattern,ctx=_ctx,case_insensitive=request.case_insensitive,+ node_limit=request.node_limit,)return Response(status="ok", result=result)diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.pyindex bec8a0dab..ce3d1a94d 100644--- a/openviking/service/fs_service.py+++ b/openviking/service/fs_service.py@@ -70,7 +70,11 @@ class FSService:)else:entries = await viking_fs.ls(- uri, ctx=ctx, output="original", show_all_hidden=show_all_hidden+ uri,+ ctx=ctx,+ output="original",+ show_all_hidden=show_all_hidden,+ node_limit=node_limit,)return [e.get("uri", "") for e in entries]@@ -91,6 +95,7 @@ class FSService:output=output,abs_limit=abs_limit,show_all_hidden=show_all_hidden,+ node_limit=node_limit,)return entries@@ -152,11 +157,18 @@ class FSService:return await viking_fs.overview(uri, ctx=ctx)async def grep(- self, uri: str, pattern: str, ctx: RequestContext, case_insensitive: bool = False+ self,+ uri: str,+ pattern: str,+ ctx: RequestContext,+ case_insensitive: bool = False,+ node_limit: Optional[int] = None,) -> Dict:"""Content search."""viking_fs = self._ensure_initialized()- return await viking_fs.grep(uri, pattern, case_insensitive=case_insensitive, ctx=ctx)+ return await viking_fs.grep(+ uri, pattern, case_insensitive=case_insensitive, node_limit=node_limit, ctx=ctx+ )async def glob(self, pattern: str, ctx: RequestContext, uri: str = "viking://") -> Dict:"""File pattern matching."""diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.pyindex c18abc29c..12fbca952 100644--- a/openviking/storage/viking_fs.py+++ b/openviking/storage/viking_fs.py@@ -300,12 +300,15 @@ class VikingFS:uri: str,pattern: str,case_insensitive: bool = False,+ node_limit: Optional[int] = None,ctx: Optional[RequestContext] = None,) -> Dict:"""Content search by pattern or keywords."""self._ensure_access(uri, ctx)path = self._uri_to_path(uri, ctx=ctx)- result = self.agfs.grep(path, pattern, True, case_insensitive)+ result = self.agfs.grep(+ path, pattern, True, case_insensitive, stream=False, node_limit=node_limit+ )if result.get("matches", None) is None:result["matches"] = []new_matches = []@@ -1312,6 +1315,7 @@ class VikingFS:output: str = "original",abs_limit: int = 256,show_all_hidden: bool = False,+ node_limit: int = 1000,ctx: Optional[RequestContext] = None,) -> List[Dict[str, Any]]:"""@@ -1322,6 +1326,7 @@ class VikingFS:output: str = "original"abs_limit: int = 256show_all_hidden: bool = False (list all hidden files, like -a)+ node_limit: int = 1000 (maximum number of nodes to list)output="original"[{'name': '.abstract.md', 'size': 100, 'mode': 420, 'modTime': '2026-02-11T16:52:16.256334192+08:00', 'isDir': False, 'meta': {'Name': 'localfs', 'Type': 'local', 'Content': None}, 'uri': 'viking://resources/.abstract.md'}]@@ -1331,9 +1336,9 @@ class VikingFS:"""self._ensure_access(uri, ctx)if output == "original":- return await self._ls_original(uri, show_all_hidden, ctx=ctx)+ return await self._ls_original(uri, show_all_hidden, node_limit, ctx=ctx)elif output == "agent":- return await self._ls_agent(uri, abs_limit, show_all_hidden, ctx=ctx)+ return await self._ls_agent(uri, abs_limit, show_all_hidden, node_limit, ctx=ctx)else:raise ValueError(f"Invalid output format: {output}")@@ -1342,6 +1347,7 @@ class VikingFS:uri: str,abs_limit: int,show_all_hidden: bool,+ node_limit: int = 1000,ctx: Optional[RequestContext] = None,) -> List[Dict[str, Any]]:"""List directory contents (URI version)."""@@ -1355,6 +1361,8 @@ class VikingFS:now = datetime.now()all_entries = []for entry in entries:+ if len(all_entries) >= node_limit:+ breakname = entry.get("name", "")# 修改后:通过截断字符串来兼容 7 位或更多位的微秒raw_time = entry.get("modTime", "")@@ -1386,6 +1394,7 @@ class VikingFS:self,uri: str,show_all_hidden: bool = False,+ node_limit: int = 1000,ctx: Optional[RequestContext] = None,) -> List[Dict[str, Any]]:"""List directory contents (URI version)."""@@ -1396,6 +1405,8 @@ class VikingFS:# AGFS returns read-only structure, need to create new dictall_entries = []for entry in entries:+ if len(all_entries) >= node_limit:+ breakname = entry.get("name", "")new_entry = dict(entry) # Copy original datanew_entry["uri"] = self._path_to_uri(f"{path}/{name}", ctx=ctx)diff --git a/openviking_cli/cli/__init__.py b/openviking_cli/cli/__init__.pydeleted file mode 100644index ab2b537a0..000000000--- a/openviking_cli/cli/__init__.py+++ /dev/null@@ -1,7 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""OpenViking CLI package."""--from openviking_cli.cli.main import app--__all__ = ["app"]diff --git a/openviking_cli/cli/commands/__init__.py b/openviking_cli/cli/commands/__init__.pydeleted file mode 100644index c6dfc6386..000000000--- a/openviking_cli/cli/commands/__init__.py+++ /dev/null@@ -1,36 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Command registration for OpenViking CLI."""--import typer--from openviking_cli.cli.commands import (- admin,- content,- debug,- filesystem,- observer,- pack,- relations,- resources,- search,- serve,- session,- system,-)---def register_commands(app: typer.Typer) -> None:- """Register all supported commands into the root CLI app."""- serve.register(app)- admin.register(app)- resources.register(app)- filesystem.register(app)- content.register(app)- search.register(app)- relations.register(app)- pack.register(app)- system.register(app)- debug.register(app)- observer.register(app)- session.register(app)diff --git a/openviking_cli/cli/commands/admin.py b/openviking_cli/cli/commands/admin.pydeleted file mode 100644index 728538832..000000000--- a/openviking_cli/cli/commands/admin.py+++ /dev/null@@ -1,107 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Admin commands for multi-tenant account and user management."""--import typer--from openviking_cli.cli.context import get_cli_context-from openviking_cli.cli.errors import execute_client_command, run-from openviking_cli.cli.output import output_success--admin_app = typer.Typer(help="Account and user management commands (multi-tenant)")---# ---- Account commands -------@admin_app.command("create-account")-def create_account_command(- ctx: typer.Context,- account_id: str = typer.Argument(..., help="Account ID to create"),- admin_user_id: str = typer.Option(..., "--admin", help="First admin user ID"),-) -> None:- """Create a new account with its first admin user."""- run(ctx, lambda client: client.admin_create_account(account_id, admin_user_id))---@admin_app.command("list-accounts")-def list_accounts_command(ctx: typer.Context) -> None:- """List all accounts (ROOT only)."""- run(ctx, lambda client: client.admin_list_accounts())---@admin_app.command("delete-account")-def delete_account_command(- ctx: typer.Context,- account_id: str = typer.Argument(..., help="Account ID to delete"),-) -> None:- """Delete an account and all associated users (ROOT only)."""- cli_ctx = get_cli_context(ctx)- result = execute_client_command(cli_ctx, lambda client: client.admin_delete_account(account_id))- output_success(cli_ctx, result if result is not None else {"account_id": account_id})---# ---- User commands -------@admin_app.command("register-user")-def register_user_command(- ctx: typer.Context,- account_id: str = typer.Argument(..., help="Account ID"),- user_id: str = typer.Argument(..., help="User ID to register"),- role: str = typer.Option("user", "--role", help="Role: admin or user"),-) -> None:- """Register a new user in an account."""- run(ctx, lambda client: client.admin_register_user(account_id, user_id, role))---@admin_app.command("list-users")-def list_users_command(- ctx: typer.Context,- account_id: str = typer.Argument(..., help="Account ID"),-) -> None:- """List all users in an account."""- run(ctx, lambda client: client.admin_list_users(account_id))---@admin_app.command("remove-user")-def remove_user_command(- ctx: typer.Context,- account_id: str = typer.Argument(..., help="Account ID"),- user_id: str = typer.Argument(..., help="User ID to remove"),-) -> None:- """Remove a user from an account."""- cli_ctx = get_cli_context(ctx)- result = execute_client_command(- cli_ctx, lambda client: client.admin_remove_user(account_id, user_id)- )- output_success(- cli_ctx,- result if result is not None else {"account_id": account_id, "user_id": user_id},- )---@admin_app.command("set-role")-def set_role_command(- ctx: typer.Context,- account_id: str = typer.Argument(..., help="Account ID"),- user_id: str = typer.Argument(..., help="User ID"),- role: str = typer.Argument(..., help="New role: admin or user"),-) -> None:- """Change a user's role (ROOT only)."""- run(ctx, lambda client: client.admin_set_role(account_id, user_id, role))---@admin_app.command("regenerate-key")-def regenerate_key_command(- ctx: typer.Context,- account_id: str = typer.Argument(..., help="Account ID"),- user_id: str = typer.Argument(..., help="User ID"),-) -> None:- """Regenerate a user's API key. Old key is immediately invalidated."""- run(ctx, lambda client: client.admin_regenerate_key(account_id, user_id))---def register(app: typer.Typer) -> None:- """Register admin command group."""- app.add_typer(admin_app, name="admin")diff --git a/openviking_cli/cli/commands/content.py b/openviking_cli/cli/commands/content.pydeleted file mode 100644index 613eefa45..000000000--- a/openviking_cli/cli/commands/content.py+++ /dev/null@@ -1,37 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Content reading commands."""--import typer--from openviking_cli.cli.errors import run---def register(app: typer.Typer) -> None:- """Register content commands."""-- @app.command("read")- def read_command(- ctx: typer.Context,- uri: str = typer.Argument(..., help="Viking URI"),- offset: int = typer.Option(0, "--offset", "-s", help="Starting line number (0-indexed)"),- limit: int = typer.Option(-1, "--limit", "-n", help="Number of lines to read (-1 = all)"),- ) -> None:- """Read full file content (L2)."""- run(ctx, lambda client: client.read(uri, offset=offset, limit=limit))-- @app.command("abstract")- def abstract_command(- ctx: typer.Context,- uri: str = typer.Argument(..., help="Viking URI"),- ) -> None:- """Read abstract content (L0)."""- run(ctx, lambda client: client.abstract(uri))-- @app.command("overview")- def overview_command(- ctx: typer.Context,- uri: str = typer.Argument(..., help="Viking URI"),- ) -> None:- """Read overview content (L1)."""- run(ctx, lambda client: client.overview(uri))diff --git a/openviking_cli/cli/commands/debug.py b/openviking_cli/cli/commands/debug.pydeleted file mode 100644index e821c0768..000000000--- a/openviking_cli/cli/commands/debug.py+++ /dev/null@@ -1,27 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Debug and health commands."""--import typer--from openviking_cli.cli.context import get_cli_context-from openviking_cli.cli.errors import execute_client_command, run-from openviking_cli.cli.output import output_success---def register(app: typer.Typer) -> None:- """Register debug commands."""-- @app.command("status")- def status_command(ctx: typer.Context) -> None:- """Show OpenViking component status."""- run(ctx, lambda client: client.get_status())-- @app.command("health")- def health_command(ctx: typer.Context) -> None:- """Quick health check."""- cli_ctx = get_cli_context(ctx)- result = execute_client_command(cli_ctx, lambda client: client.is_healthy())- output_success(cli_ctx, {"healthy": result})- if not result:- raise typer.Exit(1)diff --git a/openviking_cli/cli/commands/filesystem.py b/openviking_cli/cli/commands/filesystem.pydeleted file mode 100644index 651f7298d..000000000--- a/openviking_cli/cli/commands/filesystem.py+++ /dev/null@@ -1,106 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Filesystem commands."""--import typer--from openviking_cli.cli.errors import run---def register(app: typer.Typer) -> None:- """Register filesystem commands."""-- @app.command("ls")- def ls_command(- ctx: typer.Context,- uri: str = typer.Argument("viking://", help="Viking URI"),- simple: bool = typer.Option(False, "--simple", "-s", help="Simple path output"),- recursive: bool = typer.Option(- False,- "--recursive",- "-r",- help="List all subdirectories recursively",- ),- output_format: str = typer.Option(- "agent", "--output-format", "-f", help="Output format: agent or original"- ),- abs_limit: int = typer.Option(256, "--abs-limit", "-l", help="Abstract content limit"),- show_all_hidden: bool = typer.Option(False, "--all", "-a", help="Show all hidden files"),- node_limit: int = typer.Option(- 1000, "--node-limit", "-n", help="Maximum number of nodes to list"- ),- ) -> None:- """List directory contents."""- run(- ctx,- lambda client: client.ls(- uri,- simple=simple,- recursive=recursive,- output=output_format,- abs_limit=abs_limit,- show_all_hidden=show_all_hidden,- node_limit=node_limit,- ),- )-- @app.command("tree")- def tree_command(- ctx: typer.Context,- uri: str = typer.Argument(..., help="Viking URI"),- output_format: str = typer.Option(- "agent", "--output-format", "-f", help="Output format: agent or original"- ),- abs_limit: int = typer.Option(128, "--abs-limit", "-l", help="Abstract content limit"),- show_all_hidden: bool = typer.Option(False, "--all", "-a", help="Show all hidden files"),- node_limit: int = typer.Option(- 1000, "--node-limit", "-n", help="Maximum number of nodes to list"- ),- ) -> None:- """- Get directory tree info.- """- run(- ctx,- lambda client: client.tree(- uri,- output=output_format,- abs_limit=abs_limit,- show_all_hidden=show_all_hidden,- node_limit=node_limit,- ),- )-- @app.command("mkdir")- def mkdir_command(- ctx: typer.Context,- uri: str = typer.Argument(..., help="Directory URI to create"),- ) -> None:- """Create a directory."""- run(ctx, lambda client: client.mkdir(uri))-- @app.command("rm")- def rm_command(- ctx: typer.Context,- uri: str = typer.Argument(..., help="Viking URI to remove"),- recursive: bool = typer.Option(False, "--recursive", "-r", help="Remove recursively"),- ) -> None:- """Remove a resource."""- run(ctx, lambda client: client.rm(uri, recursive=recursive))-- @app.command("mv")- def mv_command(- ctx: typer.Context,- from_uri: str = typer.Argument(..., help="Source URI"),- to_uri: str = typer.Argument(..., help="Target URI"),- ) -> None:- """Move or rename a resource."""- run(ctx, lambda client: client.mv(from_uri, to_uri))-- @app.command("stat")- def stat_command(- ctx: typer.Context,- uri: str = typer.Argument(..., help="Viking URI"),- ) -> None:- """Get resource metadata and status."""- run(ctx, lambda client: client.stat(uri))diff --git a/openviking_cli/cli/commands/observer.py b/openviking_cli/cli/commands/observer.pydeleted file mode 100644index 1de1c52a5..000000000--- a/openviking_cli/cli/commands/observer.py+++ /dev/null@@ -1,38 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Observer commands."""--import typer--from openviking_cli.cli.errors import run--observer_app = typer.Typer(help="Observer status commands")---@observer_app.command("queue")-def observer_queue_command(ctx: typer.Context) -> None:- """Get queue status."""- run(ctx, lambda client: client.observer.queue)---@observer_app.command("vikingdb")-def observer_vikingdb_command(ctx: typer.Context) -> None:- """Get VikingDB status."""- run(ctx, lambda client: client.observer.vikingdb)---@observer_app.command("vlm")-def observer_vlm_command(ctx: typer.Context) -> None:- """Get VLM status."""- run(ctx, lambda client: client.observer.vlm)---@observer_app.command("system")-def observer_system_command(ctx: typer.Context) -> None:- """Get overall system status."""- run(ctx, lambda client: client.observer.system)---def register(app: typer.Typer) -> None:- """Register observer command group."""- app.add_typer(observer_app, name="observer")diff --git a/openviking_cli/cli/commands/pack.py b/openviking_cli/cli/commands/pack.pydeleted file mode 100644index 2f8d900eb..000000000--- a/openviking_cli/cli/commands/pack.py+++ /dev/null@@ -1,45 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Import/export pack commands."""--import typer--from openviking_cli.cli.errors import run---def register(app: typer.Typer) -> None:- """Register pack commands."""-- @app.command("export")- def export_command(- ctx: typer.Context,- uri: str = typer.Argument(..., help="Source URI"),- to: str = typer.Argument(..., help="Output .ovpack file path"),- ) -> None:- """Export context as .ovpack."""- run(ctx, lambda client: {"file": client.export_ovpack(uri, to)})-- @app.command("import")- def import_command(- ctx: typer.Context,- file_path: str = typer.Argument(..., help="Input .ovpack file path"),- target_uri: str = typer.Argument(..., help="Target parent URI"),- force: bool = typer.Option(False, "--force", help="Overwrite when conflicts exist"),- no_vectorize: bool = typer.Option(- False,- "--no-vectorize",- help="Disable vectorization after import",- ),- ) -> None:- """Import .ovpack into target URI."""- run(- ctx,- lambda client: {- "uri": client.import_ovpack(- file_path=file_path,- target=target_uri,- force=force,- vectorize=not no_vectorize,- )- },- )diff --git a/openviking_cli/cli/commands/relations.py b/openviking_cli/cli/commands/relations.pydeleted file mode 100644index aa066f80c..000000000--- a/openviking_cli/cli/commands/relations.py+++ /dev/null@@ -1,58 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Relation management commands."""--from typing import List--import typer--from openviking_cli.cli.context import get_cli_context-from openviking_cli.cli.errors import execute_client_command, run-from openviking_cli.cli.output import output_success---def register(app: typer.Typer) -> None:- """Register relation commands."""-- @app.command("relations")- def relations_command(- ctx: typer.Context,- uri: str = typer.Argument(..., help="Viking URI"),- ) -> None:- """List relations of a resource."""- run(ctx, lambda client: client.relations(uri))-- @app.command("link")- def link_command(- ctx: typer.Context,- from_uri: str = typer.Argument(..., help="Source URI"),- to_uris: List[str] = typer.Argument(..., help="One or more target URIs"),- reason: str = typer.Option("", "--reason", help="Reason for linking"),- ) -> None:- """Create relation links from one URI to one or more targets."""- cli_ctx = get_cli_context(ctx)- result = execute_client_command(- cli_ctx,- lambda client: client.link(from_uri, to_uris, reason),- )- output_success(- cli_ctx,- result if result is not None else {"from": from_uri, "to": to_uris, "reason": reason},- )-- @app.command("unlink")- def unlink_command(- ctx: typer.Context,- from_uri: str = typer.Argument(..., help="Source URI"),- to_uri: str = typer.Argument(..., help="Target URI to unlink"),- ) -> None:- """Remove a relation link."""- cli_ctx = get_cli_context(ctx)- result = execute_client_command(- cli_ctx,- lambda client: client.unlink(from_uri, to_uri),- )- output_success(- cli_ctx,- result if result is not None else {"from": from_uri, "to": to_uri},- )diff --git a/openviking_cli/cli/commands/resources.py b/openviking_cli/cli/commands/resources.pydeleted file mode 100644index 6fafbb189..000000000--- a/openviking_cli/cli/commands/resources.py+++ /dev/null@@ -1,128 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Resource management commands."""--from pathlib import Path-from typing import Optional--import typer--from openviking_cli.cli.errors import run---def register(app: typer.Typer) -> None:- """Register resource commands."""-- @app.command("add-resource")- def add_resource_command(- ctx: typer.Context,- path: str = typer.Argument(..., help="Local path or URL to import"),- to: Optional[str] = typer.Option(None, "--to", help="Target URI"),- reason: str = typer.Option("", help="Reason for import"),- instruction: str = typer.Option("", help="Additional instruction"),- wait: bool = typer.Option(False, "--wait", help="Wait until processing is complete"),- timeout: Optional[float] = typer.Option(600.0, help="Wait timeout in seconds"),- no_strict: bool = typer.Option(- False, "--no-strict", help="No strict mode for directory scanning"- ),- ignore_dirs: Optional[str] = typer.Option(- None, "--ignore-dirs", help='Ignore directories, e.g. --ignore-dirs "node_modules,dist"'- ),- include: Optional[str] = typer.Option(- None, "--include", help='Include files extensions, e.g. --include "*.pdf,*.md"'- ),- exclude: Optional[str] = typer.Option(- None, "--exclude", help='Exclude files extensions, e.g. --exclude "*.tmp,*.log"'- ),- no_directly_upload_media: bool = typer.Option(- False, "--no-directly-upload-media", help="Do not directly upload media files"- ),- ) -> None:- """Add resources into OpenViking."""- # Validate path: if it's a local path, check if it exists- final_path = path- if not (- path.startswith(("http://", "https://", "git@", "ssh://", "git://"))- ):- unescaped_path = path.replace("\\ ", " ")- local_path = Path(unescaped_path)- final_path = unescaped_path- if not local_path.exists():- # Check if there are extra arguments (possible unquoted path with spaces)- import sys-- # Find the index of 'add-resource' in sys.argv- try:- add_resource_idx = sys.argv.index("add-resource")- except ValueError:- add_resource_idx = sys.argv.index("add") if "add" in sys.argv else -1-- if add_resource_idx != -1 and len(sys.argv) > add_resource_idx + 2:- # There are extra positional arguments - likely unquoted path with spaces- extra_args = sys.argv[add_resource_idx + 2 :]- suggested_path = f"{path} {' '.join(extra_args)}"- typer.echo(- typer.style(- f"Error: Path '{path}' does not exist.",- fg=typer.colors.RED,- bold=True,- ),- err=True,- )- typer.echo(- typer.style(- "\nIt looks like you may have forgotten to quote a path with spaces.",- fg=typer.colors.YELLOW,- ),- err=True,- )- typer.echo(- typer.style(- f'Suggested command: ov add-resource "{suggested_path}"',- fg=typer.colors.CYAN,- ),- err=True,- )- raise typer.Exit(code=1)- else:- typer.echo(- typer.style(- f"Error: Path '{path}' does not exist.", fg=typer.colors.RED, bold=True- ),- err=True,- )- raise typer.Exit(code=1)-- run(- ctx,- lambda client: client.add_resource(- path=final_path,- target=to,- reason=reason,- instruction=instruction,- wait=wait,- timeout=timeout,- strict=not no_strict,- ignore_dirs=ignore_dirs,- include=include,- exclude=exclude,- directly_upload_media=not no_directly_upload_media,- ),- )-- @app.command("add-skill")- def add_skill_command(- ctx: typer.Context,- data: str = typer.Argument(..., help="Skill directory, SKILL.md, or raw content"),- wait: bool = typer.Option(False, "--wait", help="Wait until processing is complete"),- timeout: Optional[float] = typer.Option(600.0, help="Wait timeout in seconds"),- ) -> None:- """Add a skill into OpenViking."""- run(- ctx,- lambda client: client.add_skill(- data=data,- wait=wait,- timeout=timeout,- ),- )diff --git a/openviking_cli/cli/commands/search.py b/openviking_cli/cli/commands/search.pydeleted file mode 100644index be599019b..000000000--- a/openviking_cli/cli/commands/search.py+++ /dev/null@@ -1,86 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Search commands."""--from typing import Optional--import typer--from openviking_cli.cli.errors import run---def register(app: typer.Typer) -> None:- """Register search commands."""-- @app.command("find")- def find_command(- ctx: typer.Context,- query: str = typer.Argument(..., help="Search query"),- uri: str = typer.Option("", "--uri", "-u", help="Target URI"),- limit: int = typer.Option(10, "--limit", "-n", help="Maximum number of results"),- threshold: Optional[float] = typer.Option(- None,- "--threshold",- "-t",- help="Score threshold",- ),- ) -> None:- """Run semantic retrieval."""- run(- ctx,- lambda client: client.find(- query=query,- target_uri=uri,- limit=limit,- score_threshold=threshold,- ),- )-- @app.command("search")- def search_command(- ctx: typer.Context,- query: str = typer.Argument(..., help="Search query"),- uri: str = typer.Option("", "--uri", "-u", help="Target URI"),- session_id: Optional[str] = typer.Option(- None,- "--session-id",- help="Session ID for context-aware search",- ),- limit: int = typer.Option(10, "--limit", "-n", help="Maximum number of results"),- threshold: Optional[float] = typer.Option(- None,- "--threshold",- "-t",- help="Score threshold",- ),- ) -> None:- """Run context-aware retrieval."""- run(- ctx,- lambda client: client.search(- query=query,- target_uri=uri,- session_id=session_id,- limit=limit,- score_threshold=threshold,- ),- )-- @app.command("grep")- def grep_command(- ctx: typer.Context,- uri: str = typer.Option("viking://", "--uri", "-u", help="Target URI"),- pattern: str = typer.Argument(..., help="Search pattern"),- ignore_case: bool = typer.Option(False, "--ignore-case", "-i", help="Case insensitive"),- ) -> None:- """Run content pattern search."""- run(ctx, lambda client: client.grep(uri, pattern, case_insensitive=ignore_case))-- @app.command("glob")- def glob_command(- ctx: typer.Context,- pattern: str = typer.Argument(..., help="Glob pattern"),- uri: str = typer.Option("viking://", "--uri", "-u", help="Search root URI"),- ) -> None:- """Run file glob pattern search."""- run(ctx, lambda client: client.glob(pattern, uri=uri))diff --git a/openviking_cli/cli/commands/serve.py b/openviking_cli/cli/commands/serve.pydeleted file mode 100644index 302a76ae7..000000000--- a/openviking_cli/cli/commands/serve.py+++ /dev/null@@ -1,45 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""`serve` command implementation."""--import os-from typing import Optional--import typer--from openviking_cli.cli.context import get_cli_context-from openviking_cli.cli.errors import handle_command_error---def register(app: typer.Typer) -> None:- """Register `serve` command."""-- @app.command("serve")- def serve_command(- ctx: typer.Context,- host: Optional[str] = typer.Option(None, help="Host to bind to"),- port: Optional[int] = typer.Option(None, help="Port to bind to"),- config: Optional[str] = typer.Option(None, help="Path to ov.conf config file"),- ) -> None:- """Start OpenViking HTTP server."""- cli_ctx = get_cli_context(ctx)-- try:- import uvicorn-- from openviking.server.app import create_app- from openviking.server.config import load_server_config-- if config is not None:- os.environ["OPENVIKING_CONFIG_FILE"] = config-- server_config = load_server_config(config)- if host is not None:- server_config.host = host- if port is not None:- server_config.port = port-- app_instance = create_app(server_config)- uvicorn.run(app_instance, host=server_config.host, port=server_config.port)- except Exception as exc: # noqa: BLE001- handle_command_error(cli_ctx, exc)diff --git a/openviking_cli/cli/commands/session.py b/openviking_cli/cli/commands/session.pydeleted file mode 100644index 592f0bd81..000000000--- a/openviking_cli/cli/commands/session.py+++ /dev/null@@ -1,70 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Session commands."""--import typer--from openviking_cli.cli.context import get_cli_context-from openviking_cli.cli.errors import execute_client_command, run-from openviking_cli.cli.output import output_success--session_app = typer.Typer(help="Session management commands")---@session_app.command("new")-def session_new_command(- ctx: typer.Context,-) -> None:- """Create a new session."""- run(ctx, lambda client: client.create_session())---@session_app.command("list")-def session_list_command(ctx: typer.Context) -> None:- """List sessions."""- run(ctx, lambda client: client.list_sessions())---@session_app.command("get")-def session_get_command(- ctx: typer.Context,- session_id: str = typer.Argument(..., help="Session ID"),-) -> None:- """Get session details."""- run(ctx, lambda client: client.get_session(session_id))---@session_app.command("delete")-def session_delete_command(- ctx: typer.Context,- session_id: str = typer.Argument(..., help="Session ID"),-) -> None:- """Delete a session."""- cli_ctx = get_cli_context(ctx)- result = execute_client_command(cli_ctx, lambda client: client.delete_session(session_id))- output_success(cli_ctx, result if result is not None else {"session_id": session_id})---@session_app.command("add-message")-def session_add_message_command(- ctx: typer.Context,- session_id: str = typer.Argument(..., help="Session ID"),- role: str = typer.Option(..., "--role", help="Message role, e.g. user/assistant"),- content: str = typer.Option(..., "--content", help="Message content"),-) -> None:- """Add one message to a session."""- run(ctx, lambda client: client.add_message(session_id=session_id, role=role, content=content))---@session_app.command("commit")-def session_commit_command(- ctx: typer.Context,- session_id: str = typer.Argument(..., help="Session ID"),-) -> None:- """Commit a session (archive messages and extract memories)."""- run(ctx, lambda client: client.commit_session(session_id))---def register(app: typer.Typer) -> None:- """Register session command group."""- app.add_typer(session_app, name="session")diff --git a/openviking_cli/cli/commands/system.py b/openviking_cli/cli/commands/system.pydeleted file mode 100644index 4ee328793..000000000--- a/openviking_cli/cli/commands/system.py+++ /dev/null@@ -1,21 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""System utility commands."""--from typing import Optional--import typer--from openviking_cli.cli.errors import run---def register(app: typer.Typer) -> None:- """Register system utility commands."""-- @app.command("wait")- def wait_command(- ctx: typer.Context,- timeout: Optional[float] = typer.Option(None, help="Wait timeout in seconds"),- ) -> None:- """Wait for queued async processing to complete."""- run(ctx, lambda client: client.wait_processed(timeout))diff --git a/openviking_cli/cli/context.py b/openviking_cli/cli/context.pydeleted file mode 100644index e3fcae80e..000000000--- a/openviking_cli/cli/context.py+++ /dev/null@@ -1,52 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Runtime context and client factory for CLI commands."""--from dataclasses import dataclass, field-from typing import TYPE_CHECKING, Optional--import typer--if TYPE_CHECKING:- from openviking_cli.client.sync_http import SyncHTTPClient---class CliConfigError(ValueError):- """Raised when required CLI configuration is missing or invalid."""---@dataclass-class CLIContext:- """Shared state for one CLI invocation."""-- compact: bool = True- output_format: str = "table"- _client: Optional["SyncHTTPClient"] = field(default=None, init=False, repr=False)-- def get_client_http_only(self) -> "SyncHTTPClient":- """Create an HTTP client (auto-loads ovcli.conf)."""- if self._client is not None:- return self._client-- from openviking_cli.client.sync_http import SyncHTTPClient-- try:- self._client = SyncHTTPClient()- except ValueError as e:- raise CliConfigError(str(e)) from e- self._client.initialize()- return self._client-- def close_client(self) -> None:- """Close the client if it has been created."""- if self._client is None:- return- self._client.close()- self._client = None---def get_cli_context(ctx: typer.Context) -> CLIContext:- """Return a typed CLI context from Typer context."""- if not isinstance(ctx.obj, CLIContext):- raise RuntimeError("CLI context is not initialized")- return ctx.objdiff --git a/openviking_cli/cli/errors.py b/openviking_cli/cli/errors.pydeleted file mode 100644index 808d8762b..000000000--- a/openviking_cli/cli/errors.py+++ /dev/null@@ -1,81 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Exception handling helpers for CLI commands."""--from typing import Any, Callable--import httpx-import typer--from openviking_cli.cli.context import CliConfigError, CLIContext, get_cli_context-from openviking_cli.cli.output import output_error, output_success-from openviking_cli.exceptions import OpenVikingError---def handle_command_error(ctx: CLIContext, exc: Exception) -> None:- """Normalize command exceptions into user-facing output and exit codes."""- if isinstance(exc, typer.Exit):- raise exc-- if isinstance(exc, CliConfigError):- output_error(- ctx,- message=str(exc),- code="CLI_CONFIG",- details={"config_file": "ovcli.conf"},- exit_code=2,- )-- elif isinstance(exc, OpenVikingError):- output_error(- ctx,- message=exc.message,- code=exc.code,- details=exc.details,- exit_code=1,- )-- elif isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout, httpx.ReadTimeout)):- output_error(- ctx,- message=(- "Failed to connect to OpenViking server. "- "Check the url in ovcli.conf and ensure the server is running."- ),- code="CONNECTION_ERROR",- exit_code=3,- details={"exception": str(exc)},- )-- else:- output_error(- ctx,- message=str(exc),- code="CLI_ERROR",- exit_code=1,- details={"exception": type(exc).__name__},- )---def execute_client_command(- ctx: CLIContext,- operation: Callable[[Any], Any],-) -> Any:- """Run a client command with consistent error handling and cleanup."""- try:- client = ctx.get_client_http_only()- return operation(client)- except Exception as exc: # noqa: BLE001- handle_command_error(ctx, exc)- finally:- ctx.close_client()---def run(- ctx: typer.Context,- fn: Callable[[Any], Any],-) -> None:- """Execute a client command with boilerplate: context → execute → output."""- cli_ctx = get_cli_context(ctx)- result = execute_client_command(cli_ctx, fn)- output_success(cli_ctx, result)diff --git a/openviking_cli/cli/main.py b/openviking_cli/cli/main.pydeleted file mode 100644index fca32abcc..000000000--- a/openviking_cli/cli/main.py+++ /dev/null@@ -1,73 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""Typer entrypoint for OpenViking CLI."""--from typing import Optional--import typer--from openviking_cli.cli.commands import register_commands-from openviking_cli.cli.context import CLIContext-from openviking_cli.utils.config.config_loader import (- DEFAULT_OVCLI_CONF,- OPENVIKING_CLI_CONFIG_ENV,- load_json_config,- resolve_config_path,-)--app = typer.Typer(- help="OpenViking - An Agent-native context database",- no_args_is_help=True,- add_completion=False,-)---def _version_callback(value: bool) -> None:- if value:- from openviking import __version__-- typer.echo(f"openviking {__version__}")- raise typer.Exit()---def main(- ctx: typer.Context,- compact: bool = typer.Option(- True,- "--compact",- "-c",- help="Compact representation, defaults to true - compacts JSON output or uses simplified representation for Table output",- ),- output_format: Optional[str] = typer.Option(- None, "--output", "-o", help="Output format: table (default), json"- ),- version: Optional[bool] = typer.Option(- None,- "--version",- callback=_version_callback,- is_eager=True,- help="Show version and exit",- ),-) -> None:- """Configure shared CLI options."""- # Priority: --output CLI arg > ovcli.conf "output" field > default "table"- if output_format is None:- config_path = resolve_config_path(None, OPENVIKING_CLI_CONFIG_ENV, DEFAULT_OVCLI_CONF)- if config_path is not None:- try:- cfg = load_json_config(config_path)- output_format = cfg.get("output")- except (ValueError, FileNotFoundError):- pass- if output_format is None:- output_format = "table"-- ctx.obj = CLIContext(compact=compact, output_format=output_format)---register_commands(app)---if __name__ == "__main__":- app()diff --git a/openviking_cli/cli/output.py b/openviking_cli/cli/output.pydeleted file mode 100644index 91260f9a1..000000000--- a/openviking_cli/cli/output.py+++ /dev/null@@ -1,186 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""CLI output helpers."""--import json-from dataclasses import asdict, is_dataclass-from typing import Any, Dict, List, Optional--import typer-from tabulate import tabulate--from openviking_cli.cli.context import CLIContext--_MAX_COL_WIDTH = 256---def _to_serializable(value: Any) -> Any:- """Convert rich Python values to JSON-serializable primitives."""- if value is None or isinstance(value, (str, int, float, bool)):- return value- if hasattr(value, "to_dict"):- return _to_serializable(value.to_dict())- if is_dataclass(value):- return _to_serializable(asdict(value))- if isinstance(value, dict):- return {str(k): _to_serializable(v) for k, v in value.items()}- if isinstance(value, (list, tuple, set)):- return [_to_serializable(item) for item in value]- return str(value)---def _truncate(val: Any) -> Any:- """Truncate a value to _MAX_COL_WIDTH for table display."""- s = str(val) if not isinstance(val, str) else val- return s[: _MAX_COL_WIDTH - 3] + "..." if len(s) > _MAX_COL_WIDTH else val---def _format_list_table(rows: List[Dict[str, Any]], compact: bool = True) -> Optional[str]:- """Render a list of dict rows as a table with truncation, skipping empty columns when compact=True."""- if not rows:- return None-- all_headers: List[str] = []- for row in rows:- for key in row.keys():- key_str = str(key)- if key_str not in all_headers:- all_headers.append(key_str)-- if not all_headers:- return None-- non_empty_headers = []- for header in all_headers:- has_value = False- for row in rows:- val = row.get(header)- if val:- if val is not None and val != "" and not (isinstance(val, list) and len(val) == 0):- has_value = True- break- if has_value or not compact:- non_empty_headers.append(header)- if not non_empty_headers:- return None-- values = [[_truncate(row.get(h, "")) for h in non_empty_headers] for row in rows]- return tabulate(values, headers=non_empty_headers, tablefmt="plain")---def _is_primitive_list(v: Any) -> bool:- return isinstance(v, list) and v and all(isinstance(r, (str, int, float, bool)) for r in v)---def _is_dict_list(v: Any) -> bool:- return isinstance(v, list) and v and all(isinstance(r, dict) for r in v)---def _to_table(data: Any, compact: bool = True) -> Optional[str]:- """Try to render data as a table. Returns None if not possible."""- # Rule 1: list[dict] -> multi-row table- if isinstance(data, list) and data and all(isinstance(r, dict) for r in data):- return _format_list_table(data, compact)-- if not isinstance(data, dict):- return None-- # Rule 5: ComponentStatus (name + is_healthy + status)- if {"name", "is_healthy", "status"}.issubset(data):- health = "healthy" if data["is_healthy"] else "unhealthy"- return f"[{data['name']}] ({health})\n{data['status']}"-- # Rule 6: SystemStatus (is_healthy + components)- if "components" in data and "is_healthy" in data:- lines: List[str] = []- for comp in data["components"].values():- table = _to_table(comp, compact)- if table:- lines.append(table)- lines.append("")- health = "healthy" if data["is_healthy"] else "unhealthy"- lines.append(f"[system] ({health})")- if data.get("errors"):- lines.append(f"Errors: {', '.join(data['errors'])}")- return "\n".join(lines)-- # Extract list fields- dict_lists = {k: v for k, v in data.items() if _is_dict_list(v)}- prim_lists = {k: v for k, v in data.items() if _is_primitive_list(v)}-- # Rule 3a: single list[primitive] -> one item per line- if not dict_lists and len(prim_lists) == 1:- key, items = next(iter(prim_lists.items()))- col = key.rstrip("es") if key.endswith("es") else key.rstrip("s")- return _format_list_table([{col: item} for item in items], compact)-- # Rule 3b: single list[dict] -> render directly- if len(dict_lists) == 1 and not prim_lists:- return _format_list_table(next(iter(dict_lists.values())), compact)-- # Rule 2: multiple list[dict] -> flatten with type column- if dict_lists:- merged: List[Dict[str, Any]] = []- for key, items in dict_lists.items():- for item in items:- merged.append({"type": key.rstrip("s"), **item})- if merged:- return _format_list_table(merged, compact)-- # Rule 4: plain dict (no expandable lists) -> single-row horizontal table- if not dict_lists and not prim_lists:- return tabulate(- [[_truncate(v) for v in data.values()]], headers=data.keys(), tablefmt="plain"- )-- return None---def output_success(ctx: CLIContext, result: Any) -> None:- """Print successful command result."""- serializable = _to_serializable(result)-- if ctx.output_format == "json" and ctx.compact:- typer.echo(json.dumps({"ok": True, "result": serializable}, ensure_ascii=False))- return- if serializable is None:- return- if isinstance(serializable, str):- typer.echo(serializable)- return-- if ctx.output_format == "table":- table = _to_table(serializable, ctx.compact)- if table is not None:- typer.echo(table)- return-- if ctx.compact:- typer.echo(json.dumps(serializable, ensure_ascii=False))- else:- typer.echo(json.dumps(serializable, ensure_ascii=False, indent=2))---def output_error(- ctx: CLIContext,- *,- message: str,- code: str,- exit_code: int,- details: Optional[Dict[str, Any]] = None,-) -> None:- """Print error in JSON or plain format then exit."""- details = details or {}- if ctx.output_format == "json" and ctx.compact:- payload = {- "ok": False,- "error": {- "code": code,- "message": message,- "details": _to_serializable(details),- },- }- typer.echo(json.dumps(payload, ensure_ascii=False), err=True)- else:- typer.echo(f"ERROR[{code}]: {message}", err=True)- raise typer.Exit(exit_code)diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.pyindex e63a3a407..0c6f612f7 100644--- a/openviking_cli/client/http.py+++ b/openviking_cli/client/http.py@@ -504,18 +504,20 @@ class AsyncHTTPClient(BaseClient):query: str,target_uri: str = "",limit: int = 10,+ node_limit: Optional[int] = None,score_threshold: Optional[float] = None,filter: Optional[Dict[str, Any]] = None,) -> FindResult:"""Semantic search without session context."""if target_uri:target_uri = VikingURI.normalize(target_uri)+ actual_limit = node_limit if node_limit is not None else limitresponse = await self._http.post("/api/v1/search/find",json={"query": query,"target_uri": target_uri,- "limit": limit,+ "limit": actual_limit,"score_threshold": score_threshold,"filter": filter,},@@ -529,12 +531,14 @@ class AsyncHTTPClient(BaseClient):session: Optional[Any] = None,session_id: Optional[str] = None,limit: int = 10,+ node_limit: Optional[int] = None,score_threshold: Optional[float] = None,filter: Optional[Dict[str, Any]] = None,) -> FindResult:"""Semantic search with optional session context."""if target_uri:target_uri = VikingURI.normalize(target_uri)+ actual_limit = node_limit if node_limit is not None else limitsid = session_id or (session.session_id if session else None)response = await self._http.post("/api/v1/search/search",@@ -542,23 +546,32 @@ class AsyncHTTPClient(BaseClient):"query": query,"target_uri": target_uri,"session_id": sid,- "limit": limit,+ "limit": actual_limit,"score_threshold": score_threshold,"filter": filter,},)return FindResult.from_dict(self._handle_response(response))- async def grep(self, uri: str, pattern: str, case_insensitive: bool = False) -> Dict[str, Any]:+ async def grep(+ self,+ uri: str,+ pattern: str,+ case_insensitive: bool = False,+ node_limit: Optional[int] = None,+ ) -> Dict[str, Any]:"""Content search with pattern."""uri = VikingURI.normalize(uri)+ request_json = {+ "uri": uri,+ "pattern": pattern,+ "case_insensitive": case_insensitive,+ }+ if node_limit is not None:+ request_json["node_limit"] = node_limitresponse = await self._http.post("/api/v1/search/grep",- json={- "uri": uri,- "pattern": pattern,- "case_insensitive": case_insensitive,- },+ json=request_json,)return self._handle_response(response)diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.pyindex d9b329c84..584a72e4b 100644--- a/openviking_cli/client/sync_http.py+++ b/openviking_cli/client/sync_http.py@@ -164,6 +164,7 @@ class SyncHTTPClient:session: Optional[Any] = None,session_id: Optional[str] = None,limit: int = 10,+ node_limit: Optional[int] = None,score_threshold: Optional[float] = None,filter: Optional[Dict] = None,):@@ -175,6 +176,7 @@ class SyncHTTPClient:session=session,session_id=session_id,limit=limit,+ node_limit=node_limit,score_threshold=score_threshold,filter=filter,)@@ -185,15 +187,24 @@ class SyncHTTPClient:query: str,target_uri: str = "",limit: int = 10,+ node_limit: Optional[int] = None,score_threshold: Optional[float] = None,filter: Optional[Dict] = None,):"""Semantic search without session context."""- return run_async(self._async_client.find(query, target_uri, limit, score_threshold, filter))+ return run_async(+ self._async_client.find(query, target_uri, limit, node_limit, score_threshold, filter)+ )- def grep(self, uri: str, pattern: str, case_insensitive: bool = False) -> Dict:+ def grep(+ self,+ uri: str,+ pattern: str,+ case_insensitive: bool = False,+ node_limit: Optional[int] = None,+ ) -> Dict:"""Content search with pattern."""- return run_async(self._async_client.grep(uri, pattern, case_insensitive))+ return run_async(self._async_client.grep(uri, pattern, case_insensitive, node_limit))def glob(self, pattern: str, uri: str = "viking://") -> Dict:"""File pattern matching."""diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.pydeleted file mode 100644index 47a8ef80b..000000000--- a/tests/cli/test_cli.py+++ /dev/null@@ -1,243 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: Apache-2.0-"""CLI tests that use real HTTP requests."""--import json-import os-import tempfile--from typer.testing import CliRunner--from openviking_cli.cli.main import app--runner = CliRunner()---def _make_ovcli_conf(url: str, tmp_dir: str) -> str:- """Create a temporary ovcli.conf and return its path."""- conf_path = os.path.join(tmp_dir, "ovcli.conf")- with open(conf_path, "w") as f:- json.dump({"url": url, "api_key": None}, f)- return conf_path---def _run_cli(args, server_url, env=None, expected_exit_code=0):- """Run a CLI command and optionally parse JSON output.-- Args:- args: CLI arguments- server_url: OpenViking server URL- env: Extra environment variables- expected_exit_code: Expected exit code (default 0)-- Returns:- Parsed JSON payload if exit_code is 0 and output is valid JSON,- otherwise the raw CliRunner Result.- """- with tempfile.TemporaryDirectory() as tmp_dir:- conf_path = _make_ovcli_conf(server_url, tmp_dir)- merged_env = {"OPENVIKING_CLI_CONFIG_FILE": conf_path}- if env:- merged_env.update(env)- result = runner.invoke(app, ["-o", "json", *args], env=merged_env)- assert result.exit_code == expected_exit_code, (- f"Expected exit_code={expected_exit_code}, got {result.exit_code}\n"- f"args={args}\n{result.output}"- )- if expected_exit_code != 0:- return result- try:- payload = json.loads(result.output)- except json.JSONDecodeError:- return result- assert payload["ok"] is True- return payload---def test_requires_ovcli_conf():- result = runner.invoke(- app,- ["find", "hello"],- env={"OPENVIKING_CLI_CONFIG_FILE": "/tmp/nonexistent/ovcli.conf"},- )-- assert result.exit_code == 2- assert "ovcli.conf" in result.output---def test_cli_version():- """--version should print version string and exit 0."""- result = runner.invoke(app, ["--version"], env={})- assert result.exit_code == 0- assert "openviking" in result.output---def test_cli_help_smoke():- """All commands should print help without errors."""- commands = [- # root- ["--help"],- # content- ["read", "--help"],- ["abstract", "--help"],- ["overview", "--help"],- # debug- ["status", "--help"],- ["health", "--help"],- # filesystem- ["ls", "--help"],- ["tree", "--help"],- ["mkdir", "--help"],- ["rm", "--help"],- ["mv", "--help"],- ["stat", "--help"],- # pack- ["export", "--help"],- ["import", "--help"],- # relations- ["relations", "--help"],- ["link", "--help"],- ["unlink", "--help"],- # resources- ["add-resource", "--help"],- ["add-skill", "--help"],- # search- ["find", "--help"],- ["search", "--help"],- ["grep", "--help"],- ["glob", "--help"],- # serve- ["serve", "--help"],- # system- ["wait", "--help"],- # observer group- ["observer", "--help"],- ["observer", "queue", "--help"],- ["observer", "vikingdb", "--help"],- ["observer", "vlm", "--help"],- ["observer", "system", "--help"],- # session group- ["session", "--help"],- ["session", "new", "--help"],- ["session", "list", "--help"],- ["session", "get", "--help"],- ["session", "delete", "--help"],- ["session", "add-message", "--help"],- ["session", "commit", "--help"],- ]-- for args in commands:- result = runner.invoke(app, args, env={})- assert result.exit_code == 0, "command failed: {}\n{}".format(" ".join(args), result.output)---def test_cli_connection_refused():- """Connecting to a non-existent server should exit with code 3."""- with tempfile.TemporaryDirectory() as tmp_dir:- conf_path = _make_ovcli_conf("http://127.0.0.1:19999", tmp_dir)- result = runner.invoke(- app,- ["-o", "json", "health"],- env={"OPENVIKING_CLI_CONFIG_FILE": conf_path},- )- assert result.exit_code == 3- payload = json.loads(result.output)- assert payload["ok"] is False- assert payload["error"]["code"] == "CONNECTION_ERROR"---def test_cli_real_requests(openviking_server, tmp_path):- server_url = openviking_server-- sample_file = tmp_path / "sample.txt"- sample_file.write_text("OpenViking CLI real request test")-- # -- add resource --- add_payload = _run_cli(["add-resource", str(sample_file)], server_url)- root_uri = add_payload["result"].get("root_uri")- assert root_uri- assert isinstance(root_uri, str)-- file_uri = root_uri- if file_uri.endswith("/"):- file_uri = f"{file_uri}{sample_file.name}"-- # -- debug / system --- health_payload = _run_cli(["health"], server_url)- assert "result" in health_payload-- _run_cli(["status"], server_url)- _run_cli(["observer", "queue"], server_url)- _run_cli(["observer", "vikingdb"], server_url)- _run_cli(["observer", "vlm"], server_url)- _run_cli(["observer", "system"], server_url)-- # -- filesystem --- ls_payload = _run_cli(["ls", "viking://resources/"], server_url)- assert isinstance(ls_payload["result"], list)-- _run_cli(["tree", "viking://resources/"], server_url)- _run_cli(["stat", file_uri], server_url)- _run_cli(["read", "viking://resources/.abstract.md"], server_url)- _run_cli(["abstract", "viking://resources"], server_url)- _run_cli(["overview", "viking://resources"], server_url)-- # -- search --- _run_cli(["grep", "OpenViking", "--uri", root_uri], server_url)- _run_cli(["glob", "*.txt", "--uri", root_uri], server_url)- _run_cli(["search", "OpenViking", "--uri", root_uri], server_url)-- # -- mkdir / mv / rm --- mkdir_uri = "viking://resources/cli-temp-dir"- moved_uri = "viking://resources/cli-temp-dir-moved"- _run_cli(["mkdir", mkdir_uri], server_url)- _run_cli(["mv", mkdir_uri, moved_uri], server_url)- _run_cli(["rm", moved_uri], server_url)-- # -- relations --- _run_cli(["relations", file_uri], server_url)- _run_cli(["link", file_uri, root_uri, "--reason", "ref"], server_url)- _run_cli(["unlink", file_uri, root_uri], server_url)-- # -- pack --- export_path = tmp_path / "openviking_cli_test.ovpack"- _run_cli(["export", file_uri, str(export_path)], server_url)- _run_cli(- ["import", str(export_path), "viking://resources/ovpack-import", "--no-vectorize"],- server_url,- )-- # -- session lifecycle --- session_payload = _run_cli(["session", "new"], server_url)- session_id = session_payload["result"]["session_id"]- assert isinstance(session_id, str) and len(session_id) > 0-- list_payload = _run_cli(["session", "list"], server_url)- assert isinstance(list_payload["result"], list)-- get_payload = _run_cli(["session", "get", session_id], server_url)- assert get_payload["result"]["session_id"] == session_id-- _run_cli(- [- "session",- "add-message",- session_id,- "--role",- "user",- "--content",- "hello",- ],- server_url,- )- _run_cli(["session", "delete", session_id], server_url)---def test_cli_nonexistent_resource(openviking_server):- """Accessing a non-existent resource should fail with exit code 1."""- result = _run_cli(- ["stat", "viking://resources/does-not-exist-xyz"],- openviking_server,- expected_exit_code=1,- )- assert result.exit_code == 1diff --git a/third_party/agfs/agfs-sdk/go/client.go b/third_party/agfs/agfs-sdk/go/client.goindex 7af63c557..7e6709933 100644--- a/third_party/agfs/agfs-sdk/go/client.go+++ b/third_party/agfs/agfs-sdk/go/client.go@@ -543,6 +543,7 @@ type GrepRequest struct {Pattern string `json:"pattern"`Recursive bool `json:"recursive"`CaseInsensitive bool `json:"case_insensitive"`+ NodeLimit int `json:"node_limit"` // Maximum number of results to return (0 means no limit)}// GrepMatch represents a single match result@@ -572,12 +573,17 @@ type DigestResponse struct {}// Grep searches for a pattern in files using regular expressions-func (c *Client) Grep(path, pattern string, recursive, caseInsensitive bool) (*GrepResponse, error) {+func (c *Client) Grep(path, pattern string, recursive, caseInsensitive bool, nodeLimit int) (*GrepResponse, error) {+ nl := 0+ if nodeLimit > 0 {+ nl = nodeLimit+ }reqBody := GrepRequest{Path: path,Pattern: pattern,Recursive: recursive,CaseInsensitive: caseInsensitive,+ NodeLimit: nl,}body, err := json.Marshal(reqBody)diff --git a/third_party/agfs/agfs-sdk/python/pyagfs/client.py b/third_party/agfs/agfs-sdk/python/pyagfs/client.pyindex cbc60f0c5..f532333a9 100644--- a/third_party/agfs/agfs-sdk/python/pyagfs/client.py+++ b/third_party/agfs/agfs-sdk/python/pyagfs/client.py@@ -504,6 +504,7 @@ class AGFSClient:recursive: bool = False,case_insensitive: bool = False,stream: bool = False,+ node_limit: Optional[int] = None,):"""Search for a pattern in files using regular expressions@@ -513,6 +514,7 @@ class AGFSClient: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'@@ -531,15 +533,18 @@ class AGFSClient:... 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_limitresponse = self.session.post(f"{self.api_base}/grep",- json={- "path": path,- "pattern": pattern,- "recursive": recursive,- "case_insensitive": case_insensitive,- "stream": stream,- },+ json=json_payload,timeout=None if stream else self.timeout,stream=stream,)diff --git a/third_party/agfs/agfs-server/pkg/handlers/handlers.go b/third_party/agfs/agfs-server/pkg/handlers/handlers.goindex 10a2aa23b..c83257909 100644--- a/third_party/agfs/agfs-server/pkg/handlers/handlers.go+++ b/third_party/agfs/agfs-server/pkg/handlers/handlers.go@@ -814,6 +814,7 @@ type GrepRequest struct {Recursive bool `json:"recursive"` // Whether to search recursively in directoriesCaseInsensitive bool `json:"case_insensitive"` // Case-insensitive matchingStream bool `json:"stream"` // Stream results as NDJSON (one match per line)+ NodeLimit int `json:"node_limit"` // Maximum number of results to return (0 means no limit)}// GrepMatch represents a single match result@@ -870,7 +871,7 @@ func (h *Handler) Grep(w http.ResponseWriter, r *http.Request) {// Handle stream modeif req.Stream {- h.grepStream(w, req.Path, re, info.IsDir, req.Recursive)+ h.grepStream(w, req.Path, re, info.IsDir, req.Recursive, req.NodeLimit)return}@@ -880,18 +881,13 @@ func (h *Handler) Grep(w http.ResponseWriter, r *http.Request) {// Search in file or directoryif info.IsDir {if req.Recursive {- matches, err = h.grepDirectory(req.Path, re)+ matches, err = h.grepDirectory(req.Path, re, req.NodeLimit)} else {writeError(w, http.StatusBadRequest, "path is a directory, use recursive=true to search")return}} else {- matches, err = h.grepFile(req.Path, re)- }-- if err != nil {- writeError(w, http.StatusInternalServerError, "grep failed: "+err.Error())- return+ matches, err = h.grepFile(req.Path, re, req.NodeLimit)}response := GrepResponse{@@ -903,7 +899,7 @@ func (h *Handler) Grep(w http.ResponseWriter, r *http.Request) {}// grepStream handles streaming grep results as NDJSON-func (h *Handler) grepStream(w http.ResponseWriter, path string, re *regexp.Regexp, isDir bool, recursive bool) {+func (h *Handler) grepStream(w http.ResponseWriter, path string, re *regexp.Regexp, isDir bool, recursive bool, nodeLimit int) {// Set headers for NDJSON streamingw.Header().Set("Content-Type", "application/x-ndjson")w.Header().Set("Transfer-Encoding", "chunked")@@ -941,9 +937,9 @@ func (h *Handler) grepStream(w http.ResponseWriter, path string, re *regexp.Regeflusher.Flush()return}- err = h.grepDirectoryStream(path, re, sendMatch)+ _, err = h.grepDirectoryStream(path, re, nodeLimit, sendMatch)} else {- err = h.grepFileStream(path, re, sendMatch)+ _, err = h.grepFileStream(path, re, nodeLimit, sendMatch)}// Send final summary with count@@ -959,18 +955,22 @@ func (h *Handler) grepStream(w http.ResponseWriter, path string, re *regexp.Rege}// grepFileStream searches for pattern in a single file and calls callback for each match-func (h *Handler) grepFileStream(path string, re *regexp.Regexp, callback func(GrepMatch) error) error {+func (h *Handler) grepFileStream(path string, re *regexp.Regexp, nodeLimit int, callback func(GrepMatch) error) (int, error) {// Read file contentdata, err := h.fs.Read(path, 0, -1)// io.EOF is normal when reading entire file, only return error for other errorsif err != nil && err != io.EOF {- return err+ return 0, err}scanner := bufio.NewScanner(bytes.NewReader(data))lineNum := 1+ count := 0for scanner.Scan() {+ if nodeLimit > 0 && count >= nodeLimit {+ break+ }line := scanner.Text()if re.MatchString(line) {match := GrepMatch{@@ -979,42 +979,52 @@ func (h *Handler) grepFileStream(path string, re *regexp.Regexp, callback func(GContent: line,}if err := callback(match); err != nil {- return err+ return count, err}+ count++}lineNum++}if err := scanner.Err(); err != nil {- return err+ return count, err}- return nil+ return count, nil}// grepDirectoryStream recursively searches for pattern in a directory and calls callback for each match-func (h *Handler) grepDirectoryStream(dirPath string, re *regexp.Regexp, callback func(GrepMatch) error) error {+func (h *Handler) grepDirectoryStream(dirPath string, re *regexp.Regexp, nodeLimit int, callback func(GrepMatch) error) (int, error) {// List directory contentsentries, err := h.fs.ReadDir(dirPath)if err != nil {- return err+ return 0, err}+ totalCount := 0+for _, entry := range entries {+ if nodeLimit > 0 && totalCount >= nodeLimit {+ break+ }// Build full path// Use path.Join for VFS paths to ensure forward slashes on all OSfullPath := path.Join(dirPath, entry.Name)if entry.IsDir {// Recursively search subdirectories- if err := h.grepDirectoryStream(fullPath, re, callback); err != nil {+ count, err := h.grepDirectoryStream(fullPath, re, nodeLimit-totalCount, callback)+ totalCount += count+ if err != nil {// Log error but continue searching other fileslog.Warnf("failed to search directory %s: %v", fullPath, err)continue}} else {// Search in file- if err := h.grepFileStream(fullPath, re, callback); err != nil {+ count, err := h.grepFileStream(fullPath, re, nodeLimit-totalCount, callback)+ totalCount += count+ if err != nil {// Log error but continue searching other fileslog.Warnf("failed to search file %s: %v", fullPath, err)continue@@ -1022,11 +1032,11 @@ func (h *Handler) grepDirectoryStream(dirPath string, re *regexp.Regexp, callbac}}- return nil+ return totalCount, nil}// grepFile searches for pattern in a single file-func (h *Handler) grepFile(path string, re *regexp.Regexp) ([]GrepMatch, error) {+func (h *Handler) grepFile(path string, re *regexp.Regexp, nodeLimit int) ([]GrepMatch, error) {// Read file contentdata, err := h.fs.Read(path, 0, -1)// io.EOF is normal when reading entire file, only return error for other errors@@ -1039,6 +1049,9 @@ func (h *Handler) grepFile(path string, re *regexp.Regexp) ([]GrepMatch, error)lineNum := 1for scanner.Scan() {+ if nodeLimit > 0 && len(matches) >= nodeLimit {+ break+ }line := scanner.Text()if re.MatchString(line) {matches = append(matches, GrepMatch{@@ -1058,7 +1071,7 @@ func (h *Handler) grepFile(path string, re *regexp.Regexp) ([]GrepMatch, error)}// grepDirectory recursively searches for pattern in a directory-func (h *Handler) grepDirectory(dirPath string, re *regexp.Regexp) ([]GrepMatch, error) {+func (h *Handler) grepDirectory(dirPath string, re *regexp.Regexp, nodeLimit int) ([]GrepMatch, error) {var allMatches []GrepMatch// List directory contents@@ -1068,13 +1081,16 @@ func (h *Handler) grepDirectory(dirPath string, re *regexp.Regexp) ([]GrepMatch,}for _, entry := range entries {+ if nodeLimit > 0 && len(allMatches) >= nodeLimit {+ break+ }// Build full path// Use path.Join for VFS paths to ensure forward slashes on all OSfullPath := path.Join(dirPath, entry.Name)if entry.IsDir {// Recursively search subdirectories- subMatches, err := h.grepDirectory(fullPath, re)+ subMatches, err := h.grepDirectory(fullPath, re, nodeLimit-len(allMatches))if err != nil {// Log error but continue searching other fileslog.Warnf("failed to search directory %s: %v", fullPath, err)@@ -1083,7 +1099,7 @@ func (h *Handler) grepDirectory(dirPath string, re *regexp.Regexp) ([]GrepMatch,allMatches = append(allMatches, subMatches...)} else {// Search in file- matches, err := h.grepFile(fullPath, re)+ matches, err := h.grepFile(fullPath, re, nodeLimit-len(allMatches))if err != nil {// Log error but continue searching other fileslog.Warnf("failed to search file %s: %v", fullPath, err)diff --git a/uv.lock b/uv.lockindex e88f7e1a2..d31b61fec 100644--- a/uv.lock+++ b/uv.lock@@ -1,5 +1,5 @@version = 1-revision = 2+revision = 3requires-python = ">=3.10"resolution-markers = ["python_full_version >= '3.14' and sys_platform == 'win32'",@@ -1075,7 +1075,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/38/3f/9859f655d11901e7b2996c6e3d33e0caa9a1d4572c3bc61ed0faa64b2f4c/greenlet-3.3.2-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:9bc885b89709d901859cf95179ec9f6bb67a3d2bb1f0e88456461bd4b7f8fd0d", size = 277747, upload-time = "2026-02-20T20:16:21.325Z" },{ url = "https://files.pythonhosted.org/packages/fb/07/cb284a8b5c6498dbd7cba35d31380bb123d7dceaa7907f606c8ff5993cbf/greenlet-3.3.2-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b568183cf65b94919be4438dc28416b234b678c608cafac8874dfeeb2a9bbe13", size = 579202, upload-time = "2026-02-20T20:47:28.955Z" },{ url = "https://files.pythonhosted.org/packages/ed/45/67922992b3a152f726163b19f890a85129a992f39607a2a53155de3448b8/greenlet-3.3.2-cp310-cp310-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:527fec58dc9f90efd594b9b700662ed3fb2493c2122067ac9c740d98080a620e", size = 590620, upload-time = "2026-02-20T20:55:55.581Z" },- { url = "https://files.pythonhosted.org/packages/03/5f/6e2a7d80c353587751ef3d44bb947f0565ec008a2e0927821c007e96d3a7/greenlet-3.3.2-cp310-cp310-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:508c7f01f1791fbc8e011bd508f6794cb95397fdb198a46cb6635eb5b78d85a7", size = 602132, upload-time = "2026-02-20T21:02:43.261Z" },{ url = "https://files.pythonhosted.org/packages/ad/55/9f1ebb5a825215fadcc0f7d5073f6e79e3007e3282b14b22d6aba7ca6cb8/greenlet-3.3.2-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ad0c8917dd42a819fe77e6bdfcb84e3379c0de956469301d9fd36427a1ca501f", size = 591729, upload-time = "2026-02-20T20:20:58.395Z" },{ url = "https://files.pythonhosted.org/packages/24/b4/21f5455773d37f94b866eb3cf5caed88d6cea6dd2c6e1f9c34f463cba3ec/greenlet-3.3.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:97245cc10e5515dbc8c3104b2928f7f02b6813002770cfaffaf9a6e0fc2b94ef", size = 1551946, upload-time = "2026-02-20T20:49:31.102Z" },{ url = "https://files.pythonhosted.org/packages/00/68/91f061a926abead128fe1a87f0b453ccf07368666bd59ffa46016627a930/greenlet-3.3.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8c1fdd7d1b309ff0da81d60a9688a8bd044ac4e18b250320a96fc68d31c209ca", size = 1618494, upload-time = "2026-02-20T20:21:06.541Z" },@@ -1083,7 +1082,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/f3/47/16400cb42d18d7a6bb46f0626852c1718612e35dcb0dffa16bbaffdf5dd2/greenlet-3.3.2-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:c56692189a7d1c7606cb794be0a8381470d95c57ce5be03fb3d0ef57c7853b86", size = 278890, upload-time = "2026-02-20T20:19:39.263Z" },{ url = "https://files.pythonhosted.org/packages/a3/90/42762b77a5b6aa96cd8c0e80612663d39211e8ae8a6cd47c7f1249a66262/greenlet-3.3.2-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ebd458fa8285960f382841da585e02201b53a5ec2bac6b156fc623b5ce4499f", size = 581120, upload-time = "2026-02-20T20:47:30.161Z" },{ url = "https://files.pythonhosted.org/packages/bf/6f/f3d64f4fa0a9c7b5c5b3c810ff1df614540d5aa7d519261b53fba55d4df9/greenlet-3.3.2-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a443358b33c4ec7b05b79a7c8b466f5d275025e750298be7340f8fc63dff2a55", size = 594363, upload-time = "2026-02-20T20:55:56.965Z" },- { url = "https://files.pythonhosted.org/packages/9c/8b/1430a04657735a3f23116c2e0d5eb10220928846e4537a938a41b350bed6/greenlet-3.3.2-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4375a58e49522698d3e70cc0b801c19433021b5c37686f7ce9c65b0d5c8677d2", size = 605046, upload-time = "2026-02-20T21:02:45.234Z" },{ url = "https://files.pythonhosted.org/packages/72/83/3e06a52aca8128bdd4dcd67e932b809e76a96ab8c232a8b025b2850264c5/greenlet-3.3.2-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e2cd90d413acbf5e77ae41e5d3c9b3ac1d011a756d7284d7f3f2b806bbd6358", size = 594156, upload-time = "2026-02-20T20:20:59.955Z" },{ url = "https://files.pythonhosted.org/packages/70/79/0de5e62b873e08fe3cef7dbe84e5c4bc0e8ed0c7ff131bccb8405cd107c8/greenlet-3.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:442b6057453c8cb29b4fb36a2ac689382fc71112273726e2423f7f17dc73bf99", size = 1554649, upload-time = "2026-02-20T20:49:32.293Z" },{ url = "https://files.pythonhosted.org/packages/5a/00/32d30dee8389dc36d42170a9c66217757289e2afb0de59a3565260f38373/greenlet-3.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:45abe8eb6339518180d5a7fa47fa01945414d7cca5ecb745346fc6a87d2750be", size = 1619472, upload-time = "2026-02-20T20:21:07.966Z" },@@ -1092,7 +1090,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ea/ab/1608e5a7578e62113506740b88066bf09888322a311cff602105e619bd87/greenlet-3.3.2-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:ac8d61d4343b799d1e526db579833d72f23759c71e07181c2d2944e429eb09cd", size = 280358, upload-time = "2026-02-20T20:17:43.971Z" },{ url = "https://files.pythonhosted.org/packages/a5/23/0eae412a4ade4e6623ff7626e38998cb9b11e9ff1ebacaa021e4e108ec15/greenlet-3.3.2-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3ceec72030dae6ac0c8ed7591b96b70410a8be370b6a477b1dbc072856ad02bd", size = 601217, upload-time = "2026-02-20T20:47:31.462Z" },{ url = "https://files.pythonhosted.org/packages/f8/16/5b1678a9c07098ecb9ab2dd159fafaf12e963293e61ee8d10ecb55273e5e/greenlet-3.3.2-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a2a5be83a45ce6188c045bcc44b0ee037d6a518978de9a5d97438548b953a1ac", size = 611792, upload-time = "2026-02-20T20:55:58.423Z" },- { url = "https://files.pythonhosted.org/packages/5c/c5/cc09412a29e43406eba18d61c70baa936e299bc27e074e2be3806ed29098/greenlet-3.3.2-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ae9e21c84035c490506c17002f5c8ab25f980205c3e61ddb3a2a2a2e6c411fcb", size = 626250, upload-time = "2026-02-20T21:02:46.596Z" },{ url = "https://files.pythonhosted.org/packages/50/1f/5155f55bd71cabd03765a4aac9ac446be129895271f73872c36ebd4b04b6/greenlet-3.3.2-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43e99d1749147ac21dde49b99c9abffcbc1e2d55c67501465ef0930d6e78e070", size = 613875, upload-time = "2026-02-20T20:21:01.102Z" },{ url = "https://files.pythonhosted.org/packages/fc/dd/845f249c3fcd69e32df80cdab059b4be8b766ef5830a3d0aa9d6cad55beb/greenlet-3.3.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4c956a19350e2c37f2c48b336a3afb4bff120b36076d9d7fb68cb44e05d95b79", size = 1571467, upload-time = "2026-02-20T20:49:33.495Z" },{ url = "https://files.pythonhosted.org/packages/2a/50/2649fe21fcc2b56659a452868e695634722a6655ba245d9f77f5656010bf/greenlet-3.3.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6c6f8ba97d17a1e7d664151284cb3315fc5f8353e75221ed4324f84eb162b395", size = 1640001, upload-time = "2026-02-20T20:21:09.154Z" },@@ -1101,7 +1098,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ac/48/f8b875fa7dea7dd9b33245e37f065af59df6a25af2f9561efa8d822fde51/greenlet-3.3.2-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:aa6ac98bdfd716a749b84d4034486863fd81c3abde9aa3cf8eff9127981a4ae4", size = 279120, upload-time = "2026-02-20T20:19:01.9Z" },{ url = "https://files.pythonhosted.org/packages/49/8d/9771d03e7a8b1ee456511961e1b97a6d77ae1dea4a34a5b98eee706689d3/greenlet-3.3.2-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ab0c7e7901a00bc0a7284907273dc165b32e0d109a6713babd04471327ff7986", size = 603238, upload-time = "2026-02-20T20:47:32.873Z" },{ url = "https://files.pythonhosted.org/packages/59/0e/4223c2bbb63cd5c97f28ffb2a8aee71bdfb30b323c35d409450f51b91e3e/greenlet-3.3.2-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d248d8c23c67d2291ffd47af766e2a3aa9fa1c6703155c099feb11f526c63a92", size = 614219, upload-time = "2026-02-20T20:55:59.817Z" },- { url = "https://files.pythonhosted.org/packages/94/2b/4d012a69759ac9d77210b8bfb128bc621125f5b20fc398bce3940d036b1c/greenlet-3.3.2-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ccd21bb86944ca9be6d967cf7691e658e43417782bce90b5d2faeda0ff78a7dd", size = 628268, upload-time = "2026-02-20T21:02:48.024Z" },{ url = "https://files.pythonhosted.org/packages/7a/34/259b28ea7a2a0c904b11cd36c79b8cef8019b26ee5dbe24e73b469dea347/greenlet-3.3.2-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b6997d360a4e6a4e936c0f9625b1c20416b8a0ea18a8e19cabbefc712e7397ab", size = 616774, upload-time = "2026-02-20T20:21:02.454Z" },{ url = "https://files.pythonhosted.org/packages/0a/03/996c2d1689d486a6e199cb0f1cf9e4aa940c500e01bdf201299d7d61fa69/greenlet-3.3.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:64970c33a50551c7c50491671265d8954046cb6e8e2999aacdd60e439b70418a", size = 1571277, upload-time = "2026-02-20T20:49:34.795Z" },{ url = "https://files.pythonhosted.org/packages/d9/c4/2570fc07f34a39f2caf0bf9f24b0a1a0a47bc2e8e465b2c2424821389dfc/greenlet-3.3.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1a9172f5bf6bd88e6ba5a84e0a68afeac9dc7b6b412b245dd64f52d83c81e55b", size = 1640455, upload-time = "2026-02-20T20:21:10.261Z" },@@ -1110,7 +1106,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/3f/ae/8bffcbd373b57a5992cd077cbe8858fff39110480a9d50697091faea6f39/greenlet-3.3.2-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8d1658d7291f9859beed69a776c10822a0a799bc4bfe1bd4272bb60e62507dab", size = 279650, upload-time = "2026-02-20T20:18:00.783Z" },{ url = "https://files.pythonhosted.org/packages/d1/c0/45f93f348fa49abf32ac8439938726c480bd96b2a3c6f4d949ec0124b69f/greenlet-3.3.2-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:18cb1b7337bca281915b3c5d5ae19f4e76d35e1df80f4ad3c1a7be91fadf1082", size = 650295, upload-time = "2026-02-20T20:47:34.036Z" },{ url = "https://files.pythonhosted.org/packages/b3/de/dd7589b3f2b8372069ab3e4763ea5329940fc7ad9dcd3e272a37516d7c9b/greenlet-3.3.2-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c2e47408e8ce1c6f1ceea0dffcdf6ebb85cc09e55c7af407c99f1112016e45e9", size = 662163, upload-time = "2026-02-20T20:56:01.295Z" },- { url = "https://files.pythonhosted.org/packages/cd/ac/85804f74f1ccea31ba518dcc8ee6f14c79f73fe36fa1beba38930806df09/greenlet-3.3.2-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e3cb43ce200f59483eb82949bf1835a99cf43d7571e900d7c8d5c62cdf25d2f9", size = 675371, upload-time = "2026-02-20T21:02:49.664Z" },{ url = "https://files.pythonhosted.org/packages/d2/d8/09bfa816572a4d83bccd6750df1926f79158b1c36c5f73786e26dbe4ee38/greenlet-3.3.2-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:63d10328839d1973e5ba35e98cccbca71b232b14051fd957b6f8b6e8e80d0506", size = 664160, upload-time = "2026-02-20T20:21:04.015Z" },{ url = "https://files.pythonhosted.org/packages/48/cf/56832f0c8255d27f6c35d41b5ec91168d74ec721d85f01a12131eec6b93c/greenlet-3.3.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8e4ab3cfb02993c8cc248ea73d7dae6cec0253e9afa311c9b37e603ca9fad2ce", size = 1619181, upload-time = "2026-02-20T20:49:36.052Z" },{ url = "https://files.pythonhosted.org/packages/0a/23/b90b60a4aabb4cec0796e55f25ffbfb579a907c3898cd2905c8918acaa16/greenlet-3.3.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:94ad81f0fd3c0c0681a018a976e5c2bd2ca2d9d94895f23e7bb1af4e8af4e2d5", size = 1687713, upload-time = "2026-02-20T20:21:11.684Z" },@@ -1119,7 +1114,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/98/6d/8f2ef704e614bcf58ed43cfb8d87afa1c285e98194ab2cfad351bf04f81e/greenlet-3.3.2-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:e26e72bec7ab387ac80caa7496e0f908ff954f31065b0ffc1f8ecb1338b11b54", size = 286617, upload-time = "2026-02-20T20:19:29.856Z" },{ url = "https://files.pythonhosted.org/packages/5e/0d/93894161d307c6ea237a43988f27eba0947b360b99ac5239ad3fe09f0b47/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8b466dff7a4ffda6ca975979bab80bdadde979e29fc947ac3be4451428d8b0e4", size = 655189, upload-time = "2026-02-20T20:47:35.742Z" },{ url = "https://files.pythonhosted.org/packages/f5/2c/d2d506ebd8abcb57386ec4f7ba20f4030cbe56eae541bc6fd6ef399c0b41/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b8bddc5b73c9720bea487b3bffdb1840fe4e3656fba3bd40aa1489e9f37877ff", size = 658225, upload-time = "2026-02-20T20:56:02.527Z" },- { url = "https://files.pythonhosted.org/packages/d1/67/8197b7e7e602150938049d8e7f30de1660cfb87e4c8ee349b42b67bdb2e1/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:59b3e2c40f6706b05a9cd299c836c6aa2378cabe25d021acd80f13abf81181cf", size = 666581, upload-time = "2026-02-20T21:02:51.526Z" },{ url = "https://files.pythonhosted.org/packages/8e/30/3a09155fbf728673a1dea713572d2d31159f824a37c22da82127056c44e4/greenlet-3.3.2-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b26b0f4428b871a751968285a1ac9648944cea09807177ac639b030bddebcea4", size = 657907, upload-time = "2026-02-20T20:21:05.259Z" },{ url = "https://files.pythonhosted.org/packages/f3/fd/d05a4b7acd0154ed758797f0a43b4c0962a843bedfe980115e842c5b2d08/greenlet-3.3.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:1fb39a11ee2e4d94be9a76671482be9398560955c9e568550de0224e41104727", size = 1618857, upload-time = "2026-02-20T20:49:37.309Z" },{ url = "https://files.pythonhosted.org/packages/6f/e1/50ee92a5db521de8f35075b5eff060dd43d39ebd46c2181a2042f7070385/greenlet-3.3.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:20154044d9085151bc309e7689d6f7ba10027f8f5a8c0676ad398b951913d89e", size = 1680010, upload-time = "2026-02-20T20:21:13.427Z" },@@ -2583,6 +2577,7 @@ dependencies = [{ name = "requests" },{ name = "tabulate" },{ name = "tree-sitter" },+ { name = "tree-sitter-c-sharp" },{ name = "tree-sitter-cpp" },{ name = "tree-sitter-go" },{ name = "tree-sitter-java" },@@ -2620,9 +2615,13 @@ eval = []test = [{ name = "boto3" },+ { name = "datasets" },+ { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },+ { name = "pandas", version = "3.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },{ name = "pytest" },{ name = "pytest-asyncio" },{ name = "pytest-cov" },+ { name = "ragas" },][package.metadata]@@ -2630,6 +2629,7 @@ requires-dist = [{ name = "apscheduler", specifier = ">=3.11.0" },{ name = "boto3", marker = "extra == 'test'", specifier = ">=1.42.44" },{ name = "datasets", marker = "extra == 'eval'", specifier = ">=2.0.0" },+ { name = "datasets", marker = "extra == 'test'", specifier = ">=2.0.0" },{ name = "ebooklib", specifier = ">=0.18.0" },{ name = "fastapi", specifier = ">=0.128.0" },{ name = "httpx", specifier = ">=0.25.0" },@@ -2642,6 +2642,7 @@ requires-dist = [{ name = "openai", specifier = ">=1.0.0" },{ name = "openpyxl", specifier = ">=3.0.0" },{ name = "pandas", marker = "extra == 'eval'", specifier = ">=2.0.0" },+ { name = "pandas", marker = "extra == 'test'", specifier = ">=2.0.0" },{ name = "pdfminer-six", specifier = ">=20251230" },{ name = "pdfplumber", specifier = ">=0.10.0" },{ name = "protobuf", specifier = ">=6.33.5" },@@ -2655,6 +2656,7 @@ requires-dist = [{ name = "python-pptx", specifier = ">=1.0.0" },{ name = "pyyaml", specifier = ">=6.0" },{ name = "ragas", marker = "extra == 'eval'", specifier = ">=0.1.0" },+ { name = "ragas", marker = "extra == 'test'", specifier = ">=0.1.0" },{ name = "readabilipy", specifier = ">=0.2.0" },{ name = "requests", specifier = ">=2.31.0" },{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.1.0" },@@ -2662,6 +2664,7 @@ requires-dist = [{ name = "sphinx-rtd-theme", marker = "extra == 'doc'", specifier = ">=1.3.0" },{ name = "tabulate", specifier = ">=0.9.0" },{ name = "tree-sitter", specifier = ">=0.23.0" },+ { name = "tree-sitter-c-sharp", specifier = ">=0.23.0" },{ name = "tree-sitter-cpp", specifier = ">=0.23.0" },{ name = "tree-sitter-go", specifier = ">=0.23.0" },{ name = "tree-sitter-java", specifier = ">=0.23.0" },@@ -4827,6 +4830,21 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/a6/6e/e64621037357acb83d912276ffd30a859ef117f9c680f2e3cb955f47c680/tree_sitter-0.25.2-cp314-cp314-win_arm64.whl", hash = "sha256:b8d4429954a3beb3e844e2872610d2a4800ba4eb42bb1990c6a4b1949b18459f", size = 117470, upload-time = "2025-09-25T17:37:58.431Z" },]+[[package]]+name = "tree-sitter-c-sharp"+version = "0.23.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/22/85/a61c782afbb706a47d990eaee6977e7c2bd013771c5bf5c81c617684f286/tree_sitter_c_sharp-0.23.1.tar.gz", hash = "sha256:322e2cfd3a547a840375276b2aea3335fa6458aeac082f6c60fec3f745c967eb", size = 1317728, upload-time = "2024-11-11T05:25:32.535Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/58/04/f6c2df4c53a588ccd88d50851155945cff8cd887bd70c175e00aaade7edf/tree_sitter_c_sharp-0.23.1-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2b612a6e5bd17bb7fa2aab4bb6fc1fba45c94f09cb034ab332e45603b86e32fd", size = 372235, upload-time = "2024-11-11T05:25:19.424Z" },+ { url = "https://files.pythonhosted.org/packages/99/10/1aa9486f1e28fc22810fa92cbdc54e1051e7f5536a5e5b5e9695f609b31e/tree_sitter_c_sharp-0.23.1-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a8b98f62bc53efcd4d971151950c9b9cd5cbe3bacdb0cd69fdccac63350d83e", size = 419046, upload-time = "2024-11-11T05:25:20.679Z" },+ { url = "https://files.pythonhosted.org/packages/0f/21/13df29f8fcb9ba9f209b7b413a4764b673dfd58989a0dd67e9c7e19e9c2e/tree_sitter_c_sharp-0.23.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:986e93d845a438ec3c4416401aa98e6a6f6631d644bbbc2e43fcb915c51d255d", size = 415999, upload-time = "2024-11-11T05:25:22.359Z" },+ { url = "https://files.pythonhosted.org/packages/ca/72/fc6846795bcdae2f8aa94cc8b1d1af33d634e08be63e294ff0d6794b1efc/tree_sitter_c_sharp-0.23.1-cp39-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a8024e466b2f5611c6dc90321f232d8584893c7fb88b75e4a831992f877616d2", size = 402830, upload-time = "2024-11-11T05:25:24.198Z" },+ { url = "https://files.pythonhosted.org/packages/fe/3a/b6028c5890ce6653807d5fa88c72232c027c6ceb480dbeb3b186d60e5971/tree_sitter_c_sharp-0.23.1-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7f9bf876866835492281d336b9e1f9626ab668737f74e914c31d285261507da7", size = 397880, upload-time = "2024-11-11T05:25:25.937Z" },+ { url = "https://files.pythonhosted.org/packages/47/d2/4facaa34b40f8104d8751746d0e1cd2ddf0beb9f1404b736b97f372bd1f3/tree_sitter_c_sharp-0.23.1-cp39-abi3-win_amd64.whl", hash = "sha256:ae9a9e859e8f44e2b07578d44f9a220d3fa25b688966708af6aa55d42abeebb3", size = 377562, upload-time = "2024-11-11T05:25:27.539Z" },+ { url = "https://files.pythonhosted.org/packages/d8/88/3cf6bd9959d94d1fec1e6a9c530c5f08ff4115a474f62aedb5fedb0f7241/tree_sitter_c_sharp-0.23.1-cp39-abi3-win_arm64.whl", hash = "sha256:c81548347a93347be4f48cb63ec7d60ef4b0efa91313330e69641e49aa5a08c5", size = 375157, upload-time = "2024-11-11T05:25:30.839Z" },+]+[[package]]name = "tree-sitter-cpp"version = "0.23.4"