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
docs: update api docs for 01,02 (#1784)
MaojiaShenga578f356cb3f
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.mdindex bccb43e2e..3e881867f 100644--- a/docs/en/api/01-overview.md+++ b/docs/en/api/01-overview.md@@ -2,9 +2,11 @@This page covers how to connect to OpenViking and the conventions shared across all API endpoints.-## Connecting to OpenViking+## Connection Modes-OpenViking supports three connection modes:+OpenViking supports two usage modes: **Embedded Mode** (direct Python API calls) and **Client-Server Mode** (via HTTP API).++This API documentation primarily focuses on the HTTP API usage in **Client-Server Mode**. Embedded mode is available but will not be covered separately in subsequent documentation.| Mode | Use Case | Description ||------|----------|-------------|@@ -12,7 +14,9 @@ OpenViking supports three connection modes:| **HTTP** | Connect to OpenViking Server | Connects to a remote server via HTTP API || **CLI** | Shell scripting, agent tool-use | Connects to server via CLI commands |-### Embedded Mode+### Embedded Mode (Brief Overview)++Embedded mode allows direct OpenViking API calls within a Python process without starting a separate server process.```pythonimport openviking as ov@@ -21,7 +25,7 @@ client = ov.OpenViking(path="./data")client.initialize()```-Embedded mode uses `ov.conf` to configure embedding, vlm, storage, and other modules. Default path: `~/.openviking/ov.conf`. You can also specify the path via environment variable:+Embedded mode uses `ov.conf` to configure embedding, vlm, storage, and other modules. Default configuration path: `~/.openviking/ov.conf`. You can also specify the path via environment variable:```bashexport OPENVIKING_CONFIG_FILE=/path/to/ov.conf@@ -53,9 +57,15 @@ For `provider: "openai-codex"`, `vlm.api_key` is optional once Codex OAuth is avFor full configuration options and provider-specific examples, see the [Configuration Guide](../guides/01-configuration.md).-### HTTP Mode+### Client-Server Mode (Main Focus)++Client-Server mode connects to an OpenViking server via HTTP API, supporting multi-tenancy, remote access, and other features. See the deployment documentation for how to start the OpenViking server.++#### Python SDK Client```python+import openviking as ov+client = ov.SyncHTTPClient(url="http://localhost:1933",api_key="your-key",@@ -65,12 +75,14 @@ client = ov.SyncHTTPClient(client.initialize()```-When `url` is not explicitly provided, the HTTP client automatically loads connection info from `ovcli.conf`. This config file is shared between the HTTP client and CLI. Default path: `~/.openviking/ovcli.conf`. You can also specify the path via environment variable:+When `url` is not explicitly provided, the HTTP client automatically reads connection information from `ovcli.conf`. `ovcli.conf` is a configuration file shared between the HTTP client and CLI. Default path: `~/.openviking/ovcli.conf`. You can also specify the path via environment variable:```bashexport OPENVIKING_CLI_CONFIG_FILE=/path/to/ovcli.conf```+Configuration file example:+```json{"url": "http://localhost:1933",@@ -81,10 +93,12 @@ export OPENVIKING_CLI_CONFIG_FILE=/path/to/ovcli.conf}```+Configuration field description:+| Field | Description | Default ||-------|-------------|---------|| `url` | Server address | (required) |-| `api_key` | API key | `null` (no auth) |+| `api_key` | API Key | `null` (no auth) || `account` | Default account header for tenant-scoped requests | `null` || `user` | Default user header for tenant-scoped requests | `null` || `agent_id` | Agent identifier header | `null` |@@ -93,31 +107,53 @@ export OPENVIKING_CLI_CONFIG_FILE=/path/to/ovcli.confSee the [Configuration Guide](../guides/01-configuration.md#ovcliconf) for details.-**Local files in HTTP mode**+#### Using Python SDK Client Without Configuration File-- CLI, `SyncHTTPClient`, and `AsyncHTTPClient` automatically upload local files and directories before calling the server API.-- Raw HTTP callers do not get this convenience layer. When using `curl` or another HTTP client, upload the file with `POST /api/v1/resources/temp_upload` first, then call the target API with the returned `temp_file_id`.-- For local directories in raw HTTP mode, zip the directory first and upload the `.zip` file; the server does not accept direct host directory paths.-- `POST /api/v1/resources` accepts remote URLs directly, but does not accept direct host filesystem paths such as `./doc.md` or `/tmp/doc.md`.+`SyncHTTPClient` and `AsyncHTTPClient` support operating completely without relying on the `ovcli.conf` configuration file, by **explicitly passing all parameters** during initialization:-### Direct HTTP (curl)+```python+import openviking as ov++client = ov.SyncHTTPClient(+ url="http://localhost:1933", # Explicitly provided+ api_key="your-key", # Explicitly provided (api_key usually identifies user identity)+ timeout=30.0, # Don't use default 60.0+ extra_headers={} # Pass empty dict instead of None, useful for gateway auth in some scenarios+)+client.initialize()+```++⚠️ **Note**: The client will attempt to load the configuration file if any of the following conditions are met:+- `url` is `None`+- `api_key` is `None`+- `timeout` equals `60.0` (default value)+- `extra_headers` is `None`++#### HTTP Call Examples++- CLI, `SyncHTTPClient`, and `AsyncHTTPClient` automatically upload local files or directories before calling the server API.+- Raw HTTP calls don't get this convenience layer. When using `curl` or other HTTP clients, you need to first call `POST /api/v1/resources/temp_upload`, then pass the returned `temp_file_id` to the target API.+- For raw HTTP imports of local directories, you need to first zip them into a `.zip` file and upload using the above method; the server does not accept direct host directory paths.+- `POST /api/v1/resources` can directly accept remote URLs, but does not accept host local paths like `./doc.md` or `/tmp/doc.md`.++Direct HTTP (curl) call example:```bashcurl http://localhost:1933/api/v1/fs/ls?uri=viking:// \-H "X-API-Key: your-key"```-### CLI Mode+#### CLI Mode-The CLI connects to an OpenViking server and exposes all operations as shell commands. The CLI also loads connection info from `ovcli.conf` (shared with the HTTP client).+The OpenViking CLI (can be abbreviated as `ov` command) connects to an OpenViking server and exposes all operations as shell commands. The CLI also reads connection information from `ovcli.conf` (shared with the HTTP client).-**Basic Usage**+Basic usage:```bashopenviking [global options] <command> [arguments] [command options]```-**Global Options** (must be placed before the command name)+Global options (must be placed before the command name):| Option | Description ||--------|-------------|@@ -132,7 +168,7 @@ openviking -o json ls viking://resources/## Lifecycle-**Embedded Mode**+### Embedded Mode```pythonimport openviking as ov@@ -145,7 +181,7 @@ client.initialize()client.close()```-**HTTP Mode**+### Client-Server Mode```pythonimport openviking as ov@@ -158,20 +194,26 @@ client.initialize()client.close()```+The CLI is called directly via the command line, requiring the `ovcli.conf` file to be configured first, with no additional client initialization needed:++```+openviking -o json ls viking://resources/+```+## Authentication-See [Authentication Guide](../guides/04-authentication.md) for full details.+See the [Authentication Guide](../guides/04-authentication.md) for full details.+- **Authorization Bearer** header: `Authorization: Bearer your-key` (recommended)- **X-API-Key** header: `X-API-Key: your-key`-- **Bearer** header: `Authorization: Bearer your-key`-- If no API key is configured on the server, authentication is skipped.-- The `/health` endpoint never requires authentication.+- If the server doesn't have an API Key configured, authentication is skipped.+- The `/health` and `/ready` endpoints never require authentication.## Response FormatAll HTTP API responses follow a unified format:-**Success**+### Success Response```json{@@ -181,12 +223,9 @@ All HTTP API responses follow a unified format:}```-The top-level `status` describes whether the HTTP API request succeeded. Some successful-operations return domain-level status fields inside `result`, such as-`"status": "success"`, `"status": "accepted"`, or task states. Those fields are not API-transport errors.+The top-level `status` describes whether the HTTP API request succeeded. Some successful operations return domain-level status fields inside `result`, such as `"status": "success"`, `"status": "accepted"`, or task states. Those fields are not API transport errors.-**Error**+### Error Response```json{@@ -199,23 +238,15 @@ transport errors.}```-HTTP errors always use the top-level error envelope. Synchronous processing failures, such as-resource parsing or synchronous reindex failures, are returned as non-2xx responses with-`status="error"` and an `error` object. Clients should not look for `result.status="error"` to-detect request failure.+HTTP errors always use the top-level error envelope. Synchronous processing failures, such as resource parsing or synchronous reindex failures, are returned as non-2xx responses with `status="error"` and an `error` object. Clients should not look for `result.status="error"` to detect request failure.-Request validation failures, including malformed JSON, missing required fields, and invalid-parameter values, return HTTP `400` with `error.code="INVALID_ARGUMENT"`. The response never uses-FastAPI's raw `{"detail": ...}` error format; when field-level validation information is-available, it is exposed under `error.details.validation_errors`.+Request validation failures, including malformed JSON, missing required fields, and invalid parameter values, return HTTP `400` with `error.code="INVALID_ARGUMENT"`. The response never uses FastAPI's raw `{"detail": ...}` error format; when field-level validation information is available, it is exposed under `error.details.validation_errors`.-Python HTTP SDKs (`SyncHTTPClient` and `AsyncHTTPClient`) raise the corresponding-`OpenVikingError` subclass for this envelope. For example, `PROCESSING_ERROR` is raised as-`ProcessingError`.+Python HTTP SDKs (`SyncHTTPClient` and `AsyncHTTPClient`) raise the corresponding `OpenVikingError` subclass for this envelope. For example, `PROCESSING_ERROR` is raised as `ProcessingError`.## CLI Output Format-### Table Mode (default)+### Table Mode (Default)List data is rendered as tables; non-list data falls back to formatted JSON:@@ -227,7 +258,7 @@ openviking ls viking://resources/### JSON Mode (`--output json`)-All commands output formatted JSON matching the API response `result` structure:+All commands output formatted JSON, matching the `result` structure of API responses:```bashopenviking -o json ls viking://resources/@@ -243,17 +274,18 @@ The default output format can be set in `ovcli.conf`:}```-### Script Mode (`-o json`)+### Compact Mode (`--compact`, `-c`)-Compact JSON with status wrapper (when `--compact` is true, which is the default), suitable for scripting:+- When `--output=json`: Compact JSON format + `{ok, result}` wrapper, suitable for scripts+- When `--output=table`: Simplified representation for table output (e.g., removing empty columns)-**Success**+JSON output - success:```json{"ok": true, "result": ...}```-**Error**+JSON output - error:```json{"ok": false, "error": {"code": "NOT_FOUND", "message": "Resource not found", "details": {}}}@@ -266,6 +298,8 @@ Compact JSON with status wrapper (when `--compact` is true, which is the default### Exit Codes+**Note**: Exit codes are return codes from the CLI (command line tool), not HTTP API status codes.+| Code | Meaning ||------|---------|| 0 | Success |@@ -295,28 +329,38 @@ Compact JSON with status wrapper (when `--compact` is true, which is the default| `EMBEDDING_FAILED` | 500 | Embedding generation failed || `VLM_FAILED` | 500 | VLM call failed || `SESSION_EXPIRED` | 410 | Session no longer exists |+| `NOT_INITIALIZED` | - | Service or component not initialized (need to call initialize() first) |++---## API Endpoints+Below are all HTTP API endpoints provided by OpenViking, grouped by functional module:+### System-| Method | Path | Description |-|--------|------|-------------|-| GET | `/health` | Health check (no auth) |-| GET | `/ready` | Readiness probe (no auth) |-| GET | `/metrics` | Prometheus metrics export |-| GET | `/api/v1/system/status` | System status |-| POST | `/api/v1/system/wait` | Wait for processing |+| Method | Path | Description | Authentication |+|--------|------|-------------|----------------|+| GET | `/health` | Health check (no auth) | No auth required |+| GET | `/ready` | Readiness probe (no auth) | No auth required |+| GET | `/metrics` | Prometheus metrics export | Optional |+| GET | `/api/v1/system/status` | System status | Required |+| POST | `/api/v1/system/wait` | Wait for processing | Required |### Resources| Method | Path | Description ||--------|------|-------------|| POST | `/api/v1/resources/temp_upload` | Upload local file for raw HTTP resource / pack import |-| POST | `/api/v1/resources` | Add resource |+| POST | `/api/v1/resources` | Add resource (supports URL or temp_file_id) || POST | `/api/v1/skills` | Add skill |-| POST | `/api/v1/pack/export` | Export .ovpack |-| POST | `/api/v1/pack/import` | Import .ovpack |++### Pack++| Method | Path | Description | Permission |+|--------|------|-------------|------------|+| POST | `/api/v1/pack/export` | Export .ovpack | ROOT/ADMIN |+| POST | `/api/v1/pack/import` | Import .ovpack | ROOT/ADMIN |### File System@@ -327,7 +371,7 @@ Compact JSON with status wrapper (when `--compact` is true, which is the default| GET | `/api/v1/fs/stat` | Resource status || POST | `/api/v1/fs/mkdir` | Create directory || DELETE | `/api/v1/fs` | Delete resource |-| POST | `/api/v1/fs/mv` | Move resource |+| POST | `/api/v1/fs/mv` | Move/rename resource |### Content@@ -338,18 +382,18 @@ Compact JSON with status wrapper (when `--compact` is true, which is the default| GET | `/api/v1/content/overview` | Read overview (L1) || GET | `/api/v1/content/download` | Download raw file bytes || POST | `/api/v1/content/write` | Update an existing file and refresh semantics/vectors |-| POST | `/api/v1/content/reindex` | Rebuild semantic/vector index for existing content |+| POST | `/api/v1/content/reindex` | Rebuild semantic/vector index for existing content (deprecated, use maintenance) |### Search| Method | Path | Description ||--------|------|-------------|-| POST | `/api/v1/search/find` | Semantic search |-| POST | `/api/v1/search/search` | Context-aware search |-| POST | `/api/v1/search/grep` | Pattern search |+| POST | `/api/v1/search/find` | Semantic search (no session context) |+| POST | `/api/v1/search/search` | Context-aware search (supports sessions) |+| POST | `/api/v1/search/grep` | Content pattern search || POST | `/api/v1/search/glob` | File pattern matching |-### Relations+### Relations (Experimental, may change in future versions)| Method | Path | Description ||--------|------|-------------|@@ -363,14 +407,14 @@ Compact JSON with status wrapper (when `--compact` is true, which is the default|--------|------|-------------|| POST | `/api/v1/sessions` | Create session || GET | `/api/v1/sessions` | List sessions |-| GET | `/api/v1/sessions/{id}` | Get session |-| GET | `/api/v1/sessions/{id}/context` | Get assembled session context |-| DELETE | `/api/v1/sessions/{id}` | Delete session |-| POST | `/api/v1/sessions/{id}/commit` | Commit session |-| POST | `/api/v1/sessions/{id}/extract` | Extract memories from a session |-| POST | `/api/v1/sessions/{id}/messages` | Add message |-| POST | `/api/v1/sessions/{id}/used` | Record contexts / skills actually used |-| GET | `/api/v1/sessions/{id}/archives/{archive_id}` | Get a specific session archive |+| GET | `/api/v1/sessions/{session_id}` | Get session |+| GET | `/api/v1/sessions/{session_id}/context` | Get assembled session context |+| GET | `/api/v1/sessions/{session_id}/archives/{archive_id}` | Get a specific session archive |+| DELETE | `/api/v1/sessions/{session_id}` | Delete session |+| POST | `/api/v1/sessions/{session_id}/commit` | Commit session (archive and extract memories) |+| POST | `/api/v1/sessions/{session_id}/extract` | Extract memories from a session |+| POST | `/api/v1/sessions/{session_id}/messages` | Add message |+| POST | `/api/v1/sessions/{session_id}/used` | Record contexts / skills actually used |### Privacy Configs@@ -389,7 +433,7 @@ Compact JSON with status wrapper (when `--compact` is true, which is the default| Method | Path | Description ||--------|------|-------------|| GET | `/api/v1/tasks/{task_id}` | Get background task status |-| GET | `/api/v1/tasks` | List background tasks |+| GET | `/api/v1/tasks` | List background tasks (supports filtering by type, status, resource) |### Observer@@ -410,27 +454,68 @@ Compact JSON with status wrapper (when `--compact` is true, which is the default| GET | `/api/v1/debug/vector/scroll` | Paginated vector record inspection || GET | `/api/v1/debug/vector/count` | Count vector records |+### Maintenance++| Method | Path | Description | Permission |+|--------|------|-------------|------------|+| POST | `/api/v1/maintenance/reindex` | Reindex content (optional abstract regeneration) | ROOT/ADMIN |++### Statistics++| Method | Path | Description |+|--------|------|-------------|+| GET | `/api/v1/stats/memories` | Get memory health statistics (supports category filtering) |+| GET | `/api/v1/stats/sessions/{session_id}` | Get session extraction statistics |+### Admin (Multi-tenant)+| Method | Path | Description | Permission |+|--------|------|-------------|------------|+| POST | `/api/v1/admin/accounts` | Create workspace + first admin | ROOT |+| GET | `/api/v1/admin/accounts` | List workspaces | ROOT |+| DELETE | `/api/v1/admin/accounts/{account_id}` | Delete workspace (cascade data cleanup) | ROOT |+| POST | `/api/v1/admin/accounts/{account_id}/users` | Register user | ROOT/ADMIN |+| GET | `/api/v1/admin/accounts/{account_id}/users` | List users | ROOT/ADMIN |+| DELETE | `/api/v1/admin/accounts/{account_id}/users/{user_id}` | Remove user | ROOT/ADMIN |+| PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | Change user role | ROOT |+| POST | `/api/v1/admin/accounts/{account_id}/users/{user_id}/key` | Regenerate user key | ROOT/ADMIN |++### VikingBot Interaction Endpoints (Optional)++VikingBot API requires the server to be started with the `--with-bot` option:++| Method | Path | Description |+|--------|------|-------------|+| GET | `/health` | Bot health check (reused with system /health) |+| POST | `/chat` | Send message to Bot |+| POST | `/chat/stream` | Bot streaming response |++### WebDAV Endpoints+| Method | Path | Description ||--------|------|-------------|-| POST | `/api/v1/admin/accounts` | Create workspace + first admin (ROOT) |-| GET | `/api/v1/admin/accounts` | List workspaces (ROOT) |-| DELETE | `/api/v1/admin/accounts/{account_id}` | Delete workspace (ROOT) |-| POST | `/api/v1/admin/accounts/{account_id}/users` | Register user (ROOT, ADMIN) |-| GET | `/api/v1/admin/accounts/{account_id}/users` | List users (ROOT, ADMIN) |-| DELETE | `/api/v1/admin/accounts/{account_id}/users/{user_id}` | Remove user (ROOT, ADMIN) |-| PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | Change user role (ROOT) |-| POST | `/api/v1/admin/accounts/{account_id}/users/{user_id}/key` | Regenerate user key (ROOT, ADMIN) |--## Related Documentation--- [Resources](02-resources.md) - Resource management API-- [Retrieval](06-retrieval.md) - Search API-- [File System](03-filesystem.md) - File system operations-- [Sessions](05-sessions.md) - Session management-- [Skills](04-skills.md) - Skill management-- [System](07-system.md) - System and monitoring API-- [Privacy Configs](10-privacy.md) - Privacy config version management and activation-- [Metrics](09-metrics.md) - Prometheus metrics export and scraping guide-- [Admin](08-admin.md) - Multi-tenant management API+| OPTIONS | `/webdav/resources`, `/webdav/resources/{path}` | WebDAV options query |+| PROPFIND | `/webdav/resources`, `/webdav/resources/{path}` | WebDAV property query |+| GET/HEAD | `/webdav/resources/{path}` | Read file |+| PUT | `/webdav/resources/{path}` | Upload/create file (UTF-8 text only) |+| DELETE | `/webdav/resources/{path}` | Delete file/directory |+| MKCOL | `/webdav/resources/{path}` | Create directory |+| MOVE | `/webdav/resources/{path}` | Move/rename resource |++---++## Documentation Reading Plan++Subsequent API documentation is organized by functional module as follows:++| Document | Content |+|----------|---------|+| [Resources](02-resources.md) - Resource management API | Adding, importing, exporting resources and skills |+| [Retrieval](06-retrieval.md) - Search API | Search, relations, context acquisition |+| [File System](03-filesystem.md) - File system operations | Directory operations, content reading and writing |+| [Sessions](05-sessions.md) - Session management | Session creation, message management, memory extraction |+| [Skills](04-skills.md) - Skill management API | Skill management |+| [System](07-system.md) - System and monitoring API | System status, monitoring, debug API |+| [Privacy Configs](10-privacy.md) - Privacy config version management and activation | Privacy configuration |+| [Metrics](09-metrics.md) - Prometheus metrics export and scraping guide | Metrics documentation |+| [Admin](08-admin.md) - Multi-tenant management API | Multi-tenant account and user management |diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.mdindex d048a209f..b62a5840c 100644--- a/docs/en/api/02-resources.md+++ b/docs/en/api/02-resources.md@@ -1,913 +1,552 @@-# Resources+# Resource Management-Resources are external knowledge that agents can reference. This guide covers how to add, manage, and retrieve resources.+Resources are external knowledge that agents can reference. This module provides functionality for adding, importing/exporting, and uploading temporary files for resources.-## Supported Formats+## Core Concepts-| Format | Extensions | Processing |-|--------|------------|------------|-| PDF | `.pdf` | Text and image extraction |-| Markdown | `.md` | Native support |-| HTML | `.html`, `.htm` | Cleaned text extraction |-| Plain Text | `.txt` | Direct import |-| JSON/YAML | `.json`, `.yaml`, `.yml` | Structured parsing |-| Code | `.py`, `.js`, `.ts`, `.go`, `.java`, etc. | Syntax-aware parsing |-| Images | `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp` | VLM description |-| Video | `.mp4`, `.mov`, `.avi` | Frame extraction + VLM |-| Audio | `.mp3`, `.wav`, `.m4a` | Transcription |-| Documents | `.docx` | Text extraction |-| Feishu/Lark | URL (`*.feishu.cn`, `*.larksuite.com`, `*.larkoffice.com`) | Cloud document parsing via `lark-oapi` |+### Resource Types-## Processing Pipeline+OpenViking supports various resource types, categorized by functionality:-```-Input -> Parser -> TreeBuilder -> AGFS -> SemanticQueue -> Vector Index-```+**Documents**-1. **Parser**: Extracts content based on file type-2. **TreeBuilder**: Creates directory structure-3. **AGFS**: Stores files in virtual file system-4. **SemanticQueue**: Generates L0/L1 asynchronously-5. **Vector Index**: Indexes for semantic search+| Type | Extensions | Description |+|------|------------|-------------|+| PDF | `.pdf` | Supports local parsing and MinerU API conversion |+| Markdown | `.md`, `.markdown`, `.mdown`, `.mkd` | Native support, extracts structure and stores in segments |+| HTML | `.html`, `.htm` | Cleans navigation/ads and extracts content, converts to Markdown |+| Word | `.docx` | Extracts text, headings, tables and converts to Markdown |+| Plain Text | `.txt`, `.text` | Direct import and processing |+| EPUB | `.epub` | E-book format, supports ebooklib or manual extraction |-## API Reference+**Spreadsheets & Presentations**-### add_resource()+| Type | Extensions | Description |+|------|------------|-------------|+| Excel | `.xlsx`, `.xls`, `.xlsm` | Supports new and legacy Excel formats, converts to Markdown tables by worksheet |+| PowerPoint | `.pptx` | Extracts content by slide, supports extracting notes |-Add a resource to the knowledge base.+**Code**-**Parameters**+| Type | Resource Name | Description |+|------|---------------|-------------|+| Code Files | `*.py`, `*.js`, ... | Supports common programming languages (Python, JavaScript, Go, Rust, Java, etc.) |+| Git Protocol Repository | `git://...` | Git URL, local directory, `.zip` package, automatically filters `.git`, `node_modules` and other directories |+| Git Code Hosting Platform | `https://github.com/{org}/{repo}` | URLs from GitHub, GitLab, Bitbucket and other code hosting platforms |+| Raw Files from Git Hosting | `https://github.com/{org}/{repo}/raw/{branch}/{path}` | Raw file download URLs from GitHub, GitLab, Bitbucket and other platforms |-| Parameter | Type | Required | Default | Description |-|-----------|------|----------|---------|-------------|-| path | str | Yes | - | SDK/CLI: local path, directory path, or URL. Raw HTTP: remote URL only |-| temp_file_id | str | No | None | Upload ID returned by `POST /api/v1/resources/temp_upload` for raw HTTP local file ingestion |-| to | str | No | None | Exact target Viking URI (must be in `resources` scope) |-| parent | str | No | None | Parent URI under which the resource will be stored. Cannot be combined with `to` |-| reason | str | No | "" | Why this resource is being added (improves search relevance) |-| instruction | str | No | "" | Special processing instructions |-| wait | bool | No | False | Wait for semantic processing to complete |-| timeout | float | No | None | Timeout in seconds (only used when wait=True) |-| watch_interval | float | No | 0 | Watch interval (minutes). >0 enables/updates watch; <=0 disables watch. Only takes effect when `to` is provided |+**Media**-`POST /api/v1/resources` uses `to` in JSON. CLI uses `--to`.+| Type | Resource Name | Description |+|------|---------------|-------------|+| Images | `*.jpg`, `*.jpeg`, `*.png`, `*.gif` ... | Various image formats, descriptions generated via VLM (Experimental) |+| Video | `*.mp4`, `*.avi`, `*.mov` ... | Extracts keyframes and analyzes with VLM (Planning) |+| Audio | `*.mp3`, `*.wav`, `*.m4a` ... | Performs speech transcription (Planning) |-**How local files and directories work**+**Cloud Documents**-- Python SDK and CLI accept local file and directory paths directly. In HTTP mode they automatically upload local files before calling the server API.-- Raw HTTP callers should think in two categories:- - Remote source: pass `path` directly, for example `https://example.com/doc.pdf`- - Local file: call `POST /api/v1/resources/temp_upload` first, then pass the returned `temp_file_id`- - Local directory: zip it first, upload the `.zip` file, then pass the returned `temp_file_id`-- `POST /api/v1/resources` does not accept direct host filesystem paths such as `./guide.md`, `/tmp/guide.md`, or `/tmp/my-dir/`.+| Type | Description |+|------|-------------|+| Feishu/Lark | URL-based, supports docx, wiki, sheets, bitable, requires FEISHU_APP_ID and FEISHU_APP_SECRET configuration |-**Incremental Updates**+### Resource Processing Pipeline-When you call `add_resource()` repeatedly for the same resource URI, the system performs an incremental update instead of rebuilding everything from scratch:+Resources go through the following processing stages when added:-- **Trigger**: `to` is provided and already exists in the knowledge base.-- **High-level idea**: each ingestion first builds a temporary resource tree from the new input. During asynchronous semantic processing, the temporary tree is compared against the existing tree at `to`, and only the changed parts are re-processed and synchronized.-- **Incremental behavior in the semantic stage**:- - **Unchanged files**: reuse existing L0 summaries and vector index records; skip vectorization.- - **Changed files**: regenerate summaries and vector index entries.- - **Directory-level L0/L1 (abstract/overview)**: if the child set and their change status are unchanged, reuse existing results and skip vectorization; otherwise recompute and update.-- **Filesystem + index sync**: after the semantic DAG finishes, a top-down diff is applied from the temporary tree to `to` to synchronize additions, deletions, and updates. Vector store records are kept consistent: deletions remove corresponding vectors, while moves/overwrites update vector records’ URI mapping, completing an incremental update of both the resource tree and the semantic index.+```+Source Input -> Parse -> Resource Tree Build -> Persistence -> Semantic Processing+ ↓ ↓ ↓ ↓ ↓+ URL/File Parser TreeBuilder AGFS Summarizer/Vector+```-**Python SDK (Embedded / HTTP)**+#### Stage 1: Parse+- Uses `UnifiedResourceProcessor` to parse content based on resource type+- Supports multiple formats: documents (PDF/Markdown/Word), spreadsheets (Excel/PPT), code, media files, etc.+- Parsed results are written to a temporary VikingFS directory+- Media files have descriptions generated via VLM (Vision Language Model)-```python-result = client.add_resource(- "./documents/guide.md",- reason="User guide documentation"-)-print(f"Added: {result['root_uri']}")+#### Stage 2: Resource Tree Build (TreeBuilder)+- `TreeBuilder.finalize_from_temp()` scans the temporary directory structure+- Builds resource tree nodes, handles URI conflicts (auto-renames)+- Establishes relationships between directories and resources-client.wait_processed()-```+#### Stage 3: Persistence+- Checks if target URI already exists+- New resources: moves temporary files to permanent AGFS location+- Existing resources: retains temporary tree for subsequent diff comparison+- Acquires lifecycle lock to prevent concurrent modifications+- Cleans up temporary directory-**HTTP API**+#### Stage 4: Semantic Processing+- **Summary Generation**: `Summarizer` generates L0 (abstract) and L1 (overview)+- **Vector Index**: Vectorizes content for semantic search+- Processed asynchronously via `SemanticQueue`, can wait for completion with `wait=True`-```-POST /api/v1/resources-```+### Incremental Updates for Resources-```bash-curl -X POST http://localhost:1933/api/v1/resources \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "path": "https://example.com/guide.md",- "reason": "User guide documentation"- }'-```+Resource incremental updates are implemented via the **Watch Task** mechanism:-**CLI**+#### Watch Task Creation+- Set `watch_interval > 0` (in minutes) when calling `add_resource` to create a watch task+- Must specify the `to` parameter to define the target URI+- `WatchManager` handles task persistence+- Supports multi-tenant permission control (ROOT/ADMIN/USER permission levels)-```bash-openviking add-resource ./documents/guide.md --reason "User guide documentation"-```+#### Task Scheduling & Execution+- `WatchScheduler` checks for expired tasks every 60 seconds+- Default concurrency control prevents duplicate execution+- Expired tasks automatically re-invoke `add_resource`+- Updates task's last execution time and next execution time-**Response**+#### Task Management Operations+- **Create**: Creates new task or reactivates disabled task when `watch_interval > 0`+- **Update**: Re-sets parameters for the same target URI+- **Cancel**: Disables task when `watch_interval <= 0` for the same target URI+- **Query**: Queries task status by task ID or target URI-```json-{- "status": "ok",- "result": {- "status": "success",- "root_uri": "viking://resources/documents/guide.md",- "source_path": "./documents/guide.md",- "errors": []- },- "time": 0.1-}-```+## API Reference-**Synchronous Processing Error**+### add_resource-If ingestion fails before producing a resource, raw HTTP returns the standard error envelope-with a non-2xx HTTP status. For example:+Add a resource to the knowledge base. Supports local files/directories, URLs, and other sources.-```json-{- "status": "error",- "error": {- "code": "PROCESSING_ERROR",- "message": "Parse error: [Errno 2] No such file or directory: 'git'"- }-}-```+#### 1. API Implementation Overview-`SyncHTTPClient`, `AsyncHTTPClient`, and CLI commands surface this as an error instead of-returning a successful result with `result.status="error"`.+This endpoint is the core entry point for resource management, supporting adding resources from various sources with optional waiting for semantic processing completion.-**Example: Add from URL**+**Processing Flow**:+1. Identify resource source (URL or uploaded temporary file)+2. Call corresponding Parser to parse content+3. Build directory tree and write to AGFS+4. Set up scheduled update task if `watch_interval` is specified+5. Wait for semantic processing completion if `wait=true`-**Python SDK (Embedded / HTTP)**+**Code Entry Points**:+- `openviking/client/local.py:LocalClient.add_resource` - SDK entry (embedded)+- `openviking_cli/client/http.py:AsyncHTTPClient.add_resource` - SDK entry (HTTP)+- `openviking/server/routers/resources.py:add_resource` - HTTP router+- `openviking/service/resource_service.py` - Core service implementation+- `crates/ov_cli/src/handlers.rs:handle_add_resource` - CLI handler-```python-result = client.add_resource(- "https://example.com/api-docs.md",- to="viking://resources/external/",- reason="External API documentation"-)-client.wait_processed()-```+#### 2. Interface and Parameter Description-**HTTP API**+**Parameters**-```bash-curl -X POST http://localhost:1933/api/v1/resources \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "path": "https://example.com/api-docs.md",- "to": "viking://resources/external/",- "reason": "External API documentation",- "wait": true- }'-```+| Parameter | Type | Required | Default | Description |+|-----------|------|----------|---------|-------------|+| path | string | No | - | Remote resource URL (HTTP/HTTPS/Git). Mutually exclusive with `temp_file_id` |+| temp_file_id | string | No | - | Temporary upload file ID. Mutually exclusive with `path` |+| to | string | No | - | Target Viking URI (exact location). Mutually exclusive with `parent` |+| parent | string | No | - | Parent Viking URI (resource placed under this directory). Mutually exclusive with `to` |+| reason | string | No | "" | Reason for adding the resource (for documentation and relevance improvement, experimental feature) |+| instruction | string | No | "" | Processing instructions for semantic extraction (experimental feature) |+| wait | bool | No | False | Whether to wait for semantic processing and vectorization to complete before returning |+| timeout | float | No | None | Timeout in seconds, only effective when `wait=True` |+| strict | bool | No | False | Whether to use strict mode |+| ignore_dirs | string | No | None | Directory names to ignore (comma-separated) |+| include | string | No | None | File patterns to include (glob) |+| exclude | string | No | None | File patterns to exclude (glob) |+| directly_upload_media | bool | No | True | Whether to directly upload media files |+| preserve_structure | bool | No | None | Whether to preserve directory structure |+| watch_interval | float | No | 0 | Scheduled update interval (minutes). >0 creates task; <=0 cancels task |+| telemetry | TelemetryRequest | No | False | Whether to return telemetry data |++**Additional Notes**:+- `to` and `parent` cannot be specified together+- `path` and `temp_file_id` cannot be specified together+- Raw HTTP calls for local files require first uploading via [temp_upload](#temp_upload) to obtain `temp_file_id`+- When `to` is specified and the target already exists, triggers incremental update+- `watch_interval` only takes effect when `to` is provided++#### 3. Usage Examples-**CLI**+**HTTP API**-```bash-openviking add-resource https://example.com/api-docs.md --to viking://resources/external/ --reason "External API documentation"```--**Example: Add a Local File with Raw HTTP**--When you call the HTTP API directly, upload local files first and then use `temp_file_id`.+POST /api/v1/resources+Content-Type: application/json+``````bash-# Step 1: upload the local file-TEMP_FILE_ID=$(- curl -sS -X POST http://localhost:1933/api/v1/resources/temp_upload \- -H "X-API-Key: your-key" \- -F 'file=@./documents/guide.md' \- | jq -r '.result.temp_file_id'-)--# Step 2: add the uploaded file+# Add resource from URLcurl -X POST http://localhost:1933/api/v1/resources \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \- -d "{- \"temp_file_id\": \"$TEMP_FILE_ID\",- \"reason\": \"User guide documentation\",- \"wait\": true- }"-```--**Example: Add a Local Directory with Raw HTTP**--When you call the HTTP API directly, zip the directory yourself first. CLI and SDK do this automatically for you.--```bash-# Step 1: zip the local directory-cd ./documents-zip -r /tmp/guide.zip ./guide+ -d '{+ "path": "https://example.com/guide.md",+ "reason": "User guide documentation",+ "wait": true+ }'-# Step 2: upload the zip file+# Add from local file (requires temp_upload first)TEMP_FILE_ID=$(- curl -sS -X POST http://localhost:1933/api/v1/resources/temp_upload \+ curl -s -X POST http://localhost:1933/api/v1/resources/temp_upload \-H "X-API-Key: your-key" \- -F 'file=@/tmp/guide.zip' \+ -F "file=@./documents/guide.md" \| jq -r '.result.temp_file_id')-# Step 3: add the uploaded directory archivecurl -X POST http://localhost:1933/api/v1/resources \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d "{\"temp_file_id\": \"$TEMP_FILE_ID\",- \"reason\": \"Import local directory\",- \"wait\": true+ \"to\": \"viking://resources/guide.md\",+ \"reason\": \"User guide\"}"```-**Example: Add Feishu/Lark Cloud Documents**--[Feishu](https://www.feishu.cn) (飞书) and its international version [Lark](https://www.larksuite.com) are widely used for documentation in Chinese tech companies. OpenViking can directly import cloud documents by URL.--Supported document types:+**Python SDK**-| Type | URL Pattern |-|------|-------------|-| Documents | `https://*.feishu.cn/docx/{id}` |-| Wiki pages | `https://*.feishu.cn/wiki/{token}` |-| Spreadsheets | `https://*.feishu.cn/sheets/{token}` |-| Bitable | `https://*.feishu.cn/base/{token}` |+```python+import openviking as ov-> **Setup**: Install the optional dependency: `pip install 'openviking[bot-feishu]'`->-> Configure credentials via `ov.conf` (see [Configuration](../../guides/01-configuration.md#feishu)) or environment variables:-> ```bash-> export FEISHU_APP_ID="cli_xxx"-> export FEISHU_APP_SECRET="xxx"-> ```+# Using embedded mode+client = ov.OpenViking(path="./data")+client.initialize()-**Python SDK (Embedded / HTTP)**+# Or using HTTP client+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()-```python-# Import a Feishu document+# Add local fileresult = client.add_resource(- "https://example.feishu.cn/docx/doxcnABC123",- reason="Project design document"+ "./documents/guide.md",+ reason="User guide documentation")-client.wait_processed()--# Import a wiki page (auto-resolves to underlying type)-client.add_resource("https://example.feishu.cn/wiki/wikiXYZ")--# Import a spreadsheet-client.add_resource("https://example.feishu.cn/sheets/shtcn456")-```--**CLI**--```bash-# Import a Feishu document-openviking add-resource "https://example.feishu.cn/docx/doxcnABC123" --reason "Project design document"--# Import a wiki page-openviking add-resource "https://example.feishu.cn/wiki/wikiXYZ"--# Incremental update to an existing target-openviking add-resource "https://example.feishu.cn/docx/doxcnABC123" --to viking://resources/design-doc-```--**Example: Wait for Processing**--**Python SDK (Embedded / HTTP)**--```python-# Option 1: Wait inline-result = client.add_resource("./documents/guide.md", wait=True)-print(f"Queue status: {result['queue_status']}")--# Option 2: Wait separately (for batch processing)-client.add_resource("./file1.md")-client.add_resource("./file2.md")-client.add_resource("./file3.md")--status = client.wait_processed()-print(f"All processed: {status}")-```--**HTTP API**--```bash-# Wait inline-curl -X POST http://localhost:1933/api/v1/resources \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{"path": "https://example.com/guide.md", "wait": true}'--# Wait separately after batch-curl -X POST http://localhost:1933/api/v1/system/wait \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{}'-```--**CLI**--```bash-openviking add-resource ./documents/guide.md --wait-```--**Example: Watch for Updates (watch_interval)**--`watch_interval` is in minutes and periodically triggers re-processing for the specified target URI:--- `watch_interval > 0`: create (or reactivate and update) a watch task for the `to`-- `watch_interval <= 0`: disable (deactivate) the watch task for the `to`-- watch tasks are only managed when `to` / CLI `--to` is provided+print(f"Added: {result['root_uri']}")-If there is already an active watch task for the same `to`, submitting another request with `watch_interval > 0` returns a conflict error. Disable it first (`watch_interval = 0`) and then set a new interval.+# Add from URL to specific location+result = client.add_resource(+ "https://example.com/api-docs.md",+ to="viking://resources/external/api-docs.md",+ reason="External API documentation"+)-**Python SDK (Embedded / HTTP)**+# Wait for processing to complete+client.wait_processed()-```python+# Enable scheduled updatesclient.add_resource("./documents/guide.md",- to="viking://resources/documents/guide.md",- watch_interval=60,+ to="viking://resources/guide.md",+ watch_interval=60 # Update every 60 minutes)```-**HTTP API**--```bash-curl -X POST http://localhost:1933/api/v1/resources \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "path": "https://example.com/guide.md",- "to": "viking://resources/documents/guide.md",- "watch_interval": 60- }'-```-**CLI**```bash-openviking add-resource ./documents/guide.md --to viking://resources/documents/guide.md --watch-interval 60+# Add local file+ov add-resource ./documents/guide.md --reason "User guide"-# Disable watch-openviking add-resource ./documents/guide.md --to viking://resources/documents/guide.md --watch-interval 0-```+# Add from URL+ov add-resource https://example.com/guide.md --to viking://resources/guide.md------### export_ovpack()--Export a resource tree as a `.ovpack` file.--**SDK / CLI parameters**--| Parameter | Type | Required | Default | Description |-|-----------|------|----------|---------|-------------|-| uri | str | Yes | - | Viking URI to export |-| to | str | Yes | - | Target file path |+# Wait for processing to complete+ov add-resource ./documents/guide.md --wait-**Raw HTTP request body**+# Enable scheduled updates (check every 60 minutes)+ov add-resource https://github.com/example/repo.git --to viking://resources/guide.md --watch-interval 60-| Parameter | Type | Required | Default | Description |-|-----------|------|----------|---------|-------------|-| uri | str | Yes | - | Viking URI to export |--**Python SDK (Embedded / HTTP)**--```python-path = client.export_ovpack(- "viking://resources/my-project/",- "./exports/my-project.ovpack"-)-print(f"Exported to: {path}")+# Cancel scheduled updates+ov add-resource https://github.com/example/repo.git --to viking://resources/guide.md --watch-interval 0```-**HTTP API**--```-POST /api/v1/pack/export-```--```bash-curl -X POST http://localhost:1933/api/v1/pack/export \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "uri": "viking://resources/my-project/"- }'-```--**CLI**--```bash-openviking export viking://resources/my-project/ ./exports/my-project.ovpack-```--**Response**--The HTTP API streams the `.ovpack` file directly as a download (`Content-Type: application/zip`). It does not return a JSON envelope for this endpoint.-------### import_ovpack()--Import a `.ovpack` file.--**SDK / CLI parameters**--| Parameter | Type | Required | Default | Description |-|-----------|------|----------|---------|-------------|-| file_path | str | Yes | - | Local `.ovpack` file path |-| parent | str | Yes | - | Target parent URI |-| force | bool | No | False | Overwrite existing resources |-| vectorize | bool | No | True | Trigger vectorization after import |--**Raw HTTP request body**--| Parameter | Type | Required | Default | Description |-|-----------|------|----------|---------|-------------|-| temp_file_id | str | Yes | - | Upload ID returned by `POST /api/v1/resources/temp_upload` |-| parent | str | Yes | - | Target parent URI |-| force | bool | No | False | Overwrite existing resources |-| vectorize | bool | No | True | Trigger vectorization after import |+**Response Example**-**Python SDK (Embedded / HTTP)**--```python-uri = client.import_ovpack(- "./exports/my-project.ovpack",- "viking://resources/imported/",- force=True,- vectorize=True-)-print(f"Imported to: {uri}")--client.wait_processed()-```--**HTTP API**--```-POST /api/v1/pack/import-```--```bash-# Step 1: upload the local ovpack file-TEMP_FILE_ID=$(- curl -sS -X POST http://localhost:1933/api/v1/resources/temp_upload \- -H "X-API-Key: your-key" \- -F 'file=@./exports/my-project.ovpack' \- | jq -r '.result.temp_file_id'-)--# Step 2: import using temp_file_id-curl -X POST http://localhost:1933/api/v1/pack/import \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d "{- \"temp_file_id\": \"$TEMP_FILE_ID\",- \"parent\": \"viking://resources/imported/\",- \"force\": true,- \"vectorize\": true- }"-```--**CLI**--```bash-openviking import ./exports/my-project.ovpack viking://resources/imported/ --force-```--**Response**+**HTTP API Response (JSON)**```json{"status": "ok","result": {- "uri": "viking://resources/imported/my-project/"+ "status": "success",+ "root_uri": "viking://resources/guide.md",+ "temp_uri": "viking://temp/username/04291108_b62dc7/guide.md",+ "source_path": "./documents/guide.md",+ "meta": {},+ "errors": [],+ "queue_status": {+ "pending": 5,+ "processing": 2,+ "completed": 10+ }},- "time": 0.1+ "telemetry": {+ "operation_id": "550e8400-e29b-41d4-a716-446655440000"+ }}```------## Managing Resources--### List Resources--**Python SDK (Embedded / HTTP)**--```python-# List all resources-entries = client.ls("viking://resources/")--# List with details-for entry in entries:- type_str = "dir" if entry['isDir'] else "file"- print(f"{entry['name']} - {type_str}")--# Simple path list-paths = client.ls("viking://resources/", simple=True)-# Returns: ["project-a/", "project-b/", "shared/"]--# Recursive listing-all_entries = client.ls("viking://resources/", recursive=True)-```--**HTTP API**--```-GET /api/v1/fs/ls?uri={uri}&simple={bool}&recursive={bool}-```--```bash-# List all resources-curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://resources/" \- -H "X-API-Key: your-key"--# Simple path list-curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://resources/&simple=true" \- -H "X-API-Key: your-key"+**CLI Response (Default Table Format)**-# Recursive listing-curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://resources/&recursive=true" \- -H "X-API-Key: your-key"```--**CLI**--```bash-# List all resources-openviking ls viking://resources/--# Simple path list-openviking ls viking://resources/ --simple--# Recursive listing-openviking ls viking://resources/ --recursive+Note: Resource is being processed in the background.+Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.+status success+errors []+source_path /Users/bytedance/workspace/github.com/OpenViking/docs/en/api/01-overview.md+meta {}+root_uri viking://resources/01-overview+temp_uri viking://temp/shengmaojia/04291108_b62dc7/01-overview```-**Response**+**CLI Response (JSON Format, using -o json)**```json{- "status": "ok",- "result": [- {- "name": "project-a",- "size": 4096,- "isDir": true,- "uri": "viking://resources/project-a/"- }- ],- "time": 0.1+ "status": "success",+ "root_uri": "viking://resources/01-overview",+ "temp_uri": "viking://temp/shengmaojia/04291108_b62dc7/01-overview",+ "source_path": "/Users/bytedance/workspace/github.com/OpenViking/docs/en/api/01-overview.md",+ "meta": {},+ "errors": []}```------### Read Resource Content+**Field Description**-**Python SDK (Embedded / HTTP)**+| Field | Type | Description |+|-------|------|-------------|+| `status` | string | Processing status: "success" or "error" |+| `root_uri` | string | Final URI of the resource in OpenViking |+| `temp_uri` | string | Temporary URI during processing (only valid during background processing) |+| `source_path` | string | Original source file path or URL |+| `meta` | object | Metadata from resource parsing (file type, size, etc.) |+| `errors` | array | List of errors encountered during processing |+| `warnings` | array | (Optional) List of warnings (only when `strict=False`) |+| `queue_status` | object | (Optional, only when `wait=true`) Queue processing status with `pending`, `processing`, `completed` counts |-```python-# L0: Abstract-abstract = client.abstract("viking://resources/docs/")--# L1: Overview-overview = client.overview("viking://resources/docs/")--# L2: Full content-content = client.read("viking://resources/docs/api.md")-```--**HTTP API**+----```bash-# L0: Abstract-curl -X GET "http://localhost:1933/api/v1/content/abstract?uri=viking://resources/docs/" \- -H "X-API-Key: your-key"+### add_skill-# L1: Overview-curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://resources/docs/" \- -H "X-API-Key: your-key"+Add a skill to the knowledge base.-# L2: Full content-curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://resources/docs/api.md" \- -H "X-API-Key: your-key"-```+#### 1. API Implementation Overview-**CLI**+Skills are special resources used to define operations or tools that agents can execute.-```bash-# L0: Abstract-openviking abstract viking://resources/docs/+**Processing Flow**:+1. Receive skill data or uploaded temporary file+2. Parse skill definition+3. Store to skill directory+4. Wait for skill processing completion if `wait=true`-# L1: Overview-openviking overview viking://resources/docs/+**Code Entry Points**:+- `openviking/client/local.py:LocalClient.add_skill` - SDK entry (embedded)+- `openviking_cli/client/http.py:AsyncHTTPClient.add_skill` - SDK entry (HTTP)+- `openviking/server/routers/resources.py:add_skill` - HTTP router+- `openviking/service/resource_service.py` - Core service implementation+- `crates/ov_cli/src/handlers.rs:handle_add_skill` - CLI handler-# L2: Full content-openviking read viking://resources/docs/api.md-```+#### 2. Interface and Parameter Description-**Response**--```json-{- "status": "ok",- "result": "Documentation for the project API, covering authentication, endpoints...",- "time": 0.1-}-```-------### Move Resources+**Parameters**-**Python SDK (Embedded / HTTP)**+| Parameter | Type | Required | Default | Description |+|-----------|------|----------|---------|-------------|+| data | Any | No | - | Inline skill content or structured data. Mutually exclusive with `temp_file_id` |+| temp_file_id | string | No | - | Temporary upload file ID (obtained via [temp_upload](#temp_upload)). Mutually exclusive with `data` |+| wait | bool | No | False | Whether to wait for skill processing to complete |+| timeout | float | No | None | Timeout in seconds, only effective when `wait=True` |+| telemetry | TelemetryRequest | No | False | Whether to return telemetry data |-```python-client.mv(- "viking://resources/old-project/",- "viking://resources/new-project/"-)-```+#### 3. Usage Examples**HTTP API**```-POST /api/v1/fs/mv+POST /api/v1/skills+Content-Type: application/json``````bash-curl -X POST http://localhost:1933/api/v1/fs/mv \+# Using inline data+curl -X POST http://localhost:1933/api/v1/skills \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{- "from_uri": "viking://resources/old-project/",- "to_uri": "viking://resources/new-project/"+ "data": {+ "name": "my-skill",+ "description": "My custom skill",+ "steps": []+ }}'-```--**CLI**--```bash-openviking mv viking://resources/old-project/ viking://resources/new-project/-```-**Response**+# Using local file (requires temp_upload first)+TEMP_FILE_ID=$(+ curl -s -X POST http://localhost:1933/api/v1/resources/temp_upload \+ -H "X-API-Key: your-key" \+ -F "file=@./skills/my-skill.json" \+ | jq -r '.result.temp_file_id'+)-```json-{- "status": "ok",- "result": {- "from": "viking://resources/old-project/",- "to": "viking://resources/new-project/"- },- "time": 0.1-}+curl -X POST http://localhost:1933/api/v1/skills \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d "{+ \"temp_file_id\": \"$TEMP_FILE_ID\"+ }"```------### Delete Resources--**Python SDK (Embedded / HTTP)**+**Python SDK**```python-# Delete single file-client.rm("viking://resources/docs/old.md")--# Delete directory recursively-client.rm("viking://resources/old-project/", recursive=True)-```--**HTTP API**+import openviking as ov-```-DELETE /api/v1/fs?uri={uri}&recursive={bool}-```+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()-```bash-# Delete single file-curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://resources/docs/old.md" \- -H "X-API-Key: your-key"+# Add skill from local file+result = client.add_skill("./skills/my-skill.json")-# Delete directory recursively-curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://resources/old-project/&recursive=true" \- -H "X-API-Key: your-key"+# Wait for processing to complete+client.wait_processed()```**CLI**```bash-# Delete single file-openviking rm viking://resources/docs/old.md+# Add skill+ov add-skill ./skills/my-skill.json-# Delete directory recursively-openviking rm viking://resources/old-project/ --recursive+# Wait for processing to complete+ov add-skill ./skills/my-skill.json --wait```-**Response**+#### 4. Response Example++**HTTP API Response (JSON)**```json{"status": "ok","result": {- "uri": "viking://resources/docs/old.md"+ "status": "success",+ "root_uri": "viking://agent/skills/my-skill",+ "uri": "viking://agent/skills/my-skill",+ "name": "my-skill",+ "auxiliary_files": 2,+ "queue_status": {+ "pending": 0,+ "processing": 0,+ "completed": 1+ }},- "time": 0.1+ "telemetry": {+ "operation_id": "550e8400-e29b-41d4-a716-446655440000"+ }}```------### Create Links--**Python SDK (Embedded / HTTP)**--```python-# Link related resources-client.link(- "viking://resources/docs/auth/",- "viking://resources/docs/security/",- reason="Security best practices for authentication"-)--# Multiple links-client.link(- "viking://resources/docs/api/",- [- "viking://resources/docs/auth/",- "viking://resources/docs/errors/"- ],- reason="Related documentation"-)-```--**HTTP API**+**CLI Response (Default Table Format)**```-POST /api/v1/relations/link+Note: Skill is being processed in the background.+Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.+status success+root_uri viking://agent/skills/my-skill+uri viking://agent/skills/my-skill+name my-skill+auxiliary_files 2```-```bash-# Single link-curl -X POST http://localhost:1933/api/v1/relations/link \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "from_uri": "viking://resources/docs/auth/",- "to_uris": "viking://resources/docs/security/",- "reason": "Security best practices for authentication"- }'--# Multiple links-curl -X POST http://localhost:1933/api/v1/relations/link \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "from_uri": "viking://resources/docs/api/",- "to_uris": ["viking://resources/docs/auth/", "viking://resources/docs/errors/"],- "reason": "Related documentation"- }'-```--**CLI**--```bash-openviking link viking://resources/docs/auth/ viking://resources/docs/security/ --reason "Security best practices"-```--**Response**+**CLI Response (JSON Format, using -o json)**```json{- "status": "ok",- "result": {- "from": "viking://resources/docs/auth/",- "to": "viking://resources/docs/security/"- },- "time": 0.1+ "status": "success",+ "root_uri": "viking://agent/skills/my-skill",+ "uri": "viking://agent/skills/my-skill",+ "name": "my-skill",+ "auxiliary_files": 2}```------### Get Relations--**Python SDK (Embedded / HTTP)**+**Field Description**-```python-relations = client.relations("viking://resources/docs/auth/")-for rel in relations:- print(f"{rel['uri']}: {rel['reason']}")-```+| Field | Type | Description |+|-------|------|-------------|+| `status` | string | Processing status: "success" or "error" |+| `root_uri` | string | Final URI of the skill in OpenViking (same as `uri`) |+| `uri` | string | Final URI of the skill in OpenViking (same as `root_uri`) |+| `name` | string | Skill name |+| `auxiliary_files` | number | Number of auxiliary files attached to the skill |+| `queue_status` | object | (Optional, only when `wait=true`) Queue processing status with `pending`, `processing`, `completed` counts |-**HTTP API**+----```-GET /api/v1/relations?uri={uri}-```+### temp_upload-```bash-curl -X GET "http://localhost:1933/api/v1/relations?uri=viking://resources/docs/auth/" \- -H "X-API-Key: your-key"-```+Upload a temporary file for subsequent importing of local files via [add_resource](#add_resource) or [add_skill](#add_skill).-**CLI**+#### 1. API Implementation Overview-```bash-openviking relations viking://resources/docs/auth/-```+This endpoint is used to upload local files to server temporary storage, returning a `temp_file_id` for use with subsequent API calls. This is a helper endpoint typically not called directly but used automatically via the SDK or CLI.-**Response**+**Processing Flow**:+1. Receive uploaded file+2. Clean up expired temporary files+3. Save to temporary directory and record original filename+4. Return temporary file ID-```json-{- "status": "ok",- "result": [- {"uri": "viking://resources/docs/security/", "reason": "Security best practices"},- {"uri": "viking://resources/docs/errors/", "reason": "Error handling"}- ],- "time": 0.1-}-```+**Code Entry Points**:+- `openviking/server/routers/resources.py:temp_upload` - HTTP router+- `openviking/service/resource_service.py` - Service implementation----+#### 2. Interface and Parameter Description-### Remove Links+**Parameters**-**Python SDK (Embedded / HTTP)**+| Parameter | Type | Required | Default | Description |+|-----------|------|----------|---------|-------------|+| file | UploadFile | Yes | - | Uploaded file (multipart/form-data) |+| telemetry | bool | No | False | Whether to return telemetry data |-```python-client.unlink(- "viking://resources/docs/auth/",- "viking://resources/docs/security/"-)-```+#### 3. Usage Examples**HTTP API**```-DELETE /api/v1/relations/link+POST /api/v1/resources/temp_upload+Content-Type: multipart/form-data``````bash-curl -X DELETE http://localhost:1933/api/v1/relations/link \- -H "Content-Type: application/json" \+curl -X POST http://localhost:1933/api/v1/resources/temp_upload \-H "X-API-Key: your-key" \- -d '{- "from_uri": "viking://resources/docs/auth/",- "to_uri": "viking://resources/docs/security/"- }'+ -F "file=@./documents/guide.md"```+**Python SDK**++The `add_resource`, `add_skill` and other endpoints in the Python SDK automatically handle local file uploads, no need to call this endpoint manually.+**CLI**-```bash-openviking unlink viking://resources/docs/auth/ viking://resources/docs/security/-```+CLI commands also automatically handle local file uploads, no need to call this endpoint manually.-**Response**+**Response Example**```json{"status": "ok","result": {- "from": "viking://resources/docs/auth/",- "to": "viking://resources/docs/security/"+ "temp_file_id": "upload_abc123def456.md"},- "time": 0.1+ "telemetry": {+ "operation_id": "550e8400-e29b-41d4-a716-446655440000"+ }}```----## Best Practices--### Organize by Project--```-viking://resources/-+-- project-a/-| +-- docs/-| +-- specs/-| +-- references/-+-- project-b/-| +-- ...-+-- shared/- +-- common-docs/-```-## Related Documentation-- [Retrieval](06-retrieval.md) - Search resources-- [File System](03-filesystem.md) - File operations-- [Context Types](../concepts/02-context-types.md) - Resource concept+- [File System](03-filesystem.md) - File and directory operations+- [Skills](04-skills.md) - Skill management APIs+- [Retrieval](06-retrieval.md) - Search and context acquisition+- [ovpack Guide](../guides/09-ovpack.md) - Detailed ovpack import/export documentationdiff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.mdindex 0e0365ac9..6011c14c0 100644--- a/docs/en/api/03-filesystem.md+++ b/docs/en/api/03-filesystem.md@@ -975,6 +975,182 @@ openviking unlink viking://resources/docs/auth/ viking://resources/docs/security---+### export_ovpack++Export a resource tree as a `.ovpack` file.++#### 1. API Implementation Overview++Packages all resources under the specified URI into a `.ovpack` file for backup or migration. Requires ROOT or ADMIN permissions.++**Processing Flow**:+1. Verify user permissions+2. Traverse resources under the specified URI+3. Package into zip format (`.ovpack`)+4. Return as file stream++**Code Entry Points**:+- `openviking/server/routers/pack.py:export_ovpack` - HTTP router+- `openviking/service/pack_service.py` - Core service implementation+- `crates/ov_cli/src/handlers.rs:handle_export` - CLI handler++#### 2. Interface and Parameter Description++**Parameters**++| Parameter | Type | Required | Default | Description |+|-----------|------|----------|---------|-------------|+| uri | string | Yes | - | Viking URI to export |++**Permission Requirements**: ROOT or ADMIN++#### 3. Usage Examples++**HTTP API**++```+POST /api/v1/pack/export+Content-Type: application/json+```++```bash+curl -X POST http://localhost:1933/api/v1/pack/export \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-admin-key" \+ -d '{+ "uri": "viking://resources/my-project/"+ }' \+ --output my-project.ovpack+```++**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-admin-key")+client.initialize()++# Export to local file (HTTP SDK automatically handles download)+# Note: Export functionality is primarily used via CLI+```++**CLI**++```bash+# Export resource+ov export viking://resources/my-project/ ./exports/my-project.ovpack+```++**Response Example**++This endpoint directly returns a file stream (`Content-Type: application/zip`), does not return a JSON envelope.++---++### import_ovpack++Import a `.ovpack` file.++#### 1. API Implementation Overview++Imports a `.ovpack` file to a specified location for restoring or migrating data. Requires ROOT or ADMIN permissions.++**Processing Flow**:+1. Verify user permissions+2. Parse uploaded `.ovpack` file+3. Import resources to target location+4. Optionally trigger vectorization++**Code Entry Points**:+- `openviking/server/routers/pack.py:import_ovpack` - HTTP router+- `openviking/service/pack_service.py` - Core service implementation+- `crates/ov_cli/src/handlers.rs:handle_import` - CLI handler++#### 2. Interface and Parameter Description++**Parameters**++| Parameter | Type | Required | Default | Description |+|-----------|------|----------|---------|-------------|+| temp_file_id | string | Yes | - | Temporary upload file ID (obtained via [temp_upload](02-resources.md#temp_upload)) |+| parent | string | Yes | - | Target parent URI (import to this location) |+| force | bool | No | False | Whether to overwrite existing resources |+| vectorize | bool | No | True | Whether to trigger vectorization |++**Permission Requirements**: ROOT or ADMIN++#### 3. Usage Examples++**HTTP API**++```+POST /api/v1/pack/import+Content-Type: application/json+```++```bash+# Step 1: Upload .ovpack file+TEMP_FILE_ID=$(+ curl -s -X POST http://localhost:1933/api/v1/resources/temp_upload \+ -H "X-API-Key: your-admin-key" \+ -F "file=@./exports/my-project.ovpack" \+ | jq -r '.result.temp_file_id'+)++# Step 2: Import+curl -X POST http://localhost:1933/api/v1/pack/import \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-admin-key" \+ -d "{+ \"temp_file_id\": \"$TEMP_FILE_ID\",+ \"parent\": \"viking://resources/imported/\",+ \"force\": true,+ \"vectorize\": true+ }"+```++**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-admin-key")+client.initialize()++# Import .ovpack file (HTTP SDK automatically handles upload)+# Note: Import functionality is primarily used via CLI+```++**CLI**++```bash+# Import .ovpack file+ov import ./exports/my-project.ovpack viking://resources/imported/++# Force overwrite existing content+ov import ./exports/my-project.ovpack viking://resources/imported/ --force++# Skip vectorization+ov import ./exports/my-project.ovpack viking://resources/imported/ --no-vectorize+```++**Response Example**++```json+{+ "status": "ok",+ "result": {+ "uri": "viking://resources/imported/my-project/"+ },+ "telemetry": {+ "operation_id": "550e8400-e29b-41d4-a716-446655440000"+ }+}+```++---+## Related Documentation- [Viking URI](../concepts/04-viking-uri.md) - URI specificationdiff --git a/docs/en/api/99-api-doc-writing-guide.md b/docs/en/api/99-api-doc-writing-guide.mdnew file mode 100644index 000000000..531729c0e--- /dev/null+++ b/docs/en/api/99-api-doc-writing-guide.md@@ -0,0 +1,237 @@+# API Documentation Writing Guide++This document defines the unified structure and writing conventions for API module documentation in the `docs/en/api/` directory.++## Directory Structure++API documentation is organized by module, with one file per module, using a two-digit numerical prefix.++## Unified File Structure++Each API module documentation should follow the structure below:++```markdown+# Module Name++Brief introduction explaining the main features and purpose of this module.++## Optional Concepts/Introduction Section++(If needed, explain core concepts, workflows, etc., related to this module)++## API Reference++### API Method Name 1++#### 1. API Implementation Introduction++Explain the purpose of this API, point to the corresponding code entry, and briefly describe the principles and workflow.++**Code Entry**:+- `openviking/<module>/<file>.py:<ClassName>.<MethodName>` - Core implementation+- `openviking/server/routers/<router-file>.py` - HTTP router+- `openviking_cli/commands/<command-file>.py` - CLI command++#### 2. Interface and Parameter Description++**Parameters**++| Parameter | Type | Required | Default | Description |+|-----------|------|----------|---------|-------------|+| <param-name> | <type> | <yes/no> | <default> | <detailed description> |+| ... | ... | ... | ... | ... |++**Optional Supplementary Section**++(If needed, explain special behaviors, considerations, usage scenarios, etc.)++#### 3. Usage Examples++**HTTP API**++```+<HTTP Method> <Path>+```++```bash+<curl example>+```++**Python SDK**++```python+<SDK call example>+```++**CLI**++```bash+<CLI command example>+```++**Response Example**++```json+<JSON response example>+```+++#### 4. Response Example, Error Handling, and Exception Handling (Optional)++---++### API Method Name 2++(Repeat the above structure)++---++## Optional Additional Sections++## Related Documentation++- [Document Title](<relative-path>) - <brief description>+```++## Structure Details++### Title and Introduction++- The level 1 heading is the module name+- The introduction uses a paragraph to explain the purpose and main features of the module++### API Reference Section++Each API is organized in the following three parts:++#### 1. API Implementation Introduction++- Explain the purpose of this API+- Provide code entry paths for readers to reference the source code+- Briefly describe the implementation principles and processing workflow++**Code Entry Notes**:+- Core implementation: points to the main business logic code+- HTTP router: points to the FastAPI route definition+- CLI command: points to the CLI command implementation (if available)++#### 2. Interface and Parameter Description++- Parameter table: includes parameter name, type, required status, default value, description+- Supplementary notes (optional): special behaviors, considerations, usage scenarios, etc.++#### 3. Usage Examples++Provide in order:+- HTTP API (method + path + curl example)+- Python SDK example+- CLI example+- Response example++## Example: Complete API Documentation++```markdown+### add_resource()++#### 1. API Implementation Introduction++Add resources to the knowledge base, supporting various sources such as local files, directories, URLs, etc.++**Processing Workflow**:+1. Identify resource type (local file/directory/URL)+2. Call corresponding parser to parse content+3. Build directory tree and write to AGFS+4. Asynchronously generate L0/L1 semantic abstracts+5. Build vector index++**Code Entry**:+- `openviking/core/client.py:OpenViking.add_resource()` - SDK entry+- `openviking/resource/importer.py:ResourceImporter.import_resource()` - Core implementation+- `openviking/server/routers/resources.py` - HTTP router+- `openviking_cli/commands/resources.py` - CLI command++#### 2. Interface and Parameter Description++**Parameters**++| Parameter | Type | Required | Default | Description |+|-----------|------|----------|---------|-------------|+| path | str | Yes | - | Local path, directory path, or URL |+| to | str | No | None | Target Viking URI (must be within the resources scope) |+| reason | str | No | "" | Reason for adding this resource |+| wait | bool | No | False | Whether to wait for semantic processing completion |++**Notes**++- SDK/CLI can directly pass local paths; raw HTTP requires `temp_upload` first+- When `to` is specified and the target already exists, an incremental update process is used++#### 3. Usage Examples++**HTTP API**++```+POST /api/v1/resources+```++```bash+curl -X POST http://localhost:1933/api/v1/resources \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "path": "https://example.com/guide.md",+ "reason": "User guide documentation",+ "wait": true+ }'+```++**Python SDK**++```python+import openviking as ov++client = ov.OpenViking(path="./data")+client.initialize()++result = client.add_resource(+ "./documents/guide.md",+ reason="User guide documentation"+)+print(f"Added: {result['root_uri']}")++client.wait_processed()+```++**CLI**++```bash+openviking add-resource ./documents/guide.md --reason "User guide documentation" --wait+```++**Response Example**++```json+{+ "status": "ok",+ "result": {+ "status": "success",+ "root_uri": "viking://resources/documents/guide.md",+ "source_path": "./documents/guide.md",+ "errors": []+ },+ "time": 0.123+}+```++---+```++## Documentation Maintenance Checklist++When adding or modifying API documentation, please check:++- [ ] Implementation introduction is clear and code entry paths are correct+- [ ] Parameter table is complete and accurate+- [ ] Example code is concise and runnable+- [ ] HTTP method and path are correct+- [ ] Response example matches actual outputdiff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.mdindex 91888aba3..972d8f66c 100644--- a/docs/zh/api/01-overview.md+++ b/docs/zh/api/01-overview.md@@ -2,17 +2,21 @@本页介绍如何连接 OpenViking 以及所有 API 端点共享的约定。-## 连接 OpenViking+## 连接模式-OpenViking 支持三种连接模式:+OpenViking 支持两种使用模式:**嵌入式模式**(直接调用 Python API)和 **Client-Server 模式**(通过 HTTP API 连接)。-| 模式 | 使用场景 | 说明 |+本 API 文档主要介绍 **Client-Server 模式**的 HTTP API 使用方式。嵌入式模式虽然可用,但后续文档将不单独展开介绍。++| 模式 | 适用场景 | 说明 ||------|----------|------|-| **嵌入式** | 本地开发,单进程 | 本地运行,数据存储在本地 |-| **HTTP** | 连接 OpenViking Server | 通过 HTTP API 连接远程服务 |-| **CLI** | Shell 脚本、Agent 工具调用 | 通过 CLI 命令连接服务端 |+| **嵌入式模式** | 本地开发、单进程 | 使用本地数据存储运行 |+| **HTTP** | 连接 OpenViking 服务器 | 通过 HTTP API 连接远程服务器 |+| **CLI** | Shell 脚本、Agent 工具使用 | 通过 CLI 命令连接服务器 |-### 嵌入式模式+### 嵌入式模式(简要说明)++嵌入式模式允许在 Python 进程内直接调用 OpenViking API,无需启动独立的服务器进程。```pythonimport openviking as ov@@ -21,7 +25,7 @@ client = ov.OpenViking(path="./data")client.initialize()```-嵌入式模式通过 `ov.conf` 配置 embedding、vlm、storage 等模块。默认路径 `~/.openviking/ov.conf`,也可通过环境变量指定:+嵌入式模式通过 `ov.conf` 配置 embedding、vlm、storage 等模块。默认配置路径为 `~/.openviking/ov.conf`,也可通过环境变量指定:```bashexport OPENVIKING_CONFIG_FILE=/path/to/ov.conf@@ -49,13 +53,19 @@ export OPENVIKING_CONFIG_FILE=/path/to/ov.conf}```-当 `provider: "openai-codex"` 时,只要通过 `openviking-server init` 完成 Codex OAuth,就可以不填写 `vlm.api_key`。+对于 `provider: "openai-codex"`,通过 `openviking-server init` 配置 Codex OAuth 后,`vlm.api_key` 是可选的。++完整的配置选项和 provider 特定示例,请参见 [配置指南](../guides/01-configuration.md)。-完整配置选项和各服务商示例见 [配置指南](../guides/01-configuration.md)。+### Client-Server 模式(主要介绍)-### HTTP 模式+Client-Server 模式通过 HTTP API 连接 OpenViking 服务器,支持多租户、远程访问等特性。OpenViking 的服务器启动方式请参见相关部署文档。++#### Python SDK 客户端```python+import openviking as ov+client = ov.SyncHTTPClient(url="http://localhost:1933",api_key="your-key",@@ -71,6 +81,8 @@ client.initialize()export OPENVIKING_CLI_CONFIG_FILE=/path/to/ovcli.conf```+配置文件示例:+```json{"url": "http://localhost:1933",@@ -81,43 +93,67 @@ export OPENVIKING_CLI_CONFIG_FILE=/path/to/ovcli.conf}```+配置字段说明:+| 字段 | 说明 | 默认值 ||------|------|--------|| `url` | 服务端地址 | (必填) || `api_key` | API Key | `null`(无认证) |-| `account` | 面向租户请求的默认 account 请求头 | `null` |-| `user` | 面向租户请求的默认 user 请求头 | `null` |-| `agent_id` | Agent 标识符 | `null` |+| `account` | 租户级请求的默认账户请求头 | `null` |+| `user` | 租户级请求的默认用户请求头 | `null` |+| `agent_id` | Agent 标识符请求头 | `null` || `timeout` | HTTP 请求超时时间(秒) | `60.0` || `output` | 默认输出格式:`"table"` 或 `"json"` | `"table"` |-详见 [配置指南](../guides/01-configuration.md#ovcliconf)。+详细内容请参见 [配置指南](../guides/01-configuration.md#ovcliconf)。++#### 完全不依赖配置文件使用 Python SDK 客户端++`SyncHTTPClient` 和 `AsyncHTTPClient` 支持完全不依赖 `ovcli.conf` 配置文件,只需在初始化时**显式传入所有参数**即可:++```python+import openviking as ov++client = ov.SyncHTTPClient(+ url="http://localhost:1933", # 显式传入+ api_key="your-key", # 显式传入(默认情况下 api_key 已经能标识用户身份)+ timeout=30.0, # 不要用默认值 60.0+ extra_headers={} # 传空 dict 而不是 None,可用于某些场景的网关认证等+)+client.initialize()+```++⚠️ **注意**:只要以下任一条件满足,客户端就会尝试加载配置文件:+- `url` 为 `None`+- `api_key` 为 `None`+- `timeout` 等于 `60.0`(默认值)+- `extra_headers` 为 `None`-**HTTP 模式下的本地文件**+#### HTTP 调用示例- CLI、`SyncHTTPClient`、`AsyncHTTPClient` 遇到本地文件或目录时,会先自动上传,再调用服务端 API。- 裸 HTTP 调用没有这层封装。使用 `curl` 或其他 HTTP 客户端时,需要先调用 `POST /api/v1/resources/temp_upload`,再把返回的 `temp_file_id` 传给目标 API。-- 裸 HTTP 如果导入本地目录,需要先自行打成 `.zip` 再上传;服务端不接受直接传宿主机目录路径。+- 裸 HTTP 如果导入本地目录,需要先自行打成 `.zip` 再通过上述方法上传;服务端不接受直接传宿主机目录路径。- `POST /api/v1/resources` 可以直接接收远端 URL,但不接受 `./doc.md`、`/tmp/doc.md` 这类宿主机本地路径。-### 直接 HTTP(curl)+直接 HTTP(curl)调用示例如下```bashcurl http://localhost:1933/api/v1/fs/ls?uri=viking:// \- -H "X-API-Key: your-key"+ -H "X-API-Key: your-key"```-### CLI 模式+#### CLI 模式-CLI 连接到 OpenViking 服务端,将所有操作暴露为 Shell 命令。CLI 同样从 `ovcli.conf` 读取连接信息(与 HTTP 客户端共享)。+OpenViking CLI (可简写为 ov 命令)连接到 OpenViking 服务端,将所有操作暴露为 Shell 命令。CLI 同样从 `ovcli.conf` 读取连接信息(与 HTTP 客户端共享)。-**基本用法**+基本用法:```bashopenviking [全局选项] <command> [参数] [命令选项]```-**全局选项**(必须放在命令名之前)+全局选项(必须放在命令名之前):| 选项 | 说明 ||------|------|@@ -132,7 +168,7 @@ openviking -o json ls viking://resources/## 生命周期-**嵌入式模式**+### 嵌入式模式```pythonimport openviking as ov@@ -145,7 +181,7 @@ client.initialize()client.close()```-**HTTP 模式**+### Client-Server 模式```pythonimport openviking as ov@@ -158,20 +194,26 @@ client.initialize()client.close()```+CLI 则直接通过命令行调用,需要先配置 ovcli.conf 文件,无需额外初始化客户端:++```+openviking -o json ls viking://resources/+```+## 认证详见 [认证指南](../guides/04-authentication.md)。+- **Authorization Bearer** 请求头:`Authorization: Bearer your-key` (建议的方式)- **X-API-Key** 请求头:`X-API-Key: your-key`-- **Bearer** 请求头:`Authorization: Bearer your-key`- 如果服务端未配置 API Key,则跳过认证。-- `/health` 端点始终不需要认证。+- `/health` 和 `/ready` 端点始终不需要认证。## 响应格式所有 HTTP API 响应遵循统一格式:-**成功**+### 成功响应```json{@@ -181,11 +223,9 @@ client.close()}```-顶层 `status` 表示本次 HTTP API 请求是否成功。某些成功响应会在 `result` 中返回业务状态,-例如 `"status": "success"`、`"status": "accepted"` 或任务状态。这些字段不是 API-传输层错误。+顶层 `status` 表示本次 HTTP API 请求是否成功。某些成功响应会在 `result` 中返回业务状态,例如 `"status": "success"`、`"status": "accepted"` 或任务状态。这些字段不是 API 传输层错误。-**错误**+### 错误响应```json{@@ -198,16 +238,11 @@ client.close()}```-HTTP 错误始终使用顶层错误 envelope。资源解析、同步 reindex 等同步处理失败会返回非 2xx-响应,顶层为 `status="error"`,并包含 `error` 对象。客户端不应通过-`result.status="error"` 判断请求失败。+HTTP 错误始终使用顶层错误 envelope。资源解析、同步 reindex 等同步处理失败会返回非 2xx 响应,顶层为 `status="error"`,并包含 `error` 对象。客户端不应通过 `result.status="error"` 判断请求失败。-请求校验失败,包括 JSON 格式错误、缺少必填字段和参数值非法,统一返回 HTTP `400`,-并使用 `error.code="INVALID_ARGUMENT"`。响应不会使用 FastAPI 原生的 `{"detail": ...}`-错误格式;当存在字段级校验信息时,会通过 `error.details.validation_errors` 返回。+请求校验失败,包括 JSON 格式错误、缺少必填字段和参数值非法,统一返回 HTTP `400`,并使用 `error.code="INVALID_ARGUMENT"`。响应不会使用 FastAPI 原生的 `{"detail": ...}` 错误格式;当存在字段级校验信息时,会通过 `error.details.validation_errors` 返回。-Python HTTP SDK(`SyncHTTPClient` 和 `AsyncHTTPClient`)会把该 envelope 映射为对应的-`OpenVikingError` 子类。例如 `PROCESSING_ERROR` 会抛出 `ProcessingError`。+Python HTTP SDK(`SyncHTTPClient` 和 `AsyncHTTPClient`)会把该 envelope 映射为对应的 `OpenVikingError` 子类。例如 `PROCESSING_ERROR` 会抛出 `ProcessingError`。## CLI 输出格式@@ -218,7 +253,7 @@ Python HTTP SDK(`SyncHTTPClient` 和 `AsyncHTTPClient`)会把该 envelope```bashopenviking ls viking://resources/# name size mode isDir uri-# .abstract.md 100 420 False viking://resources/.abstract.md+# .abstract.md 100 420 false viking://resources/.abstract.md```### JSON 模式(`--output json`)@@ -244,16 +279,16 @@ openviking -o json ls viking://resources/- 当 `--output=json` 时:紧凑 JSON 格式 + `{ok, result}` 包装,适用于脚本- 当 `--output=table` 时:对表格输出采取精简表示(如去除空列等)-**JSON 输出 - 成功**+JSON 输出 - 成功:```json{"ok": true, "result": ...}```-**JSON 输出 - 错误**+JSON 输出 - 错误:```json-{"ok": false, "error": {"code": "NOT_FOUND", "message": "Resource not found", "details": {}}}+{"ok": false, "error": {"code": "NOT_FOUND", "message": "...", "details": {}}}```### 特殊情况@@ -263,12 +298,14 @@ openviking -o json ls viking://resources/### 退出码-| 退出码 | 含义 |-|--------|------|-| 0 | 成功 |-| 1 | 一般错误 |-| 2 | 配置错误 |-| 3 | 连接错误 |+**注:退出码是 CLI(命令行工具)的返回码,不是 HTTP API 的状态码。**++| 退出码 | 说明 | 触发场景 |+|--------|------|----------|+| 0 | 成功 | 命令执行成功 |+| 1 | 一般错误 | 命令执行失败(如 API 调用失败、网络错误、找不到二进制文件等) |+| 2 | 配置错误 | 无法加载 `ovcli.conf` 配置文件、`--sudo` 需要 `root_api_key` 但未配置、`--sudo` 用于非管理员命令 |+| 3 | 连接错误 | 无法连接到服务器 |## 错误码@@ -292,41 +329,51 @@ openviking -o json ls viking://resources/| `EMBEDDING_FAILED` | 500 | Embedding 生成失败 || `VLM_FAILED` | 500 | VLM 调用失败 || `SESSION_EXPIRED` | 410 | 会话已过期 |+| `NOT_INITIALIZED` | - | 服务或组件未初始化(需要先调用 initialize()) |-## API 端点+----### 系统+## API 端点总览-| 方法 | 路径 | 说明 |-|------|------|------|-| GET | `/health` | 健康检查(无需认证) |-| GET | `/ready` | 就绪探针(无需认证) |-| GET | `/metrics` | Prometheus 指标导出 |-| GET | `/api/v1/system/status` | 系统状态 |-| POST | `/api/v1/system/wait` | 等待处理完成 |+以下是 OpenViking 提供的所有 HTTP API 端点,按功能模块分组:++### 系统端点-### 资源+| 方法 | 路径 | 说明 | 认证 |+|------|------|------|------|+| GET | `/health` | 健康检查 | 无需认证 |+| GET | `/ready` | 就绪探针(检查 AGFS、VectorDB、APIKeyManager) | 无需认证 |+| GET | `/metrics` | Prometheus 指标导出 | 可选 |+| GET | `/api/v1/system/status` | 系统状态 | 需要 |+| POST | `/api/v1/system/wait` | 等待处理完成 | 需要 |++### 资源端点| 方法 | 路径 | 说明 ||------|------|------|-| POST | `/api/v1/resources/temp_upload` | 裸 HTTP 导入资源 / pack 时上传本地文件 |-| POST | `/api/v1/resources` | 添加资源 |+| POST | `/api/v1/resources/temp_upload` | 临时文件上传(用于后续资源导入) |+| POST | `/api/v1/resources` | 添加资源(支持 URL 或 temp_file_id) || POST | `/api/v1/skills` | 添加技能 |-| POST | `/api/v1/pack/export` | 导出 .ovpack |-| POST | `/api/v1/pack/import` | 导入 .ovpack |-### 文件系统+### Pack 端点++| 方法 | 路径 | 说明 | 权限 |+|------|------|------|------|+| POST | `/api/v1/pack/export` | 导出 .ovpack 文件 | ROOT/ADMIN |+| POST | `/api/v1/pack/import` | 导入 .ovpack 文件 | ROOT/ADMIN |++### 文件系统端点| 方法 | 路径 | 说明 ||------|------|------|-| GET | `/api/v1/fs/ls` | 列出目录 |-| GET | `/api/v1/fs/tree` | 目录树 |-| GET | `/api/v1/fs/stat` | 资源状态 |+| GET | `/api/v1/fs/ls` | 列出目录内容 |+| GET | `/api/v1/fs/tree` | 获取目录树结构 |+| GET | `/api/v1/fs/stat` | 获取资源状态 || POST | `/api/v1/fs/mkdir` | 创建目录 || DELETE | `/api/v1/fs` | 删除资源 |-| POST | `/api/v1/fs/mv` | 移动资源 |+| POST | `/api/v1/fs/mv` | 移动/重命名资源 |-### 内容+### 内容端点| 方法 | 路径 | 说明 ||------|------|------|@@ -335,39 +382,39 @@ openviking -o json ls viking://resources/| GET | `/api/v1/content/overview` | 读取概览(L1) || GET | `/api/v1/content/download` | 下载原始文件字节流 || POST | `/api/v1/content/write` | 修改已有文件并自动刷新语义与向量 |-| POST | `/api/v1/content/reindex` | 重新构建已有内容的语义/向量索引 |+| POST | `/api/v1/content/reindex` | 重新构建语义/向量索引(已废弃,请使用 maintenance) |-### 搜索+### 搜索端点| 方法 | 路径 | 说明 ||------|------|------|-| POST | `/api/v1/search/find` | 语义搜索 |-| POST | `/api/v1/search/search` | 上下文感知搜索 |-| POST | `/api/v1/search/grep` | 模式搜索 |+| POST | `/api/v1/search/find` | 语义搜索(无会话上下文) |+| POST | `/api/v1/search/search` | 上下文感知搜索(支持会话) |+| POST | `/api/v1/search/grep` | 内容模式搜索 || POST | `/api/v1/search/glob` | 文件模式匹配 |-### 关联+### 关系端点(实验特性,可能在后续版本中改变)| 方法 | 路径 | 说明 ||------|------|------|-| GET | `/api/v1/relations` | 获取关联 |-| POST | `/api/v1/relations/link` | 创建链接 |-| DELETE | `/api/v1/relations/link` | 删除链接 |+| GET | `/api/v1/relations` | 获取资源关联 |+| POST | `/api/v1/relations/link` | 创建资源链接 |+| DELETE | `/api/v1/relations/link` | 删除资源链接 |-### 会话+### 会话端点| 方法 | 路径 | 说明 ||------|------|------|| POST | `/api/v1/sessions` | 创建会话 || GET | `/api/v1/sessions` | 列出会话 |-| GET | `/api/v1/sessions/{id}` | 获取会话 |-| GET | `/api/v1/sessions/{id}/context` | 获取组装后的会话上下文 |-| DELETE | `/api/v1/sessions/{id}` | 删除会话 |-| POST | `/api/v1/sessions/{id}/commit` | 提交会话 |-| POST | `/api/v1/sessions/{id}/extract` | 从会话提取记忆 |-| POST | `/api/v1/sessions/{id}/messages` | 添加消息 |-| POST | `/api/v1/sessions/{id}/used` | 记录实际使用的上下文 / 技能 |-| GET | `/api/v1/sessions/{id}/archives/{archive_id}` | 获取特定会话归档 |+| GET | `/api/v1/sessions/{session_id}` | 获取会话 |+| GET | `/api/v1/sessions/{session_id}/context` | 获取组装后的会话上下文 |+| GET | `/api/v1/sessions/{session_id}/archives/{archive_id}` | 获取特定会话归档 |+| DELETE | `/api/v1/sessions/{session_id}` | 删除会话 |+| POST | `/api/v1/sessions/{session_id}/commit` | 提交会话(归档并提取记忆) |+| POST | `/api/v1/sessions/{session_id}/extract` | 从会话提取记忆 |+| POST | `/api/v1/sessions/{session_id}/messages` | 添加消息 |+| POST | `/api/v1/sessions/{session_id}/used` | 记录实际使用的上下文 / 技能 |### 隐私配置@@ -381,25 +428,25 @@ openviking -o json ls viking://resources/| GET | `/api/v1/privacy-configs/{category}/{target_key}/versions/{version}` | 获取指定版本详情 || POST | `/api/v1/privacy-configs/{category}/{target_key}/activate` | 激活指定版本 |-### 任务+### 任务端点| 方法 | 路径 | 说明 ||------|------|------|-| GET | `/api/v1/tasks/{task_id}` | 获取后台任务状态 |-| GET | `/api/v1/tasks` | 列出后台任务 |+| GET | `/api/v1/tasks/{task_id}` | 获取单个后台任务状态 |+| GET | `/api/v1/tasks` | 列出后台任务(支持按类型、状态、资源过滤) |-### Observer+### 观测端点| 方法 | 路径 | 说明 ||------|------|------|-| GET | `/api/v1/observer/queue` | 队列状态 |+| GET | `/api/v1/observer/queue` | 队列系统状态 || GET | `/api/v1/observer/vikingdb` | VikingDB 状态 || GET | `/api/v1/observer/models` | 模型状态(VLM / embedding / rerank) || GET | `/api/v1/observer/lock` | 锁子系统状态 || GET | `/api/v1/observer/retrieval` | 检索子系统状态 |-| GET | `/api/v1/observer/system` | 系统状态 |+| GET | `/api/v1/observer/system` | 系统整体状态 |-### 调试+### 调试端点| 方法 | 路径 | 说明 ||------|------|------|@@ -407,27 +454,68 @@ openviking -o json ls viking://resources/| GET | `/api/v1/debug/vector/scroll` | 分页查看向量记录 || GET | `/api/v1/debug/vector/count` | 统计向量记录数量 |-### 管理员(多租户)+### 维护端点++| 方法 | 路径 | 说明 | 权限 |+|------|------|------|------|+| POST | `/api/v1/maintenance/reindex` | 重新索引内容(可选择重新生成摘要) | ROOT/ADMIN |++### 统计端点| 方法 | 路径 | 说明 ||------|------|------|-| POST | `/api/v1/admin/accounts` | 创建工作区 + 首个 admin(ROOT) |-| GET | `/api/v1/admin/accounts` | 列出工作区(ROOT) |-| DELETE | `/api/v1/admin/accounts/{account_id}` | 删除工作区(ROOT) |-| POST | `/api/v1/admin/accounts/{account_id}/users` | 注册用户(ROOT, ADMIN) |-| GET | `/api/v1/admin/accounts/{account_id}/users` | 列出用户(ROOT, ADMIN) |-| DELETE | `/api/v1/admin/accounts/{account_id}/users/{user_id}` | 移除用户(ROOT, ADMIN) |-| PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | 修改用户角色(ROOT) |-| POST | `/api/v1/admin/accounts/{account_id}/users/{user_id}/key` | 重新生成 User Key(ROOT, ADMIN) |--## 相关文档--- [资源管理](02-resources.md) - 资源管理 API-- [检索](06-retrieval.md) - 搜索 API-- [文件系统](03-filesystem.md) - 文件系统操作-- [会话管理](05-sessions.md) - 会话管理-- [技能](04-skills.md) - 技能管理-- [系统](07-system.md) - 系统和监控 API-- [隐私配置](10-privacy.md) - 隐私配置版本管理与切换-- [指标与 Metrics](09-metrics.md) - Prometheus 指标导出与抓取说明-- [管理员](08-admin.md) - 多租户管理 API+| GET | `/api/v1/stats/memories` | 获取记忆健康统计(支持按类别过滤) |+| GET | `/api/v1/stats/sessions/{session_id}` | 获取会话提取统计 |++### 管理员端点(多租户)++| 方法 | 路径 | 说明 | 权限 |+|------|------|------|------|+| POST | `/api/v1/admin/accounts` | 创建工作区 + 首个 admin | ROOT |+| GET | `/api/v1/admin/accounts` | 列出所有工作区 | ROOT |+| DELETE | `/api/v1/admin/accounts/{account_id}` | 删除工作区(级联清理数据) | ROOT |+| POST | `/api/v1/admin/accounts/{account_id}/users` | 注册用户 | ROOT/ADMIN |+| GET | `/api/v1/admin/accounts/{account_id}/users` | 列出用户 | ROOT/ADMIN |+| DELETE | `/api/v1/admin/accounts/{account_id}/users/{user_id}` | 移除用户 | ROOT/ADMIN |+| PUT | `/api/v1/admin/accounts/{account_id}/users/{user_id}/role` | 修改用户角色 | ROOT |+| POST | `/api/v1/admin/accounts/{account_id}/users/{user_id}/key` | 重新生成 User Key | ROOT/ADMIN |++### VikingBot 交互端点(可选)++VikingBot API 需要服务器启动时指定 `--with-bot` 选项:++| 方法 | 路径 | 说明 |+|------|------|------|+| GET | `/health` | Bot 健康检查(与系统 /health 复用) |+| POST | `/chat` | 发送消息给 Bot |+| POST | `/chat/stream` | Bot 流式响应 |++### WebDAV 端点++| 方法 | 路径 | 说明 |+|------|------|------|+| OPTIONS | `/webdav/resources`, `/webdav/resources/{path}` | WebDAV 选项查询 |+| PROPFIND | `/webdav/resources`, `/webdav/resources/{path}` | WebDAV 属性查询 |+| GET/HEAD | `/webdav/resources/{path}` | 读取文件 |+| PUT | `/webdav/resources/{path}` | 上传/创建文件(仅 UTF-8 文本) |+| DELETE | `/webdav/resources/{path}` | 删除文件/目录 |+| MKCOL | `/webdav/resources/{path}` | 创建目录 |+| MOVE | `/webdav/resources/{path}` | 移动/重命名资源 |++---++## 文档阅读计划++后续 API 文档按功能模块组织如下:++| 文档 | 内容 |+|------|------|+| [资源管理](02-resources.md) | 资源和技能的添加、导入、导出 |+| [文件系统](03-filesystem.md) | 目录操作、内容读写 |+| [技能](04-skills.md) | 技能管理 API |+| [会话管理](05-sessions.md) | 会话创建、消息管理、记忆提取 |+| [检索](06-retrieval.md) | 搜索、关联、上下文获取 |+| [系统](07-system.md) | 系统状态、监控、调试 API |+| [隐私配置](10-privacy.md) | 隐私配置版本管理与切换 |+| [指标与 Metrics](09-metrics.md) | Prometheus 指标导出与抓取说明 |+| [管理员](08-admin.md) | 多租户账号和用户管理 |diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.mdindex 566184714..a86c3da76 100644--- a/docs/zh/api/02-resources.md+++ b/docs/zh/api/02-resources.md@@ -1,912 +1,545 @@# 资源管理-资源是智能体可以引用的外部知识。本指南介绍如何添加、管理和检索资源。--## 支持的格式--| 格式 | 扩展名 | 处理方式 |-|------|--------|----------|-| PDF | `.pdf` | 文本和图像提取 |-| Markdown | `.md` | 原生支持 |-| HTML | `.html`, `.htm` | 清洗后文本提取 |-| 纯文本 | `.txt` | 直接导入 |-| JSON/YAML | `.json`, `.yaml`, `.yml` | 结构化解析 |-| 代码 | `.py`, `.js`, `.ts`, `.go`, `.java` 等 | 语法感知解析 |-| 图像 | `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp` | VLM 描述 |-| 视频 | `.mp4`, `.mov`, `.avi` | 帧提取 + VLM |-| 音频 | `.mp3`, `.wav`, `.m4a` | 语音转录 |-| 文档 | `.docx` | 文本提取 |-| 飞书/Lark | URL(`*.feishu.cn`、`*.larksuite.com`、`*.larkoffice.com`) | 云端文档解析(`lark-oapi`) |--## 处理流程--```-Input -> Parser -> TreeBuilder -> AGFS -> SemanticQueue -> Vector Index-```--1. **Parser**:根据文件类型提取内容-2. **TreeBuilder**:创建目录结构-3. **AGFS**:将文件存储到虚拟文件系统-4. **SemanticQueue**:异步生成 L0/L1-5. **Vector Index**:建立语义搜索索引+资源是智能体可以引用的外部知识。本模块提供资源的添加、导入/导出、临时文件上传等功能。++## 核心概念++### 资源类型++OpenViking 支持多种资源类型,按照功能分类如下:++文档类+| 类型 | 扩展名 | 说明 |+|------|--------|------|+| PDF | `.pdf` | 支持本地解析和 MinerU API 转换 |+| Markdown | `.md`, `.markdown`, `.mdown`, `.mkd` | 原生支持,会提取结构并分段存储 |+| HTML | `.html`, `.htm` | 清理导航/广告后提取内容,转换为 Markdown |+| Word | `.docx` | 提取文本、标题、表格并转换为 Markdown |+| 纯文本 | `.txt`, `.text` | 直接导入处理 |+| EPUB | `.epub` | 电子书格式,支持 ebooklib 或手动提取 |++表格类+| 类型 | 扩展名 | 说明 |+|------|--------|------|+| Excel | `.xlsx`, `.xls`, `.xlsm` | 支持新版和老版 Excel,按工作表转换为 Markdown 表格 |+| PowerPoint | `.pptx` | 按幻灯片提取内容,支持提取备注 |++代码类+| 类型 | 资源名 | 说明 |+|------|--------|------|+| 代码文件 | `*.py`, `*.js`, ... | 支持常见编程语言(Python, JavaScript, Go, Rust, Java 等) |+| Git 协议代码仓库 | `git://...` | Git URL, 本地目录, `.zip` 包,会自动过滤 `.git`, `node_modules` 等目录 |+| Git 代码托管平台 | `https://github.com/{org}/{repo}` | GitHub, GitLab, Bitbucket 等代码托管平台的 URL |+| Git 代码托管平台上的 raw 文件 | `https://github.com/{org}/{repo}/raw/{branch}/{path}` | GitHub, GitLab, Bitbucket 等代码托管平台的 raw 文件下载 URL |++媒体类+| 类型 | 资源名 | 说明 |+|------|--------|------|+| 图片 | `*.jpg`, `*.jpeg`, `*.png`, `*.gif` ... | 多种图片格式,通过 VLM 生成描述(实验特性) |+| 视频 | `*.mp4`, `*.avi`, `*.mov` ... | 提取关键帧后使用 VLM 分析(规划) |+| 音频 | `*.mp3`, `*.wav`, `*.m4a` ... | 进行语音转录处理(规划) |++云文档类+| 类型 | 说明 |+|------|------|+| 飞书/Lark | URL 方式,支持 docx, wiki, sheets, bitable,需要配置 FEISHU_APP_ID 和 FEISHU_APP_SECRET |++### 资源处理流程++资源添加经过以下处理阶段:++```+源输入 → 解析 → 资源树构建 → 持久化 → 语义处理+ ↓ ↓ ↓ ↓ ↓+URL/文件 Parser TreeBuilder AGFS Summarizer/Vector+```++#### 阶段 1:源解析 (Parse)+- 使用 `UnifiedResourceProcessor` 根据资源类型解析内容+- 支持多种格式:文档(PDF/Markdown/Word)、表格(Excel/PPT)、代码、媒体文件等+- 解析结果写入临时 VikingFS 目录+- 媒体文件通过 VLM(视觉语言模型)生成描述++#### 阶段 2:资源树构建 (TreeBuilder)+- `TreeBuilder.finalize_from_temp()` 扫描临时目录结构+- 构建资源树节点,处理 URI 冲突(自动重命名)+- 建立目录与资源的关联关系++#### 阶段 3:持久化存储 (Persist)+- 检查目标 URI 是否已存在+- 新资源:移动临时文件到正式 AGFS 位置+- 已存在资源:保留临时树用于后续差异比较+- 获取生命周期锁防止并发修改+- 清理临时目录++#### 阶段 4:语义处理 (Semantic Processing)+- **摘要生成**:`Summarizer` 生成 L0(摘要)和 L1(概述)+- **向量索引**:将内容向量化用于语义搜索+- 通过 `SemanticQueue` 异步处理,可通过 `wait=True` 等待完成++### 资源的增量更新++资源增量更新通过**监控任务 (Watch Task)** 机制实现:++#### 监控任务创建+- 调用 `add_resource` 时设置 `watch_interval > 0` (单位:分钟)创建监控任务+- 需指定 `to` 参数确定目标 URI+- `WatchManager` 负责任务持久化存储+- 支持多租户权限控制(ROOT/ADMIN/USER 权限分级)++#### 任务调度执行+- `WatchScheduler` 每 60 秒检查到期任务+- 默认并发控制,避免重复执行+- 到期任务自动重新调用 `add_resource` 处理+- 更新任务的最后执行时间和下次执行时间++#### 任务管理操作+- **创建**:`watch_interval > 0` 时创建新任务或重新激活已停用任务+- **更新**:对同一目标 URI 重新设置参数+- **取消**:对同一目标 URI 设置 `watch_interval <= 0` 时停用任务+- **查询**:通过任务 ID 或目标 URI 查询任务状态## API 参考-### add_resource()+### add_resource-向知识库添加资源。+向知识库添加资源,支持本地文件/目录、URL 等多种来源。-**参数**+#### 1. API 实现介绍-| 参数 | 类型 | 必填 | 默认值 | 说明 |-|------|------|------|--------|------|-| path | str | 是 | - | SDK/CLI 可传本地路径、目录路径或 URL;裸 HTTP 仅支持远端 URL |-| temp_file_id | str | 否 | None | `POST /api/v1/resources/temp_upload` 返回的上传 ID,用于裸 HTTP 导入本地文件 |-| to | str | 否 | None | 精确目标 Viking URI(必须在 `resources` 作用域内) |-| parent | str | 否 | None | 资源将被放入的父级 URI,不能与 `to` 同时使用 |-| reason | str | 否 | "" | 添加该资源的原因(可提升搜索相关性) |-| instruction | str | 否 | "" | 特殊处理指令 |-| wait | bool | 否 | False | 等待语义处理完成 |-| timeout | float | 否 | None | 超时时间(秒),仅在 wait=True 时生效 |-| watch_interval | float | 否 | 0 | 定时更新间隔(分钟)。>0 开启/更新定时任务;<=0 关闭(停用)定时任务。仅在指定 `to` 时生效 |+此接口是资源管理的核心入口,支持多种来源的资源添加,并可选择等待语义处理完成。-`POST /api/v1/resources` 的 JSON 字段名是 `to`;CLI 对应参数是 `--to`。+**处理流程**:+1. 识别资源来源(URL 或上传的临时文件)+2. 调用对应 Parser 解析内容+3. 构建目录树并写入 AGFS+4. 如指定 `--watch-interval`,设置定时更新任务+5. 如指定 `--wait=true`,等待语义处理完成-**本地文件和目录如何处理**+**代码入口**:+- `openviking/client/local.py:LocalClient.add_resource` - SDK 入口(嵌入式)+- `openviking_cli/client/http.py:AsyncHTTPClient.add_resource` - SDK 入口(HTTP)+- `openviking/server/routers/resources.py:add_resource` - HTTP 路由+- `openviking/service/resource_service.py` - 核心服务实现+- `crates/ov_cli/src/handlers.rs:handle_add_resource` - CLI 处理-- Python SDK 和 CLI 可以直接接收本地文件和目录路径。处于 HTTP 模式时,它们会先自动上传,再调用服务端 API。-- 裸 HTTP 调用可以按两类理解:- - 远端资源:直接传 `path`,例如 `https://example.com/doc.pdf`- - 本地文件:先调用 `POST /api/v1/resources/temp_upload`,再把返回的 `temp_file_id` 传给目标 API- - 本地目录:先自行打成 `.zip`,上传该压缩包,再把返回的 `temp_file_id` 传给目标 API-- `POST /api/v1/resources` 不接受 `./guide.md`、`/tmp/guide.md`、`/tmp/my-dir/` 这类宿主机本地路径。+#### 2. 接口和参数说明-**增量更新(Incremental Update)**--当你为同一个资源 URI 反复调用 `add_resource()` 时,系统会走“增量更新”而不是每次全量重建:--- **触发条件**:请求里显式指定 `to`,且该 `to` 在知识库中已存在。-- **总体思路**:每次导入都会先把新内容解析/构建成一棵“临时资源树”,随后在异步语义处理阶段,将临时树与 `to` 对应的现有资源树进行对比,只对发生变化的部分做重算与同步。-- **语义阶段的增量**:- - 对**未变化的文件**:复用已有 L0(摘要)与向量索引记录,跳过向量化。- - 对**发生变化的文件**:重新生成摘要/向量索引。- - 对**目录级 L0/L1(abstract/overview)**:若目录下子项及其变更状态不变,则复用已有结果并跳过向量化;否则重算并更新。-- **落盘与索引同步**:语义 DAG 结束后会对临时树与 `to` 做一次 top-down diff,同步三类变更:新增(添加新文件/目录)、删除(移除消失项)、更新(覆盖变化项)。同步过程中会同时联动更新向量库中的记录:删除项会删除对应向量记录;移动/覆盖会同步更新向量记录的 URI 映射,从而完成“文件树与向量索引的一致性增量更新”。--**Python SDK (Embedded / HTTP)**--```python-result = client.add_resource(- "./documents/guide.md",- reason="User guide documentation"-)-print(f"Added: {result['root_uri']}")+**参数**-client.wait_processed()-```+| 参数 | 类型 | 必填 | 默认值 | 说明 |+|------|------|------|--------|------|+| path | string | 否 | - | 远程资源 URL(HTTP/HTTPS/Git)。与 `temp_file_id` 二选一 |+| temp_file_id | string | 否 | - | 临时上传文件 ID。与 `path` 二选一 |+| to | string | 否 | - | 目标 Viking URI(精确位置)。与 `parent` 二选一 |+| parent | string | 否 | - | 父级 Viking URI(资源放入此目录下)。与 `to` 二选一 |+| reason | string | 否 | "" | 添加资源的原因(用于文档化和相关性提升,实验特性) |+| instruction | string | 否 | "" | 语义提取的处理指令(实验特性) |+| wait | bool | 否 | False | 是否等待语义处理和向量化完成才返回 |+| timeout | float | 否 | None | 超时时间(秒),仅 `wait=true` 时生效 |+| strict | bool | 否 | False | 是否使用严格模式 |+| ignore_dirs | string | 否 | None | 要忽略的目录名(逗号分隔) |+| include | string | 否 | None | 包含的文件模式(glob) |+| exclude | string | 否 | None | 排除的文件模式(glob) |+| directly_upload_media | bool | 否 | True | 是否直接上传媒体文件 |+| preserve_structure | bool | 否 | None | 是否保留目录结构 |+| watch_interval | float | 否 | 0 | 定时更新间隔(分钟)。>0 创建任务;≤0 取消任务,依赖 `to` 目标指定 |+| telemetry | TelemetryRequest | 否 | False | 是否返回遥测数据 |++**补充说明**:+- `to` 和 `parent` 都可用于指定目标路径,但不能同时使用;指定 `to` 且目标已存在时,触发增量更新。+- `path` 和 `temp_file_id` 不能同时指定,上传本地文件需要先通过 [temp_upload](#temp_upload) 上传获取 `temp_file_id`,在 SDK 和 CLI 中已经封装好。+- `watch_interval` 仅在指定 `to` 时生效++#### 3. 使用示例**HTTP API**```POST /api/v1/resources+Content-Type: application/json``````bash+# 从 URL 添加资源curl -X POST http://localhost:1933/api/v1/resources \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{"path": "https://example.com/guide.md",- "reason": "User guide documentation"- }'-```--**CLI**--```bash-openviking add-resource ./documents/guide.md --reason "User guide documentation"-```--**响应**--```json-{- "status": "ok",- "result": {- "status": "success",- "root_uri": "viking://resources/documents/guide.md",- "source_path": "./documents/guide.md",- "errors": []- },- "time": 0.1-}-```--**同步处理错误**--如果导入在生成资源前失败,裸 HTTP 会返回标准错误 envelope,并使用非 2xx HTTP 状态码。例如:--```json-{- "status": "error",- "error": {- "code": "PROCESSING_ERROR",- "message": "Parse error: [Errno 2] No such file or directory: 'git'"- }-}-```--`SyncHTTPClient`、`AsyncHTTPClient` 和 CLI 命令会把它作为错误抛出/展示,而不是返回-`result.status="error"` 的成功结果。--**示例:从 URL 添加**--**Python SDK (Embedded / HTTP)**--```python-result = client.add_resource(- "https://example.com/api-docs.md",- to="viking://resources/external/",- reason="External API documentation"-)-client.wait_processed()-```--**HTTP API**--```bash-curl -X POST http://localhost:1933/api/v1/resources \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "path": "https://example.com/api-docs.md",- "to": "viking://resources/external/",- "reason": "External API documentation",+ "reason": "User guide documentation","wait": true}'-```--**CLI**--```bash-openviking add-resource https://example.com/api-docs.md --to viking://resources/external/ --reason "External API documentation"-```--**示例:用裸 HTTP 添加本地文件**--如果你直接调用 HTTP API,本地文件要先上传,再使用 `temp_file_id`。-```bash-# 第一步:上传本地文件-TEMP_FILE_ID=$(- curl -sS -X POST http://localhost:1933/api/v1/resources/temp_upload \- -H "X-API-Key: your-key" \- -F 'file=@./documents/guide.md' \- | jq -r '.result.temp_file_id'-)--# 第二步:用 temp_file_id 添加资源-curl -X POST http://localhost:1933/api/v1/resources \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d "{- \"temp_file_id\": \"$TEMP_FILE_ID\",- \"reason\": \"User guide documentation\",- \"wait\": true- }"-```--**示例:用裸 HTTP 添加本地目录**--如果你直接调用 HTTP API,本地目录需要先自行打成 zip。CLI 和 SDK 会自动完成这一步。--```bash-# 第一步:先把本地目录打成 zip-cd ./documents-zip -r /tmp/guide.zip ./guide--# 第二步:上传 zip 文件+# 从本地文件添加(需先使用 temp_upload 上传)TEMP_FILE_ID=$(- curl -sS -X POST http://localhost:1933/api/v1/resources/temp_upload \+ curl -s -X POST http://localhost:1933/api/v1/resources/temp_upload \-H "X-API-Key: your-key" \- -F 'file=@/tmp/guide.zip' \+ -F "file=@./documents/guide.md" \| jq -r '.result.temp_file_id')-# 第三步:用上传后的目录压缩包添加资源curl -X POST http://localhost:1933/api/v1/resources \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d "{\"temp_file_id\": \"$TEMP_FILE_ID\",- \"reason\": \"Import local directory\",- \"wait\": true+ \"to\": \"viking://resources/guide.md\",+ \"reason\": \"User guide\"}"```-**示例:添加飞书/Lark 云端文档**+**Python SDK**-[飞书](https://www.feishu.cn)及其国际版 [Lark](https://www.larksuite.com) 是国内科技公司广泛使用的协作平台。OpenViking 可以通过 URL 直接导入飞书云端文档。--支持的文档类型:--| 类型 | URL 格式 |-|------|----------|-| 文档 | `https://*.feishu.cn/docx/{id}` |-| 知识库 | `https://*.feishu.cn/wiki/{token}` |-| 电子表格 | `https://*.feishu.cn/sheets/{token}` |-| 多维表格 | `https://*.feishu.cn/base/{token}` |+```python+import openviking as ov-> **前置配置**:安装可选依赖 `pip install 'openviking[bot-feishu]'`->-> 通过 `ov.conf` 配置凭据(详见[配置文档](../../zh/guides/01-configuration.md#feishu)),或设置环境变量:-> ```bash-> export FEISHU_APP_ID="cli_xxx"-> export FEISHU_APP_SECRET="xxx"-> ```+# 使用嵌入式模式(以后不再推荐和详细介绍)+client = ov.OpenViking(path="./data")+client.initialize()-**Python SDK (Embedded / HTTP)**+# 使用 HTTP 客户端模式+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()-```python-# 导入飞书文档+## 添加本地文件result = client.add_resource(- "https://example.feishu.cn/docx/doxcnABC123",- reason="项目设计文档"+ "./documents/guide.md",+ reason="User guide documentation")-client.wait_processed()--# 导入知识库页面(自动解析为底层文档类型)-client.add_resource("https://example.feishu.cn/wiki/wikiXYZ")--# 导入电子表格-client.add_resource("https://example.feishu.cn/sheets/shtcn456")-```--**CLI**--```bash-# 导入飞书文档-openviking add-resource "https://example.feishu.cn/docx/doxcnABC123" --reason "项目设计文档"--# 导入知识库页面-openviking add-resource "https://example.feishu.cn/wiki/wikiXYZ"--# 增量更新到已有 URI-openviking add-resource "https://example.feishu.cn/docx/doxcnABC123" --to viking://resources/design-doc-```--**示例:等待处理完成**--**Python SDK (Embedded / HTTP)**--```python-# 方式 1:内联等待-result = client.add_resource("./documents/guide.md", wait=True)-print(f"Queue status: {result['queue_status']}")--# 方式 2:单独等待(适用于批量处理)-client.add_resource("./file1.md")-client.add_resource("./file2.md")-client.add_resource("./file3.md")--status = client.wait_processed()-print(f"All processed: {status}")-```--**HTTP API**--```bash-# 内联等待-curl -X POST http://localhost:1933/api/v1/resources \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{"path": "https://example.com/guide.md", "wait": true}'--# 批量添加后单独等待-curl -X POST http://localhost:1933/api/v1/system/wait \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{}'-```--**CLI**--```bash-openviking add-resource ./documents/guide.md --wait-```--**示例:开启定时更新(watch_interval)**--`watch_interval` 的单位为分钟,用于对指定目标 URI 定期触发更新处理:--- `watch_interval > 0`:创建(或重新激活并更新)该 `to` 的定时任务-- `watch_interval <= 0`:关闭(停用)该 `to` 的定时任务-- 只有在指定 `to` / CLI `--to` 时才会创建定时任务+print(f"Added: {result['root_uri']}")-如果同一个 `to` 已存在激活中的定时任务,再次以 `watch_interval > 0` 提交会返回冲突错误;需要先将 `watch_interval` 设为 `0`(取消/停用)后再重新设置新的间隔。+## 从 URL 添加到指定位置+result = client.add_resource(+ "https://example.com/api-docs.md",+ to="viking://resources/external/api-docs.md",+ reason="External API docs"+)-**Python SDK (Embedded / HTTP)**+## 等待处理完成+client.wait_processed()-```python+## 开启定时更新client.add_resource("./documents/guide.md",- to="viking://resources/documents/guide.md",- watch_interval=60,+ to="viking://resources/guide.md",+ watch_interval=60 # 每60分钟更新一次)```-**HTTP API**--```bash-curl -X POST http://localhost:1933/api/v1/resources \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "path": "https://example.com/guide.md",- "to": "viking://resources/documents/guide.md",- "watch_interval": 60- }'-```-**CLI**```bash-openviking add-resource ./documents/guide.md --to viking://resources/documents/guide.md --watch-interval 60+# 添加本地文件+ov add-resource ./documents/guide.md --reason "User guide"-# 取消监控-openviking add-resource ./documents/guide.md --to viking://resources/documents/guide.md --watch-interval 0-```+# 从 URL 添加+ov add-resource https://example.com/guide.md --to viking://resources/guide.md------### export_ovpack()--将资源树导出为 `.ovpack` 文件。--**SDK / CLI 参数**--| 参数 | 类型 | 必填 | 默认值 | 说明 |-|------|------|------|--------|------|-| uri | str | 是 | - | 要导出的 Viking URI |-| to | str | 是 | - | 目标文件路径 |+# 等待处理完成+ov add-resource ./documents/guide.md --wait-**裸 HTTP 请求体**+# 开启定时更新(每60分钟检测一次)+ov add-resource https://github.com/example/repo.git --to viking://resources/my_repo --watch-interval 60-| 参数 | 类型 | 必填 | 默认值 | 说明 |-|------|------|------|--------|------|-| uri | str | 是 | - | 要导出的 Viking URI |--**Python SDK (Embedded / HTTP)**--```python-path = client.export_ovpack(- "viking://resources/my-project/",- "./exports/my-project.ovpack"-)-print(f"Exported to: {path}")+# 取消定时更新+ov add-resource https://github.com/example/repo.git --to viking://resources/my_repo --watch-interval 0```-**HTTP API**--```-POST /api/v1/pack/export-```--```bash-curl -X POST http://localhost:1933/api/v1/pack/export \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "uri": "viking://resources/my-project/"- }'-```--**CLI**--```bash-openviking export viking://resources/my-project/ ./exports/my-project.ovpack-```--**响应**--该 HTTP 接口会直接以下载流的形式返回 `.ovpack` 文件(`Content-Type: application/zip`),不会返回 JSON 包装体。-------### import_ovpack()--导入 `.ovpack` 文件。--**SDK / CLI 参数**--| 参数 | 类型 | 必填 | 默认值 | 说明 |-|------|------|------|--------|------|-| file_path | str | 是 | - | 本地 `.ovpack` 文件路径 |-| parent | str | 是 | - | 目标父级 URI |-| force | bool | 否 | False | 覆盖已有资源 |-| vectorize | bool | 否 | True | 导入后触发向量化 |--**裸 HTTP 请求体**--| 参数 | 类型 | 必填 | 默认值 | 说明 |-|------|------|------|--------|------|-| temp_file_id | str | 是 | - | `POST /api/v1/resources/temp_upload` 返回的上传 ID |-| parent | str | 是 | - | 目标父级 URI |-| force | bool | 否 | False | 覆盖已有资源 |-| vectorize | bool | 否 | True | 导入后触发向量化 |+#### 4. 响应示例-**Python SDK (Embedded / HTTP)**--```python-uri = client.import_ovpack(- "./exports/my-project.ovpack",- "viking://resources/imported/",- force=True,- vectorize=True-)-print(f"Imported to: {uri}")--client.wait_processed()-```--**HTTP API**--```-POST /api/v1/pack/import-```--```bash-# 第一步:上传本地 ovpack 文件-TEMP_FILE_ID=$(- curl -sS -X POST http://localhost:1933/api/v1/resources/temp_upload \- -H "X-API-Key: your-key" \- -F 'file=@./exports/my-project.ovpack' \- | jq -r '.result.temp_file_id'-)--# 第二步:使用 temp_file_id 导入-curl -X POST http://localhost:1933/api/v1/pack/import \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d "{- \"temp_file_id\": \"$TEMP_FILE_ID\",- \"parent\": \"viking://resources/imported/\",- \"force\": true,- \"vectorize\": true- }"-```--**CLI**--```bash-openviking import ./exports/my-project.ovpack viking://resources/imported/ --force-```--**响应**+**HTTP API 响应 (JSON)**```json{"status": "ok","result": {- "uri": "viking://resources/imported/my-project/"+ "status": "success",+ "root_uri": "viking://resources/guide.md",+ "temp_uri": "viking://temp/username/04291108_b62dc7/guide.md",+ "source_path": "./documents/guide.md",+ "meta": {},+ "errors": [],+ "queue_status": {+ "pending": 5,+ "processing": 2,+ "completed": 10+ }},- "time": 0.1+ "telemetry": {+ "operation_id": "550e8400-e29b-41d4-a716-446655440000"+ }}```------## 管理资源--### 列出资源--**Python SDK (Embedded / HTTP)**--```python-# 列出所有资源-entries = client.ls("viking://resources/")--# 列出详细信息-for entry in entries:- type_str = "dir" if entry['isDir'] else "file"- print(f"{entry['name']} - {type_str}")--# 简单路径列表-paths = client.ls("viking://resources/", simple=True)-# Returns: ["project-a/", "project-b/", "shared/"]--# 递归列出-all_entries = client.ls("viking://resources/", recursive=True)-```--**HTTP API**--```-GET /api/v1/fs/ls?uri={uri}&simple={bool}&recursive={bool}-```--```bash-# 列出所有资源-curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://resources/" \- -H "X-API-Key: your-key"--# 简单路径列表-curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://resources/&simple=true" \- -H "X-API-Key: your-key"+**CLI 响应 (默认表格格式)**-# 递归列出-curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://resources/&recursive=true" \- -H "X-API-Key: your-key"```--**CLI**--```bash-# 列出所有资源-openviking ls viking://resources/--# 简单路径列表-openviking ls viking://resources/ --simple--# 递归列出-openviking ls viking://resources/ --recursive+Note: Resource is being processed in the background.+Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.+status success+errors []+source_path /Users/bytedance/workspace/github.com/OpenViking/docs/en/api/01-overview.md+meta {}+root_uri viking://resources/01-overview+temp_uri viking://temp/shengmaojia/04291108_b62dc7/01-overview```-**响应**+**CLI 响应 (JSON 格式,使用 -o json)**```json{- "status": "ok",- "result": [- {- "name": "project-a",- "size": 4096,- "isDir": true,- "uri": "viking://resources/project-a/"- }- ],- "time": 0.1+ "status": "success",+ "root_uri": "viking://resources/01-overview",+ "temp_uri": "viking://temp/shengmaojia/04291108_b62dc7/01-overview",+ "source_path": "/Users/bytedance/workspace/github.com/OpenViking/docs/en/api/01-overview.md",+ "meta": {},+ "errors": []}```------### 读取资源内容+**字段说明**-**Python SDK (Embedded / HTTP)**+| 字段 | 类型 | 说明 |+|------|------|------|+| `status` | string | 处理状态:"success" 成功,"error" 失败 |+| `root_uri` | string | 资源在 OpenViking 中的最终 URI |+| `temp_uri` | string | 处理过程中的临时 URI(仅在后台处理阶段有效) |+| `source_path` | string | 原始源文件路径或 URL |+| `meta` | object | 资源解析过程中的元数据(如文件类型、大小等) |+| `errors` | array | 处理过程中的错误列表 |+| `warnings` | array | (可选)处理过程中的警告列表(仅在 `strict=False` 时可能出现) |+| `queue_status` | object | (可选,仅当 `wait=true` 时)队列处理状态,包含 `pending`、`processing`、`completed` 计数 |-```python-# L0:摘要-abstract = client.abstract("viking://resources/docs/")--# L1:概览-overview = client.overview("viking://resources/docs/")--# L2:完整内容-content = client.read("viking://resources/docs/api.md")-```--**HTTP API**+----```bash-# L0:摘要-curl -X GET "http://localhost:1933/api/v1/content/abstract?uri=viking://resources/docs/" \- -H "X-API-Key: your-key"+### add_skill-# L1:概览-curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://resources/docs/" \- -H "X-API-Key: your-key"+向知识库添加技能。-# L2:完整内容-curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://resources/docs/api.md" \- -H "X-API-Key: your-key"-```+#### 1. API 实现介绍-**CLI**+技能是一种特殊的资源,用于定义智能体可以执行的操作或工具。-```bash-# L0:摘要-openviking abstract viking://resources/docs/+**处理流程**:+1. 接收技能数据或上传的临时文件+2. 解析技能定义+3. 存储到技能目录+4. 如指定 `wait=true`,等待技能处理完成-# L1:概览-openviking overview viking://resources/docs/+**代码入口**:+- `openviking/client/local.py:LocalClient.add_skill` - SDK 入口(嵌入式)+- `openviking_cli/client/http.py:AsyncHTTPClient.add_skill` - SDK 入口(HTTP)+- `openviking/server/routers/resources.py:add_skill` - HTTP 路由+- `openviking/service/resource_service.py` - 核心服务实现+- `crates/ov_cli/src/handlers.rs:handle_add_skill` - CLI 处理-# L2:完整内容-openviking read viking://resources/docs/api.md-```+#### 2. 接口和参数说明-**响应**--```json-{- "status": "ok",- "result": "Documentation for the project API, covering authentication, endpoints...",- "time": 0.1-}-```-------### 移动资源+**参数**-**Python SDK (Embedded / HTTP)**+| 参数 | 类型 | 必填 | 默认值 | 说明 |+|------|------|------|--------|------|+| data | Any | 否 | - | 内联技能内容或结构化数据。与 `temp_file_id` 二选一 |+| temp_file_id | string | 否 | - | 临时上传文件 ID(通过 [temp_upload](#temp_upload) 获取)。与 `data` 二选一 |+| wait | bool | 否 | False | 是否等待技能处理完成 |+| timeout | float | 否 | None | 超时时间(秒),仅 `wait=true` 时生效 |+| telemetry | TelemetryRequest | 否 | False | 是否返回遥测数据 |-```python-client.mv(- "viking://resources/old-project/",- "viking://resources/new-project/"-)-```+#### 3. 使用示例**HTTP API**```-POST /api/v1/fs/mv+POST /api/v1/skills+Content-Type: application/json``````bash-curl -X POST http://localhost:1933/api/v1/fs/mv \+# 使用内联数据+curl -X POST http://localhost:1933/api/v1/skills \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{- "from_uri": "viking://resources/old-project/",- "to_uri": "viking://resources/new-project/"+ "data": {+ "name": "my-skill",+ "description": "My custom skill",+ "steps": []+ }}'-```--**CLI**--```bash-openviking mv viking://resources/old-project/ viking://resources/new-project/-```-**响应**+# 使用本地文件(需先使用 temp_upload 上传)+TEMP_FILE_ID=$(+ curl -s -X POST http://localhost:1933/api/v1/resources/temp_upload \+ -H "X-API-Key: your-key" \+ -F "file=@./skills/my-skill.json" \+ | jq -r '.result.temp_file_id'+)-```json-{- "status": "ok",- "result": {- "from": "viking://resources/old-project/",- "to": "viking://resources/new-project/"- },- "time": 0.1-}+curl -X POST http://localhost:1933/api/v1/skills \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d "{+ \"temp_file_id\": \"$TEMP_FILE_ID\"+ }"```------### 删除资源--**Python SDK (Embedded / HTTP)**+**Python SDK**```python-# 删除单个文件-client.rm("viking://resources/docs/old.md")--# 递归删除目录-client.rm("viking://resources/old-project/", recursive=True)-```--**HTTP API**+import openviking as ov-```-DELETE /api/v1/fs?uri={uri}&recursive={bool}-```+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()-```bash-# 删除单个文件-curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://resources/docs/old.md" \- -H "X-API-Key: your-key"+# 从本地文件添加技能+result = client.add_skill("./skills/my-skill.json")-# 递归删除目录-curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://resources/old-project/&recursive=true" \- -H "X-API-Key: your-key"+# 等待处理完成+client.wait_processed()```**CLI**```bash-# 删除单个文件-openviking rm viking://resources/docs/old.md+# 添加技能+ov add-skill ./skills/my-skill.json-# 递归删除目录-openviking rm viking://resources/old-project/ --recursive+# 等待处理完成+ov add-skill ./skills/my-skill.json --wait```-**响应**+#### 4. 响应示例++**HTTP API 响应 (JSON)**```json{"status": "ok","result": {- "uri": "viking://resources/docs/old.md"+ "status": "success",+ "root_uri": "viking://agent/skills/my-skill",+ "uri": "viking://agent/skills/my-skill",+ "name": "my-skill",+ "auxiliary_files": 2,+ "queue_status": {+ "pending": 0,+ "processing": 0,+ "completed": 1+ }},- "time": 0.1+ "telemetry": {+ "operation_id": "550e8400-e29b-41d4-a716-446655440000"+ }}```------### 创建链接--**Python SDK (Embedded / HTTP)**--```python-# 链接相关资源-client.link(- "viking://resources/docs/auth/",- "viking://resources/docs/security/",- reason="Security best practices for authentication"-)--# 多个链接-client.link(- "viking://resources/docs/api/",- [- "viking://resources/docs/auth/",- "viking://resources/docs/errors/"- ],- reason="Related documentation"-)-```--**HTTP API**+**CLI 响应 (默认表格格式)**```-POST /api/v1/relations/link+Note: Skill is being processed in the background.+Use 'ov wait' to wait for completion, or 'ov observer queue' to check status.+status success+root_uri viking://agent/skills/my-skill+uri viking://agent/skills/my-skill+name my-skill+auxiliary_files 2```-```bash-# 单个链接-curl -X POST http://localhost:1933/api/v1/relations/link \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "from_uri": "viking://resources/docs/auth/",- "to_uris": "viking://resources/docs/security/",- "reason": "Security best practices for authentication"- }'--# 多个链接-curl -X POST http://localhost:1933/api/v1/relations/link \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "from_uri": "viking://resources/docs/api/",- "to_uris": ["viking://resources/docs/auth/", "viking://resources/docs/errors/"],- "reason": "Related documentation"- }'-```--**CLI**--```bash-openviking link viking://resources/docs/auth/ viking://resources/docs/security/ --reason "Security best practices"-```--**响应**+**CLI 响应 (JSON 格式,使用 -o json)**```json{- "status": "ok",- "result": {- "from": "viking://resources/docs/auth/",- "to": "viking://resources/docs/security/"- },- "time": 0.1+ "status": "success",+ "root_uri": "viking://agent/skills/my-skill",+ "uri": "viking://agent/skills/my-skill",+ "name": "my-skill",+ "auxiliary_files": 2}```------### 获取关联--**Python SDK (Embedded / HTTP)**+**字段说明**-```python-relations = client.relations("viking://resources/docs/auth/")-for rel in relations:- print(f"{rel['uri']}: {rel['reason']}")-```+| 字段 | 类型 | 说明 |+|------|------|------|+| `status` | string | 处理状态:"success" 成功,"error" 失败 |+| `root_uri` | string | 技能在 OpenViking 中的最终 URI(同 `uri`) |+| `uri` | string | 技能在 OpenViking 中的最终 URI(同 `root_uri`) |+| `name` | string | 技能名称 |+| `auxiliary_files` | number | 技能附带的辅助文件数量 |+| `queue_status` | object | (可选,仅当 `wait=true` 时)队列处理状态,包含 `pending`、`processing`、`completed` 计数 |-**HTTP API**+----```-GET /api/v1/relations?uri={uri}-```+### temp_upload-```bash-curl -X GET "http://localhost:1933/api/v1/relations?uri=viking://resources/docs/auth/" \- -H "X-API-Key: your-key"-```+上传临时文件,用于后续通过 [add_resource](#add_resource) 或 [add_skill](#add_skill) 导入本地文件。-**CLI**+#### 1. API 实现介绍-```bash-openviking relations viking://resources/docs/auth/-```+此接口用于上传本地文件到服务器临时存储,返回 `temp_file_id` 供后续 API 使用。这是一个辅助接口,通常不直接调用,而是通过 SDK 或 CLI 自动使用。-**响应**+**处理流程**:+1. 接收上传的文件+2. 清理过期的临时文件+3. 保存到临时目录并记录原始文件名+4. 返回临时文件 ID-```json-{- "status": "ok",- "result": [- {"uri": "viking://resources/docs/security/", "reason": "Security best practices"},- {"uri": "viking://resources/docs/errors/", "reason": "Error handling"}- ],- "time": 0.1-}-```+**代码入口**:+- `openviking/server/routers/resources.py:temp_upload` - HTTP 路由+- `openviking/service/resource_service.py` - 服务实现----+#### 2. 接口和参数说明-### 删除链接+**参数**-**Python SDK (Embedded / HTTP)**+| 参数 | 类型 | 必填 | 默认值 | 说明 |+|------|------|------|--------|------|+| file | UploadFile | 是 | - | 上传的文件(multipart/form-data) |+| telemetry | bool | 否 | False | 是否返回遥测数据 |-```python-client.unlink(- "viking://resources/docs/auth/",- "viking://resources/docs/security/"-)-```+#### 3. 使用示例**HTTP API**```-DELETE /api/v1/relations/link+POST /api/v1/resources/temp_upload+Content-Type: multipart/form-data``````bash-curl -X DELETE http://localhost:1933/api/v1/relations/link \- -H "Content-Type: application/json" \+curl -X POST http://localhost:1933/api/v1/resources/temp_upload \-H "X-API-Key: your-key" \- -d '{- "from_uri": "viking://resources/docs/auth/",- "to_uri": "viking://resources/docs/security/"- }'+ -F "file=@./documents/guide.md"```+**Python SDK**++Python SDK 中的 `add_resource`、`add_skill` 等接口会自动处理本地文件上传,无需手动调用此接口。+**CLI**-```bash-openviking unlink viking://resources/docs/auth/ viking://resources/docs/security/-```+CLI 命令也会自动处理本地文件上传,无需手动调用此接口。-**响应**+**响应示例**```json{"status": "ok","result": {- "from": "viking://resources/docs/auth/",- "to": "viking://resources/docs/security/"+ "temp_file_id": "upload_abc123def456.md"},- "time": 0.1+ "telemetry": {+ "operation_id": "550e8400-e29b-41d4-a716-446655440000"+ }}```----## 最佳实践--### 按项目组织--```-viking://resources/-+-- project-a/-| +-- docs/-| +-- specs/-| +-- references/-+-- project-b/-| +-- ...-+-- shared/- +-- common-docs/-```-## 相关文档-- [检索](06-retrieval.md) - 搜索资源-- [文件系统](03-filesystem.md) - 文件系统操作-- [上下文类型](../concepts/02-context-types.md) - 资源概念+- [文件系统](03-filesystem.md) - 文件和目录操作+- [技能](04-skills.md) - 技能管理 API+- [检索](06-retrieval.md) - 搜索和上下文获取+- [ovpack 指南](../guides/09-ovpack.md) - ovpack 导入导出详细说明diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.mdindex ca81716b8..6dd230d34 100644--- a/docs/zh/api/03-filesystem.md+++ b/docs/zh/api/03-filesystem.md@@ -975,6 +975,182 @@ openviking unlink viking://resources/docs/auth/ viking://resources/docs/security---+### export_ovpack++将资源树导出为 `.ovpack` 文件。++#### 1. API 实现介绍++将指定 URI 下的所有资源打包成 `.ovpack` 格式文件,用于备份或迁移。需要 ROOT 或 ADMIN 权限。++**处理流程**:+1. 验证用户权限+2. 遍历指定 URI 下的资源+3. 打包成 zip 格式(.ovpack)+4. 以文件流形式返回++**代码入口**:+- `openviking/server/routers/pack.py:export_ovpack` - HTTP 路由+- `openviking/service/pack_service.py` - 核心服务实现+- `crates/ov_cli/src/handlers.rs:handle_export` - CLI 处理++#### 2. 接口和参数说明++**参数**++| 参数 | 类型 | 必填 | 默认值 | 说明 |+|------|------|------|--------|------|+| uri | string | 是 | - | 要导出的 Viking URI |++**权限要求**:ROOT 或 ADMIN++#### 3. 使用示例++**HTTP API**++```+POST /api/v1/pack/export+Content-Type: application/json+```++```bash+curl -X POST http://localhost:1933/api/v1/pack/export \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-admin-key" \+ -d '{+ "uri": "viking://resources/my-project/"+ }' \+ --output my-project.ovpack+```++**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-admin-key")+client.initialize()++# 导出到本地文件(HTTP SDK 会自动处理下载)+# 注意:导出功能主要通过 CLI 使用+```++**CLI**++```bash+# 导出资源+ov export viking://resources/my-project/ ./exports/my-project.ovpack+```++**响应示例**++此接口直接返回文件流(`Content-Type: application/zip`),不返回 JSON 包装体。++---++### import_ovpack++导入 `.ovpack` 文件。++#### 1. API 实现介绍++将 `.ovpack` 文件导入到指定位置,用于恢复或迁移数据。需要 ROOT 或 ADMIN 权限。++**处理流程**:+1. 验证用户权限+2. 解析上传的 `.ovpack` 文件+3. 导入资源到目标位置+4. 可选地触发向量化++**代码入口**:+- `openviking/server/routers/pack.py:import_ovpack` - HTTP 路由+- `openviking/service/pack_service.py` - 核心服务实现+- `crates/ov_cli/src/handlers.rs:handle_import` - CLI 处理++#### 2. 接口和参数说明++**参数**++| 参数 | 类型 | 必填 | 默认值 | 说明 |+|------|------|------|--------|------|+| temp_file_id | string | 是 | - | 临时上传文件 ID(通过 [temp_upload](02-resources.md#temp_upload) 获取) |+| parent | string | 是 | - | 目标父级 URI(导入到此处) |+| force | bool | 否 | False | 是否覆盖已有资源 |+| vectorize | bool | 否 | True | 是否触发向量化 |++**权限要求**:ROOT 或 ADMIN++#### 3. 使用示例++**HTTP API**++```+POST /api/v1/pack/import+Content-Type: application/json+```++```bash+# 第一步:上传 .ovpack 文件+TEMP_FILE_ID=$(+ curl -s -X POST http://localhost:1933/api/v1/resources/temp_upload \+ -H "X-API-Key: your-admin-key" \+ -F "file=@./exports/my-project.ovpack" \+ | jq -r '.result.temp_file_id'+)++# 第二步:导入+curl -X POST http://localhost:1933/api/v1/pack/import \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-admin-key" \+ -d "{+ \"temp_file_id\": \"$TEMP_FILE_ID\",+ \"parent\": \"viking://resources/imported/\",+ \"force\": true,+ \"vectorize\": true+ }"+```++**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-admin-key")+client.initialize()++# 导入 .ovpack 文件(HTTP SDK 会自动处理上传)+# 注意:导入功能主要通过 CLI 使用+```++**CLI**++```bash+# 导入 .ovpack 文件+ov import ./exports/my-project.ovpack viking://resources/imported/++# 强制覆盖已有内容+ov import ./exports/my-project.ovpack viking://resources/imported/ --force++# 不进行向量化+ov import ./exports/my-project.ovpack viking://resources/imported/ --no-vectorize+```++**响应示例**++```json+{+ "status": "ok",+ "result": {+ "uri": "viking://resources/imported/my-project/"+ },+ "telemetry": {+ "operation_id": "550e8400-e29b-41d4-a716-446655440000"+ }+}+```++---+## 相关文档- [Viking URI](../concepts/04-viking-uri.md) - URI 规范diff --git a/docs/zh/api/99-api-doc-writing-guide.md b/docs/zh/api/99-api-doc-writing-guide.mdnew file mode 100644index 000000000..6b3ffdf6c--- /dev/null+++ b/docs/zh/api/99-api-doc-writing-guide.md@@ -0,0 +1,236 @@+# API 文档编写说明++本文档定义 `docs/zh/api/` 目录下各 API 模块文档的统一结构和编写规范。++## 目录结构++API 文档按模块组织,每个模块一个文件,使用两位数字序号前缀。++## 文件统一结构++每个 API 模块文档应遵循以下结构:++```markdown+# <模块名称>++<简短介绍,说明本模块的主要功能和用途>++## <可选的概念/介绍章节>++(如需要,介绍本模块涉及的核心概念、工作流程等)++## API 参考++### <API 方法名 1>++#### 1. API 实现介绍++<介绍该 API 的用途,指向对应的代码入口,简单介绍原理和流程>++**代码入口**:+- `openviking/<模块>/<文件>.py:<类名>.<方法名>` - 核心实现+- `openviking/server/routers/<路由文件>.py` - HTTP 路由+- `openviking_cli/commands/<命令文件>.py` - CLI 命令++#### 2. 接口和参数说明++**参数**++| 参数 | 类型 | 必填 | 默认值 | 说明 |+|------|------|------|--------|------|+| <参数名> | <类型> | <是/否> | <默认值> | <详细说明> |+| ... | ... | ... | ... | ... |++**<可选的补充说明章节>**++(如需要,说明特殊行为、注意事项、使用场景等)++#### 3. 使用示例++**HTTP API**++```+<HTTP 方法> <路径>+```++```bash+<curl 示例>+```++**Python SDK**++```python+<SDK 调用示例>+```++**CLI**++```bash+<CLI 命令示例>+```++**响应示例**++```json+<JSON 响应示例>+```++#### 4. 响应示例、错误和异常处理等(可选)++---++### <API 方法名 2>++(重复上述结构)++---++## <可选的其他章节>++## 相关文档++- [<文档标题>](<相对路径>) - <简短说明>+```++## 结构详解++### 标题与简介++- 一级标题是模块名称+- 简介用一段话说明该模块的用途和主要功能++### API 参考章节++每个接口按以下三个部分组织:++#### 1. API 实现介绍++- 说明该 API 的用途+- 提供代码入口路径,方便读者查阅源码+- 简单介绍实现原理和处理流程++**代码入口说明**:+- 核心实现:指向主要业务逻辑代码+- HTTP 路由:指向 FastAPI 路由定义+- CLI 命令:指向 CLI 命令实现(如有)++#### 2. 接口和参数说明++- 参数表:包含参数名、类型、是否必填、默认值、说明+- 补充说明(可选):特殊行为、注意事项、使用场景等++#### 3. 使用示例++按顺序提供:+- HTTP API(方法 + 路径 + curl 示例)+- Python SDK 示例+- CLI 示例+- 响应示例++## 示例:完整接口文档++```markdown+### add_resource()++#### 1. API 实现介绍++向知识库添加资源,支持本地文件、目录、URL 等多种来源。++**处理流程**:+1. 识别资源类型(本地文件/目录/URL)+2. 调用对应 Parser 解析内容+3. 构建目录树并写入 AGFS+4. 异步生成 L0/L1 语义摘要+5. 建立向量索引++**代码入口**:+- `openviking/core/client.py:OpenViking.add_resource()` - SDK 入口+- `openviking/resource/importer.py:ResourceImporter.import_resource()` - 核心实现+- `openviking/server/routers/resources.py` - HTTP 路由+- `openviking_cli/commands/resources.py` - CLI 命令++#### 2. 接口和参数说明++**参数**++| 参数 | 类型 | 必填 | 默认值 | 说明 |+|------|------|------|--------|------|+| path | str | 是 | - | 本地路径、目录路径或 URL |+| to | str | 否 | None | 目标 Viking URI(必须在 resources 作用域内) |+| reason | str | 否 | "" | 添加该资源的原因 |+| wait | bool | 否 | False | 是否等待语义处理完成 |++**说明**++- SDK/CLI 可直接传本地路径;裸 HTTP 需要先用 `temp_upload` 上传+- 当指定 `to` 且目标已存在时,走增量更新流程++#### 3. 使用示例++**HTTP API**++```+POST /api/v1/resources+```++```bash+curl -X POST http://localhost:1933/api/v1/resources \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "path": "https://example.com/guide.md",+ "reason": "User guide documentation",+ "wait": true+ }'+```++**Python SDK**++```python+import openviking as ov++client = ov.OpenViking(path="./data")+client.initialize()++result = client.add_resource(+ "./documents/guide.md",+ reason="User guide documentation"+)+print(f"Added: {result['root_uri']}")++client.wait_processed()+```++**CLI**++```bash+openviking add-resource ./documents/guide.md --reason "User guide documentation" --wait+```++**响应示例**++```json+{+ "status": "ok",+ "result": {+ "status": "success",+ "root_uri": "viking://resources/documents/guide.md",+ "source_path": "./documents/guide.md",+ "errors": []+ },+ "time": 0.123+}+```++---+```++## 文档维护清单++新增或修改 API 文档时,请检查:++- [ ] 实现介绍清晰,代码入口路径正确+- [ ] 参数表完整且准确+- [ ] 示例代码简洁且可运行+- [ ] HTTP 方法和路径正确+- [ ] 响应示例与实际返回一致