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 04-08 (#1802)
MaojiaShengfd71f677ccd6
diff --git a/docs/en/api/04-skills.md b/docs/en/api/04-skills.mdindex 08165a079..8f66fdaef 100644--- a/docs/en/api/04-skills.md+++ b/docs/en/api/04-skills.md@@ -1,101 +1,205 @@# Skills-Skills are callable capabilities that agents can invoke. This guide covers how to add and manage skills.+Skills are callable capabilities that agents can invoke. This module provides skill addition and management functionality.-## API Reference+## Core Concepts-### add_skill()+### Skill Types-Add a skill to the knowledge base.+OpenViking supports multiple skill definition formats:-**Parameters**+1. **Structured skill data**: Dictionary with name, description, content, etc.+2. **SKILL.md files**: Markdown files with YAML frontmatter+3. **MCP Tool format**: Automatically detected and converted to OpenViking skill format-| Parameter | Type | Required | Default | Description |-|-----------|------|----------|---------|-------------|-| data | Any | Yes | - | Skill data. Raw HTTP accepts structured data or raw `SKILL.md` content, not direct host paths |-| temp_file_id | str | No | None | Upload ID returned by `POST /api/v1/resources/temp_upload` for raw HTTP local file ingestion |-| wait | bool | No | False | Wait for vectorization to complete |-| timeout | float | No | None | Timeout in seconds |+### Skill Storage Structure-**How local skill files work**+Skills are stored at `viking://agent/skills/`:-- Python SDK and CLI accept local `SKILL.md` files or directories directly. In HTTP mode they automatically upload local files before calling the server API.-- Raw HTTP callers should either:- - send structured skill data directly in `data`- - send raw `SKILL.md` content in `data`- - upload a local `SKILL.md` file first with `POST /api/v1/resources/temp_upload`, then call `POST /api/v1/skills` with `temp_file_id`- - zip a local skill directory first, upload the `.zip` file, then call `POST /api/v1/skills` with `temp_file_id`-- `POST /api/v1/skills` does not accept direct host filesystem paths in `data`.+```+viking://agent/skills/++-- search-web/+| +-- .abstract.md # L0: Brief description+| +-- .overview.md # L1: Parameters and usage overview+| +-- SKILL.md # L2: Full documentation+| +-- [auxiliary files] # Any additional files++-- calculator/+| +-- .abstract.md+| +-- .overview.md+| +-- SKILL.md++-- ...+```-**Supported Data Formats**+### SKILL.md Format-1. **Dict (Skill format)**:-```python-{- "name": "skill-name",- "description": "Skill description",- "content": "Full markdown content",- "allowed_tools": ["Tool1", "Tool2"], # optional- "tags": ["tag1", "tag2"] # optional-}+Skills can be defined using SKILL.md files with YAML frontmatter:++```markdown+---+name: skill-name+description: Brief description of the skill+allowed_tools:+ - Tool1+ - Tool2+tags:+ - tag1+ - tag2+---++# Skill Name++Full skill documentation in Markdown format.++## Parameters+- **param1** (type, required): Description+- **param2** (type, optional): Description++## Usage+When and how to use this skill.++## Examples+Concrete examples of skill invocation.```-2. **Dict (MCP Tool format)** - Auto-detected and converted:+**Required Fields**++| Field | Type | Description |+|-------|------|-------------|+| name | str | Skill name (kebab-case recommended) |+| description | str | Brief description |++**Optional Fields**++| Field | Type | Description |+|-------|------|-------------|+| allowed_tools | List[str] | Tools this skill can use |+| tags | List[str] | Tags for categorization |++### MCP Format Automatic Conversion++OpenViking automatically detects and converts MCP tool definitions to skill format.++**Detection Rule**: A dictionary is treated as MCP format if it contains an `inputSchema` field.++**Conversion Process**:+1. Name is converted to kebab-case+2. Description is preserved+3. Parameters are extracted from `inputSchema.properties`+4. Required fields are marked from `inputSchema.required`+5. Markdown content is generated++**Conversion Example**:++Input (MCP format):```python{- "name": "tool_name",- "description": "Tool description",+ "name": "search_web",+ "description": "Search the web","inputSchema": {"type": "object",- "properties": {...},- "required": [...]+ "properties": {+ "query": {+ "type": "string",+ "description": "Search query"+ },+ "limit": {+ "type": "integer",+ "description": "Max results"+ }+ },+ "required": ["query"]}}```-3. **String (SKILL.md content)**:+Output (Skill format):```python-"""----name: skill-name-description: Skill description+{+ "name": "search-web",+ "description": "Search the web",+ "content": """---+name: search-web+description: Search the web----# Skill Content-"""-```+# search-web-4. **Path (file or directory)**:- - Single file: Path to `SKILL.md` file- - Directory: Path to directory containing `SKILL.md` (auxiliary files included)+Search the web-**Python SDK (Embedded / HTTP)**+## Parameters-```python-skill = {- "name": "search-web",- "description": "Search the web for current information",- "content": """-# search-web+- **query** (string) (required): Search query+- **limit** (integer) (optional): Max results-Search the web for current information.+## Usage-## Parameters-- **query** (string, required): Search query-- **limit** (integer, optional): Max results, default 10+This tool wraps the MCP tool `search-web`. Call this when the user needs functionality matching the description above."""}--result = client.add_skill(skill)-print(f"Added: {result['root_uri']}")```+## API Reference++### add_skill++Add a skill to the knowledge base.++#### 1. API Implementation Overview++Skills are a special type of resource that define actions or tools agents can perform.++**Processing Flow**:+1. Receive skill data or uploaded temporary file+2. Detect data format (structured data, SKILL.md content, MCP format)+3. Parse skill definition+4. Store to `viking://agent/skills/` path+5. If `wait=true`, wait for vectorization to complete++**Code Entry Points**:+- `openviking/client/local.py:LocalClient.add_skill` - SDK entry point (embedded)+- `openviking_cli/client/http.py:AsyncHTTPClient.add_skill` - SDK entry point (HTTP)+- `openviking/server/routers/resources.py:add_skill` - HTTP router+- `openviking/service/resource_service.py:ResourceService.add_skill` - Core service implementation+- `crates/ov_cli/src/handlers.rs:handle_add_skill` - CLI handler++#### 2. Interface and Parameters++**Parameters**++| Parameter | Type | Required | Default | Description |+|-----------|------|----------|---------|-------------|+| data | Any | No | - | Inline skill content or structured data. Mutually exclusive with `temp_file_id` |+| temp_file_id | str | No | - | Temporary upload file ID (from `temp_upload`). Mutually exclusive with `data` |+| wait | bool | No | False | 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 |++**Additional Notes**:+- **Local file handling**:+ - Python SDK and CLI accept local `SKILL.md` files or directories directly. In HTTP mode they automatically upload before calling the server API.+ - Raw HTTP callers should either:+ - Send structured skill data directly in `data`+ - Send raw `SKILL.md` content in `data`+ - First call `POST /api/v1/resources/temp_upload` to upload a local `SKILL.md` file/zip directory, then call `POST /api/v1/skills` with `temp_file_id`+ - `POST /api/v1/skills` does not accept direct host filesystem paths in `data`.++- **Supported data formats**:+ 1. **Dict (Skill format)**: Includes `name`, `description`, `content`, etc.+ 2. **Dict (MCP Tool format)**: Includes `name`, `description`, `inputSchema`, auto-detected and converted+ 3. **String (SKILL.md content)**: Complete SKILL.md content+ 4. **Path (file or directory)**: Path to `SKILL.md` file, or directory containing `SKILL.md` (auxiliary files included)++#### 3. Usage Examples+**HTTP API**```POST /api/v1/skills+Content-Type: application/json``````bash+# Using inline structured datacurl -X POST http://localhost:1933/api/v1/skills \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \@@ -104,77 +208,19 @@ curl -X POST http://localhost:1933/api/v1/skills \"name": "search-web","description": "Search the web for current information","content": "# search-web\n\nSearch the web for current information.\n\n## Parameters\n- **query** (string, required): Search query\n- **limit** (integer, optional): Max results, default 10"- }+ },+ "wait": true}'-```--**CLI**--```bash-openviking add-skill ./my-skill/ [--wait]-```--**Response**--```json-{- "status": "ok",- "result": {- "status": "success",- "root_uri": "viking://agent/skills/search-web/",- "uri": "viking://agent/skills/search-web/",- "name": "search-web",- "auxiliary_files": 0- },- "time": 0.1-}-```-**Synchronous Processing Error**--If skill parsing or processing fails synchronously, raw HTTP returns the standard error-envelope with a non-2xx HTTP status:--```json-{- "status": "error",- "error": {- "code": "PROCESSING_ERROR",- "message": "Skill parse error: invalid skill metadata"- }-}-```--The Python HTTP SDKs raise the mapped exception for this response.--**Example: Add from MCP Tool**--**Python SDK (Embedded / HTTP)**--```python-# MCP tool format is auto-detected and converted-mcp_tool = {- "name": "calculator",- "description": "Perform mathematical calculations",- "inputSchema": {- "type": "object",- "properties": {- "expression": {- "type": "string",- "description": "Mathematical expression to evaluate"- }- },- "required": ["expression"]- }-}--result = client.add_skill(mcp_tool)-print(f"Added: {result['uri']}")-```--**HTTP API**+# Using inline SKILL.md content+curl -X POST http://localhost:1933/api/v1/skills \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "data": "---\nname: my-skill\ndescription: My custom skill\n---\n\n# My Skill\n\nSkill content here."+ }'-```bash+# Using MCP Tool format (auto-detected and convertedcurl -X POST http://localhost:1933/api/v1/skills \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \@@ -194,35 +240,15 @@ curl -X POST http://localhost:1933/api/v1/skills \}}}'-```--**Example: Add from SKILL.md File**--**Python SDK (Embedded / HTTP)**--```python-# Add from file path-result = client.add_skill("./skills/search-web/SKILL.md")-print(f"Added: {result['uri']}")-# Add from directory (includes auxiliary files)-result = client.add_skill("./skills/code-runner/")-print(f"Added: {result['uri']}")-print(f"Auxiliary files: {result['auxiliary_files']}")-```--**HTTP API**--```bash-# Step 1: upload the local SKILL.md file+# Using local file (first use 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=@./skills/search-web/SKILL.md' \+ -F "file=@./skills/my-skill.json" \| jq -r '.result.temp_file_id')-# Step 2: add the uploaded skillcurl -X POST http://localhost:1933/api/v1/skills \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \@@ -231,64 +257,158 @@ curl -X POST http://localhost:1933/api/v1/skills \}"```-For a local skill directory, zip the directory first, upload the `.zip` file, then call the same `POST /api/v1/skills` request with the returned `temp_file_id`.+**Python SDK**----+```python+import openviking as ov-## SKILL.md Format+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()-Skills can be defined using SKILL.md files with YAML frontmatter.+# Approach 1: Using structured skill data+skill = {+ "name": "search-web",+ "description": "Search the web for current information",+ "content": """# search-web-**Structure**+Search the web for current information.-```markdown-----name: skill-name-description: Brief description of the skill-allowed-tools:- - Tool1- - Tool2-tags:- - tag1- - tag2----+## Parameters+- **query** (string, required): Search query+- **limit** (integer, optional): Max results, default 10+"""+}+result = client.add_skill(skill)+print(f"Added: {result['root_uri']}")-# Skill Name+# Approach 2: Using MCP Tool format (auto-detected and converted+mcp_tool = {+ "name": "calculator",+ "description": "Perform mathematical calculations",+ "inputSchema": {+ "type": "object",+ "properties": {+ "expression": {+ "type": "string",+ "description": "Mathematical expression to evaluate"+ }+ },+ "required": ["expression"]+ }+}+result = client.add_skill(mcp_tool)+print(f"Added: {result['uri']}")-Full skill documentation in Markdown format.+# Approach 3: Add from local SKILL.md file+result = client.add_skill("./skills/search-web/SKILL.md")+print(f"Added: {result['uri']}")-## Parameters-- **param1** (type, required): Description-- **param2** (type, optional): Description+# Approach 4: Add from directory containing SKILL.md (auxiliary files included+result = client.add_skill("./skills/code-runner/")+print(f"Added: {result['uri']}")+print(f"Auxiliary files: {result['auxiliary_files']}")-## Usage-When and how to use this skill.+# Wait for processing completion+result = client.add_skill("./skills/my-skill/", wait=True)+client.wait_processed()+```-## Examples-Concrete examples of skill invocation.+**CLI**++```bash+# Add skill (from file or directory+ov add-skill ./skills/my-skill.json+ov add-skill ./skills/search-web/SKILL.md+ov add-skill ./skills/code-runner/++# Wait for processing completion+ov add-skill ./skills/my-skill/ --wait++# Use JSON output format+ov add-skill ./skills/my-skill/ -o json```-**Required Fields**+**Response Examples**-| Field | Type | Description |-|-------|------|-------------|-| name | str | Skill name (kebab-case recommended) |-| description | str | Brief description |+**HTTP API response (JSON)**:+```json+{+ "status": "ok",+ "result": {+ "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+ }+ },+ "telemetry": {+ "operation_id": "550e8400-e29b-41d4-a716-446655440000"+ },+ "time": 0.1+}+```-**Optional Fields**+**CLI response (default table format)**:+```+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+```++**CLI response (JSON format, using -o json)**:+```json+{+ "status": "success",+ "root_uri": "viking://agent/skills/my-skill",+ "uri": "viking://agent/skills/my-skill",+ "name": "my-skill",+ "auxiliary_files": 2+}+```++**Field Description**:| Field | Type | Description ||-------|------|-------------|-| allowed-tools | List[str] | Tools this skill can use |-| tags | List[str] | Tags for categorization |+| `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 included with the skill |+| `queue_status` | object | (Optional, only when `wait=true`) Queue processing status with `pending`, `processing`, `completed` counts |----+#### 4. Error Handling++**Synchronous Processing Errors**:-## Managing Skills+If skill parsing or processing fails synchronously, raw HTTP returns the standard error envelope with a non-2xx HTTP status code:++```json+{+ "status": "error",+ "error": {+ "code": "PROCESSING_ERROR",+ "message": "Skill parse error: invalid skill metadata"+ }+}+```++The Python HTTP SDK raises the corresponding mapped exception for this response.++## Skill Management Operations### List Skills-**Python SDK (Embedded / HTTP)**+**Python SDK**```python# List all skills@@ -296,7 +416,7 @@ skills = client.ls("viking://agent/skills/")for skill in skills:print(f"{skill['name']}")-# Simple list (names only)+# Simple list (names onlynames = client.ls("viking://agent/skills/", simple=True)print(names)```@@ -310,7 +430,7 @@ curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://agent/skills/" \### Read Skill Content-**Python SDK (Embedded / HTTP)**+**Python SDK**```pythonuri = "viking://agent/skills/search-web/"@@ -346,7 +466,7 @@ curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://agent/skills### Search Skills-**Python SDK (Embedded / HTTP)**+**Python SDK**```python# Semantic search for skills@@ -375,9 +495,9 @@ curl -X POST http://localhost:1933/api/v1/search/find \}'```-### Remove Skills+### Delete Skills-**Python SDK (Embedded / HTTP)**+**Python SDK**```pythonclient.rm("viking://agent/skills/old-skill/", recursive=True)@@ -390,102 +510,6 @@ curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://agent/skills/old-sk-H "X-API-Key: your-key"```------## MCP Conversion--OpenViking automatically detects and converts MCP tool definitions to skill format.--**Detection**--A dict is treated as MCP format if it contains an `inputSchema` field:--```python-if "inputSchema" in data:- # Convert to skill format- skill = mcp_to_skill(data)-```--**Conversion Process**--1. Name is converted to kebab-case-2. Description is preserved-3. Parameters are extracted from `inputSchema.properties`-4. Required fields are marked from `inputSchema.required`-5. Markdown content is generated--**Example Conversion**--Input (MCP format):-```python-{- "name": "search_web",- "description": "Search the web",- "inputSchema": {- "type": "object",- "properties": {- "query": {- "type": "string",- "description": "Search query"- },- "limit": {- "type": "integer",- "description": "Max results"- }- },- "required": ["query"]- }-}-```--Output (Skill format):-```python-{- "name": "search-web",- "description": "Search the web",- "content": """----name: search-web-description: Search the web------# search-web--Search the web--## Parameters--- **query** (string) (required): Search query-- **limit** (integer) (optional): Max results--## Usage--This tool wraps the MCP tool `search-web`. Call this when the user needs functionality matching the description above.-"""-}-```-------## Skill Storage Structure--Skills are stored at `viking://agent/skills/`:--```-viking://agent/skills/-+-- search-web/-| +-- .abstract.md # L0: Brief description-| +-- .overview.md # L1: Parameters and usage-| +-- SKILL.md # L2: Full documentation-| +-- [auxiliary files] # Any additional files-+-- calculator/-| +-- .abstract.md-| +-- .overview.md-| +-- SKILL.md-+-- ...-```------## Best Practices### Clear Descriptions@@ -517,14 +541,14 @@ Include in your skill content:### Consistent NamingUse kebab-case for skill names:-- `search-web` (good)+- `search-web` (recommended)- `searchWeb` (avoid)- `search_web` (avoid)-----## Related Documentation+- [Resource Management](02-resources.md) - Resource addition and management+- [File System](03-filesystem.md) - File and directory operations- [Context Types](../concepts/02-context-types.md) - Skill concept- [Retrieval](06-retrieval.md) - Finding skills- [Sessions](05-sessions.md) - Tracking skill usagediff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.mdindex 101e61866..4188b8aa0 100644--- a/docs/en/api/05-sessions.md+++ b/docs/en/api/05-sessions.md@@ -1,12 +1,31 @@# Sessions-Sessions manage conversation state, track context usage, and extract long-term memories.+Sessions manage conversation state, track context usage, and extract long-term memories. Sessions use tiered storage (L0/L1/L2) to optimize token usage:+- L0 (abstract): Session overview summary+- L1 (overview): Key decisions+- L2 (messages): Complete messages## API Reference### create_session()-Create a new session.+#### 1. API Implementation Introduction++Create a new session. Sessions are containers for conversations, storing messages, tracking context usage, and supporting commits for long-term memory extraction.++**Processing Flow:**+1. Generate or use provided session_id+2. Initialize session metadata (creation time, user info, etc.)+3. Create session directory structure in storage+4. Return session info++**Code Entries:**+- `openviking/session/session.py:Session.__init__()` - Core Session class+- `openviking/server/routers/sessions.py:create_session()` - HTTP route+- `openviking_cli/client/base.py:BaseClient.create_session()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:new_session()` - CLI command++#### 2. Interface and Parameter Description**Parameters**@@ -14,21 +33,11 @@ Create a new session.|-----------|------|----------|---------|-------------|| session_id | str | No | None | Session ID. Creates new session with auto-generated ID if None |-**Python SDK (Embedded / HTTP)**--```python-# Create new session (auto-generated ID)-session = client.session()-print(f"Session URI: {session.uri}")--# Create new session with specified ID-session = client.create_session(session_id="my-custom-session-id")-print(f"Session ID: {session['session_id']}")-```+#### 3. Usage Examples**HTTP API**-```+```httpPOST /api/v1/sessions```@@ -45,13 +54,30 @@ curl -X POST http://localhost:1933/api/v1/sessions \-d '{"session_id": "my-custom-session-id"}'```+**Python SDK**++```python+import openviking as ov++# Use HTTP client+client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# Create new session (auto-generated ID)+result = await client.create_session()+print(f"Session ID: {result['session_id']}")++# Create new session with specified ID+result = await client.create_session(session_id="my-custom-session-id")+print(f"Session ID: {result['session_id']}")+```+**CLI**```bash-openviking session new+ov session new```-**Response**+**Response Example**```json{@@ -72,19 +98,26 @@ openviking session new### list_sessions()-List all sessions.+#### 1. API Implementation Introduction-**Python SDK (Embedded / HTTP)**+List all sessions for the current user. Returns session IDs and URI info for further operations.-```python-sessions = client.list_sessions()-for s in sessions:- print(f"{s['session_id']} -> {s['uri']}")-```+**Code Entries:**+- `openviking/server/routers/sessions.py:list_sessions()` - HTTP route+- `openviking_cli/client/base.py:BaseClient.list_sessions()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:list_sessions()` - CLI command++#### 2. Interface and Parameter Description++**Parameters**++None.++#### 3. Usage Examples**HTTP API**-```+```httpGET /api/v1/sessions```@@ -93,20 +126,40 @@ curl -X GET http://localhost:1933/api/v1/sessions \-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++sessions = await client.list_sessions()+for s in sessions:+ print(f"{s['session_id']} -> {s['uri']}")+```+**CLI**```bash-openviking session list+ov session list```-**Response**+**Response Example**```json{"status": "ok","result": [- {"session_id": "a1b2c3d4", "uri": "viking://session/alice/a1b2c3d4", "is_dir": true},- {"session_id": "e5f6g7h8", "uri": "viking://session/alice/e5f6g7h8", "is_dir": true}+ {+ "session_id": "a1b2c3d4",+ "uri": "viking://session/alice/a1b2c3d4",+ "is_dir": true+ },+ {+ "session_id": "e5f6g7h8",+ "uri": "viking://session/alice/e5f6g7h8",+ "is_dir": true+ }],"time": 0.1}@@ -116,7 +169,24 @@ openviking session list### get_session()-Get session details. Returns NOT_FOUND when the session does not exist by default. Pass `auto_create=True` to create it automatically.+#### 1. API Implementation Introduction++Get session details including metadata, message statistics, commit history, etc. Supports auto-creating sessions when they don't exist.++**Return Fields Description:**+- `message_count`: Number of current live, unarchived messages+- `total_message_count`: Cumulative count of archived and current live messages (older sessions may omit this field)+- `commit_count`: Number of successful commits+- `memories_extracted`: Count statistics of extracted memories by category+- `last_commit_at`: Time of last commit++**Code Entries:**+- `openviking/session/session.py:Session.load()` - Session loading+- `openviking/server/routers/sessions.py:get_session()` - HTTP route+- `openviking_cli/client/base.py:BaseClient.get_session()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:get_session()` - CLI command++#### 2. Interface and Parameter Description**Parameters**@@ -125,20 +195,11 @@ Get session details. Returns NOT_FOUND when the session does not exist by defaul| session_id | str | Yes | - | Session ID || auto_create | bool | No | False | Whether to auto-create the session if it does not exist |-**Python SDK (Embedded / HTTP)**--```python-# Get existing session (raises NotFoundError if not found)-info = client.get_session("a1b2c3d4")-print(f"Live Messages: {info['message_count']}, Total Messages: {info.get('total_message_count', 'n/a')}, Commits: {info['commit_count']}")--# Get or create session-info = client.get_session("a1b2c3d4", auto_create=True)-```+#### 3. Usage Examples**HTTP API**-```+```httpGET /api/v1/sessions/{session_id}?auto_create=false```@@ -147,13 +208,30 @@ curl -X GET http://localhost:1933/api/v1/sessions/a1b2c3d4 \-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# Get existing session (raises NotFoundError if not found)+info = await client.get_session("a1b2c3d4")+print(f"Live Messages: {info['message_count']}")+print(f"Total Messages: {info.get('total_message_count', 'n/a')}")+print(f"Commits: {info['commit_count']}")++# Get or create session+info = await client.get_session("a1b2c3d4", auto_create=True)+```+**CLI**```bash-openviking session get a1b2c3d4+ov session get a1b2c3d4```-**Response**+**Response Example**```json{@@ -186,34 +264,39 @@ openviking session get a1b2c3d4"account_id": "default","user_id": "alice","agent_id": "default"- }+ },+ "pending_tokens": 450}}```-Notes:-- `message_count` is the number of current live, unarchived messages.-- `total_message_count` is the cumulative count of archived and current live messages when present. Sessions created before this field existed may omit it.-- `commit_count` and `last_commit_at` are updated when commit Phase 1 archives messages successfully; Phase 2 memory extraction progress is tracked through the returned task.----### get_session_context()-Get the assembled session context used by OpenClaw-style context rebuilding.+#### 1. API Implementation Introduction++Get the assembled session context used for LLM context building. This endpoint returns the latest archive overview and current live messages.++**Return Fields Description:**+- `latest_archive_overview`: The `overview` of the latest completed archive, when it fits the token budget+- `pre_archive_abstracts`: Kept for backward compatibility, returns empty array+- `messages`: All incomplete archive messages after the latest completed archive, plus current live session messages+- `estimatedTokens`: Estimated total tokens+- `stats`: Statistics-This endpoint returns:-- `latest_archive_overview`: the `overview` of the latest completed archive, when it fits the token budget-- `pre_archive_abstracts`: lightweight entries for completed archives, each containing `archive_id` and `abstract`-- `messages`: all incomplete archive messages after the latest completed archive, plus current live session messages-- `stats`: token and inclusion stats for the returned context+**Token Budget Allocation Strategy:**+1. First allocate to current live messages+2. Remaining budget prioritizes the latest archive overview+3. Pre-archive abstracts are not currently returned-Notes:-- `latest_archive_overview` becomes an empty string when no completed archive exists, or when the latest overview does not fit in the token budget.-- `token_budget` is applied to the assembled payload after active `messages`: `latest_archive_overview` has higher priority than `pre_archive_abstracts`, and older abstracts are dropped first when budget is tight.-- `token_budget` must be greater than or equal to `0`. `token_budget=0` is valid and disables archive payload inclusion, while active `messages` are still returned. Negative values are rejected as invalid arguments.-- Only archive content that is actually returned is counted toward `estimatedTokens` and `stats.archiveTokens`.-- Session commit generates an archive summary during Phase 2 for every non-empty archive attempt. Only archives with a completed `.done` marker are exposed here.+**Code Entries:**+- `openviking/session/session.py:Session.get_session_context()` - Core implementation+- `openviking/server/routers/sessions.py:get_session_context()` - HTTP route+- `openviking_cli/client/base.py:BaseClient.get_session_context()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:get_session_context()` - CLI command++#### 2. Interface and Parameter Description**Parameters**@@ -222,21 +305,11 @@ Notes:| session_id | str | Yes | - | Session ID || token_budget | int | No | 128000 | Non-negative token budget for assembled archive payload after active `messages` |-**Python SDK (Embedded / HTTP)**--```python-context = await client.get_session_context("a1b2c3d4", token_budget=128000)-print(context["latest_archive_overview"])-print(context["pre_archive_abstracts"])-print(len(context["messages"]))--session = client.session("a1b2c3d4")-context = await session.get_session_context(token_budget=128000)-```+#### 3. Usage Examples**HTTP API**-```+```httpGET /api/v1/sessions/{session_id}/context?token_budget=128000```@@ -245,29 +318,32 @@ curl -X GET "http://localhost:1933/api/v1/sessions/a1b2c3d4/context?token_budget-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++context = await client.get_session_context("a1b2c3d4", token_budget=128000)+print(context["latest_archive_overview"])+print(len(context["messages"]))+```+**CLI**```bashov session get-session-context a1b2c3d4 --token-budget 128000```-**Response**+**Response Example**```json{"status": "ok","result": {"latest_archive_overview": "# Session Summary\n\n**Overview**: User discussed deployment and auth setup.",- "pre_archive_abstracts": [- {- "archive_id": "archive_002",- "abstract": "User discussed deployment and authentication setup."- },- {- "archive_id": "archive_001",- "abstract": "User previously discussed repository bootstrap and authentication setup."- }- ],+ "pre_archive_abstracts": [],"messages": [{"id": "msg_pending_1",@@ -286,14 +362,14 @@ ov session get-session-context a1b2c3d4 --token-budget 128000"created_at": "2026-03-24T09:10:20Z"}],- "estimatedTokens": 173,+ "estimatedTokens": 160,"stats": {"totalArchives": 2,- "includedArchives": 2,+ "includedArchives": 1,"droppedArchives": 0,"failedArchives": 0,"activeTokens": 98,- "archiveTokens": 75+ "archiveTokens": 62}}}@@ -303,15 +379,17 @@ ov session get-session-context a1b2c3d4 --token-budget 128000### get_session_archive()-Get the full contents of one completed archive for a session.+#### 1. API Implementation Introduction++Get the full contents of one completed archive for a session. This endpoint is typically used with `get_session_context()` when you need to view older archive details.-This endpoint is intended to work with `pre_archive_abstracts[*].archive_id` returned by `get_session_context()`.+**Code Entries:**+- `openviking/session/session.py:Session.get_session_archive()` - Core implementation+- `openviking/server/routers/sessions.py:get_session_archive()` - HTTP route+- `openviking_cli/client/base.py:BaseClient.get_session_archive()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:get_session_archive()` - CLI command-This endpoint returns:-- `archive_id`: the archive ID that was expanded-- `abstract`: the lightweight summary for the archive-- `overview`: the full archive overview-- `messages`: the archived transcript for that archive+#### 2. Interface and Parameter Description**Parameters**@@ -320,21 +398,11 @@ This endpoint returns:| session_id | str | Yes | - | Session ID || archive_id | str | Yes | - | Archive ID such as `archive_002` |-**Python SDK (Embedded / HTTP)**--```python-archive = await client.get_session_archive("a1b2c3d4", "archive_002")-print(archive["archive_id"])-print(archive["overview"])-print(len(archive["messages"]))--session = client.session("a1b2c3d4")-archive = await session.get_archive("archive_002")-```+#### 3. Usage Examples**HTTP API**-```+```httpGET /api/v1/sessions/{session_id}/archives/{archive_id}```@@ -343,20 +411,33 @@ curl -X GET "http://localhost:1933/api/v1/sessions/a1b2c3d4/archives/archive_002-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++archive = await client.get_session_archive("a1b2c3d4", "archive_002")+print(archive["archive_id"])+print(archive["overview"])+print(len(archive["messages"]))+```+**CLI**```bashov session get-session-archive a1b2c3d4 archive_002```-**Response**+**Response Example**```json{"status": "ok","result": {"archive_id": "archive_002",- "abstract": "User discussed deployment and auth setup.",+ "abstract": "User discussed deployment and authentication setup.","overview": "# Session Summary\n\n**Overview**: User discussed deployment and auth setup.","messages": [{@@ -380,13 +461,34 @@ ov session get-session-archive a1b2c3d4 archive_002}```-If the archive does not exist, is incomplete, or does not belong to the session, the API returns `404`.+**Error Response**++If the archive does not exist, is incomplete, or does not belong to the session, the API returns 404:++```json+{+ "status": "error",+ "error": {+ "code": "NOT_FOUND",+ "message": "Archive archive_002 not found"+ }+}+```---### delete_session()-Delete a session.+#### 1. API Implementation Introduction++Delete a session and all its data, including messages, archive history, memories, etc. Deletion is irreversible.++**Code Entries:**+- `openviking/server/routers/sessions.py:delete_session()` - HTTP route+- `openviking_cli/client/base.py:BaseClient.delete_session()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:delete_session()` - CLI command++#### 2. Interface and Parameter Description**Parameters**@@ -394,15 +496,11 @@ Delete a session.|-----------|------|----------|---------|-------------|| session_id | str | Yes | - | Session ID to delete |-**Python SDK (Embedded / HTTP)**--```python-client.rm("viking://session/a1b2c3d4/", recursive=True)-```+#### 3. Usage Examples**HTTP API**-```+```httpDELETE /api/v1/sessions/{session_id}```@@ -411,13 +509,24 @@ curl -X DELETE http://localhost:1933/api/v1/sessions/a1b2c3d4 \-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# Delete session+await client.delete_session("a1b2c3d4")+```+**CLI**```bash-openviking session delete a1b2c3d4+ov session delete a1b2c3d4```-**Response**+**Response Example**```json{@@ -433,16 +542,33 @@ openviking session delete a1b2c3d4### add_message()-Add a message to the session.+#### 1. API Implementation Introduction++Add a message to the session. Supports two modes: simple text mode and Parts mode (supporting text, context references, tool calls, etc.).++**Part Types:**+- `TextPart`: Pure text content+- `ContextPart`: Context reference pointing to resources or memories+- `ToolPart`: Tool call and result++**Code Entries:**+- `openviking/session/session.py:Session.add_message()` - Core implementation+- `openviking/server/routers/sessions.py:add_message()` - HTTP route+- `openviking_cli/client/base.py:BaseClient.add_message()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:add_message()` - CLI command++#### 2. Interface and Parameter Description**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|+| session_id | str | Yes | - | Session ID || role | str | Yes | - | Message role: "user" or "assistant" || parts | List[Part] | Conditional | - | List of message parts (Required for Python SDK; Optional for HTTP API, mutually exclusive with content) || content | str | Conditional | - | Message text content (HTTP API simple mode, mutually exclusive with parts) || created_at | str | No | None | Optional ISO 8601 timestamp to persist on the message |+| role_id | str | No | None | Optional explicit participant ID, server-derived if omitted |> **Note**: HTTP API supports two modes:> 1. **Simple mode**: Use `content` string (backward compatible)@@ -476,27 +602,11 @@ ToolPart()```-**Python SDK (Embedded / HTTP)**--```python-from openviking.message import TextPart--session = client.session()--# Add user message-session.add_message("user", [- TextPart(text="How do I authenticate users?")-])--# Add assistant response-session.add_message("assistant", [- TextPart(text="You can use OAuth 2.0 for authentication...")-])-```+#### 3. Usage Examples**HTTP API**-```+```httpPOST /api/v1/sessions/{session_id}/messages```@@ -541,13 +651,43 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \}'```+**Python SDK**++```python+import openviking as ov+from openviking.message import TextPart, ContextPart++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# Simple mode: Add user message+await client.add_message(+ session_id="a1b2c3d4",+ role="user",+ content="How do I authenticate users?"+)++# Parts mode: Add assistant message with context reference+await client.add_message(+ session_id="a1b2c3d4",+ role="assistant",+ parts=[+ TextPart(text="Based on the documentation, you can configure embedding..."),+ ContextPart(+ uri="viking://resources/docs/auth/",+ context_type="resource",+ abstract="Authentication guide"+ )+ ]+)+```+**CLI**```bash-openviking session add-message a1b2c3d4 --role user --content "How do I authenticate users?"+ov session add-message a1b2c3d4 --role user --content "How do I authenticate users?"```-**Response**+**Response Example**```json{@@ -564,36 +704,29 @@ openviking session add-message a1b2c3d4 --role user --content "How do I authenti### used()-Record actually used contexts and skills in the session. When `commit()` is called, `active_count` is updated based on this usage data.+#### 1. API Implementation Introduction++Record actually used contexts and skills in the session. When `commit()` is called, `active_count` is updated based on this usage data to optimize future retrieval ranking.++**Code Entries:**+- `openviking/session/session.py:Session.used()` - Core implementation+- `openviking/server/routers/sessions.py:record_used()` - HTTP route++#### 2. Interface and Parameter Description**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|+| session_id | str | Yes | - | Session ID || contexts | List[str] | No | None | List of context URIs that were actually used || skill | Dict[str, Any] | No | None | Skill usage record with keys: `uri`, `input`, `output`, `success` |-**Python SDK (Embedded / HTTP)**--```python-session = client.session(session_id="a1b2c3d4")-session.load()--# Record used contexts-session.used(contexts=["viking://resources/docs/auth/"])--# Record used skill-session.used(skill={- "uri": "viking://agent/skills/search-web/",- "input": {"query": "OAuth"},- "output": "Results...",- "success": True-})-```+#### 3. Usage Examples**HTTP API**-```+```httpPOST /api/v1/sessions/{session_id}/used```@@ -611,7 +744,32 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \-d '{"skill": {"uri": "viking://agent/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'```-**Response**+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# Record used contexts+await client.session_used(+ session_id="a1b2c3d4",+ contexts=["viking://resources/docs/auth/"]+)++# Record used skill+await client.session_used(+ session_id="a1b2c3d4",+ skill={+ "uri": "viking://agent/skills/search-web/",+ "input": {"query": "OAuth"},+ "output": "Results...",+ "success": True+ }+)+```++**Response Example**```json{@@ -629,39 +787,38 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \### commit()+#### 1. API Implementation Introduction+Commit a session. Message archiving (Phase 1) completes immediately. Summary generation and memory extraction (Phase 2) run asynchronously in the background. Returns a `task_id` for polling progress.-Notes:+**Two-Phase Commit Flow:**+- **Phase 1 (Synchronous)**: Snapshot current messages, clear live session, create archive directory, write original messages+- **Phase 2 (Asynchronous)**: Generate summaries (L0/L1), extract long-term memories, update relations and active_count++**Notes:**- Rapid consecutive commits on the same session are accepted; each request gets its own `task_id`.- Background Phase 2 work is serialized by archive order: archive `N+1` waits until archive `N` writes `.done`.- If an earlier archive failed and left no `.done`, later commit requests fail with `FAILED_PRECONDITION` until that failure is resolved.+**Code Entries:**+- `openviking/session/session.py:Session.commit_async()` - Core implementation+- `openviking/server/routers/sessions.py:commit_session()` - HTTP route+- `openviking_cli/client/base.py:BaseClient.commit_session()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:commit_session()` - CLI command++#### 2. Interface and Parameter Description+**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| session_id | str | Yes | - | Session ID to commit |-**Python SDK (Embedded / HTTP)**--```python-session = client.session(session_id="a1b2c3d4")-session.load()--# Commit returns immediately with task_id; summary + memory extraction runs in background-result = session.commit()-print(f"Status: {result['status']}") # "accepted"-print(f"Task ID: {result['task_id']}")--# Poll background task progress-task = client.get_task(result["task_id"])-if task["status"] == "completed":- print(f"Memories extracted: {sum(task['result']['memories_extracted'].values())}")-```+#### 3. Usage Examples**HTTP API**-```+```httpPOST /api/v1/sessions/{session_id}/commit```@@ -676,13 +833,33 @@ curl -X GET http://localhost:1933/api/v1/tasks/{task_id} \-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# Commit returns immediately with task_id; summary + memory extraction runs in background+result = await client.commit_session("a1b2c3d4")+print(f"Status: {result['status']}")+print(f"Task ID: {result['task_id']}")++# Poll background task progress+task = await client.get_task(result["task_id"])+if task["status"] == "completed":+ memories = task["result"]["memories_extracted"]+ total = sum(memories.values())+ print(f"Memories extracted: {total}")+```+**CLI**```bash-openviking session commit a1b2c3d4+ov session commit a1b2c3d4```-**Response**+**Response Example**```json{@@ -691,7 +868,7 @@ openviking session commit a1b2c3d4"session_id": "a1b2c3d4","status": "accepted","task_id": "uuid-xxx",- "archive_uri": "viking://session/a1b2c3d4/history/archive_001",+ "archive_uri": "viking://session/alice/a1b2c3d4/history/archive_001","archived": true}}@@ -701,17 +878,26 @@ openviking session commit a1b2c3d4### extract()+#### 1. API Implementation Introduction+HTTP API only. Trigger memory extraction immediately for an existing session without creating a new commit task.+**Code Entries:**+- `openviking/server/routers/sessions.py:extract_session()` - HTTP route++#### 2. Interface and Parameter Description+**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| session_id | str | Yes | - | Session ID to extract memories from |+#### 3. Usage Examples+**HTTP API**-```+```httpPOST /api/v1/sessions/{session_id}/extract```@@ -721,7 +907,7 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/extract \-H "X-API-Key: your-key"```-**Response**+**Response Example**The endpoint returns the extracted memory write results as a JSON list. The exact item shape depends on which memories were produced for that session.@@ -729,24 +915,32 @@ The endpoint returns the extracted memory write results as a JSON list. The exac### get_task()+#### 1. API Implementation Introduction+Query background task status (e.g., commit summary generation and memory extraction progress).+**Task Statuses:**+- `pending`: Task waiting to execute+- `running`: Task in progress+- `completed`: Task successfully completed+- `failed`: Task failed++**Code Entries:**+- `openviking/server/routers/tasks.py:get_task()` - HTTP route++#### 2. Interface and Parameter Description+**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| task_id | str | Yes | - | Task ID (returned by commit) |-**Python SDK (Embedded / HTTP)**--```python-task = client.get_task(task_id)-print(f"Status: {task['status']}") # "pending" | "running" | "completed" | "failed"-```+#### 3. Usage Examples**HTTP API**-```+```httpGET /api/v1/tasks/{task_id}```@@ -755,7 +949,18 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \-H "X-API-Key: your-key"```-**Response (in progress)**+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++task = await client.get_task(task_id="uuid-xxx")+print(f"Status: {task['status']}")+```++**Response Example (in progress)**```json{@@ -768,7 +973,7 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \}```-**Response (completed)**+**Response Example (completed)**```json{@@ -779,14 +984,27 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \"status": "completed","result": {"session_id": "a1b2c3d4",- "archive_uri": "viking://session/a1b2c3d4/history/archive_001",+ "archive_uri": "viking://session/alice/a1b2c3d4/history/archive_001","memories_extracted": {"profile": 1,"preferences": 2,"entities": 1,"cases": 1},- "active_count_updated": 2+ "active_count_updated": 2,+ "token_usage": {+ "llm": {+ "prompt_tokens": 5200,+ "completion_tokens": 1800,+ "total_tokens": 7000+ },+ "embedding": {+ "total_tokens": 1500+ },+ "total": {+ "total_tokens": 8500+ }+ }}}}@@ -798,7 +1016,14 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \### list_tasks()-HTTP API only. List background tasks visible to the current caller.+#### 1. API Implementation Introduction++HTTP API only. List background tasks visible to the current caller, supporting filtering by type, status, resource.++**Code Entries:**+- `openviking/server/routers/tasks.py:list_tasks()` - HTTP route++#### 2. Interface and Parameter Description**Parameters**@@ -809,10 +1034,12 @@ HTTP API only. List background tasks visible to the current caller.| resource_id | str | No | None | Filter by task resource ID, for example a session ID || limit | int | No | 50 | Maximum number of task records to return |+#### 3. Usage Examples+**HTTP API**-```-GET /api/v1/tasks+```http+GET /api/v1/tasks?task_type=session_commit&status=running&limit=20``````bash@@ -820,7 +1047,7 @@ curl -X GET "http://localhost:1933/api/v1/tasks?task_type=session_commit&status=-H "X-API-Key: your-key"```-**Response**+**Response Example**```json{@@ -857,7 +1084,7 @@ curl -X GET "http://localhost:1933/api/v1/tasks?task_type=session_commit&status=## Session Storage Structure```-viking://session/{session_id}/+viking://session/{user_id}/{session_id}/+-- .abstract.md # L0: Session overview+-- .overview.md # L1: Key decisions+-- messages.jsonl # Current messages@@ -871,8 +1098,10 @@ viking://session/{session_id}/| +-- messages.jsonl # Written in Phase 1| +-- .abstract.md # Written in Phase 2 (background)| +-- .overview.md # Written in Phase 2 (background)+ | +-- .meta.json # Archive metadata| +-- memory_diff.json # Written in Phase 2 (background, on memory changes)| +-- .done # Phase 2 completion marker+ | +-- .failed.json # Phase 2 failure marker+-- archive_002/```@@ -895,50 +1124,61 @@ viking://session/{session_id}/## Full Example-**Python SDK (Embedded / HTTP)**+**Python SDK**```pythonimport openviking as ovfrom openviking.message import TextPart, ContextPart# Initialize client-client = ov.OpenViking(path="./my_data")-client.initialize()+client = ov.Client(base_url="http://localhost:1933", api_key="your-key")# Create new session-session = client.session()+session_result = await client.create_session()+session_id = session_result["session_id"]+print(f"Session created: {session_id}")# Add user message-session.add_message("user", [- TextPart(text="How do I configure embedding?")-])+await client.add_message(+ session_id=session_id,+ role="user",+ content="How do I configure embedding?"+)# Search with session context-results = client.search("embedding configuration", session=session)--# Add assistant response with context reference-session.add_message("assistant", [- TextPart(text="Based on the documentation, you can configure embedding..."),- ContextPart(- uri=results.resources[0].uri,- context_type="resource",- abstract=results.resources[0].abstract+results = await client.search("embedding configuration", session_id=session_id)++# Add assistant message with context reference+if results.resources:+ await client.add_message(+ session_id=session_id,+ role="assistant",+ parts=[+ TextPart(text="Based on the documentation, you can configure embedding..."),+ ContextPart(+ uri=results.resources[0].uri,+ context_type="resource",+ abstract=results.resources[0].abstract+ )+ ])-])-# Track actually used contexts-session.used(contexts=[results.resources[0].uri])+ # Track actually used contexts+ await client.session_used(+ session_id=session_id,+ contexts=[results.resources[0].uri]+ )# Commit session (returns immediately; summary + memory extraction runs in background)-result = session.commit()-print(f"Task ID: {result['task_id']}")+commit_result = await client.commit_session(session_id)+print(f"Task ID: {commit_result['task_id']}")# Optional: poll for completion-task = client.get_task(result["task_id"])+task = await client.get_task(commit_result["task_id"])if task and task["status"] == "completed":- print(f"Memories extracted: {sum(task['result']['memories_extracted'].values())}")--client.close()+ memories = task["result"]["memories_extracted"]+ total = sum(memories.values())+ print(f"Memories extracted: {total}")```**HTTP API**@@ -991,8 +1231,9 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \```python# Commit after significant interactions-if len(session.messages) > 10:- session.commit()+session_info = await client.get_session(session_id)+if session_info["message_count"] > 10:+ await client.commit_session(session_id)```### Track What's Actually Used@@ -1000,22 +1241,14 @@ if len(session.messages) > 10:```python# Only mark contexts that were actually helpfulif context_was_useful:- session.used(contexts=[ctx.uri])+ await client.session_used(session_id=session_id, contexts=[ctx.uri])```### Use Session Context for Search```python# Better search results with conversation context-results = client.search(query, session=session)-```--### Load Before Continuing--```python-# Always load when resuming an existing session-session = client.session(session_id="existing-id")-session.load()+results = await client.search(query, session_id=session_id)```---diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.mdindex 580b132ee..fb8218eb1 100644--- a/docs/en/api/06-retrieval.md+++ b/docs/en/api/06-retrieval.md@@ -1,6 +1,6 @@# Retrieval-OpenViking provides two search methods: `find` for simple semantic search and `search` for complex retrieval with session context.+OpenViking provides multiple retrieval methods, including simple vector similarity search, intelligent retrieval with session context, regex pattern matching, and file pattern matching.## find vs search@@ -12,27 +12,59 @@ OpenViking provides two search methods: `find` for simple semantic search and `s| Default Limit | 10 | 10 || Use Case | Simple queries | Conversational search |+## Retrieval Pipeline++The core retrieval pipeline is as follows:++```+Query → Intent Analysis (search only) → Vector Search (L0) → Rerank (L1) → Results+```++1. **Intent Analysis** (search only): Understand query intent, expand queries+2. **Vector Search**: Find candidates using embeddings+3. **Rerank**: Re-score using content for better accuracy+4. **Results**: Return top-k contexts+## API Reference### find()-Basic vector similarity search.+Basic vector similarity search without session context.++#### 1. API Implementation Introduction++The `find()` method performs pure vector similarity search for simple query scenarios. It uses hierarchical retrieval to search at the L0 summary level first, then matches in detail at L1/L2 levels.++**Processing Pipeline**:+1. Convert query text to vector+2. Perform global vector search within specified target URI+3. Use hierarchical retrieval strategy to recursively search relevant directories and files+4. Optional: Use rerank model to optimize result ordering+5. Return matched context list++**Code Entry Points**:+- `openviking_cli/client/sync_http.py:SyncHTTPClient.find()` - Python SDK entry (HTTP)+- `openviking/retrieve/hierarchical_retriever.py:HierarchicalRetriever.retrieve()` - Core retrieval implementation+- `openviking/server/routers/search.py:find()` - HTTP router+- `crates/ov_cli/src/commands/search.rs:find()` - Rust CLI command++#### 2. Interface and Parameter Description**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| query | str | Yes | - | Search query string |-| target_uri | str | No | "" | Limit search to specific URI prefix |+| target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix || limit | int | No | 10 | Maximum number of results || node_limit | int | No | None | Optional HTTP alias that overrides `limit` when provided || score_threshold | float | No | None | Minimum relevance score threshold |-| filter | Dict | No | None | Metadata filters |+| filter | Dict | No | None | Metadata filter || since | str | No | None | Lower time bound, accepts `2h` or ISO 8601 / `YYYY-MM-DD`. Timezone-less values are interpreted as UTC. CLI `--after` maps to this field || until | str | No | None | Upper time bound, accepts `30m` or ISO 8601 / `YYYY-MM-DD`. Timezone-less values are interpreted as UTC. CLI `--before` maps to this field |-| time_field | `"updated_at"` or `"created_at"` | No | `"updated_at"` | Metadata time field used by `since` / `until` |-| include_provenance | bool | No | False | Include provenance/query-plan details in the serialized result |-| telemetry | bool or object | No | False | Attach telemetry data to the response |+| time_field | "updated_at" \| "created_at" | No | "updated_at" | Metadata time field used by `since` / `until` |+| include_provenance | bool | No | False | Include provenance/query-plan details in serialized result |+| telemetry | bool \| object | No | False | Attach telemetry data to response |**FindResult Structure**@@ -52,33 +84,16 @@ class FindResult:class MatchedContext:uri: str # Viking URIcontext_type: ContextType # "resource", "memory", or "skill"- is_leaf: bool # Whether it's a leaf node+ level: int # Tier (0=L0, 1=L1, 2=L2)abstract: str # L0 content+ overview: Optional[str] # L1 overview (optional for non-leaf nodes)category: str # Categoryscore: float # Relevance score (0-1)match_reason: str # Why this matchedrelations: List[RelatedContext] # Related contexts```-**Python SDK (Embedded / HTTP)**--```python-results = client.find("how to authenticate users")--recent_emails = client.find(- "invoice",- target_uri="viking://resources/email/",- since="7d",- time_field="created_at",-)--for ctx in results.resources:- print(f"URI: {ctx.uri}")- print(f"Score: {ctx.score:.3f}")- print(f"Type: {ctx.context_type}")- print(f"Abstract: {ctx.abstract[:100]}...")- print("---")-```+#### 3. Usage Examples**HTTP API**@@ -88,130 +103,221 @@ POST /api/v1/search/find```bashcurl -X POST http://localhost:1933/api/v1/search/find \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "query": "how to authenticate users",- "limit": 10- }'+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "query": "how to authenticate users",+ "limit": 10+ }'```-**CLI**+**Search with Target URI and Time Filter**```bash-openviking find "how to authenticate users" [--uri viking://resources/] [--limit 10]-openviking find "invoice" --after 7d+curl -X POST http://localhost:1933/api/v1/search/find \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "query": "authentication",+ "target_uri": "viking://resources",+ "since": "7d",+ "time_field": "created_at"+ }'```-`--after` maps to API `since`, and `--before` maps to API `until`.+**Python SDK**-**Response**+```python+import openviking as ov-```json-{- "status": "ok",- "result": {- "memories": [],- "resources": [- {- "uri": "viking://resources/docs/auth/",- "context_type": "resource",- "is_leaf": false,- "abstract": "Authentication guide covering OAuth 2.0...",- "score": 0.92,- "match_reason": "Semantic match on authentication"- }- ],- "skills": [],- "total": 1- },- "time": 0.1-}-```+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()-**Example: Search with Target URI**+# Basic search+results = client.find("how to authenticate users")++# Search with filter and time range+recent_emails = client.find(+ "invoice",+ target_uri="viking://resources/email",+ since="7d",+ time_field="created_at",+)++# Iterate through results+for ctx in results.resources:+ print(f"URI: {ctx.uri}")+ print(f"Score: {ctx.score:.3f}")+ print(f"Type: {ctx.context_type}")+ print(f"Abstract: {ctx.abstract[:100]}...")+ print("---")+```-**Python SDK (Embedded / HTTP)**+**Search with Target URI Limitation**```python# Search only in resourcesresults = client.find("authentication",- target_uri="viking://resources/"+ target_uri="viking://resources")# Search only in user memoriesresults = client.find("preferences",- target_uri="viking://user/memories/"+ target_uri="viking://user/memories")# Search only in skillsresults = client.find("web search",- target_uri="viking://agent/skills/"+ target_uri="viking://agent/skills")# Search in specific projectresults = client.find("API endpoints",- target_uri="viking://resources/my-project/"+ target_uri="viking://resources/my-project")```-**HTTP API**+**CLI**```bash-# Search only in resources-curl -X POST http://localhost:1933/api/v1/search/find \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "query": "authentication",- "target_uri": "viking://resources/"- }'--# Search with score threshold-curl -X POST http://localhost:1933/api/v1/search/find \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "query": "API endpoints",- "target_uri": "viking://resources/my-project/",- "score_threshold": 0.5,- "limit": 5- }'+# Basic search+openviking find "how to authenticate users"++# Specify URI scope+openviking find "how to authenticate users" --uri "viking://resources"++# With time filter+openviking find "invoice" --after 7d++# With limit+openviking find "how to authenticate users" --limit 20+```++**Response Example**++```json+{+ "status": "ok",+ "result": {+ "memories": [],+ "resources": [+ {+ "context_type": "resource",+ "uri": "viking://resources/01-overview/API_Overview/Documentation_Reading_P_2c6ae38b.md",+ "level": 2,+ "score": 0.12808319406977778,+ "category": "",+ "match_reason": "",+ "relations": [],+ "abstract": "This document is an API documentation reading plan that outlines the structure of subsequent API reference materials organized by functional module. Main sections or topics covered include resource management API, search API, file system operations, ses...",+ "overview": null+ },+ {+ "context_type": "resource",+ "uri": "viking://resources/01-overview/API_Overview/API_Endpoints/.abstract.md",+ "level": 0,+ "score": 0.12054087276495282,+ "category": "",+ "match_reason": "",+ "relations": [],+ "abstract": "This directory contains structured API reference documentation for the OpenViking platform, compiling detailed HTTP endpoint specifications for core and extended platform capabilities. It covers functional modules including system health checks, semanti...",+ "overview": null+ }+ ],+ "skills": [],+ "total": 2+ }+}```---### search()-Search with session context and intent analysis.+Intelligent retrieval with session context and intent analysis.++#### 1. API Implementation Introduction++The `search()` method adds session context understanding and intent analysis capability on top of `find()`. It better understands user query intent based on conversation history, performs query expansion, and provides more relevant search results.++**Processing Pipeline**:+1. Load session context (if session_id is provided)+2. Analyze query intent, understand actual needs combined with conversation history+3. Expand queries to improve recall rate+4. Execute same hierarchical retrieval pipeline as `find()`+5. Return search results with query plan++**Code Entry Points**:+- `openviking_cli/client/sync_http.py:SyncHTTPClient.search()` - Python SDK entry (HTTP)+- `openviking/retrieve/hierarchical_retriever.py:HierarchicalRetriever.retrieve()` - Core retrieval implementation+- `openviking/server/routers/search.py:search()` - HTTP router+- `crates/ov_cli/src/commands/search.rs:search()` - Rust CLI command++#### 2. Interface and Parameter Description**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| query | str | Yes | - | Search query string |-| target_uri | str | No | "" | Limit search to specific URI prefix |+| target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix || session | Session | No | None | Session for context-aware search (SDK) || session_id | str | No | None | Session ID for context-aware search (HTTP) || limit | int | No | 10 | Maximum number of results || node_limit | int | No | None | Optional HTTP alias that overrides `limit` when provided || score_threshold | float | No | None | Minimum relevance score threshold |-| filter | Dict | No | None | Metadata filters |+| filter | Dict | No | None | Metadata filter || since | str | No | None | Lower time bound, accepts `2h` or ISO 8601 / `YYYY-MM-DD`. Timezone-less values are interpreted as UTC. CLI `--after` maps to this field || until | str | No | None | Upper time bound, accepts `30m` or ISO 8601 / `YYYY-MM-DD`. Timezone-less values are interpreted as UTC. CLI `--before` maps to this field |-| time_field | `"updated_at"` or `"created_at"` | No | `"updated_at"` | Metadata time field used by `since` / `until` |-| include_provenance | bool | No | False | Include provenance/query-plan details in the serialized result |-| telemetry | bool or object | No | False | Attach telemetry data to the response |+| time_field | "updated_at" \| "created_at" | No | "updated_at" | Metadata time field used by `since` / `until` |+| include_provenance | bool | No | False | Include provenance/query-plan details in serialized result |+| telemetry | bool \| object | No | False | Attach telemetry data to response |-**Python SDK (Embedded / HTTP)**+#### 3. Usage Examples++**HTTP API**++```+POST /api/v1/search/search+```++```bash+curl -X POST http://localhost:1933/api/v1/search/search \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "query": "best practices",+ "session_id": "abc123",+ "since": "2h",+ "time_field": "updated_at",+ "limit": 10+ }'+```++**Search without Session (Still Performs Intent Analysis)**++```bash+curl -X POST http://localhost:1933/api/v1/search/search \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "query": "how to implement OAuth 2.0 authorization code flow"+ }'+```++**Python SDK**```python+import openviking as ovfrom openviking.message import TextPart+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+# Create session with conversation contextsession = client.session()session.add_message("user", [@@ -221,7 +327,7 @@ session.add_message("assistant", [TextPart(text="I can help you with OAuth implementation.")])-# Search understands the conversation context+# Search understands conversation contextresults = client.search("best practices",session=session,@@ -233,92 +339,97 @@ for ctx in results.resources:print(f"Abstract: {ctx.abstract[:200]}...")```-**HTTP API**+**Search without Session**-```-POST /api/v1/search/search-```+```python+# search can also be used without session+# It still performs intent analysis on the query+results = client.search(+ "how to implement OAuth 2.0 authorization code flow"+)-```bash-curl -X POST http://localhost:1933/api/v1/search/search \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "query": "best practices",- "session_id": "abc123",- "since": "2h",- "time_field": "updated_at",- "limit": 10- }'+for ctx in results.resources:+ print(f"Found: {ctx.uri} (score: {ctx.score:.3f})")```**CLI**```bash-openviking search "best practices" [--session-id abc123] [--limit 10]-openviking search "watch vs scheduled" --after 2026-03-15 --before 2026-03-15-```+# Search with session ID+openviking search "best practices" --session-id abc123-`--after` maps to API `since`, and `--before` maps to API `until`.+# Search with time filter+openviking search "watch vs scheduled" --after 2026-03-15 --before 2026-03-20-**Response**+# Search without session (still performs intent analysis)+openviking search "how to implement OAuth 2.0 authorization code flow"+```++**Response Example**```json{- "status": "ok",- "result": {- "memories": [],- "resources": [- {- "uri": "viking://resources/docs/oauth-best-practices/",- "context_type": "resource",- "is_leaf": false,- "abstract": "OAuth 2.0 best practices for login pages...",- "score": 0.95,- "match_reason": "Context-aware match: OAuth login best practices"- }- ],- "skills": [],- "query_plan": {- "expanded_queries": ["OAuth 2.0 best practices", "login page security"]- },- "total": 1- },- "time": 0.1+ "status": "ok",+ "result": {+ "memories": [],+ "resources": [+ {+ "context_type": "resource",+ "uri": "viking://resources/docs/oauth-best-practices",+ "level": 1,+ "score": 0.95,+ "category": "",+ "match_reason": "Context-aware match: OAuth login best practices",+ "relations": [],+ "abstract": "OAuth 2.0 best practices for login pages...",+ "overview": "This guide covers OAuth 2.0 best practices including secure token handling, redirect URI validation, and state parameter usage..."+ }+ ],+ "skills": [],+ "query_plan": {+ "reasoning": "User is asking about OAuth implementation best practices, expanding to related security topics",+ "queries": [+ {+ "query": "OAuth 2.0 best practices",+ "context_type": "resource",+ "intent": "Find OAuth 2.0 implementation guidelines",+ "priority": 3+ },+ {+ "query": "login page security",+ "context_type": "resource",+ "intent": "Find login page security recommendations",+ "priority": 2+ }+ ]+ },+ "total": 1+ }}```-**Example: Search Without Session**--**Python SDK (Embedded / HTTP)**+----```python-# search can also be used without session-# It still performs intent analysis on the query-results = client.search(- "how to implement OAuth 2.0 authorization code flow",-)+### grep()-for ctx in results.resources:- print(f"Found: {ctx.uri} (score: {ctx.score:.3f})")-```+Search content by pattern (regex).-**HTTP API**+#### 1. API Implementation Introduction-```bash-curl -X POST http://localhost:1933/api/v1/search/search \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "query": "how to implement OAuth 2.0 authorization code flow"- }'-```+The `grep()` method performs regex pattern matching search in the file system, used to find files and content lines containing specific patterns. Unlike semantic search, grep is exact pattern matching.----+**Processing Pipeline**:+1. Traverse file system starting from specified URI+2. Perform regex matching on each file content+3. Collect matching lines and position information+4. Return matching results list-### grep()+**Code Entry Points**:+- `openviking_cli/client/sync_http.py:SyncHTTPClient.grep()` - Python SDK entry (HTTP)+- `openviking/server/routers/search.py:grep()` - HTTP router+- `crates/ov_cli/src/commands/search.rs:grep()` - Rust CLI command-Search content by pattern (regex).+#### 2. Interface and Parameter Description**Parameters**@@ -331,11 +442,35 @@ Search content by pattern (regex).| node_limit | int | No | None | Maximum number of nodes to search || level_limit | int | No | 5 | Maximum directory depth to traverse |-**Python SDK (Embedded / HTTP)**+#### 3. Usage Examples++**HTTP API**++```+POST /api/v1/search/grep+```++```bash+curl -X POST http://localhost:1933/api/v1/search/grep \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "uri": "viking://resources",+ "pattern": "authentication",+ "case_insensitive": true+ }'+```++**Python SDK**```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+results = client.grep(- "viking://resources/",+ "viking://resources","authentication",case_insensitive=True)@@ -346,45 +481,35 @@ for match in results['matches']:print(f" {match['content']}")```-**HTTP API**--```-POST /api/v1/search/grep-```+**CLI**```bash-curl -X POST http://localhost:1933/api/v1/search/grep \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "uri": "viking://resources/",- "pattern": "authentication",- "case_insensitive": true- }'-```+# Basic search+openviking grep viking://resources "authentication"-**CLI**+# Ignore case+openviking grep viking://resources "authentication" --ignore-case-```bash-openviking grep viking://resources/ "authentication" [--ignore-case]+# Specify depth limit+openviking grep viking://resources "TODO" --level-limit 3```-**Response**+**Response Example**```json{- "status": "ok",- "result": {- "matches": [- {- "uri": "viking://resources/docs/auth.md",- "line": 15,- "content": "User authentication is handled by..."- }- ],- "count": 1- },- "time": 0.1+ "status": "ok",+ "result": {+ "matches": [+ {+ "uri": "viking://resources/docs/auth.md",+ "line": 15,+ "content": "User authentication is handled by..."+ }+ ],+ "count": 1+ },+ "time": 0.1}```@@ -394,6 +519,23 @@ openviking grep viking://resources/ "authentication" [--ignore-case]Match files by glob pattern.+#### 1. API Implementation Introduction++The `glob()` method uses file wildcard pattern matching URIs, similar to Unix shell glob functionality. Used to find files and directories by name patterns.++**Supported Pattern Syntax**:+- `*` matches any character (except path separator)+- `**` recursively matches any directory+- `?` matches single character+- `[]` matches character range++**Code Entry Points**:+- `openviking_cli/client/sync_http.py:SyncHTTPClient.glob()` - Python SDK entry (HTTP)+- `openviking/server/routers/search.py:glob()` - HTTP router+- `crates/ov_cli/src/commands/search.rs:glob()` - Rust CLI command++#### 2. Interface and Parameter Description+**Parameters**| Parameter | Type | Required | Default | Description |@@ -402,19 +544,7 @@ Match files by glob pattern.| uri | str | No | "viking://" | Starting URI || node_limit | int | No | None | Maximum number of matches to return |-**Python SDK (Embedded / HTTP)**--```python-# Find all markdown files-results = client.glob("**/*.md", "viking://resources/")-print(f"Found {results['count']} markdown files:")-for uri in results['matches']:- print(f" {uri}")--# Find all Python files-results = client.glob("**/*.py", "viking://resources/")-print(f"Found {results['count']} Python files")-```+#### 3. Usage Examples**HTTP API**@@ -424,68 +554,87 @@ POST /api/v1/search/glob```bashcurl -X POST http://localhost:1933/api/v1/search/glob \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "pattern": "**/*.md",- "uri": "viking://resources/"- }'+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "pattern": "**/*.md",+ "uri": "viking://resources"+ }'+```++**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()++# Find all markdown files+results = client.glob("**/*.md", "viking://resources")+print(f"Found {results['count']} markdown files:")+for uri in results['matches']:+ print(f" {uri}")++# Find all Python files+results = client.glob("**/*.py", "viking://resources")+print(f"Found {results['count']} Python files")```**CLI**```bash-openviking glob "**/*.md" [--uri viking://resources/]+# Find all markdown files+openviking glob "**/*.md" --uri viking://resources++# Find all Python files+openviking glob "**/*.py"```-**Response**+**Response Example**```json{- "status": "ok",- "result": {- "matches": [- "viking://resources/docs/api.md",- "viking://resources/docs/guide.md"- ],- "count": 2- },- "time": 0.1+ "status": "ok",+ "result": {+ "matches": [+ "viking://resources/docs/api.md",+ "viking://resources/docs/guide.md"+ ],+ "count": 2+ },+ "time": 0.1}```----## Retrieval Pipeline--```-Query -> Intent Analysis -> Vector Search (L0) -> Rerank (L1) -> Results-```--1. **Intent Analysis** (search only): Understand query intent, expand queries-2. **Vector Search**: Find candidates using Embedding-3. **Rerank**: Re-score using content for accuracy-4. **Results**: Return top-k contexts-## Working with Results### Read Content Progressively-**Python SDK (Embedded / HTTP)**+Retrieval results usually only contain L0 summaries, you can progressively load more detailed content as needed.++**Python SDK**```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+results = client.find("authentication")for ctx in results.resources:# Start with L0 (abstract) - already in ctx.abstractprint(f"Abstract: {ctx.abstract}")- if not ctx.is_leaf:- # Get L1 (overview)+ if ctx.level < 2:+ # Get L1 (overview) for directoriesoverview = client.overview(ctx.uri)print(f"Overview: {overview[:500]}...")else:- # Load L2 (content)+ # Load L2 (content) for filescontent = client.read(ctx.uri)print(f"File content: {content}")```@@ -495,24 +644,29 @@ for ctx in results.resources:```bash# Step 1: Searchcurl -X POST http://localhost:1933/api/v1/search/find \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{"query": "authentication"}'+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{"query": "authentication"}'-# Step 2: Read overview for a directory result-curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://resources/docs/auth/" \- -H "X-API-Key: your-key"+# Step 2: Read overview for directory result+curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://resources/docs/auth" \+ -H "X-API-Key: your-key"-# Step 3: Read full content for a file result+# Step 3: Read full content for file resultcurl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://resources/docs/auth.md" \- -H "X-API-Key: your-key"+ -H "X-API-Key: your-key"```### Get Related Resources-**Python SDK (Embedded / HTTP)**+**Python SDK**```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+results = client.find("OAuth implementation")for ctx in results.resources:@@ -527,9 +681,9 @@ for ctx in results.resources:**HTTP API**```bash-# Get relations for a resource-curl -X GET "http://localhost:1933/api/v1/relations?uri=viking://resources/docs/auth/" \- -H "X-API-Key: your-key"+# Get relations for resource+curl -X GET "http://localhost:1933/api/v1/relations?uri=viking://resources/docs/auth" \+ -H "X-API-Key: your-key"```## Best Practices@@ -537,6 +691,11 @@ curl -X GET "http://localhost:1933/api/v1/relations?uri=viking://resources/docs/### Use Specific Queries```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+# Good - specific queryresults = client.find("OAuth 2.0 authorization code flow implementation")@@ -547,29 +706,38 @@ results = client.find("auth")### Scope Your Searches```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+# Search in relevant scope for better resultsresults = client.find("error handling",- target_uri="viking://resources/my-project/"+ target_uri="viking://resources/my-project")```### Use Session Context for Conversations```python-# For conversational search, use session+import openviking as ovfrom openviking.message import TextPart+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()++# For conversational search, use sessionsession = client.session()session.add_message("user", [TextPart(text="I'm building a login page")])-# Search understands the context+# Search understands contextresults = client.search("best practices", session=session)```-### Related Documentation+## Related Documentation- [Resources](02-resources.md) - Resource management- [Sessions](05-sessions.md) - Session contextdiff --git a/docs/en/api/07-system.md b/docs/en/api/07-system.mdindex 03bedbab7..657437d7f 100644--- a/docs/en/api/07-system.md+++ b/docs/en/api/07-system.md@@ -4,17 +4,22 @@ OpenViking provides system health, observability, and debug APIs for monitoring## API Reference-### health()+### health-Basic health check endpoint. No authentication required.+#### 1. API Implementation Overview-**Python SDK (Embedded / HTTP)**+Basic health check endpoint. No authentication required. Returns service version and health status. If authentication is provided, also returns auth mode and identity information.-```python-# Check if system is healthy-if client.observer.is_healthy():- print("System OK")-```+**Code Entry Points**:+- `openviking/server/routers/system.py:health_check` - HTTP route+- `openviking_cli/client/sync_http.py:SyncHTTPClient.health` - SDK entry+- `crates/ov_cli/src/commands/system.rs` - CLI command++#### 2. Interface and Parameters++No parameters.++#### 3. Usage Examples**HTTP API**@@ -26,27 +31,57 @@ GET /healthcurl -X GET http://localhost:1933/health```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933")+client.initialize()++healthy = client.health()+print(f"Healthy: {healthy}")+```+**CLI**```bash-openviking health+ov system health```-**Response**+**Response Example**```json{"status": "ok","healthy": true,- "version": "0.1.x"+ "version": "0.1.x",+ "auth_mode": "api_key"}```----### ready()+### ready++#### 1. API Implementation Overview++Readiness probe for deployment environments. Checks AGFS, VectorDB, APIKeyManager, and Ollama (if configured) status. Returns 200 when all configured subsystems are ready and 503 otherwise. No authentication required (designed for Kubernetes probes).++**Code Entry Points**:+- `openviking/server/routers/system.py:readiness_check` - HTTP route++#### 2. Interface and Parameters++No parameters.-Readiness probe for deployment environments. Returns `200` when core subsystems are ready and `503` otherwise.+**Check Item Descriptions**:+- `agfs`: Whether Viking filesystem is accessible+- `vectordb`: Whether vector database is healthy+- `api_key_manager`: Whether API key manager is loaded+- `ollama`: Whether Ollama service is reachable (only if configured)++#### 3. Usage Examples**HTTP API**@@ -58,7 +93,7 @@ GET /readycurl -X GET http://localhost:1933/ready```-**Response**+**Response Example**```json{@@ -74,15 +109,22 @@ curl -X GET http://localhost:1933/ready----### status()+### status-Get system status including initialization state and user info.+#### 1. API Implementation Overview-**Python SDK (Embedded / HTTP)**+Get system status including initialization state and authenticated user info. `result.user` is the authenticated request's `user_id` (from API key or headers), not the process-level service default - clients can use this to resolve multi-tenant paths.-```python-print(client.observer.system())-```+**Code Entry Points**:+- `openviking/server/routers/system.py:system_status` - HTTP route+- `openviking_cli/client/sync_http.py:SyncHTTPClient.get_status` - SDK entry+- `crates/ov_cli/src/commands/system.rs` - CLI command++#### 2. Interface and Parameters++No parameters.++#### 3. Usage Examples**HTTP API**@@ -95,13 +137,20 @@ curl -X GET http://localhost:1933/api/v1/system/status \-H "X-API-Key: your-key"```+**Python SDK**++```python+status = client.get_status()+print(status)+```+**CLI**```bash-openviking status+ov system status```-**Response**+**Response Example**```json{@@ -116,26 +165,26 @@ openviking status----### wait_processed()+### wait_processed++#### 1. API Implementation Overview-Wait for all asynchronous processing (embedding, semantic generation) to complete.+Wait for all asynchronous processing (embedding, semantic generation) to complete. This method blocks until all queued tasks are processed or timeout occurs.++**Code Entry Points**:+- `openviking/server/routers/system.py:wait_processed` - HTTP route+- `openviking_cli/client/sync_http.py:SyncHTTPClient.wait_processed` - SDK entry+- `crates/ov_cli/src/commands/system.rs` - CLI command++#### 2. Interface and Parameters**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|-| timeout | float | No | None | Timeout in seconds |+| timeout | float | No | None | Timeout in seconds. None means wait indefinitely |-**Python SDK (Embedded / HTTP)**--```python-# Add resources-client.add_resource("./docs/")--# Wait for all processing to complete-status = client.wait_processed()-print(f"Processing complete: {status}")-```+#### 3. Usage Examples**HTTP API**@@ -152,13 +201,24 @@ curl -X POST http://localhost:1933/api/v1/system/wait \}'```+**Python SDK**++```python+# Add resources+client.add_resource("./docs/")++# Wait for all processing to complete+status = client.wait_processed(timeout=60.0)+print(f"Processing complete: {status}")+```+**CLI**```bash-openviking wait [--timeout 60]+ov system wait --timeout 60```-**Response**+**Response Example**```json{@@ -189,19 +249,21 @@ The observer API provides detailed component-level monitoring.### observer.queue-Get queue system status (embedding and semantic processing queues).+#### 1. API Implementation Overview-**Python SDK (Embedded / HTTP)**+Get queue system status (embedding and semantic processing queues). Shows pending, in-progress, completed, and error counts for each queue.-```python-print(client.observer.queue)-# Output:-# [queue] (healthy)-# Queue Pending In Progress Processed Errors Total-# Embedding 0 0 10 0 10-# Semantic 0 0 10 0 10-# TOTAL 0 0 20 0 20-```+**Code Entry Points**:+- `openviking/server/routers/observer.py:observer_queue` - HTTP route+- `openviking/service/debug_service.py:ObserverService.queue` - Core implementation+- `openviking/storage/observers/queue_observer.py` - Queue observer+- `crates/ov_cli/src/commands/observer.rs` - CLI command++#### 2. Interface and Parameters++No parameters.++#### 3. Usage Examples**HTTP API**@@ -214,13 +276,25 @@ curl -X GET http://localhost:1933/api/v1/observer/queue \-H "X-API-Key: your-key"```+**Python SDK**++```python+print(client.observer.queue)+# Output:+# [queue] (healthy)+# Queue Pending In Progress Processed Errors Total+# Embedding 0 0 10 0 10+# Semantic 0 0 10 0 10+# TOTAL 0 0 20 0 20+```+**CLI**```bash-openviking observer queue+ov observer queue```-**Response**+**Response Example**```json{@@ -229,7 +303,7 @@ openviking observer queue"name": "queue","is_healthy": true,"has_errors": false,- "status": "Queue Pending In Progress Processed Errors Total\nEmbedding 0 0 10 0 10\nSemantic 0 0 10 0 10\nTOTAL 0 0 20 0 20"+ "status": "Queue Pending In Progress Processed Errors Total\nEmbedding 0 0 10 0 10\nSemantic 0 0 10 0 10\nTOTAL 0 0 20 0 20"},"time": 0.1}@@ -239,22 +313,21 @@ openviking observer queue### observer.vikingdb+#### 1. API Implementation Overview+Get VikingDB status (collections, indexes, vector counts).-**Python SDK (Embedded / HTTP)**+**Code Entry Points**:+- `openviking/server/routers/observer.py:observer_vikingdb` - HTTP route+- `openviking/service/debug_service.py:ObserverService.vikingdb` - Core implementation+- `openviking/storage/observers/vikingdb_observer.py` - VikingDB observer+- `crates/ov_cli/src/commands/observer.rs` - CLI command-```python-print(client.observer.vikingdb())-# Output:-# [vikingdb] (healthy)-# Collection Index Count Vector Count Status-# context 1 55 OK-# TOTAL 1 55+#### 2. Interface and Parameters-# Access specific attributes-print(client.observer.vikingdb().is_healthy) # True-print(client.observer.vikingdb().status) # Status table string-```+No parameters.++#### 3. Usage Examples**HTTP API**@@ -267,13 +340,28 @@ curl -X GET http://localhost:1933/api/v1/observer/vikingdb \-H "X-API-Key: your-key"```+**Python SDK**++```python+print(client.observer.vikingdb())+# Output:+# [vikingdb] (healthy)+# Collection Index Count Vector Count Status+# context 1 55 OK+# TOTAL 1 55++# Access specific attributes+print(client.observer.vikingdb().is_healthy) # True+print(client.observer.vikingdb().status) # Status table string+```+**CLI**```bash-openviking observer vikingdb+ov observer vikingdb```-**Response**+**Response Example**```json{@@ -282,7 +370,7 @@ openviking observer vikingdb"name": "vikingdb","is_healthy": true,"has_errors": false,- "status": "Collection Index Count Vector Count Status\ncontext 1 55 OK\nTOTAL 1 55"+ "status": "Collection Index Count Vector Count Status\ncontext 1 55 OK\nTOTAL 1 55"},"time": 0.1}@@ -292,19 +380,21 @@ openviking observer vikingdb### observer.models-Get aggregated model subsystem status (VLM, embedding, rerank).+#### 1. API Implementation Overview-**Python SDK (Embedded / HTTP)**+Get aggregated model subsystem status (VLM, embedding, rerank). Checks if each model provider is healthy and available.-```python-print(client.observer.models)-# Output:-# [models] (healthy)-# provider_model healthy detail-# dense_embedding yes ...-# rerank yes ...-# vlm yes ...-```+**Code Entry Points**:+- `openviking/server/routers/observer.py:observer_models` - HTTP route+- `openviking/service/debug_service.py:ObserverService.models` - Core implementation+- `openviking/storage/observers/models_observer.py` - Models observer+- `crates/ov_cli/src/commands/observer.rs` - CLI command++#### 2. Interface and Parameters++No parameters.++#### 3. Usage Examples**HTTP API**@@ -317,13 +407,25 @@ curl -X GET http://localhost:1933/api/v1/observer/models \-H "X-API-Key: your-key"```+**Python SDK**++```python+print(client.observer.models)+# Output:+# [models] (healthy)+# provider_model healthy detail+# dense_embedding yes ...+# rerank yes ...+# vlm yes ...+```+**CLI**```bash-openviking observer models+ov observer models```-**Response**+**Response Example**```json{@@ -332,7 +434,7 @@ openviking observer models"name": "models","is_healthy": true,"has_errors": false,- "status": "provider_model healthy detail\ndense_embedding yes ...\nrerank yes ...\nvlm yes ..."+ "status": "provider_model healthy detail\ndense_embedding yes ...\nrerank yes ...\nvlm yes ..."},"time": 0.1}@@ -340,77 +442,57 @@ openviking observer models----Additional HTTP observer endpoints are also available:+### observer.lock-- `GET /api/v1/observer/lock`-- `GET /api/v1/observer/retrieval`+#### 1. API Implementation Overview-### observer.system+Get distributed lock system status.-Get overall system status including all components.+**Code Entry Points**:+- `openviking/server/routers/observer.py:observer_lock` - HTTP route+- `openviking/service/debug_service.py:ObserverService.lock` - Core implementation+- `openviking/storage/observers/lock_observer.py` - Lock observer+- `crates/ov_cli/src/commands/observer.rs` - CLI command-**Python SDK (Embedded / HTTP)**+#### 2. Interface and Parameters-```python-print(client.observer.system())-# Output:-# [queue] (healthy)-# ...-#-# [vikingdb] (healthy)-# ...-#-# [models] (healthy)-# ...-#-# [system] (healthy)-```+No parameters.++#### 3. Usage Examples**HTTP API**```-GET /api/v1/observer/system+GET /api/v1/observer/lock``````bash-curl -X GET http://localhost:1933/api/v1/observer/system \+curl -X GET http://localhost:1933/api/v1/observer/lock \-H "X-API-Key: your-key"```+**Python SDK**++```python+print(client.observer.lock)+```+**CLI**```bash-openviking observer system+ov observer transaction```-**Response**+**Response Example**```json{"status": "ok","result": {+ "name": "lock","is_healthy": true,- "errors": [],- "components": {- "queue": {- "name": "queue",- "is_healthy": true,- "has_errors": false,- "status": "..."- },- "vikingdb": {- "name": "vikingdb",- "is_healthy": true,- "has_errors": false,- "status": "..."- },- "vlm": {- "name": "vlm",- "is_healthy": true,- "has_errors": false,- "status": "..."- }- }+ "has_errors": false,+ "status": "..."},"time": 0.1}@@ -418,37 +500,57 @@ openviking observer system----### is_healthy()+### observer.retrieval-Quick health check for the entire system.+#### 1. API Implementation Overview-**Python SDK (Embedded / HTTP)**+Get retrieval quality metrics.-```python-if client.observer.is_healthy():- print("System OK")-else:- print(client.observer.system())-```+**Code Entry Points**:+- `openviking/server/routers/observer.py:observer_retrieval` - HTTP route+- `openviking/service/debug_service.py:ObserverService.retrieval` - Core implementation+- `openviking/storage/observers/retrieval_observer.py` - Retrieval observer+- `crates/ov_cli/src/commands/observer.rs` - CLI command++#### 2. Interface and Parameters++No parameters.++#### 3. Usage Examples**HTTP API**```-GET /api/v1/debug/health+GET /api/v1/observer/retrieval``````bash-curl -X GET http://localhost:1933/api/v1/debug/health \+curl -X GET http://localhost:1933/api/v1/observer/retrieval \-H "X-API-Key: your-key"```-**Response**+**Python SDK**++```python+print(client.observer.retrieval)+```++**CLI**++```bash+ov observer retrieval+```++**Response Example**```json{"status": "ok","result": {- "healthy": true+ "name": "retrieval",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."},"time": 0.1}@@ -456,28 +558,101 @@ curl -X GET http://localhost:1933/api/v1/debug/health \----## Data Structures+### observer.system++#### 1. API Implementation Overview++Get overall system status, including all components (queue, vikingdb, models, lock, retrieval).++**Code Entry Points**:+- `openviking/server/routers/observer.py:observer_system` - HTTP route+- `openviking/service/debug_service.py:ObserverService.system` - Core implementation+- `crates/ov_cli/src/commands/observer.rs` - CLI command++#### 2. Interface and Parameters++No parameters.++#### 3. Usage Examples++**HTTP API**++```+GET /api/v1/observer/system+```-### ComponentStatus+```bash+curl -X GET http://localhost:1933/api/v1/observer/system \+ -H "X-API-Key: your-key"+```-Status information for a single component.+**Python SDK**-| Field | Type | Description |-|-------|------|-------------|-| name | str | Component name |-| is_healthy | bool | Whether the component is healthy |-| has_errors | bool | Whether the component has errors |-| status | str | Status table string |+```python+print(client.observer.system())+# Output:+# [queue] (healthy)+# ...+#+# [vikingdb] (healthy)+# ...+#+# [models] (healthy)+# ...+#+# [system] (healthy)+```-### SystemStatus+**CLI**-Overall system status including all components.+```bash+ov observer system+```++**Response Example**-| Field | Type | Description |-|-------|------|-------------|-| is_healthy | bool | Whether the entire system is healthy |-| components | Dict[str, ComponentStatus] | Status of each component |-| errors | List[str] | List of error messages |+```json+{+ "status": "ok",+ "result": {+ "is_healthy": true,+ "errors": [],+ "components": {+ "queue": {+ "name": "queue",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."+ },+ "vikingdb": {+ "name": "vikingdb",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."+ },+ "models": {+ "name": "models",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."+ },+ "lock": {+ "name": "lock",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."+ },+ "retrieval": {+ "name": "retrieval",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."+ }+ }+ },+ "time": 0.1+}+```---diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex 337e7648a..ba08c8eb4 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -25,12 +25,56 @@ For `/api/v1/admin/*`, trusted mode also permits requests with no explicit ident| Regenerate user key | Y | Y (own account) | N || Change user role | Y | N | N |+## CLI `--sudo` Option++When using the `ov` CLI to perform admin operations requiring ROOT privileges, you can use the `--sudo` option. This option uses the `root_api_key` from your `~/.openviking/ovcli.conf` instead of the regular `api_key`.++### Configuration Requirements++Configure `root_api_key` in `~/.openviking/ovcli.conf`:++```json+{+ "url": "http://localhost:1933",+ "api_key": "alice-user-key",+ "root_api_key": "your-root-api-key",+ ...+}+```++### Commands Supporting `--sudo`++- `ov --sudo admin` - Account and user management+- `ov --sudo system` - System utility commands+- `ov --sudo reindex` - Rebuild indexes++### Usage Limitations++- `--sudo` only works with admin commands - using it with regular data commands will error+- Must have `root_api_key` configured to use `--sudo`+## API Reference-### create_account()+### create_account++#### 1. API Implementation OverviewCreate a new workspace with its first admin user.+**Processing Flow:**+1. Verify requester has ROOT privileges+2. Use API Key Manager to create account and initial admin user+3. Initialize account-level directory structure+4. Initialize admin user's personal directory+5. Return account info and user key (not in trusted mode)++**Code Entry Points:**+- `openviking/server/routers/admin.py:create_account` - HTTP route+- `openviking/server/api_keys/new.py:APIKeyManager.create_account` - Core implementation+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_create_account` - Python SDK++#### 2. Interface and Parameters+**Parameters**| Parameter | Type | Required | Default | Description |@@ -40,6 +84,12 @@ Create a new workspace with its first admin user.| isolate_user_scope_by_agent | bool | No | false | Further isolate user scope by agent || isolate_agent_scope_by_user | bool | No | false | Further isolate agent scope by user |+**Notes:**+- In `trusted` mode, `user_key` is omitted from the response+- `isolate_user_scope_by_agent` and `isolate_agent_scope_by_user` are only available via HTTP API, not in Python SDK or CLI++#### 3. Usage Examples+**HTTP API**```@@ -52,7 +102,9 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \-H "X-API-Key: <root-key>" \-d '{"account_id": "acme",- "admin_user_id": "alice"+ "admin_user_id": "alice",+ "isolate_user_scope_by_agent": true,+ "isolate_agent_scope_by_user": false}'```@@ -100,13 +152,28 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \}'```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-key>")+client.initialize()++result = client.admin_create_account("acme", "alice")+print(f"Account created: {result['account_id']}")+print(f"Admin user: {result['admin_user_id']}")+print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")+```+**CLI**```bash-openviking admin create-account acme --admin alice+# Requires ROOT privileges, use --sudo+ov --sudo admin create-account acme --admin alice```-**Response**+**Response Example**```json{@@ -114,7 +181,9 @@ openviking admin create-account acme --admin alice"result": {"account_id": "acme","admin_user_id": "alice",- "user_key": "7f3a9c1e..."+ "user_key": "7f3a9c1e...",+ "isolate_user_scope_by_agent": true,+ "isolate_agent_scope_by_user": false},"time": 0.1}@@ -124,10 +193,28 @@ In `trusted` mode, the same response omits `user_key`.----### list_accounts()+### list_accounts++#### 1. API Implementation OverviewList all workspaces (ROOT only).+**Processing Flow:**+1. Verify requester has ROOT privileges+2. Call API Key Manager to get all accounts+3. Return list with account ID, creation time, and user count++**Code Entry Points:**+- `openviking/server/routers/admin.py:list_accounts` - HTTP route+- `openviking/server/api_keys/new.py:APIKeyManager.get_accounts` - Core implementation+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_list_accounts` - Python SDK++#### 2. Interface and Parameters++No parameters.++#### 3. Usage Examples+**HTTP API**```@@ -139,13 +226,27 @@ curl -X GET http://localhost:1933/api/v1/admin/accounts \-H "X-API-Key: <root-key>"```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-key>")+client.initialize()++accounts = client.admin_list_accounts()+for account in accounts:+ print(f"Account: {account['account_id']}, created: {account['created_at']}, users: {account['user_count']}")+```+**CLI**```bash-openviking admin list-accounts+# Requires ROOT privileges, use --sudo+ov --sudo admin list-accounts```-**Response**+**Response Example**```json{@@ -160,16 +261,37 @@ openviking admin list-accounts----### delete_account()+### delete_account++#### 1. API Implementation OverviewDelete a workspace and all associated users and data (ROOT only).+**Processing Flow:**+1. Verify requester has ROOT privileges+2. Cascade delete all AGFS data for the account (user/, agent/, session/, resources/)+3. Cascade delete all vector DB records for the account+4. Finally delete account metadata and all user keys++**Code Entry Points:**+- `openviking/server/routers/admin.py:delete_account` - HTTP route+- `openviking/server/api_keys/new.py:APIKeyManager.delete_account` - Core implementation+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_delete_account` - Python SDK++#### 2. Interface and Parameters+**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| account_id | str | Yes | - | Workspace ID to delete |+**Notes:**+- Delete operation is irreversible and cascades to all account data+- If some data fails to delete, warnings are logged and deletion continues++#### 3. Usage Examples+**HTTP API**```@@ -181,19 +303,32 @@ curl -X DELETE http://localhost:1933/api/v1/admin/accounts/acme \-H "X-API-Key: <root-key>"```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-key>")+client.initialize()++result = client.admin_delete_account("acme")+print(f"Account deleted: {result['deleted']}")+```+**CLI**```bash-openviking admin delete-account acme+# Requires ROOT privileges, use --sudo+ov --sudo admin delete-account acme```-**Response**+**Response Example**```json{"status": "ok","result": {- "account_id": "acme"+ "deleted": true},"time": 0.1}@@ -201,10 +336,25 @@ openviking admin delete-account acme----### register_user()+### register_user++#### 1. API Implementation OverviewRegister a new user in a workspace.+**Processing Flow:**+1. Verify requester has ROOT privileges or is an ADMIN of the account+2. Call API Key Manager to register new user+3. Initialize new user's personal directory+4. Return user info and user key (not in trusted mode)++**Code Entry Points:**+- `openviking/server/routers/admin.py:register_user` - HTTP route+- `openviking/server/api_keys/new.py:APIKeyManager.register_user` - Core implementation+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_register_user` - Python SDK++#### 2. Interface and Parameters+**Parameters**| Parameter | Type | Required | Default | Description |@@ -213,6 +363,13 @@ Register a new user in a workspace.| user_id | str | Yes | - | User ID || role | str | No | "user" | Role: "admin" or "user" |+**Notes:**+- In `trusted` mode, `user_key` is omitted from the response+- ADMIN can only register users in their own account+- Only ROOT can set role to "admin" for new users++#### 3. Usage Examples+**HTTP API**```@@ -229,13 +386,30 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \}'```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-or-admin-key>")+client.initialize()++result = client.admin_register_user("acme", "bob", role="user")+print(f"User registered: {result['user_id']}")+print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")+```+**CLI**```bash-openviking admin register-user acme bob --role user+# Either ROOT or account ADMIN can execute+# If using regular user's api_key who is an ADMIN of acme:+ov admin register-user acme bob --role user+# If using root_api_key (--sudo):+ov --sudo admin register-user acme bob --role user```-**Response**+**Response Example**```json{@@ -251,15 +425,39 @@ openviking admin register-user acme bob --role user----### list_users()+### list_users++#### 1. API Implementation OverviewList all users in a workspace.+**Processing Flow:**+1. Verify requester has ROOT privileges or is an ADMIN of the account+2. Call API Key Manager to get users list+3. Apply optional filters (name, role) and pagination limit+4. Return users list (trusted mode omits user_key)++**Code Entry Points:**+- `openviking/server/routers/admin.py:list_users` - HTTP route+- `openviking/server/api_keys/new.py:APIKeyManager.get_users` - Core implementation+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_list_users` - Python SDK++#### 2. Interface and Parameters+**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| account_id | str | Yes | - | Workspace ID |+| limit | int | No | 100 | Maximum number of users to return |+| name | str | No | null | Filter by user ID (prefix match) |+| role | str | No | null | Filter by role |++**Notes:**+- ADMIN can only list users in their own account+- In `trusted` mode, `user_key` is omitted from the response++#### 3. Usage Examples**HTTP API**@@ -268,17 +466,39 @@ GET /api/v1/admin/accounts/{account_id}/users``````bash+# List all userscurl -X GET http://localhost:1933/api/v1/admin/accounts/acme/users \-H "X-API-Key: <root-or-admin-key>"++# With filters+curl -X GET "http://localhost:1933/api/v1/admin/accounts/acme/users?role=admin&limit=50" \+ -H "X-API-Key: <root-or-admin-key>"+```++**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-or-admin-key>")+client.initialize()++users = client.admin_list_users("acme")+for user in users:+ print(f"User: {user['user_id']}, role: {user['role']}")```**CLI**```bash-openviking admin list-users acme+# Either ROOT or account ADMIN can execute+# If using regular user's api_key who is an ADMIN of acme:+ov admin list-users acme+# If using root_api_key (--sudo):+ov --sudo admin list-users acme```-**Response**+**Response Example**```json{@@ -293,10 +513,24 @@ openviking admin list-users acme----### remove_user()+### remove_user++#### 1. API Implementation OverviewRemove a user from a workspace. The user's API key is deleted immediately.+**Processing Flow:**+1. Verify requester has ROOT privileges or is an ADMIN of the account+2. Call API Key Manager to delete user and their API key+3. Return deletion confirmation++**Code Entry Points:**+- `openviking/server/routers/admin.py:remove_user` - HTTP route+- `openviking/server/api_keys/new.py:APIKeyManager.remove_user` - Core implementation+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_remove_user` - Python SDK++#### 2. Interface and Parameters+**Parameters**| Parameter | Type | Required | Default | Description |@@ -304,6 +538,12 @@ Remove a user from a workspace. The user's API key is deleted immediately.| account_id | str | Yes | - | Workspace ID || user_id | str | Yes | - | User ID to remove |+**Notes:**+- ADMIN can only remove users in their own account+- Cannot delete the last admin user of an account++#### 3. Usage Examples+**HTTP API**```@@ -315,20 +555,35 @@ curl -X DELETE http://localhost:1933/api/v1/admin/accounts/acme/users/bob \-H "X-API-Key: <root-or-admin-key>"```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-or-admin-key>")+client.initialize()++result = client.admin_remove_user("acme", "bob")+print(f"User deleted: {result['deleted']}")+```+**CLI**```bash-openviking admin remove-user acme bob+# Either ROOT or account ADMIN can execute+# If using regular user's api_key who is an ADMIN of acme:+ov admin remove-user acme bob+# If using root_api_key (--sudo):+ov --sudo admin remove-user acme bob```-**Response**+**Response Example**```json{"status": "ok","result": {- "account_id": "acme",- "user_id": "bob"+ "deleted": true},"time": 0.1}@@ -336,17 +591,37 @@ openviking admin remove-user acme bob----### set_role()+### set_role++#### 1. API Implementation OverviewChange a user's role (ROOT only).+**Processing Flow:**+1. Verify requester has ROOT privileges+2. Call API Key Manager to update user role+3. Return updated user info++**Code Entry Points:**+- `openviking/server/routers/admin.py:set_user_role` - HTTP route+- `openviking/server/api_keys/new.py:APIKeyManager.set_role` - Core implementation+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_set_role` - Python SDK++#### 2. Interface and Parameters+**Parameters**| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| account_id | str | Yes | - | Workspace ID || user_id | str | Yes | - | User ID |-| role | str | Yes | - | New role: "admin" or "user" |+| role | str | Yes | - | New role: "admin", "user", or "root" |++**Notes:**+- Only ROOT can change user roles+- Role can be set to "admin", "user", or "root"++#### 3. Usage Examples**HTTP API**@@ -361,13 +636,26 @@ curl -X PUT http://localhost:1933/api/v1/admin/accounts/acme/users/bob/role \-d '{"role": "admin"}'```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-key>")+client.initialize()++result = client.admin_set_role("acme", "bob", "admin")+print(f"User: {result['user_id']}, new role: {result['role']}")+```+**CLI**```bash-openviking admin set-role acme bob admin+# Requires ROOT privileges, use --sudo+ov --sudo admin set-role acme bob admin```-**Response**+**Response Example**```json{@@ -383,10 +671,25 @@ openviking admin set-role acme bob admin----### regenerate_key()+### regenerate_key++#### 1. API Implementation OverviewRegenerate a user's API key. The old key is immediately invalidated.+**Processing Flow:**+1. Verify requester has ROOT privileges or is an ADMIN of the account+2. Call API Key Manager to regenerate user key+3. Old key is immediately invalidated+4. Return new user key++**Code Entry Points:**+- `openviking/server/routers/admin.py:regenerate_key` - HTTP route+- `openviking/server/api_keys/new.py:APIKeyManager.regenerate_key` - Core implementation+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_regenerate_key` - Python SDK++#### 2. Interface and Parameters+**Parameters**| Parameter | Type | Required | Default | Description |@@ -394,6 +697,12 @@ Regenerate a user's API key. The old key is immediately invalidated.| account_id | str | Yes | - | Workspace ID || user_id | str | Yes | - | User ID |+**Notes:**+- ADMIN can only regenerate keys for users in their own account+- Old key is immediately invalidated, clients using it need to be updated++#### 3. Usage Examples+**HTTP API**```@@ -406,13 +715,29 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users/bob/key \-H "X-API-Key: <root-or-admin-key>"```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-or-admin-key>")+client.initialize()++result = client.admin_regenerate_key("acme", "bob")+print(f"New user key: {result['user_key']}")+```+**CLI**```bash-openviking admin regenerate-key acme bob+# Either ROOT or account ADMIN can execute+# If using regular user's api_key who is an ADMIN of acme:+ov admin regenerate-key acme bob+# If using root_api_key (--sudo):+ov --sudo admin regenerate-key acme bob```-**Response**+**Response Example**```json{@@ -431,28 +756,30 @@ openviking admin regenerate-key acme bob### Typical Admin Workflow```bash-# Step 1: ROOT creates workspace with alice as first admin-openviking admin create-account acme --admin alice+# Step 1: ROOT creates workspace with alice as first admin (requires --sudo)+ov --sudo admin create-account acme --admin alice# Returns alice's user_key# Step 2: alice (admin) registers regular user bob-openviking admin register-user acme bob --role user+# Configure api_key in config file to alice's user_key, no --sudo needed+ov admin register-user acme bob --role user# Returns bob's user_key# Step 3: List all users in the account-openviking admin list-users acme+ov admin list-users acme-# Step 4: ROOT promotes bob to admin-openviking admin set-role acme bob admin+# Step 4: ROOT promotes bob to admin (requires --sudo)+ov --sudo admin set-role acme bob admin# Step 5: bob lost their key, regenerate (old key immediately invalidated)-openviking admin regenerate-key acme bob+# alice as admin can do this, no --sudo needed+ov admin regenerate-key acme bob# Step 6: Remove user-openviking admin remove-user acme bob+ov admin remove-user acme bob-# Step 7: Delete entire workspace-openviking admin delete-account acme+# Step 7: Delete entire workspace (requires --sudo)+ov --sudo admin delete-account acme```### HTTP API Equivalentdiff --git a/docs/zh/api/04-skills.md b/docs/zh/api/04-skills.mdindex 3f2393b98..58bddc317 100644--- a/docs/zh/api/04-skills.md+++ b/docs/zh/api/04-skills.md@@ -1,179 +1,227 @@# 技能-技能是智能体可以调用的能力。本指南介绍如何添加和管理技能。+技能是智能体可以调用的能力定义。本模块提供技能的添加和管理功能。-## API 参考+## 核心概念-### add_skill()+### 技能类型-向知识库添加技能。+OpenViking 支持多种技能定义格式:-**参数**+1. **结构化技能数据**:包含 name、description、content 等字段的字典+2. **SKILL.md 文件**:带有 YAML frontmatter 的 Markdown 文件+3. **MCP Tool 格式**:自动检测并转换为 OpenViking 技能格式-| 参数 | 类型 | 必填 | 默认值 | 说明 |-|------|------|------|--------|------|-| data | Any | 是 | - | 技能数据。裸 HTTP 支持结构化数据或原始 `SKILL.md` 内容,不支持直接传宿主机路径 |-| temp_file_id | str | 否 | None | `POST /api/v1/resources/temp_upload` 返回的上传 ID,用于裸 HTTP 导入本地文件 |-| wait | bool | 否 | False | 等待向量化完成 |-| timeout | float | 否 | None | 超时时间(秒) |+### 技能存储结构-**本地技能文件如何处理**+技能存储在 `viking://agent/skills/` 路径下:-- Python SDK 和 CLI 可以直接接收本地 `SKILL.md` 文件或目录。处于 HTTP 模式时,它们会先自动上传,再调用服务端 API。-- 裸 HTTP 调用有三种推荐方式:- - 在 `data` 中直接传结构化 skill 数据- - 在 `data` 中直接传原始 `SKILL.md` 内容- - 先调用 `POST /api/v1/resources/temp_upload` 上传本地 `SKILL.md` 文件,再调用 `POST /api/v1/skills` 并传入 `temp_file_id`- - 先把本地 skill 目录打成 `.zip`,上传该压缩包,再调用 `POST /api/v1/skills` 并传入 `temp_file_id`-- `POST /api/v1/skills` 不接受在 `data` 中直接传宿主机本地路径。+```+viking://agent/skills/++-- search-web/+| +-- .abstract.md # L0:简要描述+| +-- .overview.md # L1:参数和使用概览+| +-- SKILL.md # L2:完整文档+| +-- [auxiliary files] # 其他辅助文件++-- calculator/+| +-- .abstract.md+| +-- .overview.md+| +-- SKILL.md++-- ...+```-**支持的数据格式**+### SKILL.md 格式-1. **字典(技能格式)**:-```python-{- "name": "skill-name",- "description": "Skill description",- "content": "Full markdown content",- "allowed_tools": ["Tool1", "Tool2"], # 可选- "tags": ["tag1", "tag2"] # 可选-}+技能可以使用带有 YAML frontmatter 的 SKILL.md 文件来定义:++```markdown+---+name: skill-name+description: Brief description of the skill+allowed_tools:+ - Tool1+ - Tool2+tags:+ - tag1+ - tag2+---++# Skill Name++Full skill documentation in Markdown format.++## Parameters+- **param1** (type, required): Description+- **param2** (type, optional): Description++## Usage+When and how to use this skill.++## Examples+Concrete examples of skill invocation.```-2. **字典(MCP Tool 格式)** - 自动检测并转换:+**必填字段**:++| 字段 | 类型 | 说明 |+|------|------|------|+| name | str | 技能名称(建议使用 kebab-case)|+| description | str | 简要描述 |++**可选字段**:++| 字段 | 类型 | 说明 |+|------|------|------|+| allowed_tools | List[str] | 该技能可使用的工具 |+| tags | List[str] | 用于分类的标签 |++### MCP 格式自动转换++OpenViking 会自动检测并将 MCP Tool 定义转换为技能格式。++**检测规则**:如果字典包含 `inputSchema` 字段,则被视为 MCP 格式。++**转换过程**:+1. 名称转换为 kebab-case+2. 描述保持不变+3. 从 `inputSchema.properties` 中提取参数+4. 从 `inputSchema.required` 中标记必填字段+5. 生成 Markdown 内容++**转换示例**:++输入(MCP 格式):```python{- "name": "tool_name",- "description": "Tool description",+ "name": "search_web",+ "description": "Search the web","inputSchema": {"type": "object",- "properties": {...},- "required": [...]+ "properties": {+ "query": {+ "type": "string",+ "description": "Search query"+ },+ "limit": {+ "type": "integer",+ "description": "Max results"+ }+ },+ "required": ["query"]}}```-3. **字符串(SKILL.md 内容)**:+输出(技能格式):```python-"""----name: skill-name-description: Skill description+{+ "name": "search-web",+ "description": "Search the web",+ "content": """---+name: search-web+description: Search the web----# Skill Content-"""-```+# search-web-4. **路径(文件或目录)**:- - 单个文件:指向 `SKILL.md` 文件的路径- - 目录:指向包含 `SKILL.md` 的目录路径(辅助文件会一并包含)+Search the web-**Python SDK (Embedded / HTTP)**+## Parameters-```python-skill = {- "name": "search-web",- "description": "Search the web for current information",- "content": """-# search-web+- **query** (string) (required): Search query+- **limit** (integer) (optional): Max results-Search the web for current information.+## Usage-## Parameters-- **query** (string, required): Search query-- **limit** (integer, optional): Max results, default 10+This tool wraps the MCP tool `search-web`. Call this when the user needs functionality matching the description above."""}--result = client.add_skill(skill)-print(f"Added: {result['root_uri']}")```-**HTTP API**+## API 参考-```-POST /api/v1/skills-```+### add_skill-```bash-curl -X POST http://localhost:1933/api/v1/skills \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "data": {- "name": "search-web",- "description": "Search the web for current information",- "content": "# search-web\n\nSearch the web for current information.\n\n## Parameters\n- **query** (string, required): Search query\n- **limit** (integer, optional): Max results, default 10"- }- }'-```+向知识库添加技能。-**CLI**+#### 1. API 实现介绍-```bash-openviking add-skill ./my-skill/ [--wait]-```+技能是一种特殊的资源,用于定义智能体可以执行的操作或工具。-**响应**+**处理流程**:+1. 接收技能数据或上传的临时文件+2. 检测数据格式(结构化数据、SKILL.md 内容、MCP 格式)+3. 解析技能定义+4. 存储到 `viking://agent/skills/` 路径下+5. 如指定 `wait=True`,等待向量化完成-```json-{- "status": "ok",- "result": {- "status": "success",- "root_uri": "viking://agent/skills/search-web/",- "uri": "viking://agent/skills/search-web/",- "name": "search-web",- "auxiliary_files": 0- },- "time": 0.1-}-```+**代码入口**:+- `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:ResourceService.add_skill` - 核心服务实现+- `crates/ov_cli/src/handlers.rs:handle_add_skill` - CLI 处理-**同步处理错误**+#### 2. 接口和参数说明-如果 skill 解析或处理同步失败,裸 HTTP 会返回标准错误 envelope,并使用非 2xx HTTP 状态码:+**参数**:-```json-{- "status": "error",- "error": {- "code": "PROCESSING_ERROR",- "message": "Skill parse error: invalid skill metadata"- }-}-```+| 参数 | 类型 | 必填 | 默认值 | 说明 |+|------|------|------|--------|------|+| data | Any | 否 | - | 内联技能内容或结构化数据。与 `temp_file_id` 二选一 |+| temp_file_id | string | 否 | - | 临时上传文件 ID(通过 `temp_upload` 获取)。与 `data` 二选一 |+| wait | bool | 否 | False | 是否等待技能处理完成 |+| timeout | float | 否 | None | 超时时间(秒),仅 `wait=True` 时生效 |+| telemetry | TelemetryRequest | 否 | False | 是否返回遥测数据 |-Python HTTP SDK 会把该响应映射为对应异常。+**补充说明**:-**示例:从 MCP Tool 添加**+- **本地文件处理**:+ - Python SDK 和 CLI 可以直接接收本地 `SKILL.md` 文件或目录。处于 HTTP 模式时,它们会先自动上传,再调用服务端 API。+ - 裸 HTTP 调用有三种推荐方式:+ 1. 在 `data` 中直接传结构化 skill 数据+ 2. 在 `data` 中直接传原始 `SKILL.md` 内容+ 3. 先调用 `POST /api/v1/resources/temp_upload` 上传本地 `SKILL.md` 文件/zip 目录,再调用 `POST /api/v1/skills` 并传入 `temp_file_id`+ - `POST /api/v1/skills` 不接受在 `data` 中直接传宿主机本地路径。-**Python SDK (Embedded / HTTP)**+- **支持的数据格式**:+ 1. **字典(技能格式)**:包含 `name`、`description`、`content` 等字段+ 2. **字典(MCP Tool 格式)**:包含 `name`、`description`、`inputSchema` 字段,会自动检测并转换+ 3. **字符串(SKILL.md 内容)**:完整的 SKILL.md 内容+ 4. **路径(文件或目录)**:指向 `SKILL.md` 文件的路径,或包含 `SKILL.md` 的目录路径(辅助文件会一并包含)-```python-# MCP tool 格式会被自动检测并转换-mcp_tool = {- "name": "calculator",- "description": "Perform mathematical calculations",- "inputSchema": {- "type": "object",- "properties": {- "expression": {- "type": "string",- "description": "Mathematical expression to evaluate"- }- },- "required": ["expression"]- }-}+#### 3. 使用示例-result = client.add_skill(mcp_tool)-print(f"Added: {result['uri']}")-```+**HTTP API**:-**HTTP API**+```+POST /api/v1/skills+Content-Type: application/json+``````bash+# 使用内联结构化数据+curl -X POST http://localhost:1933/api/v1/skills \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "data": {+ "name": "search-web",+ "description": "Search the web for current information",+ "content": "# search-web\n\nSearch the web for current information.\n\n## Parameters\n- **query** (string, required): Search query\n- **limit** (integer, optional): Max results, default 10"+ },+ "wait": true+ }'++# 使用内联 SKILL.md 内容+curl -X POST http://localhost:1933/api/v1/skills \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "data": "---\nname: my-skill\ndescription: My custom skill\n---\n\n# My Skill\n\nSkill content here."+ }'++# 使用 MCP Tool 格式(自动检测并转换)curl -X POST http://localhost:1933/api/v1/skills \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \@@ -193,35 +241,15 @@ curl -X POST http://localhost:1933/api/v1/skills \}}}'-```--**示例:从 SKILL.md 文件添加**--**Python SDK (Embedded / HTTP)**--```python-# 从文件路径添加-result = client.add_skill("./skills/search-web/SKILL.md")-print(f"Added: {result['uri']}")-# 从目录添加(包含辅助文件)-result = client.add_skill("./skills/code-runner/")-print(f"Added: {result['uri']}")-print(f"Auxiliary files: {result['auxiliary_files']}")-```--**HTTP API**--```bash-# 第一步:上传本地 SKILL.md 文件+# 使用本地文件(需先使用 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=@./skills/search-web/SKILL.md' \+ -F "file=@./skills/my-skill.json" \| jq -r '.result.temp_file_id')-# 第二步:添加上传后的技能文件curl -X POST http://localhost:1933/api/v1/skills \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \@@ -230,64 +258,158 @@ curl -X POST http://localhost:1933/api/v1/skills \}"```-如果是本地 skill 目录,先把目录打成 `.zip`,上传该压缩包,再用返回的 `temp_file_id` 调用同一个 `POST /api/v1/skills` 请求即可。+**Python SDK**:----+```python+import openviking as ov-## SKILL.md 格式+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()-技能可以使用带有 YAML frontmatter 的 SKILL.md 文件来定义。+# 方式 1:使用结构化技能数据+skill = {+ "name": "search-web",+ "description": "Search the web for current information",+ "content": """# search-web-**结构**+Search the web for current information.-```markdown-----name: skill-name-description: Brief description of the skill-allowed-tools:- - Tool1- - Tool2-tags:- - tag1- - tag2----+## Parameters+- **query** (string, required): Search query+- **limit** (integer, optional): Max results, default 10+"""+}+result = client.add_skill(skill)+print(f"Added: {result['root_uri']}")-# Skill Name+# 方式 2:使用 MCP Tool 格式(自动检测并转换)+mcp_tool = {+ "name": "calculator",+ "description": "Perform mathematical calculations",+ "inputSchema": {+ "type": "object",+ "properties": {+ "expression": {+ "type": "string",+ "description": "Mathematical expression to evaluate"+ }+ },+ "required": ["expression"]+ }+}+result = client.add_skill(mcp_tool)+print(f"Added: {result['uri']}")-Full skill documentation in Markdown format.+# 方式 3:从本地 SKILL.md 文件添加+result = client.add_skill("./skills/search-web/SKILL.md")+print(f"Added: {result['uri']}")-## Parameters-- **param1** (type, required): Description-- **param2** (type, optional): Description+# 方式 4:从包含 SKILL.md 的目录添加(辅助文件会一并包含)+result = client.add_skill("./skills/code-runner/")+print(f"Added: {result['uri']}")+print(f"Auxiliary files: {result['auxiliary_files']}")-## Usage-When and how to use this skill.+# 等待处理完成+result = client.add_skill("./skills/my-skill/", wait=True)+client.wait_processed()+```-## Examples-Concrete examples of skill invocation.+**CLI**:++```bash+# 添加技能(从文件或目录)+ov add-skill ./skills/my-skill.json+ov add-skill ./skills/search-web/SKILL.md+ov add-skill ./skills/code-runner/++# 等待处理完成+ov add-skill ./skills/my-skill/ --wait++# 使用 JSON 输出格式+ov add-skill ./skills/my-skill/ -o json```-**必填字段**+**响应示例**:-| 字段 | 类型 | 说明 |-|------|------|------|-| name | str | 技能名称(建议使用 kebab-case) |-| description | str | 简要描述 |+**HTTP API 响应 (JSON)**:+```json+{+ "status": "ok",+ "result": {+ "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+ }+ },+ "telemetry": {+ "operation_id": "550e8400-e29b-41d4-a716-446655440000"+ },+ "time": 0.1+}+```++**CLI 响应(默认表格格式)**:+```+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+```++**CLI 响应(JSON 格式,使用 -o json)**:+```json+{+ "status": "success",+ "root_uri": "viking://agent/skills/my-skill",+ "uri": "viking://agent/skills/my-skill",+ "name": "my-skill",+ "auxiliary_files": 2+}+```-**可选字段**+**字段说明**:| 字段 | 类型 | 说明 ||------|------|------|-| allowed-tools | List[str] | 该技能可使用的工具 |-| tags | List[str] | 用于分类的标签 |+| `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` 计数 |----+#### 4. 错误处理++**同步处理错误**:++如果 skill 解析或处理同步失败,裸 HTTP 会返回标准错误 envelope,并使用非 2xx HTTP 状态码:++```json+{+ "status": "error",+ "error": {+ "code": "PROCESSING_ERROR",+ "message": "Skill parse error: invalid skill metadata"+ }+}+```-## 管理技能+Python HTTP SDK 会把该响应映射为对应异常(`ProcessingError`)。++## 技能管理操作### 列出技能-**Python SDK (Embedded / HTTP)**+**Python SDK**:```python# 列出所有技能@@ -300,7 +422,7 @@ names = client.ls("viking://agent/skills/", simple=True)print(names)```-**HTTP API**+**HTTP API**:```bashcurl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://agent/skills/" \@@ -309,7 +431,7 @@ curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://agent/skills/" \### 读取技能内容-**Python SDK (Embedded / HTTP)**+**Python SDK**:```pythonuri = "viking://agent/skills/search-web/"@@ -327,7 +449,7 @@ content = client.read(uri)print(f"Content: {content}")```-**HTTP API**+**HTTP API**:```bash# L0:简要描述@@ -345,7 +467,7 @@ curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://agent/skills### 搜索技能-**Python SDK (Embedded / HTTP)**+**Python SDK**:```python# 语义搜索技能@@ -361,7 +483,7 @@ for ctx in results.skills:print(f"Description: {ctx.abstract}")```-**HTTP API**+**HTTP API**:```bashcurl -X POST http://localhost:1933/api/v1/search/find \@@ -376,115 +498,19 @@ curl -X POST http://localhost:1933/api/v1/search/find \### 删除技能-**Python SDK (Embedded / HTTP)**+**Python SDK**:```pythonclient.rm("viking://agent/skills/old-skill/", recursive=True)```-**HTTP API**+**HTTP API**:```bashcurl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://agent/skills/old-skill/&recursive=true" \-H "X-API-Key: your-key"```------## MCP 转换--OpenViking 会自动检测并将 MCP tool 定义转换为技能格式。--**检测**--如果字典包含 `inputSchema` 字段,则被视为 MCP 格式:--```python-if "inputSchema" in data:- # 转换为技能格式- skill = mcp_to_skill(data)-```--**转换过程**--1. 名称转换为 kebab-case-2. 描述保持不变-3. 从 `inputSchema.properties` 中提取参数-4. 从 `inputSchema.required` 中标记必填字段-5. 生成 Markdown 内容--**转换示例**--输入(MCP 格式):-```python-{- "name": "search_web",- "description": "Search the web",- "inputSchema": {- "type": "object",- "properties": {- "query": {- "type": "string",- "description": "Search query"- },- "limit": {- "type": "integer",- "description": "Max results"- }- },- "required": ["query"]- }-}-```--输出(技能格式):-```python-{- "name": "search-web",- "description": "Search the web",- "content": """----name: search-web-description: Search the web------# search-web--Search the web--## Parameters--- **query** (string) (required): Search query-- **limit** (integer) (optional): Max results--## Usage--This tool wraps the MCP tool `search-web`. Call this when the user needs functionality matching the description above.-"""-}-```-------## 技能存储结构--技能存储在 `viking://agent/skills/` 路径下:--```-viking://agent/skills/-+-- search-web/-| +-- .abstract.md # L0:简要描述-| +-- .overview.md # L1:参数和使用概览-| +-- SKILL.md # L2:完整文档-| +-- [auxiliary files] # 其他辅助文件-+-- calculator/-| +-- .abstract.md-| +-- .overview.md-| +-- SKILL.md-+-- ...-```------## 最佳实践### 清晰的描述@@ -505,25 +531,17 @@ skill = {}```-### 全面的内容--技能内容应包含:-- 清晰的参数描述及类型-- 何时使用该技能-- 具体示例-- 边界情况和限制--### 一致的命名+### 命名一致性建议技能名称使用 kebab-case:- `search-web`(推荐)- `searchWeb`(避免)- `search_web`(避免)-----## 相关文档+- [资源管理](02-resources.md) - 资源的添加和管理+- [文件系统](03-filesystem.md) - 文件和目录操作- [上下文类型](../concepts/02-context-types.md) - 技能概念- [检索](06-retrieval.md) - 查找技能- [会话](05-sessions.md) - 跟踪技能使用情况diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.mdindex bfd342485..b95728c07 100644--- a/docs/zh/api/05-sessions.md+++ b/docs/zh/api/05-sessions.md@@ -1,12 +1,31 @@-# 会话管理+# 会话和记忆管理-会话用于管理对话状态、跟踪上下文使用情况,并提取长期记忆。+会话用于管理对话状态、跟踪上下文使用情况,并提取长期记忆。会话采用分层存储(L0/L1/L2)来优化 token 使用:+- L0(abstract): 会话概览摘要+- L1(overview): 关键决策和总结+- L2(messages): 完整消息## API 参考### create_session()-创建新会话。+#### 1. API 实现介绍++创建新会话。会话是对话的容器,用于存储消息、跟踪上下文使用情况,并支持提交以提取长期记忆。++**处理流程**:+1. 生成或使用提供的 session_id+2. 初始化会话元数据(创建时间、用户信息等)+3. 在存储中创建会话目录结构+4. 返回会话信息++**代码入口**:+- `openviking/session/session.py:Session.__init__()` - Session 核心类+- `openviking/server/routers/sessions.py:create_session()` - HTTP 路由+- `openviking_cli/client/base.py:BaseClient.create_session()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:new_session()` - CLI 命令++#### 2. 接口和参数说明**参数**@@ -14,21 +33,11 @@|------|------|------|--------|------|| session_id | str | 否 | None | 会话 ID。如果为 None,则创建一个自动生成 ID 的新会话 |-**Python SDK (Embedded / HTTP)**--```python-# 创建新会话(自动生成 ID)-session = client.session()-print(f"Session URI: {session.uri}")--# 创建指定 ID 的新会话-session = client.create_session(session_id="my-custom-session-id")-print(f"Session ID: {session['session_id']}")-```+#### 3. 使用示例**HTTP API**-```+```httpPOST /api/v1/sessions```@@ -45,13 +54,30 @@ curl -X POST http://localhost:1933/api/v1/sessions \-d '{"session_id": "my-custom-session-id"}'```+**Python SDK**++```python+import openviking as ov++# 使用 HTTP 客户端+client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# 创建新会话(自动生成 ID)+result = await client.create_session()+print(f"Session ID: {result['session_id']}")++# 创建指定 ID 的新会话+result = await client.create_session(session_id="my-custom-session-id")+print(f"Session ID: {result['session_id']}")+```+**CLI**```bash-openviking session new+ov session new```-**响应**+**响应示例**```json{@@ -72,19 +98,26 @@ openviking session new### list_sessions()-列出所有会话。+#### 1. API 实现介绍-**Python SDK (Embedded / HTTP)**+列出当前用户的所有会话。返回会话 ID 和 URI 信息,用于进一步操作会话。-```python-sessions = client.list_sessions()-for s in sessions:- print(f"{s['session_id']} -> {s['uri']}")-```+**代码入口**:+- `openviking/server/routers/sessions.py:list_sessions()` - HTTP 路由+- `openviking_cli/client/base.py:BaseClient.list_sessions()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:list_sessions()` - CLI 命令++#### 2. 接口和参数说明++**参数**++无参数。++#### 3. 使用示例**HTTP API**-```+```httpGET /api/v1/sessions```@@ -93,20 +126,40 @@ curl -X GET http://localhost:1933/api/v1/sessions \-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++sessions = await client.list_sessions()+for s in sessions:+ print(f"{s['session_id']} -> {s['uri']}")+```+**CLI**```bash-openviking session list+ov session list```-**响应**+**响应示例**```json{"status": "ok","result": [- {"session_id": "a1b2c3d4", "uri": "viking://session/alice/a1b2c3d4", "is_dir": true},- {"session_id": "e5f6g7h8", "uri": "viking://session/alice/e5f6g7h8", "is_dir": true}+ {+ "session_id": "a1b2c3d4",+ "uri": "viking://session/alice/a1b2c3d4",+ "is_dir": true+ },+ {+ "session_id": "e5f6g7h8",+ "uri": "viking://session/alice/e5f6g7h8",+ "is_dir": true+ }],"time": 0.1}@@ -116,7 +169,24 @@ openviking session list### get_session()-获取会话详情。默认当会话不存在时返回 NOT_FOUND 错误,可通过 `auto_create=True` 自动创建。+#### 1. API 实现介绍++获取会话详情,包括元数据、消息统计、提交历史等。支持在会话不存在时自动创建。++**返回字段说明**:+- `message_count`: 当前 live session 中尚未归档的消息数+- `total_message_count`: 已归档消息与当前 live 消息的累计总数(旧会话可能不返回此字段)+- `commit_count`: 成功提交的次数+- `memories_extracted`: 各类记忆的提取数量统计+- `last_commit_at`: 最后一次提交的时间++**代码入口**:+- `openviking/session/session.py:Session.load()` - 会话加载+- `openviking/server/routers/sessions.py:get_session()` - HTTP 路由+- `openviking_cli/client/base.py:BaseClient.get_session()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:get_session()` - CLI 命令++#### 2. 接口和参数说明**参数**@@ -125,20 +195,11 @@ openviking session list| session_id | str | 是 | - | 会话 ID || auto_create | bool | 否 | False | 会话不存在时是否自动创建 |-**Python SDK (Embedded / HTTP)**--```python-# 获取已有会话(不存在时抛 NotFoundError)-info = client.get_session("a1b2c3d4")-print(f"Live Messages: {info['message_count']}, Total Messages: {info.get('total_message_count', 'n/a')}, Commits: {info['commit_count']}")--# 获取或创建会话-info = client.get_session("a1b2c3d4", auto_create=True)-```+#### 3. 使用示例**HTTP API**-```+```httpGET /api/v1/sessions/{session_id}?auto_create=false```@@ -147,13 +208,30 @@ curl -X GET http://localhost:1933/api/v1/sessions/a1b2c3d4 \-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# 获取已有会话(不存在时抛 NotFoundError)+info = await client.get_session("a1b2c3d4")+print(f"Live Messages: {info['message_count']}")+print(f"Total Messages: {info.get('total_message_count', 'n/a')}")+print(f"Commits: {info['commit_count']}")++# 获取或创建会话+info = await client.get_session("a1b2c3d4", auto_create=True)+```+**CLI**```bash-openviking session get a1b2c3d4+ov session get a1b2c3d4```-**响应**+**响应示例**```json{@@ -186,57 +264,52 @@ openviking session get a1b2c3d4"account_id": "default","user_id": "alice","agent_id": "default"- }+ },+ "pending_tokens": 450}}```-说明:-- `message_count` 表示当前 live session 中尚未归档的消息数。-- `total_message_count` 存在时表示已归档消息与当前 live 消息的累计总数;该字段引入前创建的旧 session 可能不返回。-- `commit_count` 和 `last_commit_at` 会在 commit Phase 1 成功归档消息后更新;Phase 2 记忆提取进度通过返回的 task 跟踪。----### get_session_context()-获取供上下文组装使用的会话上下文。+#### 1. API 实现介绍++获取供上下文组装使用的会话上下文。该接口返回最新的归档摘要和当前活跃消息,用于 LLM 上下文构建。-该接口返回:-- `latest_archive_overview`:最新一个已完成归档的 `overview` 文本,在 token budget 足够时返回-- `pre_archive_abstracts`:已完成归档的轻量列表,每项只包含 `archive_id` 和 `abstract`-- `messages`:最新已完成归档之后的所有未完成归档消息,再加上当前 live session 消息-- `stats`:返回结果对应的 token 与纳入统计+**返回字段说明**:+- `latest_archive_overview`: 最新一个已完成归档的 overview 文本,在 token budget 足够时返回+- `pre_archive_abstracts`: 保持 API 向下兼容,返回空数组+- `messages`: 最新已完成归档之后的所有未完成归档消息,再加上当前 live session 消息+- `estimatedTokens`: 预估总 token 数+- `stats`: 统计信息-说明:-- 没有可用 completed archive,或最新 overview 超出 token budget 时,`latest_archive_overview` 返回空字符串。-- `token_budget` 会在 active `messages` 之后作用于 assembled archive payload:`latest_archive_overview` 优先级高于 `pre_archive_abstracts`,预算紧张时先淘汰最旧的 abstracts。-- `token_budget` 必须大于等于 `0`。`token_budget=0` 合法,表示不返回 archive payload,但仍会返回 active `messages`;负数会作为非法参数拒绝。-- 只有最终实际返回的 archive 内容,才会计入 `estimatedTokens` 和 `stats.archiveTokens`。-- 当前每次有消息的 session commit 都会在 Phase 2 生成 archive 摘要;只有带 `.done` 标记的 completed archive 才会被这里返回。+**token budget 分配策略**:+1. 先分配给当前活跃消息+2. 剩余预算优先给最新归档的 overview+3. pre_archive_abstracts 目前不返回++**代码入口**:+- `openviking/session/session.py:Session.get_session_context()` - 核心实现+- `openviking/server/routers/sessions.py:get_session_context()` - HTTP 路由+- `openviking_cli/client/base.py:BaseClient.get_session_context()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:get_session_context()` - CLI 命令++#### 2. 接口和参数说明**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| session_id | str | 是 | - | 会话 ID |-| token_budget | int | 否 | 128000 | active `messages` 之后留给 assembled archive payload 的非负 token 预算 |+| token_budget | int | 否 | 128000 | active messages 之后留给 assembled archive payload 的非负 token 预算 |-**Python SDK (Embedded / HTTP)**--```python-context = await client.get_session_context("a1b2c3d4", token_budget=128000)-print(context["latest_archive_overview"])-print(context["pre_archive_abstracts"])-print(len(context["messages"]))--session = client.session("a1b2c3d4")-context = await session.get_session_context(token_budget=128000)-```+#### 3. 使用示例**HTTP API**-```+```httpGET /api/v1/sessions/{session_id}/context?token_budget=128000```@@ -245,29 +318,32 @@ curl -X GET "http://localhost:1933/api/v1/sessions/a1b2c3d4/context?token_budget-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++context = await client.get_session_context("a1b2c3d4", token_budget=128000)+print(context["latest_archive_overview"])+print(len(context["messages"]))+```+**CLI**```bashov session get-session-context a1b2c3d4 --token-budget 128000```-**响应**+**响应示例**```json{"status": "ok","result": {"latest_archive_overview": "# Session Summary\n\n**Overview**: User discussed deployment and auth setup.",- "pre_archive_abstracts": [- {- "archive_id": "archive_002",- "abstract": "用户讨论了部署和鉴权配置。"- },- {- "archive_id": "archive_001",- "abstract": "用户之前讨论了仓库初始化和鉴权配置。"- }- ],+ "pre_archive_abstracts": [],"messages": [{"id": "msg_pending_1",@@ -289,7 +365,7 @@ ov session get-session-context a1b2c3d4 --token-budget 128000"estimatedTokens": 160,"stats": {"totalArchives": 2,- "includedArchives": 2,+ "includedArchives": 1,"droppedArchives": 0,"failedArchives": 0,"activeTokens": 98,@@ -303,15 +379,17 @@ ov session get-session-context a1b2c3d4 --token-budget 128000### get_session_archive()-获取某次已完成归档的完整内容。+#### 1. API 实现介绍-该接口通常配合 `get_session_context()` 返回的 `pre_archive_abstracts[*].archive_id` 使用。+获取某次已完成归档的完整内容。该接口通常配合 `get_session_context()` 使用,当需要查看更早的归档详情时调用。-该接口返回:-- `archive_id`:被展开的 archive ID-- `abstract`:该 archive 的轻量摘要-- `overview`:该 archive 的完整 overview-- `messages`:该次 archive 对应的完整消息内容+**代码入口**:+- `openviking/session/session.py:Session.get_session_archive()` - 核心实现+- `openviking/server/routers/sessions.py:get_session_archive()` - HTTP 路由+- `openviking_cli/client/base.py:BaseClient.get_session_archive()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:get_session_archive()` - CLI 命令++#### 2. 接口和参数说明**参数**@@ -320,21 +398,11 @@ ov session get-session-context a1b2c3d4 --token-budget 128000| session_id | str | 是 | - | 会话 ID || archive_id | str | 是 | - | 归档 ID,例如 `archive_002` |-**Python SDK (Embedded / HTTP)**--```python-archive = await client.get_session_archive("a1b2c3d4", "archive_002")-print(archive["archive_id"])-print(archive["overview"])-print(len(archive["messages"]))--session = client.session("a1b2c3d4")-archive = await session.get_archive("archive_002")-```+#### 3. 使用示例**HTTP API**-```+```httpGET /api/v1/sessions/{session_id}/archives/{archive_id}```@@ -343,13 +411,26 @@ curl -X GET "http://localhost:1933/api/v1/sessions/a1b2c3d4/archives/archive_002-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++archive = await client.get_session_archive("a1b2c3d4", "archive_002")+print(archive["archive_id"])+print(archive["overview"])+print(len(archive["messages"]))+```+**CLI**```bashov session get-session-archive a1b2c3d4 archive_002```-**响应**+**响应示例**```json{@@ -380,13 +461,34 @@ ov session get-session-archive a1b2c3d4 archive_002}```-如果 archive 不存在、未完成,或者不属于该 session,接口返回 `404`。+**错误响应**++如果 archive 不存在、未完成,或者不属于该 session,接口返回 404:++```json+{+ "status": "error",+ "error": {+ "code": "NOT_FOUND",+ "message": "Archive archive_002 not found"+ }+}+```---### delete_session()-删除会话。+#### 1. API 实现介绍++删除会话及其所有数据,包括消息、归档历史、记忆等。删除操作不可逆。++**代码入口**:+- `openviking/server/routers/sessions.py:delete_session()` - HTTP 路由+- `openviking_cli/client/base.py:BaseClient.delete_session()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:delete_session()` - CLI 命令++#### 2. 接口和参数说明**参数**@@ -394,15 +496,11 @@ ov session get-session-archive a1b2c3d4 archive_002|------|------|------|--------|------|| session_id | str | 是 | - | 要删除的会话 ID |-**Python SDK (Embedded / HTTP)**--```python-client.rm("viking://session/a1b2c3d4/", recursive=True)-```+#### 3. 使用示例**HTTP API**-```+```httpDELETE /api/v1/sessions/{session_id}```@@ -411,13 +509,24 @@ curl -X DELETE http://localhost:1933/api/v1/sessions/a1b2c3d4 \-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# 删除会话+await client.delete_session("a1b2c3d4")+```+**CLI**```bash-openviking session delete a1b2c3d4+ov session delete a1b2c3d4```-**响应**+**响应示例**```json{@@ -433,16 +542,33 @@ openviking session delete a1b2c3d4### add_message()-向会话中添加消息。+#### 1. API 实现介绍++向会话中添加消息。支持两种模式:简单文本模式和 Parts 模式(支持文本、上下文引用、工具调用等)。++**Part 类型**:+- `TextPart`: 纯文本内容+- `ContextPart`: 上下文引用,指向资源或记忆+- `ToolPart`: 工具调用和结果++**代码入口**:+- `openviking/session/session.py:Session.add_message()` - 核心实现+- `openviking/server/routers/sessions.py:add_message()` - HTTP 路由+- `openviking_cli/client/base.py:BaseClient.add_message()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:add_message()` - CLI 命令++#### 2. 接口和参数说明**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|+| session_id | str | 是 | - | 会话 ID || role | str | 是 | - | 消息角色:"user" 或 "assistant" || parts | List[Part] | 条件必填 | - | 消息部分列表(Python SDK 必填;HTTP API 可选,与 content 二选一) || content | str | 条件必填 | - | 消息文本内容(HTTP API 简单模式,与 parts 二选一) || created_at | str | 否 | None | 可选的 ISO 8601 时间戳,会原样保存到消息中 |+| role_id | str | 否 | None | 可选的显式参与者 ID,省略时由服务器推导 |> **注意**:HTTP API 支持两种模式:> 1. **简单模式**:使用 `content` 字符串(向后兼容)@@ -476,27 +602,11 @@ ToolPart()```-**Python SDK (Embedded / HTTP)**--```python-from openviking.message import TextPart--session = client.session()--# 添加用户消息-session.add_message("user", [- TextPart(text="How do I authenticate users?")-])--# 添加助手回复-session.add_message("assistant", [- TextPart(text="You can use OAuth 2.0 for authentication...")-])-```+#### 3. 使用示例**HTTP API**-```+```httpPOST /api/v1/sessions/{session_id}/messages```@@ -541,13 +651,43 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \}'```+**Python SDK**++```python+import openviking as ov+from openviking.message import TextPart, ContextPart++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# 简单模式:添加用户消息+await client.add_message(+ session_id="a1b2c3d4",+ role="user",+ content="How do I authenticate users?"+)++# Parts 模式:添加带有上下文引用的助手消息+await client.add_message(+ session_id="a1b2c3d4",+ role="assistant",+ parts=[+ TextPart(text="Based on the documentation, you can configure embedding..."),+ ContextPart(+ uri="viking://resources/docs/auth/",+ context_type="resource",+ abstract="Authentication guide"+ )+ ]+)+```+**CLI**```bash-openviking session add-message a1b2c3d4 --role user --content "How do I authenticate users?"+ov session add-message a1b2c3d4 --role user --content "How do I authenticate users?"```-**响应**+**响应示例**```json{@@ -564,36 +704,29 @@ openviking session add-message a1b2c3d4 --role user --content "How do I authenti### used()-记录会话中实际使用的上下文和技能。调用 `commit()` 时,会根据此使用数据更新 `active_count`。+#### 1. API 实现介绍++记录会话中实际使用的上下文和技能。调用 `commit()` 时,会根据此使用数据更新资源的 `active_count`,用于优化未来的检索排序。++**代码入口**:+- `openviking/session/session.py:Session.used()` - 核心实现+- `openviking/server/routers/sessions.py:record_used()` - HTTP 路由++#### 2. 接口和参数说明**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|+| session_id | str | 是 | - | 会话 ID || contexts | List[str] | 否 | None | 实际使用的上下文 URI 列表 || skill | Dict[str, Any] | 否 | None | 技能使用记录,包含 `uri`、`input`、`output`、`success` 字段 |-**Python SDK (Embedded / HTTP)**--```python-session = client.session(session_id="a1b2c3d4")-session.load()--# 记录使用的上下文-session.used(contexts=["viking://resources/docs/auth/"])--# 记录使用的技能-session.used(skill={- "uri": "viking://agent/skills/search-web/",- "input": {"query": "OAuth"},- "output": "Results...",- "success": True-})-```+#### 3. 使用示例**HTTP API**-```+```httpPOST /api/v1/sessions/{session_id}/used```@@ -611,7 +744,32 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \-d '{"skill": {"uri": "viking://agent/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'```-**响应**+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# 记录使用的上下文+await client.session_used(+ session_id="a1b2c3d4",+ contexts=["viking://resources/docs/auth/"]+)++# 记录使用的技能+await client.session_used(+ session_id="a1b2c3d4",+ skill={+ "uri": "viking://agent/skills/search-web/",+ "input": {"query": "OAuth"},+ "output": "Results...",+ "success": True+ }+)+```++**响应示例**```json{@@ -629,12 +787,26 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \### commit()+#### 1. API 实现介绍+提交会话。归档消息(Phase 1)立即完成,摘要生成和记忆提取(Phase 2)在后台异步执行。返回 `task_id` 用于查询后台任务进度。-说明:-- 同一 session 的多次快速连续 commit 会被接受;每次请求都会拿到独立的 `task_id`。-- 后台 Phase 2 会按 archive 顺序串行推进:`archive N+1` 会等待 `archive N` 写出 `.done` 后再继续。-- 如果更早的 archive 已失败且没有 `.done`,后续 commit 会直接返回 `FAILED_PRECONDITION`,直到该失败被处理。+**两阶段提交流程**:+- **Phase 1(同步)**: 快照当前消息,清空 live session,创建归档目录,写入原始消息+- **Phase 2(异步)**: 生成摘要(L0/L1),提取长期记忆,更新关系和 active_count++**注意事项**:+- 同一 session 的多次快速连续 commit 会被接受;每次请求都会拿到独立的 `task_id`+- 后台 Phase 2 会按 archive 顺序串行推进:`archive_N+1` 会等待 `archive_N` 写出 `.done` 后再继续+- 如果更早的 archive 已失败且没有 `.done`,后续 commit 会直接返回错误,直到该失败被处理++**代码入口**:+- `openviking/session/session.py:Session.commit_async()` - 核心实现+- `openviking/server/routers/sessions.py:commit_session()` - HTTP 路由+- `openviking_cli/client/base.py:BaseClient.commit_session()` - Python SDK+- `crates/ov_cli/src/commands/session.rs:commit_session()` - CLI 命令++#### 2. 接口和参数说明**参数**@@ -642,26 +814,11 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \|------|------|------|--------|------|| session_id | str | 是 | - | 要提交的会话 ID |-**Python SDK (Embedded / HTTP)**--```python-session = client.session(session_id="a1b2c3d4")-session.load()--# commit 立即返回 task_id,后台异步执行摘要生成和记忆提取-result = session.commit()-print(f"Status: {result['status']}") # "accepted"-print(f"Task ID: {result['task_id']}")--# 查询后台任务进度-task = client.get_task(result["task_id"])-if task["status"] == "completed":- print(f"Memories extracted: {sum(task['result']['memories_extracted'].values())}")-```+#### 3. 使用示例**HTTP API**-```+```httpPOST /api/v1/sessions/{session_id}/commit```@@ -676,13 +833,33 @@ curl -X GET http://localhost:1933/api/v1/tasks/{task_id} \-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++# commit 立即返回 task_id,后台异步执行摘要生成和记忆提取+result = await client.commit_session("a1b2c3d4")+print(f"Status: {result['status']}")+print(f"Task ID: {result['task_id']}")++# 查询后台任务进度+task = await client.get_task(result["task_id"])+if task["status"] == "completed":+ memories = task["result"]["memories_extracted"]+ total = sum(memories.values())+ print(f"Memories extracted: {total}")+```+**CLI**```bash-openviking session commit a1b2c3d4+ov session commit a1b2c3d4```-**响应**+**响应示例**```json{@@ -691,7 +868,7 @@ openviking session commit a1b2c3d4"session_id": "a1b2c3d4","status": "accepted","task_id": "uuid-xxx",- "archive_uri": "viking://session/a1b2c3d4/history/archive_001",+ "archive_uri": "viking://session/alice/a1b2c3d4/history/archive_001","archived": true}}@@ -701,17 +878,26 @@ openviking session commit a1b2c3d4### extract()+#### 1. API 实现介绍+仅 HTTP API。立即对已有会话触发一次记忆提取,不会额外创建新的 commit 任务。+**代码入口**:+- `openviking/server/routers/sessions.py:extract_session()` - HTTP 路由++#### 2. 接口和参数说明+**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| session_id | str | 是 | - | 要提取记忆的会话 ID |+#### 3. 使用示例+**HTTP API**-```+```httpPOST /api/v1/sessions/{session_id}/extract```@@ -721,7 +907,7 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/extract \-H "X-API-Key: your-key"```-**响应**+**响应示例**该接口会直接返回本次提取产生的记忆写入结果列表。列表项的具体结构取决于该会话实际提取出了哪些记忆。@@ -729,24 +915,32 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/extract \### get_task()+#### 1. API 实现介绍+查询后台任务状态(如 commit 的摘要生成和记忆提取进度)。+**任务状态**:+- `pending`: 任务等待执行+- `running`: 任务执行中+- `completed`: 任务成功完成+- `failed`: 任务失败++**代码入口**:+- `openviking/server/routers/tasks.py:get_task()` - HTTP 路由++#### 2. 接口和参数说明+**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| task_id | str | 是 | - | 任务 ID(由 commit 返回) |-**Python SDK (Embedded / HTTP)**--```python-task = client.get_task(task_id)-print(f"Status: {task['status']}") # "pending" | "running" | "completed" | "failed"-```+#### 3. 使用示例**HTTP API**-```+```httpGET /api/v1/tasks/{task_id}```@@ -755,7 +949,18 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \-H "X-API-Key: your-key"```-**响应(进行中)**+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++task = await client.get_task(task_id="uuid-xxx")+print(f"Status: {task['status']}")+```++**响应示例(进行中)**```json{@@ -768,7 +973,7 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \}```-**响应(完成)**+**响应示例(完成)**```json{@@ -779,26 +984,44 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \"status": "completed","result": {"session_id": "a1b2c3d4",- "archive_uri": "viking://session/a1b2c3d4/history/archive_001",+ "archive_uri": "viking://session/alice/a1b2c3d4/history/archive_001","memories_extracted": {"profile": 1,"preferences": 2,"entities": 1,"cases": 1},- "active_count_updated": 2+ "active_count_updated": 2,+ "token_usage": {+ "llm": {+ "prompt_tokens": 5200,+ "completion_tokens": 1800,+ "total_tokens": 7000+ },+ "embedding": {+ "total_tokens": 1500+ },+ "total": {+ "total_tokens": 8500+ }+ }}}}```-完成态任务结果里的 `memories_extracted` 表示本次 commit 的分类计数;如果只需要本次 commit 的总数,请把这些值求和。----### list_tasks()-仅 HTTP API。列出当前调用方可见的后台任务。+#### 1. API 实现介绍++仅 HTTP API。列出当前调用方可见的后台任务,支持按类型、状态、资源过滤。++**代码入口**:+- `openviking/server/routers/tasks.py:list_tasks()` - HTTP 路由++#### 2. 接口和参数说明**参数**@@ -809,10 +1032,12 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \| resource_id | str | 否 | None | 按资源 ID 过滤,例如会话 ID || limit | int | 否 | 50 | 最多返回的任务条数 |+#### 3. 使用示例+**HTTP API**-```-GET /api/v1/tasks+```http+GET /api/v1/tasks?task_type=session_commit&status=running&limit=20``````bash@@ -820,7 +1045,7 @@ curl -X GET "http://localhost:1933/api/v1/tasks?task_type=session_commit&status=-H "X-API-Key: your-key"```-**响应**+**响应示例**```json{@@ -857,23 +1082,25 @@ curl -X GET "http://localhost:1933/api/v1/tasks?task_type=session_commit&status=## 会话存储结构```-viking://session/{session_id}/-+-- .abstract.md # L0:会话概览-+-- .overview.md # L1:关键决策-+-- messages.jsonl # 当前消息-+-- tools/ # 工具执行记录-| +-- {tool_id}/-| +-- tool.json-+-- .meta.json # 元数据-+-- .relations.json # 关联上下文-+-- history/ # 归档历史- +-- archive_001/- | +-- messages.jsonl # Phase 1 写入- | +-- .abstract.md # Phase 2 写入(后台)- | +-- .overview.md # Phase 2 写入(后台)- | +-- memory_diff.json # Phase 2 写入(后台,记忆变更时)- | +-- .done # Phase 2 完成标记- +-- archive_002/+viking://session/{user_id}/{session_id}/+├── .abstract.md # L0:会话概览+├── .overview.md # L1:关键决策+├── .meta.json # 元数据+├── .relations.json # 关联上下文+├── messages.jsonl # 当前消息+├── tools/ # 工具执行记录+│ └── {tool_id}/+│ └── tool.json+└── history/ # 归档历史+ ├── archive_001/+ │ ├── messages.jsonl # Phase 1 写入+ │ ├── .abstract.md # Phase 2 写入(后台)+ │ ├── .overview.md # Phase 2 写入(后台)+ │ ├── .meta.json # 归档元数据+ │ ├── memory_diff.json # Phase 2 写入(后台,记忆变更时)+ │ ├── .done # Phase 2 完成标记+ │ └── .failed.json # Phase 2 失败标记+ └── archive_002/```---@@ -895,50 +1122,61 @@ viking://session/{session_id}/## 完整示例-**Python SDK (Embedded / HTTP)**+**Python SDK**```pythonimport openviking as ovfrom openviking.message import TextPart, ContextPart# 初始化客户端-client = ov.OpenViking(path="./my_data")-client.initialize()+client = ov.Client(base_url="http://localhost:1933", api_key="your-key")# 创建新会话-session = client.session()+session_result = await client.create_session()+session_id = session_result["session_id"]+print(f"Session created: {session_id}")# 添加用户消息-session.add_message("user", [- TextPart(text="How do I configure embedding?")-])+await client.add_message(+ session_id=session_id,+ role="user",+ content="How do I configure embedding?"+)# 使用会话上下文进行搜索-results = client.search("embedding configuration", session=session)--# 添加带上下文引用的助手回复-session.add_message("assistant", [- TextPart(text="Based on the documentation, you can configure embedding..."),- ContextPart(- uri=results.resources[0].uri,- context_type="resource",- abstract=results.resources[0].abstract+results = await client.search("embedding configuration", session_id=session_id)++# 添加带有上下文引用的助手回复+if results.resources:+ await client.add_message(+ session_id=session_id,+ role="assistant",+ parts=[+ TextPart(text="Based on the documentation, you can configure embedding..."),+ ContextPart(+ uri=results.resources[0].uri,+ context_type="resource",+ abstract=results.resources[0].abstract+ )+ ])-])-# 跟踪实际使用的上下文-session.used(contexts=[results.resources[0].uri])+ # 跟踪实际使用的上下文+ await client.session_used(+ session_id=session_id,+ contexts=[results.resources[0].uri]+ )# 提交会话(立即返回,后台执行摘要生成和记忆提取)-result = session.commit()-print(f"Task ID: {result['task_id']}")+commit_result = await client.commit_session(session_id)+print(f"Task ID: {commit_result['task_id']}")# 可选:等待后台任务完成-task = client.get_task(result["task_id"])+task = await client.get_task(commit_result["task_id"])if task and task["status"] == "completed":- print(f"Memories extracted: {sum(task['result']['memories_extracted'].values())}")--client.close()+ memories = task["result"]["memories_extracted"]+ total = sum(memories.values())+ print(f"Memories extracted: {total}")```**HTTP API**@@ -991,8 +1229,9 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \```python# 在重要交互后提交-if len(session.messages) > 10:- session.commit()+session_info = await client.get_session(session_id)+if session_info["message_count"] > 10:+ await client.commit_session(session_id)```### 跟踪实际使用的内容@@ -1000,22 +1239,14 @@ if len(session.messages) > 10:```python# 仅标记实际有帮助的上下文if context_was_useful:- session.used(contexts=[ctx.uri])+ await client.session_used(session_id=session_id, contexts=[ctx.uri])```### 使用会话上下文进行搜索```python# 结合对话上下文可获得更好的搜索结果-results = client.search(query, session=session)-```--### 继续会话前先加载--```python-# 恢复已有会话时务必先加载-session = client.session(session_id="existing-id")-session.load()+results = await client.search(query, session_id=session_id)```---diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.mdindex e65d6d7f9..aae22ba4b 100644--- a/docs/zh/api/06-retrieval.md+++ b/docs/zh/api/06-retrieval.md@@ -1,6 +1,6 @@# 检索-OpenViking 提供两种搜索方法:`find` 用于简单的语义搜索,`search` 用于带会话上下文的复杂检索。+OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带会话上下文的智能检索、正则表达式匹配搜索和文件模式匹配。## find 与 search 对比@@ -9,30 +9,62 @@ OpenViking 提供两种搜索方法:`find` 用于简单的语义搜索,`sear| 意图分析 | 否 | 是 || 会话上下文 | 否 | 是 || 查询扩展 | 否 | 是 |-| 默认限制数 | 10 | 10 |+| 默认结果数 | 10 | 10 || 使用场景 | 简单查询 | 对话式搜索 |+## 检索流程++检索的核心流程如下:++```+查询 → 意图分析(仅search)→ 向量搜索(L0)→ 重排序(L1)→ 结果+```++1. **意图分析**(仅 search):理解查询意图,扩展查询+2. **向量搜索**:使用 Embedding 查找候选项+3. **重排序**:使用内容重新评分以提高准确性+4. **结果**:返回 top-k 上下文+## API 参考### find()-基本向量相似度搜索。+基本向量相似度搜索,无需会话上下文。++#### 1. API 实现介绍++`find()` 方法执行纯向量相似度搜索,适用于简单的查询场景。它使用分层检索器(HierarchicalRetriever)在 L0 摘要层进行初步搜索,然后在 L1/L2 层进行详细匹配。++**处理流程**:+1. 将查询文本转换为向量+2. 在指定的目标 URI 范围内执行全局向量搜索+3. 使用分层检索策略递归搜索相关目录和文件+4. 可选:使用重排序模型优化结果排序+5. 返回匹配的上下文列表++**代码入口**:+- `openviking_cli/client/sync_http.py:SyncHTTPClient.find()` - Python SDK 入口(HTTP)+- `openviking/retrieve/hierarchical_retriever.py:HierarchicalRetriever.retrieve()` - 核心检索实现+- `openviking/server/routers/search.py:find()` - HTTP 路由+- `crates/ov_cli/src/commands/search.rs:find()` - Rust CLI 命令++#### 2. 接口和参数说明**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| query | str | 是 | - | 搜索查询字符串 |-| target_uri | str | 否 | "" | 限制搜索范围到指定的 URI 前缀 |+| target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 || limit | int | 否 | 10 | 最大返回结果数 |-| node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 `limit` |+| node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 limit || score_threshold | float | 否 | None | 最低相关性分数阈值 || filter | Dict | 否 | None | 元数据过滤器 || since | str | 否 | None | 时间下界,支持 `2h` 或 ISO 8601 / `YYYY-MM-DD`。不带时区的值按 UTC 解释。CLI `--after` 会映射到这个字段 || until | str | 否 | None | 时间上界,支持 `30m` 或 ISO 8601 / `YYYY-MM-DD`。不带时区的值按 UTC 解释。CLI `--before` 会映射到这个字段 |-| time_field | `"updated_at"` 或 `"created_at"` | 否 | `"updated_at"` | `since` / `until` 使用的元数据时间字段 |+| time_field | "updated_at" \| "created_at" | 否 | "updated_at" | since/until 使用的元数据时间字段 || include_provenance | bool | 否 | False | 在序列化结果中附带 provenance / query-plan 细节 |-| telemetry | bool 或 object | 否 | False | 在响应中附带遥测数据 |+| telemetry | bool \| object | 否 | False | 在响应中附带遥测数据 |**FindResult 结构**@@ -52,33 +84,16 @@ class FindResult:class MatchedContext:uri: str # Viking URIcontext_type: ContextType # "resource"、"memory" 或 "skill"- is_leaf: bool # 是否为叶子节点+ level: int # 层级 (0=L0, 1=L1, 2=L2)abstract: str # L0 内容+ overview: Optional[str] # L1 概览(非叶子节点时可选)category: str # 分类score: float # 相关性分数 (0-1)match_reason: str # 匹配原因relations: List[RelatedContext] # 关联上下文```-**Python SDK (Embedded / HTTP)**--```python-results = client.find("how to authenticate users")--recent_emails = client.find(- "invoice",- target_uri="viking://resources/email/",- since="7d",- time_field="created_at",-)--for ctx in results.resources:- print(f"URI: {ctx.uri}")- print(f"Score: {ctx.score:.3f}")- print(f"Type: {ctx.context_type}")- print(f"Abstract: {ctx.abstract[:100]}...")- print("---")-```+#### 3. 使用示例**HTTP API**@@ -88,130 +103,221 @@ POST /api/v1/search/find```bashcurl -X POST http://localhost:1933/api/v1/search/find \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "query": "how to authenticate users",- "limit": 10- }'+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "query": "how to authenticate users",+ "limit": 10+ }'```-**CLI**+**使用 Target URI 和时间过滤**```bash-openviking find "how to authenticate users" [--uri viking://resources/] [--limit 10]-openviking find "invoice" --after 7d+curl -X POST http://localhost:1933/api/v1/search/find \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "query": "authentication",+ "target_uri": "viking://resources",+ "since": "7d",+ "time_field": "created_at"+ }'```-`--after` 会映射为 API `since`,`--before` 会映射为 API `until`。+**Python SDK**-**响应**+```python+import openviking as ov-```json-{- "status": "ok",- "result": {- "memories": [],- "resources": [- {- "uri": "viking://resources/docs/auth/",- "context_type": "resource",- "is_leaf": false,- "abstract": "Authentication guide covering OAuth 2.0...",- "score": 0.92,- "match_reason": "Semantic match on authentication"- }- ],- "skills": [],- "total": 1- },- "time": 0.1-}-```+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()++# 基础搜索+results = client.find("how to authenticate users")-**示例:使用 Target URI 搜索**+# 带过滤和时间范围的搜索+recent_emails = client.find(+ "invoice",+ target_uri="viking://resources/email",+ since="7d",+ time_field="created_at",+)++# 遍历结果+for ctx in results.resources:+ print(f"URI: {ctx.uri}")+ print(f"Score: {ctx.score:.3f}")+ print(f"Type: {ctx.context_type}")+ print(f"Abstract: {ctx.abstract[:100]}...")+ print("---")+```-**Python SDK (Embedded / HTTP)**+**使用 Target URI 限定搜索范围**```python# 仅在资源中搜索results = client.find("authentication",- target_uri="viking://resources/"+ target_uri="viking://resources")# 仅在用户记忆中搜索results = client.find("preferences",- target_uri="viking://user/memories/"+ target_uri="viking://user/memories")# 仅在技能中搜索results = client.find("web search",- target_uri="viking://agent/skills/"+ target_uri="viking://agent/skills")# 在特定项目中搜索results = client.find("API endpoints",- target_uri="viking://resources/my-project/"+ target_uri="viking://resources/my-project")```-**HTTP API**+**CLI**```bash-# 仅在资源中搜索-curl -X POST http://localhost:1933/api/v1/search/find \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "query": "authentication",- "target_uri": "viking://resources/"- }'--# 使用分数阈值搜索-curl -X POST http://localhost:1933/api/v1/search/find \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "query": "API endpoints",- "target_uri": "viking://resources/my-project/",- "score_threshold": 0.5,- "limit": 5- }'+# 基础搜索+openviking find "how to authenticate users"++# 指定 URI 范围+openviking find "how to authenticate users" --uri "viking://resources"++# 带时间过滤+openviking find "invoice" --after 7d++# 带限制数量+openviking find "how to authenticate users" --limit 20+```++**响应示例**++```json+{+ "status": "ok",+ "result": {+ "memories": [],+ "resources": [+ {+ "context_type": "resource",+ "uri": "viking://resources/01-overview/API_Overview/Documentation_Reading_P_2c6ae38b.md",+ "level": 2,+ "score": 0.12808319406977778,+ "category": "",+ "match_reason": "",+ "relations": [],+ "abstract": "This document is an API documentation reading plan that outlines the structure of subsequent API reference materials organized by functional module. Main sections or topics covered include resource management API, search API, file system operations, ses...",+ "overview": null+ },+ {+ "context_type": "resource",+ "uri": "viking://resources/01-overview/API_Overview/API_Endpoints/.abstract.md",+ "level": 0,+ "score": 0.12054087276495282,+ "category": "",+ "match_reason": "",+ "relations": [],+ "abstract": "This directory contains structured API reference documentation for the OpenViking platform, compiling detailed HTTP endpoint specifications for core and extended platform capabilities. It covers functional modules including system health checks, semanti...",+ "overview": null+ }+ ],+ "skills": [],+ "total": 2+ }+}```---### search()-带会话上下文和意图分析的搜索。+带会话上下文和意图分析的智能检索。++#### 1. API 实现介绍++`search()` 方法在 `find()` 的基础上增加了会话上下文理解和意图分析能力。它可以根据历史对话更好地理解用户查询意图,执行查询扩展,提供更相关的搜索结果。++**处理流程**:+1. 加载会话上下文(如果提供了 session_id)+2. 分析查询意图,结合对话历史理解真实需求+3. 扩展查询以提高召回率+4. 执行与 `find()` 相同的分层检索流程+5. 返回带查询计划的搜索结果++**代码入口**:+- `openviking_cli/client/sync_http.py:SyncHTTPClient.search()` - Python SDK 入口(HTTP)+- `openviking/retrieve/hierarchical_retriever.py:HierarchicalRetriever.retrieve()` - 核心检索实现+- `openviking/server/routers/search.py:search()` - HTTP 路由+- `crates/ov_cli/src/commands/search.rs:search()` - Rust CLI 命令++#### 2. 接口和参数说明**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| query | str | 是 | - | 搜索查询字符串 |-| target_uri | str | 否 | "" | 限制搜索范围到指定的 URI 前缀 |-| session | Session | 否 | None | 用于上下文感知搜索的会话(SDK) |-| session_id | str | 否 | None | 用于上下文感知搜索的会话 ID(HTTP) |+| target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 |+| session | Session | 否 | None | 用于上下文感知搜索的会话(SDK)|+| session_id | str | 否 | None | 用于上下文感知搜索的会话 ID(HTTP)|| limit | int | 否 | 10 | 最大返回结果数 |-| node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 `limit` |+| node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 limit || score_threshold | float | 否 | None | 最低相关性分数阈值 || filter | Dict | 否 | None | 元数据过滤器 || since | str | 否 | None | 时间下界,支持 `2h` 或 ISO 8601 / `YYYY-MM-DD`。不带时区的值按 UTC 解释。CLI `--after` 会映射到这个字段 || until | str | 否 | None | 时间上界,支持 `30m` 或 ISO 8601 / `YYYY-MM-DD`。不带时区的值按 UTC 解释。CLI `--before` 会映射到这个字段 |-| time_field | `"updated_at"` 或 `"created_at"` | 否 | `"updated_at"` | `since` / `until` 使用的元数据时间字段 |+| time_field | "updated_at" \| "created_at" | 否 | "updated_at" | since/until 使用的元数据时间字段 || include_provenance | bool | 否 | False | 在序列化结果中附带 provenance / query-plan 细节 |-| telemetry | bool 或 object | 否 | False | 在响应中附带遥测数据 |+| telemetry | bool \| object | 否 | False | 在响应中附带遥测数据 |++#### 3. 使用示例++**HTTP API**++```+POST /api/v1/search/search+```++```bash+curl -X POST http://localhost:1933/api/v1/search/search \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "query": "best practices",+ "session_id": "abc123",+ "since": "2h",+ "time_field": "updated_at",+ "limit": 10+ }'+```++**不带会话的搜索(仍会进行意图分析)**++```bash+curl -X POST http://localhost:1933/api/v1/search/search \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "query": "how to implement OAuth 2.0 authorization code flow"+ }'+```-**Python SDK (Embedded / HTTP)**+**Python SDK**```python+import openviking as ovfrom openviking.message import TextPart+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+# 创建带对话上下文的会话session = client.session()session.add_message("user", [@@ -233,109 +339,138 @@ for ctx in results.resources:print(f"Abstract: {ctx.abstract[:200]}...")```-**HTTP API**+**不使用会话的搜索**-```-POST /api/v1/search/search-```+```python+# search 也可以在没有会话的情况下使用+# 它仍然会对查询进行意图分析+results = client.search(+ "how to implement OAuth 2.0 authorization code flow"+)-```bash-curl -X POST http://localhost:1933/api/v1/search/search \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "query": "best practices",- "session_id": "abc123",- "since": "2h",- "time_field": "updated_at",- "limit": 10- }'+for ctx in results.resources:+ print(f"Found: {ctx.uri} (score: {ctx.score:.3f})")```**CLI**```bash-openviking search "best practices" [--session-id abc123] [--limit 10]-openviking search "watch vs scheduled" --after 2026-03-15 --before 2026-03-15-```+# 带会话 ID 的搜索+openviking search "best practices" --session-id abc123-`--after` 会映射为 API `since`,`--before` 会映射为 API `until`。+# 带时间过滤的搜索+openviking search "watch vs scheduled" --after 2026-03-15 --before 2026-03-20-**响应**+# 不带会话的搜索(仍进行意图分析)+openviking search "how to implement OAuth 2.0 authorization code flow"+```++**响应示例**```json{- "status": "ok",- "result": {- "memories": [],- "resources": [- {- "uri": "viking://resources/docs/oauth-best-practices/",- "context_type": "resource",- "is_leaf": false,- "abstract": "OAuth 2.0 best practices for login pages...",- "score": 0.95,- "match_reason": "Context-aware match: OAuth login best practices"- }- ],- "skills": [],- "query_plan": {- "expanded_queries": ["OAuth 2.0 best practices", "login page security"]- },- "total": 1- },- "time": 0.1+ "status": "ok",+ "result": {+ "memories": [],+ "resources": [+ {+ "context_type": "resource",+ "uri": "viking://resources/docs/oauth-best-practices",+ "level": 1,+ "score": 0.95,+ "category": "",+ "match_reason": "Context-aware match: OAuth login best practices",+ "relations": [],+ "abstract": "OAuth 2.0 best practices for login pages...",+ "overview": "This guide covers OAuth 2.0 best practices including secure token handling, redirect URI validation, and state parameter usage..."+ }+ ],+ "skills": [],+ "query_plan": {+ "reasoning": "User is asking about OAuth implementation best practices, expanding to related security topics",+ "queries": [+ {+ "query": "OAuth 2.0 best practices",+ "context_type": "resource",+ "intent": "Find OAuth 2.0 implementation guidelines",+ "priority": 3+ },+ {+ "query": "login page security",+ "context_type": "resource",+ "intent": "Find login page security recommendations",+ "priority": 2+ }+ ]+ },+ "total": 1+ }}```-**示例:不使用会话的搜索**--**Python SDK (Embedded / HTTP)**+----```python-# search 也可以在没有会话的情况下使用-# 它仍然会对查询进行意图分析-results = client.search(- "how to implement OAuth 2.0 authorization code flow",-)+### grep()-for ctx in results.resources:- print(f"Found: {ctx.uri} (score: {ctx.score:.3f})")-```+通过模式(正则表达式)搜索内容。-**HTTP API**+#### 1. API 实现介绍-```bash-curl -X POST http://localhost:1933/api/v1/search/search \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "query": "how to implement OAuth 2.0 authorization code flow"- }'-```+`grep()` 方法在文件系统中执行正则表达式匹配搜索,用于查找包含特定模式的文件和内容行。与语义搜索不同,grep 是精确的模式匹配。----+**处理流程**:+1. 从指定 URI 开始遍历文件系统+2. 对每个文件内容进行正则表达式匹配+3. 收集匹配的行和位置信息+4. 返回匹配结果列表-### grep()+**代码入口**:+- `openviking_cli/client/sync_http.py:SyncHTTPClient.grep()` - Python SDK 入口(HTTP)+- `openviking/server/routers/search.py:grep()` - HTTP 路由+- `crates/ov_cli/src/commands/search.rs:grep()` - Rust CLI 命令-通过模式(正则表达式)搜索内容。+#### 2. 接口和参数说明**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| uri | str | 是 | - | 要搜索的 Viking URI |-| pattern | str | 是 | - | 搜索模式(正则表达式) |+| pattern | str | 是 | - | 搜索模式(正则表达式)|| case_insensitive | bool | 否 | False | 忽略大小写 || node_limit | int | 否 | None | 最大搜索节点数 || exclude_uri | str | 否 | None | 要排除在搜索之外的 URI 前缀 || level_limit | int | 否 | 5 | 最大目录遍历深度 |-**Python SDK (Embedded / HTTP)**+#### 3. 使用示例++**HTTP API**++```+POST /api/v1/search/grep+```++```bash+curl -X POST http://localhost:1933/api/v1/search/grep \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "uri": "viking://resources",+ "pattern": "authentication",+ "case_insensitive": true+ }'+```++**Python SDK**```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+results = client.grep(- "viking://resources/",+ "viking://resources","authentication",case_insensitive=True)@@ -346,45 +481,35 @@ for match in results['matches']:print(f" {match['content']}")```-**HTTP API**--```-POST /api/v1/search/grep-```+**CLI**```bash-curl -X POST http://localhost:1933/api/v1/search/grep \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "uri": "viking://resources/",- "pattern": "authentication",- "case_insensitive": true- }'-```+# 基础搜索+openviking grep viking://resources "authentication"-**CLI**+# 忽略大小写+openviking grep viking://resources "authentication" --ignore-case-```bash-openviking grep viking://resources/ "authentication" [--ignore-case]+# 指定深度限制+openviking grep viking://resources "TODO" --level-limit 3```-**响应**+**响应示例**```json{- "status": "ok",- "result": {- "matches": [- {- "uri": "viking://resources/docs/auth.md",- "line": 15,- "content": "User authentication is handled by..."- }- ],- "count": 1- },- "time": 0.1+ "status": "ok",+ "result": {+ "matches": [+ {+ "uri": "viking://resources/docs/auth.md",+ "line": 15,+ "content": "User authentication is handled by..."+ }+ ],+ "count": 1+ },+ "time": 0.1}```@@ -394,27 +519,32 @@ openviking grep viking://resources/ "authentication" [--ignore-case]通过 glob 模式匹配文件。+#### 1. API 实现介绍++`glob()` 方法使用文件通配符模式匹配 URI,类似于 Unix shell 的 glob 功能。用于按名称模式查找文件和目录。++**支持的模式语法**:+- `*` 匹配任意字符(除路径分隔符)+- `**` 递归匹配任意目录+- `?` 匹配单个字符+- `[]` 匹配字符范围++**代码入口**:+- `openviking_cli/client/sync_http.py:SyncHTTPClient.glob()` - Python SDK 入口(HTTP)+- `openviking/server/routers/search.py:glob()` - HTTP 路由+- `crates/ov_cli/src/commands/search.rs:glob()` - Rust CLI 命令++#### 2. 接口和参数说明+**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|-| pattern | str | 是 | - | Glob 模式(例如 `**/*.md`) |+| pattern | str | 是 | - | Glob 模式(例如 `**/*.md`)|| uri | str | 否 | "viking://" | 起始 URI || node_limit | int | 否 | None | 最大返回匹配数 |-**Python SDK (Embedded / HTTP)**--```python-# 查找所有 markdown 文件-results = client.glob("**/*.md", "viking://resources/")-print(f"Found {results['count']} markdown files:")-for uri in results['matches']:- print(f" {uri}")--# 查找所有 Python 文件-results = client.glob("**/*.py", "viking://resources/")-print(f"Found {results['count']} Python files")-```+#### 3. 使用示例**HTTP API**@@ -424,68 +554,87 @@ POST /api/v1/search/glob```bashcurl -X POST http://localhost:1933/api/v1/search/glob \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{- "pattern": "**/*.md",- "uri": "viking://resources/"- }'+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "pattern": "**/*.md",+ "uri": "viking://resources"+ }'+```++**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()++# 查找所有 markdown 文件+results = client.glob("**/*.md", "viking://resources")+print(f"Found {results['count']} markdown files:")+for uri in results['matches']:+ print(f" {uri}")++# 查找所有 Python 文件+results = client.glob("**/*.py", "viking://resources")+print(f"Found {results['count']} Python files")```**CLI**```bash-openviking glob "**/*.md" [--uri viking://resources/]+# 查找所有 markdown 文件+openviking glob "**/*.md" --uri viking://resources++# 查找所有 Python 文件+openviking glob "**/*.py"```-**响应**+**响应示例**```json{- "status": "ok",- "result": {- "matches": [- "viking://resources/docs/api.md",- "viking://resources/docs/guide.md"- ],- "count": 2- },- "time": 0.1+ "status": "ok",+ "result": {+ "matches": [+ "viking://resources/docs/api.md",+ "viking://resources/docs/guide.md"+ ],+ "count": 2+ },+ "time": 0.1}```----## 检索流程--```-查询 -> 意图分析 -> 向量搜索 (L0) -> 重排序 (L1) -> 结果-```--1. **意图分析**(仅 search):理解查询意图,扩展查询-2. **向量搜索**:使用 Embedding 查找候选项-3. **重排序**:使用内容重新评分以提高准确性-4. **结果**:返回 top-k 上下文-## 处理结果### 渐进式读取内容-**Python SDK (Embedded / HTTP)**+检索结果通常只包含 L0 摘要,你可以根据需要渐进式加载更多详细内容。++**Python SDK**```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+results = client.find("authentication")for ctx in results.resources:# 从 L0(摘要)开始 - 已包含在 ctx.abstract 中print(f"Abstract: {ctx.abstract}")- if not ctx.is_leaf:- # 获取 L1(概览)+ if ctx.level < 2:+ # 获取 L1(概览)用于目录overview = client.overview(ctx.uri)print(f"Overview: {overview[:500]}...")else:- # 加载 L2(内容)+ # 加载 L2(内容)用于文件content = client.read(ctx.uri)print(f"File content: {content}")```@@ -495,24 +644,29 @@ for ctx in results.resources:```bash# 步骤 1:搜索curl -X POST http://localhost:1933/api/v1/search/find \- -H "Content-Type: application/json" \- -H "X-API-Key: your-key" \- -d '{"query": "authentication"}'+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{"query": "authentication"}'# 步骤 2:读取目录结果的概览-curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://resources/docs/auth/" \- -H "X-API-Key: your-key"+curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://resources/docs/auth" \+ -H "X-API-Key: your-key"# 步骤 3:读取文件结果的完整内容curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://resources/docs/auth.md" \- -H "X-API-Key: your-key"+ -H "X-API-Key: your-key"```### 获取关联资源-**Python SDK (Embedded / HTTP)**+**Python SDK**```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+results = client.find("OAuth implementation")for ctx in results.resources:@@ -528,8 +682,8 @@ for ctx in results.resources:```bash# 获取资源的关联关系-curl -X GET "http://localhost:1933/api/v1/relations?uri=viking://resources/docs/auth/" \- -H "X-API-Key: your-key"+curl -X GET "http://localhost:1933/api/v1/relations?uri=viking://resources/docs/auth" \+ -H "X-API-Key: your-key"```## 最佳实践@@ -537,6 +691,11 @@ curl -X GET "http://localhost:1933/api/v1/relations?uri=viking://resources/docs/### 使用具体的查询```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+# 好 - 具体的查询results = client.find("OAuth 2.0 authorization code flow implementation")@@ -547,19 +706,28 @@ results = client.find("auth")### 限定搜索范围```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()+# 在相关范围内搜索以获得更好的结果results = client.find("error handling",- target_uri="viking://resources/my-project/"+ target_uri="viking://resources/my-project")```### 在对话中使用会话上下文```python-# 对于对话式搜索,使用会话+import openviking as ovfrom openviking.message import TextPart+client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+client.initialize()++# 对于对话式搜索,使用会话session = client.session()session.add_message("user", [TextPart(text="I'm building a login page")@@ -569,7 +737,7 @@ session.add_message("user", [results = client.search("best practices", session=session)```-### 相关文档+## 相关文档- [资源](02-resources.md) - 资源管理- [会话](05-sessions.md) - 会话上下文diff --git a/docs/zh/api/07-system.md b/docs/zh/api/07-system.mdindex 7b024cf68..909d324fd 100644--- a/docs/zh/api/07-system.md+++ b/docs/zh/api/07-system.md@@ -4,17 +4,22 @@ OpenViking 提供系统健康检查、可观测性和调试 API,用于监控## API 参考-### health()+### health-基础健康检查端点。无需认证。+#### 1. API 实现介绍-**Python SDK (Embedded / HTTP)**+基础健康检查端点,无需认证。返回服务版本号和健康状态。如果提供认证信息,还会返回认证模式和身份信息。-```python-# 检查系统是否健康-if client.observer.is_healthy():- print("System OK")-```+**代码入口**:+- `openviking/server/routers/system.py:health_check` - HTTP 路由+- `openviking_cli/client/sync_http.py:SyncHTTPClient.health` - SDK 入口+- `crates/ov_cli/src/commands/system.rs` - CLI 命令++#### 2. 接口和参数说明++无参数。++#### 3. 使用示例**HTTP API**@@ -26,27 +31,57 @@ GET /healthcurl -X GET http://localhost:1933/health```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933")+client.initialize()++healthy = client.health()+print(f"Healthy: {healthy}")+```+**CLI**```bash-openviking health+ov system health```-**响应**+**响应示例**```json{"status": "ok","healthy": true,- "version": "0.1.x"+ "version": "0.1.x",+ "auth_mode": "api_key"}```----### ready()+### ready++#### 1. API 实现介绍++部署环境使用的就绪探针。检查 AGFS、VectorDB、APIKeyManager 和 Ollama(如配置)的状态。当所有配置的子系统都准备完成时返回 200,否则返回 503。无需认证(专为 Kubernetes 探针设计)。++**代码入口**:+- `openviking/server/routers/system.py:readiness_check` - HTTP 路由++#### 2. 接口和参数说明-部署环境使用的就绪探针。当核心子系统都准备完成时返回 `200`,否则返回 `503`。+无参数。++**检查项说明**:+- `agfs`: Viking 文件系统是否可访问+- `vectordb`: 向量数据库是否健康+- `api_key_manager`: API 密钥管理器是否已加载+- `ollama`: Ollama 服务是否可达(仅当配置时)++#### 3. 使用示例**HTTP API**@@ -58,7 +93,7 @@ GET /readycurl -X GET http://localhost:1933/ready```-**响应**+**响应示例**```json{@@ -74,15 +109,22 @@ curl -X GET http://localhost:1933/ready----### status()+### status-获取系统状态,包括初始化状态和用户信息。+#### 1. API 实现介绍-**Python SDK (Embedded / HTTP)**+获取系统状态,包括初始化状态和当前认证用户信息。`result.user` 是认证请求的 `user_id`(来自 API 密钥或请求头),而非进程级服务默认值,客户端可用于解析多租户路径。-```python-print(client.observer.system())-```+**代码入口**:+- `openviking/server/routers/system.py:system_status` - HTTP 路由+- `openviking_cli/client/sync_http.py:SyncHTTPClient.get_status` - SDK 入口+- `crates/ov_cli/src/commands/system.rs` - CLI 命令++#### 2. 接口和参数说明++无参数。++#### 3. 使用示例**HTTP API**@@ -95,13 +137,20 @@ curl -X GET http://localhost:1933/api/v1/system/status \-H "X-API-Key: your-key"```+**Python SDK**++```python+status = client.get_status()+print(status)+```+**CLI**```bash-openviking status+ov system status```-**响应**+**响应示例**```json{@@ -116,26 +165,26 @@ openviking status----### wait_processed()+### wait_processed++#### 1. API 实现介绍++等待所有异步处理(embedding、语义生成)完成。该方法会阻塞直到所有队列中的任务处理完毕或超时。++**代码入口**:+- `openviking/server/routers/system.py:wait_processed` - HTTP 路由+- `openviking_cli/client/sync_http.py:SyncHTTPClient.wait_processed` - SDK 入口+- `crates/ov_cli/src/commands/system.rs` - CLI 命令-等待所有异步处理(embedding、语义生成)完成。+#### 2. 接口和参数说明**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|-| timeout | float | 否 | None | 超时时间(秒) |+| timeout | float | 否 | None | 超时时间(秒),None 表示无限等待 |-**Python SDK (Embedded / HTTP)**--```python-# 添加资源-client.add_resource("./docs/")--# 等待所有处理完成-status = client.wait_processed()-print(f"Processing complete: {status}")-```+#### 3. 使用示例**HTTP API**@@ -152,13 +201,24 @@ curl -X POST http://localhost:1933/api/v1/system/wait \}'```+**Python SDK**++```python+# 添加资源+client.add_resource("./docs/")++# 等待所有处理完成+status = client.wait_processed(timeout=60.0)+print(f"Processing complete: {status}")+```+**CLI**```bash-openviking wait [--timeout 60]+ov system wait --timeout 60```-**响应**+**响应示例**```json{@@ -189,19 +249,21 @@ Observer API 提供详细的组件级监控。### observer.queue-获取队列系统状态(embedding 和语义处理队列)。+#### 1. API 实现介绍-**Python SDK (Embedded / HTTP)**+获取队列系统状态(embedding 和语义处理队列)。显示各队列的待处理、进行中、已完成和错误数量。-```python-print(client.observer.queue)-# Output:-# [queue] (healthy)-# Queue Pending In Progress Processed Errors Total-# Embedding 0 0 10 0 10-# Semantic 0 0 10 0 10-# TOTAL 0 0 20 0 20-```+**代码入口**:+- `openviking/server/routers/observer.py:observer_queue` - HTTP 路由+- `openviking/service/debug_service.py:ObserverService.queue` - 核心实现+- `openviking/storage/observers/queue_observer.py` - 队列观察者+- `crates/ov_cli/src/commands/observer.rs` - CLI 命令++#### 2. 接口和参数说明++无参数。++#### 3. 使用示例**HTTP API**@@ -214,13 +276,25 @@ curl -X GET http://localhost:1933/api/v1/observer/queue \-H "X-API-Key: your-key"```+**Python SDK**++```python+print(client.observer.queue)+# 输出:+# [queue] (healthy)+# Queue Pending In Progress Processed Errors Total+# Embedding 0 0 10 0 10+# Semantic 0 0 10 0 10+# TOTAL 0 0 20 0 20+```+**CLI**```bash-openviking observer queue+ov observer queue```-**响应**+**响应示例**```json{@@ -229,7 +303,7 @@ openviking observer queue"name": "queue","is_healthy": true,"has_errors": false,- "status": "Queue Pending In Progress Processed Errors Total\nEmbedding 0 0 10 0 10\nSemantic 0 0 10 0 10\nTOTAL 0 0 20 0 20"+ "status": "Queue Pending In Progress Processed Errors Total\nEmbedding 0 0 10 0 10\nSemantic 0 0 10 0 10\nTOTAL 0 0 20 0 20"},"time": 0.1}@@ -239,22 +313,21 @@ openviking observer queue### observer.vikingdb+#### 1. API 实现介绍+获取 VikingDB 状态(集合、索引、向量数量)。-**Python SDK (Embedded / HTTP)**+**代码入口**:+- `openviking/server/routers/observer.py:observer_vikingdb` - HTTP 路由+- `openviking/service/debug_service.py:ObserverService.vikingdb` - 核心实现+- `openviking/storage/observers/vikingdb_observer.py` - VikingDB 观察者+- `crates/ov_cli/src/commands/observer.rs` - CLI 命令-```python-print(client.observer.vikingdb())-# Output:-# [vikingdb] (healthy)-# Collection Index Count Vector Count Status-# context 1 55 OK-# TOTAL 1 55+#### 2. 接口和参数说明-# 访问特定属性-print(client.observer.vikingdb().is_healthy) # True-print(client.observer.vikingdb().status) # Status table string-```+无参数。++#### 3. 使用示例**HTTP API**@@ -267,13 +340,28 @@ curl -X GET http://localhost:1933/api/v1/observer/vikingdb \-H "X-API-Key: your-key"```+**Python SDK**++```python+print(client.observer.vikingdb())+# 输出:+# [vikingdb] (healthy)+# Collection Index Count Vector Count Status+# context 1 55 OK+# TOTAL 1 55++# 访问特定属性+print(client.observer.vikingdb().is_healthy) # True+print(client.observer.vikingdb().status) # 状态表字符串+```+**CLI**```bash-openviking observer vikingdb+ov observer vikingdb```-**响应**+**响应示例**```json{@@ -282,7 +370,7 @@ openviking observer vikingdb"name": "vikingdb","is_healthy": true,"has_errors": false,- "status": "Collection Index Count Vector Count Status\ncontext 1 55 OK\nTOTAL 1 55"+ "status": "Collection Index Count Vector Count Status\ncontext 1 55 OK\nTOTAL 1 55"},"time": 0.1}@@ -292,19 +380,21 @@ openviking observer vikingdb### observer.models-获取模型子系统的聚合状态(VLM、embedding、rerank)。+#### 1. API 实现介绍-**Python SDK (Embedded / HTTP)**+获取模型子系统的聚合状态(VLM、embedding、rerank)。检查各模型提供者是否健康可用。-```python-print(client.observer.models)-# Output:-# [models] (healthy)-# provider_model healthy detail-# dense_embedding yes ...-# rerank yes ...-# vlm yes ...-```+**代码入口**:+- `openviking/server/routers/observer.py:observer_models` - HTTP 路由+- `openviking/service/debug_service.py:ObserverService.models` - 核心实现+- `openviking/storage/observers/models_observer.py` - 模型观察者+- `crates/ov_cli/src/commands/observer.rs` - CLI 命令++#### 2. 接口和参数说明++无参数。++#### 3. 使用示例**HTTP API**@@ -317,13 +407,25 @@ curl -X GET http://localhost:1933/api/v1/observer/models \-H "X-API-Key: your-key"```+**Python SDK**++```python+print(client.observer.models)+# 输出:+# [models] (healthy)+# provider_model healthy detail+# dense_embedding yes ...+# rerank yes ...+# vlm yes ...+```+**CLI**```bash-openviking observer models+ov observer models```-**响应**+**响应示例**```json{@@ -332,7 +434,7 @@ openviking observer models"name": "models","is_healthy": true,"has_errors": false,- "status": "provider_model healthy detail\ndense_embedding yes ...\nrerank yes ...\nvlm yes ..."+ "status": "provider_model healthy detail\ndense_embedding yes ...\nrerank yes ...\nvlm yes ..."},"time": 0.1}@@ -340,77 +442,57 @@ openviking observer models----另外还有两个仅 HTTP 暴露的 Observer 端点:+### observer.lock-- `GET /api/v1/observer/lock`-- `GET /api/v1/observer/retrieval`+#### 1. API 实现介绍-### observer.system+获取分布式锁系统状态。-获取整体系统状态,包括所有组件。+**代码入口**:+- `openviking/server/routers/observer.py:observer_lock` - HTTP 路由+- `openviking/service/debug_service.py:ObserverService.lock` - 核心实现+- `openviking/storage/observers/lock_observer.py` - 锁观察者+- `crates/ov_cli/src/commands/observer.rs` - CLI 命令-**Python SDK (Embedded / HTTP)**+#### 2. 接口和参数说明-```python-print(client.observer.system())-# Output:-# [queue] (healthy)-# ...-#-# [vikingdb] (healthy)-# ...-#-# [models] (healthy)-# ...-#-# [system] (healthy)-```+无参数。++#### 3. 使用示例**HTTP API**```-GET /api/v1/observer/system+GET /api/v1/observer/lock``````bash-curl -X GET http://localhost:1933/api/v1/observer/system \+curl -X GET http://localhost:1933/api/v1/observer/lock \-H "X-API-Key: your-key"```+**Python SDK**++```python+print(client.observer.lock)+```+**CLI**```bash-openviking observer system+ov observer transaction```-**响应**+**响应示例**```json{"status": "ok","result": {+ "name": "lock","is_healthy": true,- "errors": [],- "components": {- "queue": {- "name": "queue",- "is_healthy": true,- "has_errors": false,- "status": "..."- },- "vikingdb": {- "name": "vikingdb",- "is_healthy": true,- "has_errors": false,- "status": "..."- },- "vlm": {- "name": "vlm",- "is_healthy": true,- "has_errors": false,- "status": "..."- }- }+ "has_errors": false,+ "status": "..."},"time": 0.1}@@ -418,37 +500,57 @@ openviking observer system----### is_healthy()+### observer.retrieval-快速检查整个系统的健康状态。+#### 1. API 实现介绍-**Python SDK (Embedded / HTTP)**+获取检索质量指标。-```python-if client.observer.is_healthy():- print("System OK")-else:- print(client.observer.system())-```+**代码入口**:+- `openviking/server/routers/observer.py:observer_retrieval` - HTTP 路由+- `openviking/service/debug_service.py:ObserverService.retrieval` - 核心实现+- `openviking/storage/observers/retrieval_observer.py` - 检索观察者+- `crates/ov_cli/src/commands/observer.rs` - CLI 命令++#### 2. 接口和参数说明++无参数。++#### 3. 使用示例**HTTP API**```-GET /api/v1/debug/health+GET /api/v1/observer/retrieval``````bash-curl -X GET http://localhost:1933/api/v1/debug/health \+curl -X GET http://localhost:1933/api/v1/observer/retrieval \-H "X-API-Key: your-key"```-**响应**+**Python SDK**++```python+print(client.observer.retrieval)+```++**CLI**++```bash+ov observer retrieval+```++**响应示例**```json{"status": "ok","result": {- "healthy": true+ "name": "retrieval",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."},"time": 0.1}@@ -456,28 +558,101 @@ curl -X GET http://localhost:1933/api/v1/debug/health \----## 数据结构+### observer.system++#### 1. API 实现介绍-### ComponentStatus+获取整体系统状态,包括所有组件(queue、vikingdb、models、lock、retrieval)。-单个组件的状态信息。+**代码入口**:+- `openviking/server/routers/observer.py:observer_system` - HTTP 路由+- `openviking/service/debug_service.py:ObserverService.system` - 核心实现+- `crates/ov_cli/src/commands/observer.rs` - CLI 命令-| 字段 | 类型 | 说明 |-|------|------|------|-| name | str | 组件名称 |-| is_healthy | bool | 组件是否健康 |-| has_errors | bool | 组件是否存在错误 |-| status | str | 状态表格字符串 |+#### 2. 接口和参数说明-### SystemStatus+无参数。-整体系统状态,包括所有组件。+#### 3. 使用示例++**HTTP API**-| 字段 | 类型 | 说明 |-|------|------|------|-| is_healthy | bool | 整个系统是否健康 |-| components | Dict[str, ComponentStatus] | 各组件的状态 |-| errors | List[str] | 错误信息列表 |+```+GET /api/v1/observer/system+```++```bash+curl -X GET http://localhost:1933/api/v1/observer/system \+ -H "X-API-Key: your-key"+```++**Python SDK**++```python+print(client.observer.system())+# 输出:+# [queue] (healthy)+# ...+#+# [vikingdb] (healthy)+# ...+#+# [models] (healthy)+# ...+#+# [system] (healthy)+```++**CLI**++```bash+ov observer system+```++**响应示例**++```json+{+ "status": "ok",+ "result": {+ "is_healthy": true,+ "errors": [],+ "components": {+ "queue": {+ "name": "queue",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."+ },+ "vikingdb": {+ "name": "vikingdb",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."+ },+ "models": {+ "name": "models",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."+ },+ "lock": {+ "name": "lock",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."+ },+ "retrieval": {+ "name": "retrieval",+ "is_healthy": true,+ "has_errors": false,+ "status": "..."+ }+ }+ },+ "time": 0.1+}+```---diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex dddc6f676..72769cfd9 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -25,12 +25,56 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a| 重新生成 User Key | Y | Y(本 account) | N || 修改用户角色 | Y | N | N |+## CLI `--sudo` 选项++使用 `ov` CLI 执行需要 ROOT 权限的管理操作时,可以使用 `--sudo` 选项。该选项会使用配置文件 `~/.openviking/ovcli.conf` 中的 `root_api_key` 而非普通 `api_key`。++### 配置要求++在 `~/.openviking/ovcli.conf` 中配置 `root_api_key`:++```json+{+ "url": "http://localhost:1933",+ "api_key": "alice-user-key",+ "root_api_key": "your-root-api-key",+ ...+}+```++### 支持 `--sudo` 的命令++- `ov --sudo admin` - 账户和用户管理+- `ov --sudo system` - 系统工具命令+- `ov --sudo reindex` - 重建索引++### 使用限制++- `--sudo` 仅适用于管理类命令,用于普通数据命令会报错+- 必须配置 `root_api_key` 才能使用 `--sudo`+## API 参考-### create_account()+### create_account++#### 1. API 实现介绍创建新工作区及其首个管理员用户。+**处理流程:**+1. 验证请求者具有 ROOT 权限+2. 使用 API Key Manager 创建账户和初始管理员用户+3. 初始化账户级目录结构+4. 初始化管理员用户的个人目录+5. 返回账户信息和用户密钥(非 trusted 模式下)++**代码入口:**+- `openviking/server/routers/admin.py:create_account` - HTTP 路由+- `openviking/server/api_keys/new.py:APIKeyManager.create_account` - 核心实现+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_create_account` - Python SDK++#### 2. 接口和参数说明+**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 |@@ -40,6 +84,12 @@ Admin API 用于多租户环境下的账户和用户管理。包括工作区(a| isolate_user_scope_by_agent | bool | 否 | false | 是否按 agent 进一步隔离 user scope || isolate_agent_scope_by_user | bool | 否 | false | 是否按 user 进一步隔离 agent scope |+**说明:**+- 在 `trusted` 模式下,响应中不会包含 `user_key` 字段+- `isolate_user_scope_by_agent` 和 `isolate_agent_scope_by_user` 仅可通过 HTTP API 设置,Python SDK 和 CLI 暂不支持++#### 3. 使用示例+**HTTP API**```@@ -58,28 +108,6 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \}'```-**CLI**--```bash-openviking admin create-account acme --admin alice-```--**响应**--```json-{- "status": "ok",- "result": {- "account_id": "acme",- "admin_user_id": "alice",- "user_key": "7f3a9c1e...",- "isolate_user_scope_by_agent": true,- "isolate_agent_scope_by_user": false- },- "time": 0.1-}-```-`trusted` 模式示例:```bash@@ -112,7 +140,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \}'```-`trusted` 模式也支持“不带身份头”的 ROOT 回退写法:+`trusted` 模式也支持"不带身份头"的 ROOT 回退写法:```bashcurl -X POST http://localhost:1933/api/v1/admin/accounts \@@ -124,12 +152,67 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts \}'```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-key>")+client.initialize()++result = client.admin_create_account("acme", "alice")+print(f"Account created: {result['account_id']}")+print(f"Admin user: {result['admin_user_id']}")+print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")+```++**CLI**++```bash+# 需要 ROOT 权限,使用 --sudo+ov --sudo admin create-account acme --admin alice+```++**响应示例**++```json+{+ "status": "ok",+ "result": {+ "account_id": "acme",+ "admin_user_id": "alice",+ "user_key": "7f3a9c1e...",+ "isolate_user_scope_by_agent": true,+ "isolate_agent_scope_by_user": false+ },+ "time": 0.1+}+```+----### list_accounts()+### list_accounts++#### 1. API 实现介绍列出所有工作区(仅 ROOT)。+**处理流程:**+1. 验证请求者具有 ROOT 权限+2. 调用 API Key Manager 获取所有账户列表+3. 返回包含账户 ID、创建时间和用户数量的列表++**代码入口:**+- `openviking/server/routers/admin.py:list_accounts` - HTTP 路由+- `openviking/server/api_keys/new.py:APIKeyManager.get_accounts` - 核心实现+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_list_accounts` - Python SDK++#### 2. 接口和参数说明++无参数。++#### 3. 使用示例+**HTTP API**```@@ -141,13 +224,27 @@ curl -X GET http://localhost:1933/api/v1/admin/accounts \-H "X-API-Key: <root-key>"```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-key>")+client.initialize()++accounts = client.admin_list_accounts()+for account in accounts:+ print(f"Account: {account['account_id']}, created: {account['created_at']}, users: {account['user_count']}")+```+**CLI**```bash-openviking admin list-accounts+# 需要 ROOT 权限,使用 --sudo+ov --sudo admin list-accounts```-**响应**+**响应示例**```json{@@ -160,20 +257,39 @@ openviking admin list-accounts}```-在 `trusted` 模式下,同类响应不会返回 `user_key`。-----### delete_account()+### delete_account++#### 1. API 实现介绍删除工作区及其所有关联用户和数据(仅 ROOT)。+**处理流程:**+1. 验证请求者具有 ROOT 权限+2. 级联删除账户下的所有 AGFS 数据(user/、agent/、session/、resources/)+3. 级联删除向量数据库中该账户的所有记录+4. 最后删除账户元数据和所有用户密钥++**代码入口:**+- `openviking/server/routers/admin.py:delete_account` - HTTP 路由+- `openviking/server/api_keys/new.py:APIKeyManager.delete_account` - 核心实现+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_delete_account` - Python SDK++#### 2. 接口和参数说明+**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| account_id | str | 是 | - | 要删除的工作区 ID |+**说明:**+- 删除操作是不可逆的,会级联删除该账户下的所有数据+- 如果部分数据删除失败,会记录警告日志并继续删除其他数据++#### 3. 使用示例+**HTTP API**```@@ -185,19 +301,32 @@ curl -X DELETE http://localhost:1933/api/v1/admin/accounts/acme \-H "X-API-Key: <root-key>"```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-key>")+client.initialize()++result = client.admin_delete_account("acme")+print(f"Account deleted: {result['deleted']}")+```+**CLI**```bash-openviking admin delete-account acme+# 需要 ROOT 权限,使用 --sudo+ov --sudo admin delete-account acme```-**响应**+**响应示例**```json{"status": "ok","result": {- "account_id": "acme"+ "deleted": true},"time": 0.1}@@ -205,10 +334,25 @@ openviking admin delete-account acme----### register_user()+### register_user++#### 1. API 实现介绍在工作区中注册新用户。+**处理流程:**+1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN+2. 调用 API Key Manager 注册新用户+3. 初始化新用户的个人目录+4. 返回用户信息和用户密钥(非 trusted 模式下)++**代码入口:**+- `openviking/server/routers/admin.py:register_user` - HTTP 路由+- `openviking/server/api_keys/new.py:APIKeyManager.register_user` - 核心实现+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_register_user` - Python SDK++#### 2. 接口和参数说明+**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 |@@ -217,6 +361,13 @@ openviking admin delete-account acme| user_id | str | 是 | - | 用户 ID || role | str | 否 | "user" | 角色:"admin" 或 "user" |+**说明:**+- 在 `trusted` 模式下,响应中不会包含 `user_key` 字段+- ADMIN 只能在自己所属的 account 中注册用户+- 只有 ROOT 可以将新用户角色设置为 "admin"++#### 3. 使用示例+**HTTP API**```@@ -233,13 +384,30 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \}'```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-or-admin-key>")+client.initialize()++result = client.admin_register_user("acme", "bob", role="user")+print(f"User registered: {result['user_id']}")+print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")+```+**CLI**```bash-openviking admin register-user acme bob --role user+# ROOT 或本账户的 ADMIN 都可以执行+# 如果使用普通用户的 api_key 但该用户是 acme 的 ADMIN:+ov admin register-user acme bob --role user+# 如果使用 root_api_key(--sudo):+ov --sudo admin register-user acme bob --role user```-**响应**+**响应示例**```json{@@ -255,15 +423,39 @@ openviking admin register-user acme bob --role user----### list_users()+### list_users++#### 1. API 实现介绍列出工作区中的所有用户。+**处理流程:**+1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN+2. 调用 API Key Manager 获取用户列表+3. 应用可选的过滤条件(name、role)和分页限制+4. 返回用户列表(trusted 模式下不包含 user_key)++**代码入口:**+- `openviking/server/routers/admin.py:list_users` - HTTP 路由+- `openviking/server/api_keys/new.py:APIKeyManager.get_users` - 核心实现+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_list_users` - Python SDK++#### 2. 接口和参数说明+**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| account_id | str | 是 | - | 工作区 ID |+| limit | int | 否 | 100 | 返回用户数量上限 |+| name | str | 否 | null | 按用户 ID 过滤(前缀匹配) |+| role | str | 否 | null | 按角色过滤 |++**说明:**+- ADMIN 只能列出自己所属的 account 中的用户+- 在 `trusted` 模式下,响应中不会包含 `user_key` 字段++#### 3. 使用示例**HTTP API**@@ -272,17 +464,39 @@ GET /api/v1/admin/accounts/{account_id}/users``````bash+# 列出所有用户curl -X GET http://localhost:1933/api/v1/admin/accounts/acme/users \-H "X-API-Key: <root-or-admin-key>"++# 带过滤条件+curl -X GET "http://localhost:1933/api/v1/admin/accounts/acme/users?role=admin&limit=50" \+ -H "X-API-Key: <root-or-admin-key>"+```++**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-or-admin-key>")+client.initialize()++users = client.admin_list_users("acme")+for user in users:+ print(f"User: {user['user_id']}, role: {user['role']}")```**CLI**```bash-openviking admin list-users acme+# ROOT 或本账户的 ADMIN 都可以执行+# 如果使用普通用户的 api_key 但该用户是 acme 的 ADMIN:+ov admin list-users acme+# 如果使用 root_api_key(--sudo):+ov --sudo admin list-users acme```-**响应**+**响应示例**```json{@@ -297,10 +511,24 @@ openviking admin list-users acme----### remove_user()+### remove_user++#### 1. API 实现介绍从工作区中移除用户,同时删除其 API Key。+**处理流程:**+1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN+2. 调用 API Key Manager 删除用户及其 API Key+3. 返回删除确认++**代码入口:**+- `openviking/server/routers/admin.py:remove_user` - HTTP 路由+- `openviking/server/api_keys/new.py:APIKeyManager.remove_user` - 核心实现+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_remove_user` - Python SDK++#### 2. 接口和参数说明+**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 |@@ -308,6 +536,12 @@ openviking admin list-users acme| account_id | str | 是 | - | 工作区 ID || user_id | str | 是 | - | 要移除的用户 ID |+**说明:**+- ADMIN 只能移除自己所属的 account 中的用户+- 不能删除账户的最后一个 admin 用户++#### 3. 使用示例+**HTTP API**```@@ -319,20 +553,35 @@ curl -X DELETE http://localhost:1933/api/v1/admin/accounts/acme/users/bob \-H "X-API-Key: <root-or-admin-key>"```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-or-admin-key>")+client.initialize()++result = client.admin_remove_user("acme", "bob")+print(f"User deleted: {result['deleted']}")+```+**CLI**```bash-openviking admin remove-user acme bob+# ROOT 或本账户的 ADMIN 都可以执行+# 如果使用普通用户的 api_key 但该用户是 acme 的 ADMIN:+ov admin remove-user acme bob+# 如果使用 root_api_key(--sudo):+ov --sudo admin remove-user acme bob```-**响应**+**响应示例**```json{"status": "ok","result": {- "account_id": "acme",- "user_id": "bob"+ "deleted": true},"time": 0.1}@@ -340,17 +589,37 @@ openviking admin remove-user acme bob----### set_role()+### set_role++#### 1. API 实现介绍修改用户角色(仅 ROOT)。+**处理流程:**+1. 验证请求者具有 ROOT 权限+2. 调用 API Key Manager 更新用户角色+3. 返回更新后的用户信息++**代码入口:**+- `openviking/server/routers/admin.py:set_user_role` - HTTP 路由+- `openviking/server/api_keys/new.py:APIKeyManager.set_role` - 核心实现+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_set_role` - Python SDK++#### 2. 接口和参数说明+**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| account_id | str | 是 | - | 工作区 ID || user_id | str | 是 | - | 用户 ID |-| role | str | 是 | - | 新角色:"admin" 或 "user" |+| role | str | 是 | - | 新角色:"admin" 或 "user" 或 "root" |++**说明:**+- 只有 ROOT 可以修改用户角色+- 角色可以设置为 "admin"、"user" 或 "root"++#### 3. 使用示例**HTTP API**@@ -365,13 +634,26 @@ curl -X PUT http://localhost:1933/api/v1/admin/accounts/acme/users/bob/role \-d '{"role": "admin"}'```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-key>")+client.initialize()++result = client.admin_set_role("acme", "bob", "admin")+print(f"User: {result['user_id']}, new role: {result['role']}")+```+**CLI**```bash-openviking admin set-role acme bob admin+# 需要 ROOT 权限,使用 --sudo+ov --sudo admin set-role acme bob admin```-**响应**+**响应示例**```json{@@ -387,10 +669,25 @@ openviking admin set-role acme bob admin----### regenerate_key()+### regenerate_key++#### 1. API 实现介绍重新生成用户的 API Key,旧 Key 立即失效。+**处理流程:**+1. 验证请求者具有 ROOT 权限,或为本账户的 ADMIN+2. 调用 API Key Manager 重新生成用户密钥+3. 旧密钥立即失效+4. 返回新的用户密钥++**代码入口:**+- `openviking/server/routers/admin.py:regenerate_key` - HTTP 路由+- `openviking/server/api_keys/new.py:APIKeyManager.regenerate_key` - 核心实现+- `openviking_cli/client/sync_http.py:SyncHTTPClient.admin_regenerate_key` - Python SDK++#### 2. 接口和参数说明+**参数**| 参数 | 类型 | 必填 | 默认值 | 说明 |@@ -398,6 +695,12 @@ openviking admin set-role acme bob admin| account_id | str | 是 | - | 工作区 ID || user_id | str | 是 | - | 用户 ID |+**说明:**+- ADMIN 只能为自己所属的 account 中的用户重新生成密钥+- 旧密钥会立即失效,需要更新使用该密钥的客户端++#### 3. 使用示例+**HTTP API**```@@ -410,13 +713,29 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users/bob/key \-H "X-API-Key: <root-or-admin-key>"```+**Python SDK**++```python+import openviking as ov++client = ov.SyncHTTPClient(api_key="<root-or-admin-key>")+client.initialize()++result = client.admin_regenerate_key("acme", "bob")+print(f"New user key: {result['user_key']}")+```+**CLI**```bash-openviking admin regenerate-key acme bob+# ROOT 或本账户的 ADMIN 都可以执行+# 如果使用普通用户的 api_key 但该用户是 acme 的 ADMIN:+ov admin regenerate-key acme bob+# 如果使用 root_api_key(--sudo):+ov --sudo admin regenerate-key acme bob```-**响应**+**响应示例**```json{@@ -435,28 +754,30 @@ openviking admin regenerate-key acme bob### 典型管理流程```bash-# 步骤 1:ROOT 创建工作区,指定 alice 为首个 admin-openviking admin create-account acme --admin alice+# 步骤 1:ROOT 创建工作区,指定 alice 为首个 admin(需要 --sudo)+ov --sudo admin create-account acme --admin alice# 返回 alice 的 user_key# 步骤 2:alice(admin)注册普通用户 bob-openviking admin register-user acme bob --role user+# 配置文件中的 api_key 设为 alice 的 user_key,不需要 --sudo+ov admin register-user acme bob --role user# 返回 bob 的 user_key# 步骤 3:查看账户下所有用户-openviking admin list-users acme+ov admin list-users acme-# 步骤 4:ROOT 将 bob 提升为 admin-openviking admin set-role acme bob admin+# 步骤 4:ROOT 将 bob 提升为 admin(需要 --sudo)+ov --sudo admin set-role acme bob admin# 步骤 5:bob 丢失 key,重新生成(旧 key 立即失效)-openviking admin regenerate-key acme bob+# alice 作为 admin 可以执行,不需要 --sudo+ov admin regenerate-key acme bob# 步骤 6:移除用户-openviking admin remove-user acme bob+ov admin remove-user acme bob-# 步骤 7:删除整个工作区-openviking admin delete-account acme+# 步骤 7:删除整个工作区(需要 --sudo)+ov --sudo admin delete-account acme```### HTTP API 等效流程