Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(sdk): sync go/ts/python SDKs with server find/search, recall, an… (#3737)
Jiahui Zhou9eac8a6d3d60
diff --git a/benchmark/RAG/src/core/vector_store.py b/benchmark/RAG/src/core/vector_store.pyindex 44a30a3c5..cb40590c6 100644--- a/benchmark/RAG/src/core/vector_store.py+++ b/benchmark/RAG/src/core/vector_store.py@@ -27,19 +27,17 @@ class VikingStoreWrapper:return 0return len(self.enc.encode(str(text)))- def ingest(self, samples: List[StandardDoc], max_workers=10, monitor=None, ingest_mode="per_file") -> dict:+ def ingest(+ self, samples: List[StandardDoc], max_workers=10, monitor=None, ingest_mode="per_file"+ ) -> dict:start_time = time.time()total_input_tokens = 0total_output_tokens = 0total_embedding_tokens = 0-+if not samples:- return {- "time": time.time() - start_time,- "input_tokens": 0,- "output_tokens": 0- }-+ return {"time": time.time() - start_time, "input_tokens": 0, "output_tokens": 0}+if ingest_mode == "directory":doc_paths = [os.path.abspath(s.doc_path) for s in samples]common_ancestor = None@@ -48,9 +46,13 @@ class VikingStoreWrapper:common_ancestor = os.path.commonpath(doc_paths)except ValueError:common_ancestor = None-+if common_ancestor:- result = self.client.add_resource(common_ancestor, wait=True, telemetry=True)+ result = self.client.add_resource(+ path=common_ancestor,+ wait=True,+ options={"telemetry": True},+ )telemetry = result.get("telemetry", {})summary = telemetry.get("summary", {})tokens = summary.get("tokens", {})@@ -61,7 +63,11 @@ class VikingStoreWrapper:total_embedding_tokens = embedding_tokens.get("total", 0)else:for sample in samples:- result = self.client.add_resource(sample.doc_path, wait=True, telemetry=True)+ result = self.client.add_resource(+ path=sample.doc_path,+ wait=True,+ options={"telemetry": True},+ )telemetry = result.get("telemetry", {})summary = telemetry.get("summary", {})tokens = summary.get("tokens", {})@@ -72,7 +78,11 @@ class VikingStoreWrapper:total_embedding_tokens += embedding_tokens.get("total", 0)else:for sample in samples:- result = self.client.add_resource(sample.doc_path, wait=True, telemetry=True)+ result = self.client.add_resource(+ path=sample.doc_path,+ wait=True,+ options={"telemetry": True},+ )telemetry = result.get("telemetry", {})summary = telemetry.get("summary", {})tokens = summary.get("tokens", {})@@ -86,12 +96,16 @@ class VikingStoreWrapper:"time": time.time() - start_time,"input_tokens": total_input_tokens,"output_tokens": total_output_tokens,- "embedding_tokens": total_embedding_tokens+ "embedding_tokens": total_embedding_tokens,}def retrieve(self, query: str, topk: int, target_uri: str = "viking://resources"):"""Execute retrieval"""- return self.client.find(query=query, limit=topk, target_uri=target_uri)+ return self.client.find(+ query=query,+ target_uri=target_uri,+ limit=topk,+ )def read_resource(self, uri: str) -> str:"""Read resource content"""diff --git a/benchmark/custom/session_contention_benchmark.py b/benchmark/custom/session_contention_benchmark.pyindex 44cc6b38b..e7ee9588d 100644--- a/benchmark/custom/session_contention_benchmark.py+++ b/benchmark/custom/session_contention_benchmark.py@@ -284,10 +284,9 @@ class AsyncHTTPAdapter(LoadAdapter):return await self._client.add_resource(path=path,to=to,- reason=reason,wait=wait,timeout=timeout,- strict=False,+ options={"reason": reason, "strict": False},)async def wait_processed(self, timeout: Optional[float]) -> Any:diff --git a/benchmark/locomo/openclaw/import_to_ov.py b/benchmark/locomo/openclaw/import_to_ov.pyindex ea3413aeb..9511f3ed0 100644--- a/benchmark/locomo/openclaw/import_to_ov.py+++ b/benchmark/locomo/openclaw/import_to_ov.py@@ -287,11 +287,11 @@ async def viking_ingest(session_id=session_id,role=msg["role"],parts=[{"type": "text", "text": msg["text"]}],- created_at=msg_created_at,+ options={"created_at": msg_created_at} if msg_created_at else None,)# Commit- result = await client.commit_session(session_id, telemetry=True)+ result = await client.commit_session(session_id, options={"telemetry": True})# Accept both "committed" and "accepted" as success - accepted means the session was archivedif result.get("status") not in ("committed", "accepted"):diff --git a/benchmark/locomo/vikingbot/import_to_ov.py b/benchmark/locomo/vikingbot/import_to_ov.pyindex 4dd1f08ee..287e52579 100644--- a/benchmark/locomo/vikingbot/import_to_ov.py+++ b/benchmark/locomo/vikingbot/import_to_ov.py@@ -572,7 +572,7 @@ async def viking_ingest(# Create session. Safe to retry: no messages have been written yet.create_res = await _retry_transient_http("create_session",- lambda: client.create_session(memory_policy=memory_policy),+ lambda: client.create_session(options={"memory_policy": memory_policy}),)session_id = create_res["session_id"]@@ -589,8 +589,15 @@ async def viking_ingest(session_id=session_id,role=msg["role"],parts=[{"type": "text", "text": msg["text"]}],- created_at=msg_created_at,- peer_id=msg.get("peer_id"),+ options={+ key: value+ for key, value in {+ "created_at": msg_created_at,+ "peer_id": msg.get("peer_id"),+ }.items()+ if value is not None+ }+ or None,)before_commit = await _retry_transient_http(@@ -605,7 +612,7 @@ async def viking_ingest(try:result = await _retry_transient_http(f"commit_session session={session_id}",- lambda: client.commit_session(session_id, telemetry=True),+ lambda: client.commit_session(session_id, options={"telemetry": True}),attempts=2,)except _TRANSIENT_HTTP_ERRORS as exc:diff --git a/benchmark/longmemeval/openviking/import_to_ov.py b/benchmark/longmemeval/openviking/import_to_ov.pyindex 5da0a25f9..3a50962ec 100644--- a/benchmark/longmemeval/openviking/import_to_ov.py+++ b/benchmark/longmemeval/openviking/import_to_ov.py@@ -268,10 +268,10 @@ async def submit_viking_ingest(session_id=session_id,role=msg["role"],parts=[{"type": "text", "text": msg["text"]}],- created_at=msg_created_at,+ options={"created_at": msg_created_at} if msg_created_at else None,)- result = await client.commit_session(session_id, telemetry=True)+ result = await client.commit_session(session_id, options={"telemetry": True})if result.get("status") not in ("committed", "accepted"):raise RuntimeError(f"Commit failed: {result}")diff --git a/benchmark/retrieval/grep/vikingdb_bm25/effectiveness/step1_add_resource.py b/benchmark/retrieval/grep/vikingdb_bm25/effectiveness/step1_add_resource.pyindex caaf144d1..9522dd9b6 100644--- a/benchmark/retrieval/grep/vikingdb_bm25/effectiveness/step1_add_resource.py+++ b/benchmark/retrieval/grep/vikingdb_bm25/effectiveness/step1_add_resource.py@@ -48,16 +48,18 @@ def main():t0 = time.monotonic()try:try:- client.mkdir(args.parent)+ client.mkdir(uri=args.parent)except OpenVikingError as exc:if exc.code != "ALREADY_EXISTS":raiseresult = client.add_resource(path=source,parent=args.parent,- reason="benchmark effectiveness",wait=True,- processing_mode="semantic_and_vectors",+ options={+ "reason": "benchmark effectiveness",+ "processing_mode": "semantic_and_vectors",+ },)elapsed = time.monotonic() - t0root_uri = result.get("root_uri", "?")diff --git a/benchmark/retrieval/grep/vikingdb_bm25/performance/step1_add_resource.py b/benchmark/retrieval/grep/vikingdb_bm25/performance/step1_add_resource.pyindex 9f401d707..b7020226f 100644--- a/benchmark/retrieval/grep/vikingdb_bm25/performance/step1_add_resource.py+++ b/benchmark/retrieval/grep/vikingdb_bm25/performance/step1_add_resource.py@@ -111,16 +111,18 @@ def main():t0 = time.monotonic()try:try:- client.mkdir(parent_uri)+ client.mkdir(uri=parent_uri)except OpenVikingError as exc:if exc.code != "ALREADY_EXISTS":raiseresult = client.add_resource(path=dir_path,parent=parent_uri,- reason=f"benchmark perf: {rel_dir}",wait=True,- processing_mode="vectors_only",+ options={+ "reason": f"benchmark perf: {rel_dir}",+ "processing_mode": "vectors_only",+ },)elapsed = time.monotonic() - t0root_uri = result.get("root_uri", "?")diff --git a/bot/tests/test_openviking_add_resource.py b/bot/tests/test_openviking_add_resource.pyindex 94f88199a..826776717 100644--- a/bot/tests/test_openviking_add_resource.py+++ b/bot/tests/test_openviking_add_resource.py@@ -67,6 +67,6 @@ async def test_viking_client_add_resource_forwards_optional_target(target_uri):sdk_client.add_resource.assert_awaited_once_with(path="/tmp/doc.md",to=target_uri,- reason="conversation export",+ options={"reason": "conversation export"},)assert result["root_uri"] == expected_uridiff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.pyindex 30c30926a..bc46ec3b8 100644--- a/bot/vikingbot/openviking_mount/ov_server.py+++ b/bot/vikingbot/openviking_mount/ov_server.py@@ -577,7 +577,11 @@ class VikingClient:to: Optional[str] = None,) -> Optional[Dict[str, Any]]:"""添加资源到 Viking"""- result = await self.client.add_resource(path=local_path, to=to, reason=desc)+ result = await self.client.add_resource(+ path=local_path,+ to=to,+ options={"reason": desc},+ )return resultasync def list_resources(diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.mdindex 066ab69c4..3260725a5 100644--- a/docs/en/api/02-resources.md+++ b/docs/en/api/02-resources.md@@ -333,49 +333,55 @@ client.initialize()# Add local fileresult = client.add_resource(- "./documents/guide.md",- reason="User guide documentation"+ path="./documents/guide.md",+ options={"reason": "User guide documentation"},)print(f"Added: {result['root_uri']}")# Parse each document to Markdown without splitting its bodyresult = client.add_resource(- "./documents",- args={"parse_mode": "no_split"},+ path="./documents",+ options={"args": {"parse_mode": "no_split"}},)# Add from URL to specific locationresult = client.add_resource(- "https://example.com/api-docs.md",+ path="https://example.com/api-docs.md",to="viking://resources/external/api-docs.md",- reason="External API documentation"+ options={"reason": "External API documentation"},)# Recursively crawl a site (same-host BFS; depth levels, max_pages cap)result = client.add_resource(- "https://docs.openviking.ai/getting-started/01-introduction",+ path="https://docs.openviking.ai/getting-started/01-introduction",wait=True,timeout=180,- args={"depth": 1, "max_pages": 10},+ options={+ "args": {"depth": 1, "max_pages": 10},+ },)# Recursive crawl with path-prefix filters, also downloading file linksresult = client.add_resource(- "https://docs.openviking.ai/",- args={- "depth": 2,- "max_pages": 50,- "include_paths": ["/docs/"],- "exclude_paths": ["/changelog"],- "skip_download_links": False,+ path="https://docs.openviking.ai/",+ options={+ "args": {+ "depth": 2,+ "max_pages": 50,+ "include_paths": ["/docs/"],+ "exclude_paths": ["/changelog"],+ "skip_download_links": False,+ },},)# Add to the current user's private resource rootresult = client.add_resource(- "./documents/guide.md",+ path="./documents/guide.md",parent="viking://~/resources/docs",- create_parent=True,+ options={+ "create_parent": True,+ },)# Wait for processing to complete@@ -383,25 +389,29 @@ client.wait_processed()# Enable scheduled updatesclient.add_resource(- "./documents/guide.md",+ path="./documents/guide.md",to="viking://resources/guide.md",- watch_interval=60 # Update every 60 minutes+ options={+ "watch_interval": 60, # Update every 60 minutes+ },)# Add a Feishu document with a one-time user access tokenclient.add_resource(- "https://example.feishu.cn/docx/doc_token",- args={"feishu_access_token": "u-..."},+ path="https://example.feishu.cn/docx/doc_token",+ options={"args": {"feishu_access_token": "u-..."}},)# Add a Feishu document with scheduled user-token refreshclient.add_resource(- "https://example.feishu.cn/docx/doc_token",+ path="https://example.feishu.cn/docx/doc_token",to="viking://resources/feishu/doc",- watch_interval=1440,- args={- "feishu_access_token": "u-...",- "feishu_refresh_token": "r-...",+ options={+ "watch_interval": 1440,+ "args": {+ "feishu_access_token": "u-...",+ "feishu_refresh_token": "r-...",+ },},)```diff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.mdindex a1a66eade..0a68f2014 100644--- a/docs/en/api/03-filesystem.md+++ b/docs/en/api/03-filesystem.md@@ -45,7 +45,7 @@ List directory contents.```pythonentries = client.ls(- "viking://resources/",+ uri="viking://resources/",node_limit=200,sort_by="mtime",sort_order="desc",@@ -141,7 +141,7 @@ Get directory tree structure.**Python HTTP SDK**```python-entries = client.tree("viking://resources/")+entries = client.tree(uri="viking://resources/")for entry in entries:type_str = "dir" if entry['isDir'] else "file"print(f"{entry['rel_path']} - {type_str}")@@ -225,12 +225,12 @@ Get file or directory status information. For directories, returns the count of**Python HTTP SDK**```python-info = client.stat("viking://resources/docs/api.md")+info = client.stat(uri="viking://resources/docs/api.md")print(f"Size: {info['size']}")print(f"Is directory: {info['isDir']}")# For directories, returns item count-dir_info = client.stat("viking://resources/docs")+dir_info = client.stat(uri="viking://resources/docs")if dir_info.get('isDir'):print(f"Item count: {dir_info.get('count')}")```@@ -328,7 +328,7 @@ Get logical extended attributes for a file or directory.**Python SDK (HTTP)**```python-attrs = client.attrs("viking://resources/docs/api.md")+attrs = client.attrs(uri="viking://resources/docs/api.md")print(attrs["attrs"]["tags"])```@@ -435,8 +435,8 @@ Create a directory.**Python HTTP SDK**```python-client.mkdir("viking://resources/new-project/")-client.mkdir("viking://resources/new-project/", description="API docs directory")+client.mkdir(uri="viking://resources/new-project/")+client.mkdir(uri="viking://resources/new-project/", description="API docs directory")```**TypeScript SDK**@@ -510,10 +510,10 @@ Invalid URI formats, unsupported schemes, and non-public scopes return `INVALID_```python# Remove single file-client.rm("viking://resources/docs/old.md")+client.rm(uri="viking://resources/docs/old.md")# Remove directory recursively-client.rm("viking://resources/old-project/", recursive=True)+client.rm(uri="viking://resources/old-project/", recursive=True)```**TypeScript SDK**@@ -603,8 +603,8 @@ Move file or directory.```pythonclient.mv(- "viking://resources/old-name/",- "viking://resources/new-name/"+ from_uri="viking://resources/old-name/",+ to_uri="viking://resources/new-name/",)```diff --git a/docs/en/api/04-skills.md b/docs/en/api/04-skills.mdindex 3c041ac63..801f49d9e 100644--- a/docs/en/api/04-skills.md+++ b/docs/en/api/04-skills.md@@ -94,7 +94,7 @@ OpenViking automatically detects and converts MCP tool definitions to skill form**Conversion Example**:Input (MCP format):-```python+```json{"name": "search_web","description": "Search the web",@@ -116,7 +116,7 @@ Input (MCP format):```Output (Skill format):-```python+```json{"name": "search-web","description": "Search the web",@@ -287,7 +287,7 @@ Search the web for current information.- **limit** (integer, optional): Max results, default 10"""}-result = client.add_skill(skill)+result = client.add_skill(data=skill)print(f"Added: {result['root_uri']}")# Approach 2: Using MCP Tool format (auto-detected and converted@@ -305,20 +305,20 @@ mcp_tool = {"required": ["expression"]}}-result = client.add_skill(mcp_tool)+result = client.add_skill(data=mcp_tool)print(f"Added: {result['uri']}")# Approach 3: Add from local SKILL.md file-result = client.add_skill("./skills/search-web/SKILL.md")+result = client.add_skill(data="./skills/search-web/SKILL.md")print(f"Added: {result['uri']}")# Approach 4: Add from directory containing SKILL.md (auxiliary files included-result = client.add_skill("./skills/code-runner/")+result = client.add_skill(data="./skills/code-runner/")print(f"Added: {result['uri']}")print(f"Auxiliary files: {result['auxiliary_files']}")# Wait for processing completion-result = client.add_skill("./skills/my-skill/", wait=True)+result = client.add_skill(data="./skills/my-skill/", wait=True)client.wait_processed()```@@ -474,7 +474,11 @@ curl -X GET "http://localhost:1933/api/v1/skills?node_limit=1000" \**Python SDK**```python-skill = client.get_skill("search-web", include_content=True, include_files=True)+skill = client.get_skill(+ skill_name="search-web",+ include_content=True,+ include_files=True,+)print(skill["name"])print(skill.get("content"))```@@ -507,7 +511,7 @@ curl -X GET "http://localhost:1933/api/v1/skills/search-web?include_content=true**Python SDK**```python-results = client.find_skills("search the internet", limit=5)+results = client.find_skills(query="search the internet", limit=5)for skill in results["skills"]:print(skill["name"], skill["score"])@@ -545,8 +549,12 @@ curl -X POST http://localhost:1933/api/v1/skills/find \**Python SDK**```python-validated = client.validate_skill({"name": "search-web", "description": "..."})-updated = client.update_skill("search-web", "./skills/search-web", wait=True)+validated = client.validate_skill(data={"name": "search-web", "description": "..."})+updated = client.update_skill(+ skill_name="search-web",+ data="./skills/search-web",+ wait=True,+)```**TypeScript SDK**@@ -600,7 +608,7 @@ curl -X PUT http://localhost:1933/api/v1/skills/search-web \**Python SDK**```python-client.delete_skill("old-skill")+client.delete_skill(skill_name="old-skill")```**TypeScript SDK**@@ -708,14 +716,14 @@ A successful update returns the same processing result as `add_skill` with an adskill = {"name": "search-web","description": "Search the web for current information using Google",- ...+ # Additional skill fields}# Less helpful - too vagueskill = {"name": "search","description": "Search",- ...+ # Additional skill fields}```diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.mdindex fabfce738..46a45d9b0 100644--- a/docs/en/api/05-sessions.md+++ b/docs/en/api/05-sessions.md@@ -99,7 +99,8 @@ curl -X POST http://localhost:1933/api/v1/sessions \import openviking as ov# Use HTTP client-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# Create new session (auto-generated ID)result = await client.create_session()@@ -111,13 +112,15 @@ print(f"Session ID: {result['session_id']}")# Create new session with a custom auto-commit policyresult = await client.create_session(- auto_commit_policy={- "pending_token_threshold": 8000,- "message_count_threshold": 40,- "idle_timeout_seconds": 600,- "keep_recent_count": 10,- "min_commit_interval_seconds": 0,- }+ options={+ "auto_commit_policy": {+ "pending_token_threshold": 8000,+ "message_count_threshold": 40,+ "idle_timeout_seconds": 600,+ "keep_recent_count": 10,+ "min_commit_interval_seconds": 0,+ },+ },)print(result["auto_commit_policy"])```@@ -200,9 +203,10 @@ curl -X GET http://localhost:1933/api/v1/sessions \**Python SDK**```python-import openviking as ov+from openviking_sdk import AsyncHTTPClient-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()sessions = await client.list_sessions()for s in sessions:@@ -301,18 +305,19 @@ curl -X GET http://localhost:1933/api/v1/sessions/a1b2c3d4 \**Python SDK**```python-import openviking as ov+from openviking_sdk import AsyncHTTPClient-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# Get existing session (raises NotFoundError if not found)-info = await client.get_session("a1b2c3d4")+info = await client.get_session(session_id="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)+info = await client.get_session(session_id="a1b2c3d4", auto_create=True)```**TypeScript SDK**@@ -461,11 +466,13 @@ curl -X PATCH http://localhost:1933/api/v1/sessions/a1b2c3d4/config \```pythonresult = client.update_session_config(- "a1b2c3d4",- memory_extraction_config={- "events": {"tags": ["team=search", "channel=app"]}+ session_id="a1b2c3d4",+ options={+ "memory_extraction_config": {+ "events": {"tags": ["team=search", "channel=app"]}+ },+ "auto_commit_policy": {"message_count_threshold": 25},},- auto_commit_policy={"message_count_threshold": 25},)```@@ -725,11 +732,12 @@ curl -X GET "http://localhost:1933/api/v1/sessions/a1b2c3d4/context?token_budget**Python SDK**```python-import openviking as ov+from openviking_sdk import AsyncHTTPClient-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()-context = await client.get_session_context("a1b2c3d4", token_budget=128000)+context = await client.get_session_context(session_id="a1b2c3d4", token_budget=128000)print(context["latest_archive_overview"])print(len(context["messages"]))```@@ -836,9 +844,13 @@ curl -X GET "http://localhost:1933/api/v1/sessions/a1b2c3d4/archives/archive_002```pythonimport openviking as ov-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()-archive = await client.get_session_archive("a1b2c3d4", "archive_002")+archive = await client.get_session_archive(+ session_id="a1b2c3d4",+ archive_id="archive_002",+)print(archive["archive_id"])print(archive["overview"])print(len(archive["messages"]))@@ -950,10 +962,11 @@ curl -X DELETE http://localhost:1933/api/v1/sessions/a1b2c3d4 \```pythonimport openviking as ov-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# Delete session-await client.delete_session("a1b2c3d4")+await client.delete_session(session_id="a1b2c3d4")```**TypeScript SDK**@@ -1016,8 +1029,8 @@ Add a message to the session. Supports two modes: simple text mode and Parts mod|-----------|------|----------|---------|-------------|| 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) |+| parts | List[dict \| MessagePart] | Conditional | - | SDK part dictionaries or `TextPart`/`ContextPart`/`ImagePart`/`ToolPart` objects; HTTP API accepts dictionaries only; mutually exclusive with content |+| content | str | Conditional | - | Message text content (simple mode; mutually exclusive with parts) || created_at | str | No | None | Optional ISO 8601 timestamp to persist on the message || peer_id | str | No | None | Optional stable interaction peer identity |@@ -1030,7 +1043,7 @@ Add a message to the session. Supports two modes: simple text mode and Parts mod**Part Types (Python SDK)**```python-from openviking.message import TextPart, ImagePart, ContextPart, ToolPart+from openviking_sdk import ContextPart, ImagePart, TextPart, ToolPart# Text contentTextPart(text="Hello, how can I help?")@@ -1042,7 +1055,7 @@ ImagePart(url="https://example.com/photo.png", detail="auto")ContextPart(uri="viking://resources/docs/auth/",context_type="resource", # "resource", "memory", or "skill"- abstract="Authentication guide..."+ abstract="Authentication guide...",)# Tool call@@ -1051,11 +1064,13 @@ ToolPart(tool_name="search_web",skill_uri="viking://~/skills/search-web/",tool_input={"query": "OAuth best practices"},- tool_output="",- tool_status="pending" # "pending", "running", "completed", "error"+ tool_status="pending", # "pending", "running", "completed", "error")```+You can also pass the equivalent dictionaries when you need to share the same+payload shape with HTTP, Go, or TypeScript code.+#### 3. Usage Examples**HTTP API**@@ -1121,15 +1136,15 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \```pythonimport openviking as ov-from openviking.message import TextPart, ImagePart, ContextPart-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# Simple mode: Add user messageawait client.add_message(session_id="a1b2c3d4",role="user",- content="How do I authenticate users?"+ content="How do I authenticate users?",)# Parts mode: Add assistant message with context reference@@ -1141,9 +1156,9 @@ await client.add_message(ContextPart(uri="viking://resources/docs/auth/",context_type="resource",- abstract="Authentication guide"- )- ]+ abstract="Authentication guide",+ ),+ ],)# Parts mode: Add user message with an image URL@@ -1153,7 +1168,7 @@ await client.add_message(parts=[TextPart(text="Remember this studio layout."),ImagePart(url="https://example.com/studio.png", detail="auto"),- ]+ ],)```@@ -1250,9 +1265,10 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages/batch \**Python SDK**```python-import openviking as ov+from openviking_sdk import AsyncHTTPClient-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# Add messages in batchresult = await client.batch_add_messages(@@ -1433,15 +1449,16 @@ curl -X GET http://localhost:1933/api/v1/tasks/{task_id} \```pythonimport openviking as ov-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# Commit returns immediately with task_id; summary + memory extraction runs in background-result = await client.commit_session("a1b2c3d4")+result = await client.commit_session(session_id="a1b2c3d4")print(f"Status: {result['status']}")print(f"Task ID: {result['task_id']}")# Poll background task status-task = await client.get_task(result["task_id"])+task = await client.get_task(task_id=result["task_id"])if task["status"] == "completed":memories = task["result"]["memories_extracted"]total = sum(memories.values())@@ -1644,11 +1661,11 @@ An empty `memory_diff.json` (all counts zero) is written when long-term memory e**Python SDK**```python-import openviking as ov-from openviking.message import TextPart, ContextPart+from openviking_sdk import AsyncHTTPClient, ContextPart, TextPart# Initialize client-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# Create new sessionsession_result = await client.create_session()@@ -1659,32 +1676,37 @@ print(f"Session created: {session_id}")await client.add_message(session_id=session_id,role="user",- content="How do I configure embedding?"+ content="How do I configure embedding?",)# Search with session context-results = await client.search("embedding configuration", session_id=session_id)+results = await client.search(+ query="embedding configuration",+ session_id=session_id,+)# Add assistant message with context reference-if results.resources:+resources = results.get("resources", [])+if resources:+ resource = resources[0]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,+ uri=resource["uri"],context_type="resource",- abstract=results.resources[0].abstract- )- ]+ abstract=resource.get("abstract", ""),+ ),+ ],)# Commit session (returns immediately; summary + memory extraction runs in background)-commit_result = await client.commit_session(session_id)+commit_result = await client.commit_session(session_id=session_id)print(f"Task ID: {commit_result['task_id']}")# Optional: poll for completion-task = await client.get_task(commit_result["task_id"])+task = await client.get_task(task_id=commit_result["task_id"])if task and task["status"] == "completed":memories = task["result"]["memories_extracted"]total = sum(memories.values())@@ -1741,16 +1763,16 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \```python# Commit after significant interactions-session_info = await client.get_session(session_id)+session_info = await client.get_session(session_id=session_id)if session_info["message_count"] > 10:- await client.commit_session(session_id)+ await client.commit_session(session_id=session_id)```### Use Session Context for Search```python# Better search results with conversation context-results = await client.search(query, session_id=session_id)+results = await client.search(query=query, session_id=session_id)```---diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.mdindex c70253f25..c3cfc7bec 100644--- a/docs/en/api/06-retrieval.md+++ b/docs/en/api/06-retrieval.md@@ -180,42 +180,45 @@ Tags must use strict `k=v` strings. When multiple tags are provided, `find()` re```pythonimport openviking as ovfrom openviking.retrieve import ContextType+from openviking_sdk import TextPartclient = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()# Basic search-results = client.find("how to authenticate users")+results = client.find(query="how to authenticate users")# Search with filter and time rangerecent_emails = client.find(- "invoice",+ query="invoice",target_uri="viking://resources/email",- since="7d",- time_field="created_at",+ options={+ "since": "7d",+ "time_field": "created_at",+ },)# Search only memories and resourcestyped_results = client.find(- "authentication",- context_type=[ContextType.MEMORY, ContextType.RESOURCE],+ query="authentication",+ options={"context_type": [ContextType.MEMORY, ContextType.RESOURCE]},)# Search by local image, bytes, data URI, HTTP URL, or viking:// URI-image_results = client.find(image="/path/to/photo.png")+image_results = client.find(query="", image="/path/to/photo.png")# Search by explicit retrieval tags. Multiple tags are AND-ed.tagged_results = client.find(- "rollback runbook",- tags=["env=prod", "team=search"],+ query="rollback runbook",+ options={"tags": ["env=prod", "team=search"]},)# 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]}...")+for context in results.get("resources", []):+ print(f"URI: {context['uri']}")+ print(f"Score: {context.get('score', 0.0):.3f}")+ print(f"Type: {context.get('context_type')}")+ print(f"Abstract: {context.get('abstract', '')[:100]}...")print("---")```@@ -224,19 +227,19 @@ for ctx in results.resources:```python# Search only in resourcesresults = client.find(- "authentication",- target_uri="viking://resources"+ query="authentication",+ target_uri="viking://resources",)# Search only in user memoriesresults = client.find(- "preferences",+ query="preferences",target_uri="viking://~/memories")# Search only in current-user resourcesresults = client.find(- "private docs",+ query="private docs",target_uri="viking://~/resources")@@ -246,18 +249,18 @@ peer_client = ov.SyncHTTPClient(api_key="your-key",actor_peer_id="web-visitor-alice",)-peer_results = peer_client.find("invoice follow-up")+peer_results = peer_client.find(query="invoice follow-up")# Search only in skillsresults = client.find(- "web search",+ query="web search",target_uri="viking://~/skills")# Search in specific projectresults = client.find(- "API endpoints",- target_uri="viking://resources/my-project"+ query="API endpoints",+ target_uri="viking://resources/my-project",)```@@ -454,31 +457,35 @@ curl -X POST http://localhost:1933/api/v1/search/search \```pythonimport openviking as ovfrom openviking.retrieve import ContextType-from openviking.message import TextPartclient = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()# Create session with conversation context-session = client.session()-session.add_message("user", [- TextPart(text="I'm building a login page with OAuth")-])-session.add_message("assistant", [- TextPart(text="I can help you with OAuth implementation.")-])+session_info = client.create_session()+session = client.session(session_id=session_info["session_id"])+session.add_message(+ role="user",+ parts=[TextPart(text="I'm building a login page with OAuth")],+)+session.add_message(+ role="assistant",+ parts=[TextPart(text="I can help you with OAuth implementation.")],+)# Search understands conversation contextresults = client.search(- "best practices",- session=session,- context_type=ContextType.SKILL,- since="2h"+ query="best practices",+ session_id=session.session_id,+ options={+ "context_type": ContextType.SKILL,+ "since": "2h",+ },)-for ctx in results.resources:- print(f"Found: {ctx.uri}")- print(f"Abstract: {ctx.abstract[:200]}...")+for context in results.get("resources", []):+ print(f"Found: {context['uri']}")+ print(f"Abstract: {context.get('abstract', '')[:200]}...")```**Search without Session**@@ -487,17 +494,20 @@ for ctx in results.resources:# search can also be used without session# It still performs intent analysis on the queryresults = client.search(- "how to implement OAuth 2.0 authorization code flow"+ query="how to implement OAuth 2.0 authorization code flow")-for ctx in results.resources:- print(f"Found: {ctx.uri} (score: {ctx.score:.3f})")+for context in results.get("resources", []):+ print(f"Found: {context['uri']} (score: {context.get('score', 0.0):.3f})")```**Image Search**```python-results = client.search("similar poster", image="/path/to/poster.png")+results = client.search(+ query="similar poster",+ image="/path/to/poster.png",+)```**TypeScript SDK**@@ -823,8 +833,8 @@ client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()results = client.grep(- "viking://resources",- "authentication",+ uri="viking://resources",+ pattern="authentication",case_insensitive=True,node_limit=1024,)@@ -945,13 +955,17 @@ client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()# Find all markdown files (defaults to returning at most 256 matches)-results = client.glob("**/*.md", "viking://resources")+results = client.glob(pattern="**/*.md", uri="viking://resources")print(f"Found {results['count']} markdown files:")for uri in results['matches']:print(f" {uri}")# Find all Python files with a higher explicit cap-results = client.glob("**/*.py", "viking://resources", node_limit=1024)+results = client.glob(+ pattern="**/*.py",+ uri="viking://resources",+ node_limit=1024,+)print(f"Found {results['count']} Python files")```@@ -1015,19 +1029,19 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()-results = client.find("authentication")+results = client.find(query="authentication")-for ctx in results.resources:- # Start with L0 (abstract) - already in ctx.abstract- print(f"Abstract: {ctx.abstract}")+for context in results.get("resources", []):+ # Start with L0 (abstract) - already in context["abstract"]+ print(f"Abstract: {context.get('abstract', '')}")- if ctx.level < 2:+ if context.get("level", 0) < 2:# Get L1 (overview) for directories- overview = client.overview(ctx.uri)+ overview = client.overview(uri=context["uri"])print(f"Overview: {overview[:500]}...")else:# Load L2 (content) for files- content = client.read(ctx.uri)+ content = client.read(uri=context["uri"])print(f"File content: {content}")```@@ -1060,10 +1074,10 @@ client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()# Good - specific query-results = client.find("OAuth 2.0 authorization code flow implementation")+results = client.find(query="OAuth 2.0 authorization code flow implementation")# Less effective - too broad-results = client.find("auth")+results = client.find(query="auth")```### Scope Your Searches@@ -1076,8 +1090,8 @@ client.initialize()# Search in relevant scope for better resultsresults = client.find(- "error handling",- target_uri="viking://resources/my-project"+ query="error handling",+ target_uri="viking://resources/my-project",)```@@ -1085,19 +1099,24 @@ results = client.find(```pythonimport openviking as ov-from openviking.message import TextPart+from openviking_sdk import TextPartclient = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()# For conversational search, use session-session = client.session()-session.add_message("user", [- TextPart(text="I'm building a login page")-])+session_info = client.create_session()+session = client.session(session_id=session_info["session_id"])+session.add_message(+ role="user",+ parts=[TextPart(text="I'm building a login page")],+)# Search understands context-results = client.search("best practices", session=session)+results = client.search(+ query="best practices",+ session_id=session.session_id,+)```## Related Documentationdiff --git a/docs/en/api/07-system.md b/docs/en/api/07-system.mdindex 754fd591a..c693af1cb 100644--- a/docs/en/api/07-system.md+++ b/docs/en/api/07-system.md@@ -279,7 +279,7 @@ curl -X POST http://localhost:1933/api/v1/system/consistency \**Python SDK**```python-report = client.check_consistency("viking://resources/my-project")+report = client.check_consistency(uri="viking://resources/my-project")print(report["ok"])print(report["missing_records"])```@@ -370,7 +370,7 @@ curl -X POST http://localhost:1933/api/v1/system/wait \```python# Add resources-client.add_resource("./docs/")+client.add_resource(path="./docs/")# Wait for all processing to completestatus = client.wait_processed(timeout=60.0)diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex d075adb45..befb18054 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -252,14 +252,18 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-key>")client.initialize()-result = client.admin_create_account("acme", "alice", seed="alice-seed")+result = client.admin_create_account(+ account_id="acme",+ admin_user_id="alice",+ seed="alice-seed",+)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)')}")result = client.admin_create_account(- "acme-private",- "alice",+ account_id="acme-private",+ admin_user_id="alice",user_config={"add_targets": {"resource_uri": "viking://~/resources",@@ -459,7 +463,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-key>")client.initialize()-result = client.admin_delete_account("acme")+result = client.admin_delete_account(account_id="acme")print(f"Account deleted: {result['deleted']}")```@@ -566,13 +570,18 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-or-admin-key>")client.initialize()-result = client.admin_register_user("acme", "bob", role="user", seed="bob-seed")+result = client.admin_register_user(+ account_id="acme",+ user_id="bob",+ role="user",+ seed="bob-seed",+)print(f"User registered: {result['user_id']}")print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")result = client.admin_register_user(- "acme",- "bob-private",+ account_id="acme",+ user_id="bob-private",role="user",user_config={"add_targets": {"resource_uri": "viking://~/resources/project-a"}},)@@ -691,7 +700,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-or-admin-key>")client.initialize()-users = client.admin_list_users("acme")+users = client.admin_list_users(account_id="acme")for user in users:print(f"User: {user['user_id']}, role: {user['role']}")```@@ -890,7 +899,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-key>")client.initialize()-result = client.admin_set_role("acme", "bob", "admin")+result = client.admin_set_role(account_id="acme", user_id="bob", role="admin")print(f"User: {result['user_id']}, new role: {result['role']}")```@@ -988,7 +997,11 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-or-admin-key>")client.initialize()-result = client.admin_regenerate_key("acme", "bob", seed="bob-new-seed")+result = client.admin_regenerate_key(+ account_id="acme",+ user_id="bob",+ seed="bob-new-seed",+)print(f"New user key: {result['user_key']}")```diff --git a/docs/en/api/11-snapshot.md b/docs/en/api/11-snapshot.mdindex de8972f04..5b19977bb 100644--- a/docs/en/api/11-snapshot.md+++ b/docs/en/api/11-snapshot.md@@ -659,11 +659,21 @@ client.initialize()root = "viking://resources/my_project"# 1. Write initial content and commit v1-client.write(f"{root}/guide.md", "# Guide\n\nv1 content\n", mode="create", wait=True)+client.write(+ uri=f"{root}/guide.md",+ content="# Guide\n\nv1 content\n",+ mode="create",+ wait=True,+)v1 = client.snapshot.commit(message="v1 initial import")# 2. Modify and commit v2-client.write(f"{root}/guide.md", "# Guide\n\nv2 content\n", mode="replace", wait=True)+client.write(+ uri=f"{root}/guide.md",+ content="# Guide\n\nv2 content\n",+ mode="replace",+ wait=True,+)v2 = client.snapshot.commit(message="v2 update")# 3. Walk historydiff --git a/docs/en/api/12-content.md b/docs/en/api/12-content.mdindex d1f318ec1..89f21e121 100644--- a/docs/en/api/12-content.md+++ b/docs/en/api/12-content.md@@ -18,7 +18,7 @@ Read the L0 abstract (an approximately 100-token summary), excluding the OKF hea**Python SDK**```python-abstract = client.abstract("viking://resources/docs/")+abstract = client.abstract(uri="viking://resources/docs/")print(f"Abstract: {abstract}")# Output: "Documentation for the project API, covering authentication, endpoints..."```@@ -84,7 +84,7 @@ Read the L1 overview for a directory, excluding the OKF header.**Python SDK**```python-overview = client.overview("viking://resources/docs/")+overview = client.overview(uri="viking://resources/docs/")print(f"Overview:\n{overview}")```@@ -157,7 +157,7 @@ Read the complete text of an L0, L1, or L2 file.**Python SDK**```python-content = client.read("viking://resources/docs/api.md")+content = client.read(uri="viking://resources/docs/api.md")print(f"Content:\n{content}")```@@ -235,8 +235,8 @@ Update an existing file, or create a new one when `mode="create"`, and automatic```pythonresult = client.write(- "viking://resources/docs/api.md",- "# Updated API\n\nFresh content.",+ uri="viking://resources/docs/api.md",+ content="# Updated API\n\nFresh content.",mode="replace",wait=True,)@@ -476,8 +476,8 @@ Set explicit `k=v` tags used by retrieval filters. `replace` replaces existing t```pythonresult = client.set_tags(- "viking://resources/project/",- ["team=search", "env=prod"],+ uri="viking://resources/project/",+ tags=["team=search", "env=prod"],mode="replace",recursive=True,)@@ -628,8 +628,10 @@ result = client.reindex(uri="viking://resources",mode="vectors_only",wait=True,- tags=["team=search", "env=prod"],- tag_mode="replace",+ options={+ "tags": ["team=search", "env=prod"],+ "tag_mode": "replace",+ },)print(result)```diff --git a/docs/en/api/17-tasks.md b/docs/en/api/17-tasks.mdindex 7862e6ed2..1af002252 100644--- a/docs/en/api/17-tasks.md+++ b/docs/en/api/17-tasks.md@@ -52,7 +52,7 @@ from openviking_sdk import AsyncHTTPClientclient = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")await client.initialize()-task = await client.get_task("uuid-xxx")+task = await client.get_task(task_id="uuid-xxx")print(f"Status: {task['status']}")await client.close()```@@ -172,7 +172,7 @@ Only the current user who owns the task can cancel it. ROOT identities cannot ca**Python SDK**```python-task = await client.cancel_task("uuid-xxx")+task = await client.cancel_task(task_id="uuid-xxx")print(task["status"])```diff --git a/docs/en/api/99-api-doc-writing-guide.md b/docs/en/api/99-api-doc-writing-guide.mdindex 1a9f6da6b..c450615dd 100644--- a/docs/en/api/99-api-doc-writing-guide.md+++ b/docs/en/api/99-api-doc-writing-guide.md@@ -49,7 +49,7 @@ Explain the purpose of this API, point to the corresponding code entry, and brie**Python SDK**-```python+```text<SDK call example>```@@ -229,8 +229,8 @@ from openviking_sdk import SyncHTTPClientclient = SyncHTTPClient(url="http://localhost:1933", api_key="your-key")result = client.add_resource(- "./documents/guide.md",- reason="User guide documentation"+ path="./documents/guide.md",+ options={"reason": "User guide documentation"},)print(f"Added: {result['root_uri']}")diff --git a/docs/en/concepts/02-context-types.md b/docs/en/concepts/02-context-types.mdindex b675a22df..39ff41adc 100644--- a/docs/en/concepts/02-context-types.md+++ b/docs/en/concepts/02-context-types.md@@ -31,14 +31,14 @@ Resources are external knowledge that Agents can reference.```python# Add resourceclient.add_resource(- "https://docs.example.com/api.pdf",- reason="API documentation"+ path="https://docs.example.com/api.pdf",+ options={"reason": "API documentation"},)# Search resourcesresults = client.find(- "authentication methods",- target_uri="viking://resources/"+ query="authentication methods",+ target_uri="viking://resources/",)```@@ -73,15 +73,21 @@ The schema-defined `memories/tools/` and `memories/skills/` types are disabled.### Usage```python+from openviking_sdk import TextPart+# Memories are auto-extracted from sessions-session = client.session()-await session.add_message("user", [{"type": "text", "text": "I prefer dark mode"}])+session_info = await client.create_session()+session = client.session(session_id=session_info["session_id"])+await session.add_message(+ role="user",+ parts=[TextPart(text="I prefer dark mode")],+)commit = await session.commit() # Starts background memory extraction-task = await client.get_task(commit["task_id"]) # Poll until task["status"] == "completed"+task = await client.get_task(task_id=commit["task_id"]) # Poll until task["status"] == "completed"# Search memoriesresults = await client.find(- "UI preferences",+ query="UI preferences",target_uri="viking://~/memories/")```@@ -127,25 +133,27 @@ AgentDefinedContextType includes the following subtypes, all stored under the `v```python# Add skill (defaults to viking://~/skills/)-await client.add_skill({- "name": "search-web",- "description": "Search the web for information",- "content": "# search-web\n..."-})+await client.add_skill(+ data={+ "name": "search-web",+ "description": "Search the web for information",+ "content": "# search-web\n...",+ },+)# Write to global agent skills root (public/shared) via -p overrideov skills add search-web -p viking://agent/skills# Search user skillsresults = await client.find(- "web search",+ query="web search",target_uri="viking://~/skills/")# Search global agent skillsresults = await client.find(- "web search",- target_uri="viking://agent/skills/"+ query="web search",+ target_uri="viking://agent/skills/",)```@@ -155,14 +163,14 @@ Based on Agent's needs, supports unified search across all three context types,```python# Search across all context types-results = await client.find("user authentication")--for ctx in results.memories:- print(f"Memory: {ctx.uri}")-for ctx in results.resources:- print(f"Resource: {ctx.uri}")-for ctx in results.skills:- print(f"Skill: {ctx.uri}")+results = await client.find(query="user authentication")++for context in results.get("memories", []):+ print(f"Memory: {context['uri']}")+for context in results.get("resources", []):+ print(f"Resource: {context['uri']}")+for context in results.get("skills", []):+ print(f"Skill: {context['uri']}")```## Related Documentsdiff --git a/docs/en/concepts/03-context-layers.md b/docs/en/concepts/03-context-layers.mdindex 627c3f0be..da4a9d23c 100644--- a/docs/en/concepts/03-context-layers.md+++ b/docs/en/concepts/03-context-layers.md@@ -27,7 +27,7 @@ API authentication guide covering OAuth 2.0, JWT tokens, and API keys for secureSemantic accessors return only the visible body:```python-abstract = client.abstract("viking://resources/docs/auth")+abstract = client.abstract(uri="viking://resources/docs/auth")```## L1: Overview@@ -47,7 +47,7 @@ This directory covers the primary API authentication methods.``````python-overview = client.overview("viking://resources/docs/auth")+overview = client.overview(uri="viking://resources/docs/auth")```L0 is extracted from the L1 body: the Brief Description paragraph after the H1 title and before the first `##` heading. YAML frontmatter is not part of this extraction.@@ -57,7 +57,7 @@ L0 is extracted from the L1 body: the Brief Description paragraph after the H1 tL2 is the original or fully parsed content, loaded only when needed and retaining its source format and structure.```python-content = client.read("viking://resources/docs/auth/oauth.md")+content = client.read(uri="viking://resources/docs/auth/oauth.md")```## Directory Structurediff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.mdindex e0d664888..18e2f1eef 100644--- a/docs/en/concepts/04-viking-uri.md+++ b/docs/en/concepts/04-viking-uri.md@@ -313,32 +313,32 @@ parent = VikingURI(uri).parent.uri # viking://resources/docs```python# Search only in resourcesresults = client.find(- "authentication",- target_uri="viking://resources/"+ query="authentication",+ target_uri="viking://resources/",)# Search only in your own resourcesresults = client.find(- "private project notes",+ query="private project notes",target_uri="viking://~/resources/")# Search only in your own memoriesresults = client.find(- "coding preferences",+ query="coding preferences",target_uri="viking://~/memories/")# Search only in your own skillsresults = client.find(- "web search",+ query="web search",target_uri="viking://~/skills/")# Search only in global agent skillsresults = client.find(- "web search",- target_uri="viking://agent/skills/"+ query="web search",+ target_uri="viking://agent/skills/",)```@@ -346,16 +346,16 @@ results = client.find(```python# List directory-entries = await client.ls("viking://resources/")+entries = await client.ls(uri="viking://resources/")# Read file-content = await client.read("viking://resources/docs/api.md")+content = await client.read(uri="viking://resources/docs/api.md")# Get abstract-abstract = await client.abstract("viking://resources/docs/")+abstract = await client.abstract(uri="viking://resources/docs/")# Get overview-overview = await client.overview("viking://resources/docs/")+overview = await client.overview(uri="viking://resources/docs/")```## Special Filesdiff --git a/docs/en/concepts/06-extraction.md b/docs/en/concepts/06-extraction.mdindex 38b67c7e2..05f3e7d5d 100644--- a/docs/en/concepts/06-extraction.md+++ b/docs/en/concepts/06-extraction.md@@ -177,8 +177,8 @@ This routing applies to short and long code files alike.```python# Add resourceawait client.add_resource(- "/path/to/doc.pdf",- reason="API documentation"+ path="/path/to/doc.pdf",+ options={"reason": "API documentation"},)# Flow: Parser → TreeBuilder(scope=resources) → SemanticQueue@@ -188,10 +188,12 @@ await client.add_resource(```python# Add skill-await client.add_skill({- "name": "search-web",- "content": "# search-web\\n..."-})+await client.add_skill(+ data={+ "name": "search-web",+ "content": "# search-web\\n...",+ },+)# Flow: Direct write to viking://~/skills/{name}/ → SemanticQueue```diff --git a/docs/en/concepts/07-retrieval.md b/docs/en/concepts/07-retrieval.mdindex d21a7ba4a..b7546522c 100644--- a/docs/en/concepts/07-retrieval.md+++ b/docs/en/concepts/07-retrieval.md@@ -25,14 +25,15 @@ Query → Intent Analysis → Hierarchical Retrieval → Rerank → Results```python# find(): Simple queryresults = await client.find(- "OAuth authentication",- target_uri="viking://resources/"+ query="OAuth authentication",+ target_uri="viking://resources/",)# search(): Complex task (needs session context)+session_info = await client.create_session()results = await client.search(- "Help me create an RFC document",- session_info=session+ query="Help me create an RFC document",+ session_id=session_info["session_id"],)```diff --git a/docs/en/concepts/08-session.md b/docs/en/concepts/08-session.mdindex f08130a9a..43606e189 100644--- a/docs/en/concepts/08-session.md+++ b/docs/en/concepts/08-session.md@@ -6,11 +6,13 @@ Session manages conversation messages, tracks context usage, and extracts long-t**Lifecycle**: Create → Interact → Commit-Getting a session by ID does not auto-create it by default. Use `client.get_session(..., auto_create=True)` when you want missing sessions to be created automatically.+Getting a session by ID does not create it. Create the session first, then use+`client.session(session_id=...)` to append messages or commit it.```python-session = client.session(session_id="chat_001")-session.add_message("user", [TextPart("...")])+session_info = client.create_session(session_id="chat_001")+session = client.session(session_id=session_info["session_id"])+session.add_message(role="user", content="...")session.commit()```@@ -18,51 +20,41 @@ session.commit()| Method | Description ||--------|-------------|-| `add_message(role, parts)` | Add message |-| `used(contexts, skill)` | Record used contexts/skills |+| `add_message(role, content=None, parts=None, options=None, peer_id=None)` | Add message || `commit()` | Commit: archive (sync) + summary generation and memory extraction (async background) || `get_task(task_id)` | Query background task status |### add_message```python+from openviking_sdk import ContextPart, ImagePart, TextPart+session.add_message(- "user",- [TextPart("How to configure embedding?")]+ role="user",+ content="How to configure embedding?",)session.add_message(- "assistant",- [- TextPart("Here's how..."),- ContextPart(uri="viking://~/memories/profile.md"),+ role="assistant",+ parts=[+ TextPart(text="Here's how..."),+ ContextPart(+ uri="viking://~/memories/profile.md",+ context_type="memory",+ abstract="User profile",+ ),])session.add_message(- "user",- [- TextPart("Remember this studio layout."),+ role="user",+ parts=[+ TextPart(text="Remember this studio layout."),ImagePart(url="https://example.com/studio.png", detail="auto"),])```-### used--```python-# Record used contexts-session.used(contexts=["viking://~/memories/profile.md"])--# Record used skill-session.used(skill={- "uri": "viking://~/skills/code-search",- "input": "search config",- "output": "found 3 files",- "success": True-})-```-### commit```python@@ -75,7 +67,7 @@ result = session.commit()# }# Poll background task progress-task = client.get_task(result["task_id"])+task = client.get_task(task_id=result["task_id"])# task["status"]: "pending" | "running" | "completed" | "failed"# sum(task["result"]["memories_extracted"].values()): 3```diff --git a/docs/en/faq/faq.md b/docs/en/faq/faq.mdindex 87ac93b25..45bc9dd21 100644--- a/docs/en/faq/faq.md+++ b/docs/en/faq/faq.md@@ -169,15 +169,15 @@ Embedding, VLM, storage, and other service configuration is managed by the OpenV```python# Add single fileawait client.add_resource(- "./document.pdf",- reason="Project technical documentation", # Describe resource purpose to improve retrieval quality- to="viking://resources/docs/" # Specify storage location+ path="./document.pdf",+ to="viking://resources/docs/", # Specify storage location+ options={"reason": "Project technical documentation"}, # Describe resource purpose to improve retrieval quality)# Add web pageawait client.add_resource(- "https://example.com/api-docs",- reason="API reference documentation"+ path="https://example.com/api-docs",+ options={"reason": "API reference documentation"},)# Wait for processing to complete@@ -196,14 +196,14 @@ await client.wait_processed()```python# find(): Simple direct semantic searchresults = await client.find(- "OAuth authentication flow",- target_uri="viking://resources/"+ query="OAuth authentication flow",+ target_uri="viking://resources/",)# search(): Complex tasks requiring intent analysisresults = await client.search(- "Help me implement user login functionality",- session_info=session+ query="Help me implement user login functionality",+ session_id=session.session_id,)```@@ -216,15 +216,21 @@ results = await client.search(Session management is a core capability of OpenViking, supporting conversation tracking and memory extraction:```python+from openviking_sdk import TextPart+# Create session-session = client.session()+session_info = await client.create_session()+session = client.session(session_id=session_info["session_id"])# Add conversation messages-await session.add_message("user", [{"type": "text", "text": "Help me analyze performance issues in this code"}])-await session.add_message("assistant", [{"type": "text", "text": "Let me analyze..."}])--# Mark used context (for tracking)-await session.used(["viking://resources/code/main.py"])+await session.add_message(+ role="user",+ parts=[TextPart(text="Help me analyze performance issues in this code")],+)+await session.add_message(+ role="assistant",+ parts=[TextPart(text="Let me analyze...")],+)# Commit session to trigger memory extractionawait session.commit()@@ -240,16 +246,16 @@ Memories are stored in the current User or Peer namespace; there is no current w```python# List directory contents-items = await client.ls("viking://resources/")+items = await client.ls(uri="viking://resources/")# Read full content (L2)-content = await client.read("viking://resources/doc.md")+content = await client.read(uri="viking://resources/doc.md")# Get abstract (L0)-abstract = await client.abstract("viking://resources")+abstract = await client.abstract(uri="viking://resources")# Get overview (L1)-overview = await client.overview("viking://resources")+overview = await client.overview(uri="viking://resources")```## Retrieval Optimization@@ -292,7 +298,7 @@ This strategy finds semantically matching fragments while understanding the comp1. **Didn't wait for processing to complete**```python- await client.add_resource("./doc.pdf")+ await client.add_resource(path="./doc.pdf")await client.wait_processed() # Must wait```@@ -317,7 +323,7 @@ This strategy finds semantically matching fragments while understanding the comp1. **Confirm resources have been processed**```python# Check if resources exist- items = await client.ls("viking://resources/")+ items = await client.ls(uri="viking://resources/")```2. **Check `target_uri` filter condition**@@ -330,7 +336,7 @@ This strategy finds semantically matching fragments while understanding the comp4. **Check L0 abstract quality**```python- abstract = await client.abstract("viking://resources/your-doc")+ abstract = await client.abstract(uri="viking://resources/your-doc")print(abstract) # Confirm abstract accurately reflects content```@@ -353,7 +359,10 @@ This strategy finds semantically matching fragments while understanding the comp4. **View extracted memories**```python- memories = await client.find("", target_uri="viking://~/memories/")+ memories = await client.find(+ query="",+ target_uri="viking://~/memories/",+ )```### Performance issuesdiff --git a/docs/en/getting-started/01-introduction.md b/docs/en/getting-started/01-introduction.mdindex 8779d310f..900bee02d 100644--- a/docs/en/getting-started/01-introduction.md+++ b/docs/en/getting-started/01-introduction.md@@ -51,11 +51,11 @@ viking://**Unix-like API**: Familiar command-style operations```python-client.find("user authentication") # Semantic search-client.ls("viking://resources/") # List directory-client.read("viking://resources/doc") # Read content-client.abstract("viking://...") # Get L0 abstract-client.overview("viking://...") # Get L1 overview+client.find(query="user authentication") # Semantic search+client.ls(uri="viking://resources/") # List directory+client.read(uri="viking://resources/doc") # Read content+client.abstract(uri="viking://...") # Get L0 abstract+client.overview(uri="viking://...") # Get L1 overview```### 2. Hierarchical Context On-Demand Loadingdiff --git a/docs/en/getting-started/02-quickstart.md b/docs/en/getting-started/02-quickstart.mdindex 2952f437a..cfa5c4b9f 100644--- a/docs/en/getting-started/02-quickstart.md+++ b/docs/en/getting-started/02-quickstart.md@@ -194,22 +194,25 @@ try:root_uri = add_result['root_uri']# Explore the resource tree structure- ls_result = client.ls(root_uri)+ ls_result = client.ls(uri=root_uri)print(f"Directory structure:\n{ls_result}\n")# Use glob to find markdown filesglob_result = client.glob(pattern="**/*.md", uri=root_uri)if glob_result['matches']:- content = client.read(glob_result['matches'][0])+ content = client.read(uri=glob_result["matches"][0])print(f"Content preview: {content[:200]}...\n")# Get abstract and overview of the resource- abstract = client.abstract(root_uri)- overview = client.overview(root_uri)+ abstract = client.abstract(uri=root_uri)+ overview = client.overview(uri=root_uri)print(f"Abstract:\n{abstract}\n\nOverview:\n{overview}\n")# Perform semantic search- results = client.find("what is openviking", target_uri=root_uri)+ results = client.find(+ query="what is openviking",+ target_uri=root_uri,+ )print("Search results:")for result in results.get("resources", []):print(f" {result['uri']} (score: {result.get('score', 0.0):.4f})")diff --git a/docs/en/getting-started/03-quickstart-server.md b/docs/en/getting-started/03-quickstart-server.mdindex 35cce1098..a7c73003d 100644--- a/docs/en/getting-started/03-quickstart-server.md+++ b/docs/en/getting-started/03-quickstart-server.md@@ -113,7 +113,7 @@ try:# Add a resourceresult = client.add_resource(- "https://raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/README.md"+ path="https://raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/README.md",)root_uri = result["root_uri"]@@ -121,9 +121,12 @@ try:client.wait_processed()# Search- results = client.find("what is openviking", target_uri=root_uri)- for r in results.resources:- print(f" {r.uri} (score: {r.score:.4f})")+ results = client.find(+ query="what is openviking",+ target_uri=root_uri,+ )+ for result in results.get("resources", []):+ print(f" {result['uri']} (score: {result.get('score', 0.0):.4f})")finally:client.close()diff --git a/docs/en/guides/02-volcengine-purchase-guide.md b/docs/en/guides/02-volcengine-purchase-guide.mdindex 24b039fdb..00ca259ea 100644--- a/docs/en/guides/02-volcengine-purchase-guide.md+++ b/docs/en/guides/02-volcengine-purchase-guide.md@@ -180,8 +180,8 @@ async def test():# Test adding a simple resourceresult = await client.add_resource(- "https://example.com",- reason="Connection Test"+ path="https://example.com",+ options={"reason": "Connection Test"},)print(f"✓ Configuration successful: {result['root_uri']}")diff --git a/docs/en/guides/03-deployment.md b/docs/en/guides/03-deployment.mdindex c51448849..fc139e12e 100644--- a/docs/en/guides/03-deployment.md+++ b/docs/en/guides/03-deployment.md@@ -146,7 +146,7 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()-results = client.find("how to use openviking")+results = client.find(query="how to use openviking")client.close()```diff --git a/docs/en/guides/07-operation-telemetry.md b/docs/en/guides/07-operation-telemetry.mdindex c2d0665e7..9700e6588 100644--- a/docs/en/guides/07-operation-telemetry.md+++ b/docs/en/guides/07-operation-telemetry.md@@ -339,7 +339,10 @@ from openviking_sdk import AsyncHTTPClientclient = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")await client.initialize()-result = await client.find("memory dedup", telemetry=True)+result = await client.find(+ query="memory dedup",+ options={"telemetry": True},+)print(result["telemetry"]["summary"]["operation"])print(result["telemetry"]["summary"]["duration_ms"])```diff --git a/docs/en/guides/08-encryption.md b/docs/en/guides/08-encryption.mdindex 1263b601f..ee85089d9 100644--- a/docs/en/guides/08-encryption.md+++ b/docs/en/guides/08-encryption.md@@ -68,10 +68,13 @@ async def test():# add_resource expects a file path or URLsample = Path("./encrypted-sample.txt")sample.write_text("Hello, encrypted world!", encoding="utf-8")- await client.add_resource(str(sample), reason="Test encryption")+ await client.add_resource(+ path=str(sample),+ options={"reason": "Test encryption"},+ )# Read resource (automatically decrypted)- results = await client.find("encrypted")+ results = await client.find(query="encrypted")print(f"Found {len(results)} results")await client.close()diff --git a/docs/en/guides/09-ovpack.md b/docs/en/guides/09-ovpack.mdindex 0bf0797ba..5351dc814 100644--- a/docs/en/guides/09-ovpack.md+++ b/docs/en/guides/09-ovpack.md@@ -126,7 +126,7 @@ details include only one missing key to keep logs small.Python SDK:```python-report = await client.check_consistency("viking://resources/my-project")+report = await client.check_consistency(uri="viking://resources/my-project")print(report["ok"], report["missing_records"])```@@ -201,9 +201,12 @@ async def migrate_project():Full backup:```python-await client.backup_ovpack("./backups/openviking.ovpack", include_vectors=True)+await client.backup_ovpack(+ to="./backups/openviking.ovpack",+ include_vectors=True,+)await client.restore_ovpack(- "./backups/openviking.ovpack",+ file_path="./backups/openviking.ovpack",on_conflict="overwrite",vector_mode="auto",)diff --git a/docs/en/guides/15-snapshot.md b/docs/en/guides/15-snapshot.mdindex 51e07ded0..723d3931c 100644--- a/docs/en/guides/15-snapshot.md+++ b/docs/en/guides/15-snapshot.md@@ -137,12 +137,22 @@ client.initialize()root = "viking://resources/my_project"# 1. Write initial content and commit v1-client.write(f"{root}/guide.md", "# Guide\n\nv1 content\n", mode="create", wait=True)+client.write(+ uri=f"{root}/guide.md",+ content="# Guide\n\nv1 content\n",+ mode="create",+ wait=True,+)v1 = client.snapshot.commit(message="v1 initial import")print("v1:", v1["commit_oid"])# 2. Modify and commit v2-client.write(f"{root}/guide.md", "# Guide\n\nv2 content\n", mode="replace", wait=True)+client.write(+ uri=f"{root}/guide.md",+ content="# Guide\n\nv2 content\n",+ mode="replace",+ wait=True,+)v2 = client.snapshot.commit(message="v2 update")# 3. Walk historydiff --git a/docs/images/agents/en/sdk.md b/docs/images/agents/en/sdk.mdindex 213286120..c76152dc0 100644--- a/docs/images/agents/en/sdk.md+++ b/docs/images/agents/en/sdk.md@@ -11,7 +11,7 @@ pip install openviking --upgrade --force-reinstallRefer to the standard write example from GitHub and fill in the API Key and domain automatically:```python-from openviking.client import SyncHTTPClient+from openviking_sdk import SyncHTTPClient, TextParturl = "{{OPENVIKING_BASE_URL}}"api_key = "{{OPENVIKING_API_KEY}}"@@ -37,7 +37,7 @@ reason = "[TODO]your-reason" # e.g. External API documentationclient.add_resource(path=file_path,to=resource_to,- reason=reason,+ options={"reason": reason},)```@@ -52,9 +52,9 @@ text = "[TODO]your-message-text" # e.g. I am a developersession = client.create_session()session_id = session["session_id"]client.add_message(- session_id,- "user",- parts=[{"type": "text", "text": text}],+ session_id=session_id,+ role="user",+ parts=[TextPart(text=text)],)-result = client.commit_session(session_id)+result = client.commit_session(session_id=session_id)```diff --git a/docs/images/agents/zh/sdk.md b/docs/images/agents/zh/sdk.mdindex 1da7bb700..5746bfc28 100644--- a/docs/images/agents/zh/sdk.md+++ b/docs/images/agents/zh/sdk.md@@ -9,7 +9,7 @@ pip install openviking --upgrade --force-reinstall参考 GitHub 提供的规范写入示例,自动填入 API Key 和域名```python-from openviking.client import SyncHTTPClient+from openviking_sdk import SyncHTTPClient, TextParturl = "{{OPENVIKING_BASE_URL}}"api_key = "{{OPENVIKING_API_KEY}}"@@ -35,7 +35,7 @@ reason = "[TODO]your-reason" # e.g. External API documentationclient.add_resource(path=file_path,to=resource_to,- reason=reason,+ options={"reason": reason},)```@@ -49,9 +49,9 @@ text = "[TODO]your-message-text" # e.g. I am a developersession = client.create_session()session_id = session["session_id"]client.add_message(- session_id,- "user",- parts=[{"type": "text", "text": text}],+ session_id=session_id,+ role="user",+ parts=[TextPart(text=text)],)-result = client.commit_session(session_id)+result = client.commit_session(session_id=session_id)```diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.mdindex cd3194408..ba00c5fec 100644--- a/docs/zh/api/02-resources.md+++ b/docs/zh/api/02-resources.md@@ -338,49 +338,55 @@ client.initialize()## 添加本地文件result = client.add_resource(- "./documents/guide.md",- reason="User guide documentation"+ path="./documents/guide.md",+ options={"reason": "User guide documentation"},)print(f"Added: {result['root_uri']}")## 正常解析并转换为 Markdown,但每个文档正文不拆分result = client.add_resource(- "./documents",- args={"parse_mode": "no_split"},+ path="./documents",+ options={"args": {"parse_mode": "no_split"}},)## 从 URL 添加到指定位置result = client.add_resource(- "https://example.com/api-docs.md",+ path="https://example.com/api-docs.md",to="viking://resources/external/api-docs.md",- reason="External API docs"+ options={"reason": "External API docs"},)## 递归抓取网页(同域 BFS,depth 层数、max_pages 页数上限)result = client.add_resource(- "https://docs.openviking.ai/zh/getting-started/01-introduction",+ path="https://docs.openviking.ai/zh/getting-started/01-introduction",wait=True,timeout=180,- args={"depth": 1, "max_pages": 10},+ options={+ "args": {"depth": 1, "max_pages": 10},+ },)## 递归抓取并按路径前缀过滤,同时下载页面中的文件链接result = client.add_resource(- "https://docs.openviking.ai/",- args={- "depth": 2,- "max_pages": 50,- "include_paths": ["/zh/"],- "exclude_paths": ["/changelog"],- "skip_download_links": False,+ path="https://docs.openviking.ai/",+ options={+ "args": {+ "depth": 2,+ "max_pages": 50,+ "include_paths": ["/zh/"],+ "exclude_paths": ["/changelog"],+ "skip_download_links": False,+ },},)## 添加到当前用户私有资源根result = client.add_resource(- "./documents/guide.md",+ path="./documents/guide.md",parent="viking://~/resources/docs",- create_parent=True,+ options={+ "create_parent": True,+ },)## 等待处理完成@@ -388,25 +394,29 @@ client.wait_processed()## 开启定时更新client.add_resource(- "./documents/guide.md",+ path="./documents/guide.md",to="viking://resources/guide.md",- watch_interval=60 # 每60分钟更新一次+ options={+ "watch_interval": 60, # 每60分钟更新一次+ },)# 使用一次性用户 access token 添加飞书文档client.add_resource(- "https://example.feishu.cn/docx/doc_token",- args={"feishu_access_token": "u-..."},+ path="https://example.feishu.cn/docx/doc_token",+ options={"args": {"feishu_access_token": "u-..."}},)# 使用用户 token 自动刷新添加飞书文档client.add_resource(- "https://example.feishu.cn/docx/doc_token",+ path="https://example.feishu.cn/docx/doc_token",to="viking://resources/feishu/doc",- watch_interval=1440,- args={- "feishu_access_token": "u-...",- "feishu_refresh_token": "r-...",+ options={+ "watch_interval": 1440,+ "args": {+ "feishu_access_token": "u-...",+ "feishu_refresh_token": "r-...",+ },},)```diff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.mdindex 5ea4b62c4..e1804e424 100644--- a/docs/zh/api/03-filesystem.md+++ b/docs/zh/api/03-filesystem.md@@ -46,7 +46,7 @@ OpenViking 提供类 Unix 的文件系统操作来管理上下文。```pythonentries = client.ls(- "viking://resources/",+ uri="viking://resources/",node_limit=200,sort_by="mtime",sort_order="desc",@@ -142,7 +142,7 @@ openviking ls viking://resources/ [--simple] [--recursive]**Python HTTP SDK**```python-entries = client.tree("viking://resources/")+entries = client.tree(uri="viking://resources/")for entry in entries:type_str = "dir" if entry['isDir'] else "file"print(f"{entry['rel_path']} - {type_str}")@@ -226,12 +226,12 @@ openviking tree viking://resources/my-project/**Python HTTP SDK**```python-info = client.stat("viking://resources/docs/api.md")+info = client.stat(uri="viking://resources/docs/api.md")print(f"Size: {info['size']}")print(f"Is directory: {info['isDir']}")# 对于目录,会返回项目计数-dir_info = client.stat("viking://resources/docs")+dir_info = client.stat(uri="viking://resources/docs")if dir_info.get('isDir'):print(f"Item count: {dir_info.get('count')}")```@@ -329,7 +329,7 @@ openviking stat viking://resources/my-project/docs**Python SDK (HTTP)**```python-attrs = client.attrs("viking://resources/docs/api.md")+attrs = client.attrs(uri="viking://resources/docs/api.md")print(attrs["attrs"]["tags"])```@@ -436,8 +436,8 @@ openviking attrs set-tags viking://resources/docs --tags team=search --mode appe**Python HTTP SDK**```python-client.mkdir("viking://resources/new-project/")-client.mkdir("viking://resources/new-project/", description="接口文档目录")+client.mkdir(uri="viking://resources/new-project/")+client.mkdir(uri="viking://resources/new-project/", description="接口文档目录")```**TypeScript SDK**@@ -511,10 +511,10 @@ URI 格式非法、scheme 不支持或使用非公开作用域时返回 `INVALID```python# 删除单个文件-client.rm("viking://resources/docs/old.md")+client.rm(uri="viking://resources/docs/old.md")# 递归删除目录-client.rm("viking://resources/old-project/", recursive=True)+client.rm(uri="viking://resources/old-project/", recursive=True)```**TypeScript SDK**@@ -604,8 +604,8 @@ openviking rm viking://resources/old.md [--recursive]```pythonclient.mv(- "viking://resources/old-name/",- "viking://resources/new-name/"+ from_uri="viking://resources/old-name/",+ to_uri="viking://resources/new-name/",)```diff --git a/docs/zh/api/04-skills.md b/docs/zh/api/04-skills.mdindex b01cd9401..17561e05b 100644--- a/docs/zh/api/04-skills.md+++ b/docs/zh/api/04-skills.md@@ -92,7 +92,7 @@ OpenViking 会自动检测并将 MCP Tool 定义转换为技能格式。**转换示例**:输入(MCP 格式):-```python+```json{"name": "search_web","description": "Search the web",@@ -114,7 +114,7 @@ OpenViking 会自动检测并将 MCP Tool 定义转换为技能格式。```输出(技能格式):-```python+```json{"name": "search-web","description": "Search the web",@@ -292,7 +292,7 @@ Search the web for current information.- **limit** (integer, optional): Max results, default 10"""}-result = client.add_skill(skill)+result = client.add_skill(data=skill)print(f"Added: {result['root_uri']}")# 方式 2:使用 MCP Tool 格式(自动检测并转换)@@ -310,20 +310,20 @@ mcp_tool = {"required": ["expression"]}}-result = client.add_skill(mcp_tool)+result = client.add_skill(data=mcp_tool)print(f"Added: {result['uri']}")# 方式 3:从本地 SKILL.md 文件添加-result = client.add_skill("./skills/search-web/SKILL.md")+result = client.add_skill(data="./skills/search-web/SKILL.md")print(f"Added: {result['uri']}")# 方式 4:从包含 SKILL.md 的目录添加(辅助文件会一并包含)-result = client.add_skill("./skills/code-runner/")+result = client.add_skill(data="./skills/code-runner/")print(f"Added: {result['uri']}")print(f"Auxiliary files: {result['auxiliary_files']}")# 等待处理完成-result = client.add_skill("./skills/my-skill/", wait=True)+result = client.add_skill(data="./skills/my-skill/", wait=True)client.wait_processed()```@@ -473,7 +473,11 @@ curl -X GET "http://localhost:1933/api/v1/skills?node_limit=1000" \**Python SDK**:```python-skill = client.get_skill("search-web", include_content=True, include_files=True)+skill = client.get_skill(+ skill_name="search-web",+ include_content=True,+ include_files=True,+)print(skill["name"])print(skill.get("content"))```@@ -507,7 +511,7 @@ curl -X GET "http://localhost:1933/api/v1/skills/search-web?include_content=true**Python SDK**:```python-results = client.find_skills("search the internet", limit=5)+results = client.find_skills(query="search the internet", limit=5)for skill in results["skills"]:print(skill["name"], skill["score"])@@ -546,8 +550,12 @@ curl -X POST http://localhost:1933/api/v1/skills/find \**Python SDK**:```python-validated = client.validate_skill({"name": "search-web", "description": "..."})-updated = client.update_skill("search-web", "./skills/search-web", wait=True)+validated = client.validate_skill(data={"name": "search-web", "description": "..."})+updated = client.update_skill(+ skill_name="search-web",+ data="./skills/search-web",+ wait=True,+)```**TypeScript SDK**@@ -602,7 +610,7 @@ curl -X PUT http://localhost:1933/api/v1/skills/search-web \**Python SDK**:```python-client.delete_skill("old-skill")+client.delete_skill(skill_name="old-skill")```**TypeScript SDK**@@ -710,14 +718,14 @@ curl -X DELETE "http://localhost:1933/api/v1/skills/old-skill" \skill = {"name": "search-web","description": "Search the web for current information using Google",- ...+ # 其他技能字段}# 不够好 - 过于模糊skill = {"name": "search","description": "Search",- ...+ # 其他技能字段}```diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.mdindex ac552fa58..2179eb3a9 100644--- a/docs/zh/api/05-sessions.md+++ b/docs/zh/api/05-sessions.md@@ -99,7 +99,8 @@ curl -X POST http://localhost:1933/api/v1/sessions \import openviking as ov# 使用 HTTP 客户端-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# 创建新会话(自动生成 ID)result = await client.create_session()@@ -111,13 +112,15 @@ print(f"Session ID: {result['session_id']}")# 创建带自定义自动 commit 策略的新会话result = await client.create_session(- auto_commit_policy={- "pending_token_threshold": 8000,- "message_count_threshold": 40,- "idle_timeout_seconds": 600,- "keep_recent_count": 10,- "min_commit_interval_seconds": 0,- }+ options={+ "auto_commit_policy": {+ "pending_token_threshold": 8000,+ "message_count_threshold": 40,+ "idle_timeout_seconds": 600,+ "keep_recent_count": 10,+ "min_commit_interval_seconds": 0,+ },+ },)print(result["auto_commit_policy"])```@@ -200,9 +203,10 @@ curl -X GET http://localhost:1933/api/v1/sessions \**Python SDK**```python-import openviking as ov+from openviking_sdk import AsyncHTTPClient-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()sessions = await client.list_sessions()for s in sessions:@@ -303,16 +307,17 @@ curl -X GET http://localhost:1933/api/v1/sessions/a1b2c3d4 \```pythonimport openviking as ov-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# 获取已有会话(不存在时抛 NotFoundError)-info = await client.get_session("a1b2c3d4")+info = await client.get_session(session_id="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)+info = await client.get_session(session_id="a1b2c3d4", auto_create=True)```**TypeScript SDK**@@ -459,11 +464,13 @@ curl -X PATCH http://localhost:1933/api/v1/sessions/a1b2c3d4/config \```pythonresult = client.update_session_config(- "a1b2c3d4",- memory_extraction_config={- "events": {"tags": ["team=search", "channel=app"]}+ session_id="a1b2c3d4",+ options={+ "memory_extraction_config": {+ "events": {"tags": ["team=search", "channel=app"]}+ },+ "auto_commit_policy": {"message_count_threshold": 25},},- auto_commit_policy={"message_count_threshold": 25},)```@@ -725,9 +732,10 @@ curl -X GET "http://localhost:1933/api/v1/sessions/a1b2c3d4/context?token_budget```pythonimport openviking as ov-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()-context = await client.get_session_context("a1b2c3d4", token_budget=128000)+context = await client.get_session_context(session_id="a1b2c3d4", token_budget=128000)print(context["latest_archive_overview"])print(len(context["messages"]))```@@ -834,9 +842,13 @@ curl -X GET "http://localhost:1933/api/v1/sessions/a1b2c3d4/archives/archive_002```pythonimport openviking as ov-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()-archive = await client.get_session_archive("a1b2c3d4", "archive_002")+archive = await client.get_session_archive(+ session_id="a1b2c3d4",+ archive_id="archive_002",+)print(archive["archive_id"])print(archive["overview"])print(len(archive["messages"]))@@ -948,10 +960,11 @@ curl -X DELETE http://localhost:1933/api/v1/sessions/a1b2c3d4 \```pythonimport openviking as ov-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# 删除会话-await client.delete_session("a1b2c3d4")+await client.delete_session(session_id="a1b2c3d4")```**TypeScript SDK**@@ -1013,8 +1026,8 @@ ov session delete a1b2c3d4|------|------|------|--------|------|| session_id | str | 是 | - | 会话 ID || role | str | 是 | - | 消息角色:"user" 或 "assistant" |-| parts | List[Part] | 条件必填 | - | 消息部分列表(Python SDK 必填;HTTP API 可选,与 content 二选一) |-| content | str | 条件必填 | - | 消息文本内容(HTTP API 简单模式,与 parts 二选一) |+| parts | List[dict \| MessagePart] | 条件必填 | - | SDK 可传消息片段字典或 `TextPart`/`ContextPart`/`ImagePart`/`ToolPart` 对象;HTTP API 仅接受字典;与 content 二选一 |+| content | str | 条件必填 | - | 消息文本内容(简单模式,与 parts 二选一) || created_at | str | 否 | None | 可选的 ISO 8601 时间戳,会原样保存到消息中 || peer_id | str | 否 | None | 可选的稳定交互对象 ID |@@ -1027,7 +1040,7 @@ ov session delete a1b2c3d4**Part 类型(Python SDK)**```python-from openviking.message import TextPart, ContextPart, ToolPart+from openviking_sdk import ContextPart, ImagePart, TextPart, ToolPart# 文本内容TextPart(text="Hello, how can I help?")@@ -1036,7 +1049,7 @@ TextPart(text="Hello, how can I help?")ContextPart(uri="viking://resources/docs/auth/",context_type="resource", # "resource"、"memory" 或 "skill"- abstract="Authentication guide..."+ abstract="Authentication guide...",)# 工具调用@@ -1045,11 +1058,12 @@ ToolPart(tool_name="search_web",skill_uri="viking://~/skills/search-web/",tool_input={"query": "OAuth best practices"},- tool_output="",- tool_status="pending" # "pending"、"running"、"completed"、"error"+ tool_status="pending", # "pending"、"running"、"completed"、"error")```+如果需要与 HTTP、Go 或 TypeScript 代码复用同一 payload 结构,也可以传等价的字典。+#### 3. 使用示例**HTTP API**@@ -1103,15 +1117,15 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages \```pythonimport openviking as ov-from openviking.message import TextPart, ContextPart-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# 简单模式:添加用户消息await client.add_message(session_id="a1b2c3d4",role="user",- content="How do I authenticate users?"+ content="How do I authenticate users?",)# Parts 模式:添加带有上下文引用的助手消息@@ -1123,9 +1137,9 @@ await client.add_message(ContextPart(uri="viking://resources/docs/auth/",context_type="resource",- abstract="Authentication guide"- )- ]+ abstract="Authentication guide",+ ),+ ],)```@@ -1222,9 +1236,10 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/messages/batch \**Python SDK**```python-import openviking as ov+from openviking_sdk import AsyncHTTPClient-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# 批量添加消息result = await client.batch_add_messages(@@ -1402,17 +1417,18 @@ curl -X GET http://localhost:1933/api/v1/tasks/{task_id} \**Python SDK**```python-import openviking as ov+from openviking_sdk import AsyncHTTPClient-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# commit 立即返回 task_id,后台异步执行摘要生成和记忆提取-result = await client.commit_session("a1b2c3d4")+result = await client.commit_session(session_id="a1b2c3d4")print(f"Status: {result['status']}")print(f"Task ID: {result['task_id']}")# 查询后台任务状态-task = await client.get_task(result["task_id"])+task = await client.get_task(task_id=result["task_id"])if task["status"] == "completed":memories = task["result"]["memories_extracted"]total = sum(memories.values())@@ -1615,11 +1631,11 @@ viking://user/{user_id}/sessions/{session_id}/**Python SDK**```python-import openviking as ov-from openviking.message import TextPart, ContextPart+from openviking_sdk import AsyncHTTPClient, ContextPart, TextPart# 初始化客户端-client = ov.Client(base_url="http://localhost:1933", api_key="your-key")+client = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")+await client.initialize()# 创建新会话session_result = await client.create_session()@@ -1630,32 +1646,37 @@ print(f"Session created: {session_id}")await client.add_message(session_id=session_id,role="user",- content="How do I configure embedding?"+ content="How do I configure embedding?",)# 使用会话上下文进行搜索-results = await client.search("embedding configuration", session_id=session_id)+results = await client.search(+ query="embedding configuration",+ session_id=session_id,+)# 添加带有上下文引用的助手回复-if results.resources:+resources = results.get("resources", [])+if resources:+ resource = resources[0]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,+ uri=resource["uri"],context_type="resource",- abstract=results.resources[0].abstract- )- ]+ abstract=resource.get("abstract", ""),+ ),+ ],)# 提交会话(立即返回,后台执行摘要生成和记忆提取)-commit_result = await client.commit_session(session_id)+commit_result = await client.commit_session(session_id=session_id)print(f"Task ID: {commit_result['task_id']}")# 可选:等待后台任务完成-task = await client.get_task(commit_result["task_id"])+task = await client.get_task(task_id=commit_result["task_id"])if task and task["status"] == "completed":memories = task["result"]["memories_extracted"]total = sum(memories.values())@@ -1712,16 +1733,16 @@ curl -X GET http://localhost:1933/api/v1/tasks/uuid-xxx \```python# 在重要交互后提交-session_info = await client.get_session(session_id)+session_info = await client.get_session(session_id=session_id)if session_info["message_count"] > 10:- await client.commit_session(session_id)+ await client.commit_session(session_id=session_id)```### 使用会话上下文进行搜索```python# 结合对话上下文可获得更好的搜索结果-results = await client.search(query, session_id=session_id)+results = await client.search(query=query, session_id=session_id)```---diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.mdindex 89afb4179..38d4f87ca 100644--- a/docs/zh/api/06-retrieval.md+++ b/docs/zh/api/06-retrieval.md@@ -181,42 +181,45 @@ Tags 必须使用严格的 `k=v` 字符串。传入多个 tags 时,`find()````pythonimport openviking as ovfrom openviking.retrieve import ContextType+from openviking_sdk import TextPartclient = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()# 基础搜索-results = client.find("how to authenticate users")+results = client.find(query="how to authenticate users")# 带过滤和时间范围的搜索recent_emails = client.find(- "invoice",+ query="invoice",target_uri="viking://resources/email",- since="7d",- time_field="created_at",+ options={+ "since": "7d",+ "time_field": "created_at",+ },)# 仅搜索 memories 和 resourcestyped_results = client.find(- "authentication",- context_type=[ContextType.MEMORY, ContextType.RESOURCE],+ query="authentication",+ options={"context_type": [ContextType.MEMORY, ContextType.RESOURCE]},)# 按本地图片、bytes、data URI、HTTP URL 或 viking:// URI 搜索-image_results = client.find(image="/path/to/photo.png")+image_results = client.find(query="", image="/path/to/photo.png")# 按显式检索标签搜索。多个 tags 之间是 AND 关系。tagged_results = client.find(- "rollback runbook",- tags=["env=prod", "team=search"],+ query="rollback runbook",+ options={"tags": ["env=prod", "team=search"]},)# 遍历结果-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]}...")+for context in results.get("resources", []):+ print(f"URI: {context['uri']}")+ print(f"Score: {context.get('score', 0.0):.3f}")+ print(f"Type: {context.get('context_type')}")+ print(f"Abstract: {context.get('abstract', '')[:100]}...")print("---")```@@ -225,19 +228,19 @@ for ctx in results.resources:```python# 仅在资源中搜索results = client.find(- "authentication",- target_uri="viking://resources"+ query="authentication",+ target_uri="viking://resources",)# 仅在用户记忆中搜索results = client.find(- "preferences",+ query="preferences",target_uri="viking://~/memories")# 仅在当前用户资源中搜索results = client.find(- "private docs",+ query="private docs",target_uri="viking://~/resources")@@ -247,18 +250,18 @@ peer_client = ov.SyncHTTPClient(api_key="your-key",actor_peer_id="web-visitor-alice",)-peer_results = peer_client.find("invoice follow-up")+peer_results = peer_client.find(query="invoice follow-up")# 仅在技能中搜索results = client.find(- "web search",+ query="web search",target_uri="viking://~/skills")# 在特定项目中搜索results = client.find(- "API endpoints",- target_uri="viking://resources/my-project"+ query="API endpoints",+ target_uri="viking://resources/my-project",)```@@ -456,31 +459,35 @@ curl -X POST http://localhost:1933/api/v1/search/search \```pythonimport openviking as ovfrom openviking.retrieve import ContextType-from openviking.message import TextPartclient = 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 with OAuth")-])-session.add_message("assistant", [- TextPart(text="I can help you with OAuth implementation.")-])+session_info = client.create_session()+session = client.session(session_id=session_info["session_id"])+session.add_message(+ role="user",+ parts=[TextPart(text="I'm building a login page with OAuth")],+)+session.add_message(+ role="assistant",+ parts=[TextPart(text="I can help you with OAuth implementation.")],+)# 搜索能够理解对话上下文results = client.search(- "best practices",- session=session,- context_type=ContextType.SKILL,- since="2h"+ query="best practices",+ session_id=session.session_id,+ options={+ "context_type": ContextType.SKILL,+ "since": "2h",+ },)-for ctx in results.resources:- print(f"Found: {ctx.uri}")- print(f"Abstract: {ctx.abstract[:200]}...")+for context in results.get("resources", []):+ print(f"Found: {context['uri']}")+ print(f"Abstract: {context.get('abstract', '')[:200]}...")```**不使用会话的搜索**@@ -489,17 +496,20 @@ for ctx in results.resources:# search 也可以在没有会话的情况下使用# 它仍然会对查询进行意图分析results = client.search(- "how to implement OAuth 2.0 authorization code flow"+ query="how to implement OAuth 2.0 authorization code flow")-for ctx in results.resources:- print(f"Found: {ctx.uri} (score: {ctx.score:.3f})")+for context in results.get("resources", []):+ print(f"Found: {context['uri']} (score: {context.get('score', 0.0):.3f})")```**图片搜索**```python-results = client.search("similar poster", image="/path/to/poster.png")+results = client.search(+ query="similar poster",+ image="/path/to/poster.png",+)```**TypeScript SDK**@@ -824,8 +834,8 @@ client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()results = client.grep(- "viking://resources",- "authentication",+ uri="viking://resources",+ pattern="authentication",case_insensitive=True,node_limit=1024,)@@ -946,13 +956,17 @@ client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()# 查找所有 markdown 文件(默认最多返回 256 条)-results = client.glob("**/*.md", "viking://resources")+results = client.glob(pattern="**/*.md", uri="viking://resources")print(f"Found {results['count']} markdown files:")for uri in results['matches']:print(f" {uri}")# 查找所有 Python 文件,并显式放宽返回上限-results = client.glob("**/*.py", "viking://resources", node_limit=1024)+results = client.glob(+ pattern="**/*.py",+ uri="viking://resources",+ node_limit=1024,+)print(f"Found {results['count']} Python files")```@@ -1016,19 +1030,19 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()-results = client.find("authentication")+results = client.find(query="authentication")-for ctx in results.resources:- # 从 L0(摘要)开始 - 已包含在 ctx.abstract 中- print(f"Abstract: {ctx.abstract}")+for context in results.get("resources", []):+ # 从 L0(摘要)开始 - 已包含在 context["abstract"] 中+ print(f"Abstract: {context.get('abstract', '')}")- if ctx.level < 2:+ if context.get("level", 0) < 2:# 获取 L1(概览)用于目录- overview = client.overview(ctx.uri)+ overview = client.overview(uri=context["uri"])print(f"Overview: {overview[:500]}...")else:# 加载 L2(内容)用于文件- content = client.read(ctx.uri)+ content = client.read(uri=context["uri"])print(f"File content: {content}")```@@ -1061,10 +1075,10 @@ client = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()# 好 - 具体的查询-results = client.find("OAuth 2.0 authorization code flow implementation")+results = client.find(query="OAuth 2.0 authorization code flow implementation")# 效果较差 - 过于宽泛-results = client.find("auth")+results = client.find(query="auth")```### 限定搜索范围@@ -1077,8 +1091,8 @@ client.initialize()# 在相关范围内搜索以获得更好的结果results = client.find(- "error handling",- target_uri="viking://resources/my-project"+ query="error handling",+ target_uri="viking://resources/my-project",)```@@ -1086,19 +1100,24 @@ results = client.find(```pythonimport openviking as ov-from openviking.message import TextPart+from openviking_sdk import TextPartclient = 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")-])+session_info = client.create_session()+session = client.session(session_id=session_info["session_id"])+session.add_message(+ role="user",+ parts=[TextPart(text="I'm building a login page")],+)# 搜索能够理解上下文-results = client.search("best practices", session=session)+results = client.search(+ query="best practices",+ session_id=session.session_id,+)```## 相关文档diff --git a/docs/zh/api/07-system.md b/docs/zh/api/07-system.mdindex 3a930b154..bb8240148 100644--- a/docs/zh/api/07-system.md+++ b/docs/zh/api/07-system.md@@ -273,7 +273,7 @@ curl -X POST http://localhost:1933/api/v1/system/consistency \**Python SDK**```python-report = client.check_consistency("viking://resources/my-project")+report = client.check_consistency(uri="viking://resources/my-project")print(report["ok"])print(report["missing_records"])```@@ -364,7 +364,7 @@ curl -X POST http://localhost:1933/api/v1/system/wait \```python# 添加资源-client.add_resource("./docs/")+client.add_resource(path="./docs/")# 等待所有处理完成status = client.wait_processed(timeout=60.0)diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 2365f8b66..a33d7c5c3 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -246,14 +246,18 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-key>")client.initialize()-result = client.admin_create_account("acme", "alice", seed="alice-seed")+result = client.admin_create_account(+ account_id="acme",+ admin_user_id="alice",+ seed="alice-seed",+)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)')}")result = client.admin_create_account(- "acme-private",- "alice",+ account_id="acme-private",+ admin_user_id="alice",user_config={"add_targets": {"resource_uri": "viking://~/resources",@@ -451,7 +455,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-key>")client.initialize()-result = client.admin_delete_account("acme")+result = client.admin_delete_account(account_id="acme")print(f"Account deleted: {result['deleted']}")```@@ -558,13 +562,18 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-or-admin-key>")client.initialize()-result = client.admin_register_user("acme", "bob", role="user", seed="bob-seed")+result = client.admin_register_user(+ account_id="acme",+ user_id="bob",+ role="user",+ seed="bob-seed",+)print(f"User registered: {result['user_id']}")print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")result = client.admin_register_user(- "acme",- "bob-private",+ account_id="acme",+ user_id="bob-private",role="user",user_config={"add_targets": {"resource_uri": "viking://~/resources/project-a"}},)@@ -683,7 +692,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-or-admin-key>")client.initialize()-users = client.admin_list_users("acme")+users = client.admin_list_users(account_id="acme")for user in users:print(f"User: {user['user_id']}, role: {user['role']}")```@@ -881,7 +890,7 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-key>")client.initialize()-result = client.admin_set_role("acme", "bob", "admin")+result = client.admin_set_role(account_id="acme", user_id="bob", role="admin")print(f"User: {result['user_id']}, new role: {result['role']}")```@@ -979,7 +988,11 @@ import openviking as ovclient = ov.SyncHTTPClient(api_key="<root-or-admin-key>")client.initialize()-result = client.admin_regenerate_key("acme", "bob", seed="bob-new-seed")+result = client.admin_regenerate_key(+ account_id="acme",+ user_id="bob",+ seed="bob-new-seed",+)print(f"New user key: {result['user_key']}")```diff --git a/docs/zh/api/11-snapshot.md b/docs/zh/api/11-snapshot.mdindex b665586e5..9e02ccfd1 100644--- a/docs/zh/api/11-snapshot.md+++ b/docs/zh/api/11-snapshot.md@@ -659,11 +659,21 @@ client.initialize()root = "viking://resources/my_project"# 1. 写入初始内容并提交 v1-client.write(f"{root}/guide.md", "# Guide\n\nv1 content\n", mode="create", wait=True)+client.write(+ uri=f"{root}/guide.md",+ content="# Guide\n\nv1 content\n",+ mode="create",+ wait=True,+)v1 = client.snapshot.commit(message="v1 initial import")# 2. 修改后再提交 v2-client.write(f"{root}/guide.md", "# Guide\n\nv2 content\n", mode="replace", wait=True)+client.write(+ uri=f"{root}/guide.md",+ content="# Guide\n\nv2 content\n",+ mode="replace",+ wait=True,+)v2 = client.snapshot.commit(message="v2 update")# 3. 查看历史diff --git a/docs/zh/api/12-content.md b/docs/zh/api/12-content.mdindex 079c13301..21c052ff6 100644--- a/docs/zh/api/12-content.md+++ b/docs/zh/api/12-content.md@@ -18,7 +18,7 @@**Python SDK**```python-abstract = client.abstract("viking://resources/docs/")+abstract = client.abstract(uri="viking://resources/docs/")print(f"Abstract: {abstract}")# Output: "Documentation for the project API, covering authentication, endpoints..."```@@ -84,7 +84,7 @@ openviking abstract viking://resources/docs/**Python SDK**```python-overview = client.overview("viking://resources/docs/")+overview = client.overview(uri="viking://resources/docs/")print(f"Overview:\n{overview}")```@@ -157,7 +157,7 @@ openviking overview viking://resources/docs/**Python SDK**```python-content = client.read("viking://resources/docs/api.md")+content = client.read(uri="viking://resources/docs/api.md")print(f"Content:\n{content}")```@@ -235,8 +235,8 @@ openviking read viking://resources/docs/api.md```pythonresult = client.write(- "viking://resources/docs/api.md",- "# Updated API\n\nFresh content.",+ uri="viking://resources/docs/api.md",+ content="# Updated API\n\nFresh content.",mode="replace",wait=True,)@@ -476,8 +476,8 @@ Content-Disposition: attachment; filename*=UTF-8''logo.png```pythonresult = client.set_tags(- "viking://resources/project/",- ["team=search", "env=prod"],+ uri="viking://resources/project/",+ tags=["team=search", "env=prod"],mode="replace",recursive=True,)@@ -628,8 +628,10 @@ result = client.reindex(uri="viking://resources",mode="vectors_only",wait=True,- tags=["team=search", "env=prod"],- tag_mode="replace",+ options={+ "tags": ["team=search", "env=prod"],+ "tag_mode": "replace",+ },)print(result)```diff --git a/docs/zh/api/17-tasks.md b/docs/zh/api/17-tasks.mdindex 61fbd129f..602ae16c8 100644--- a/docs/zh/api/17-tasks.md+++ b/docs/zh/api/17-tasks.md@@ -52,7 +52,7 @@ from openviking_sdk import AsyncHTTPClientclient = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")await client.initialize()-task = await client.get_task("uuid-xxx")+task = await client.get_task(task_id="uuid-xxx")print(f"Status: {task['status']}")await client.close()```@@ -170,7 +170,7 @@ ov task status uuid-xxx**Python SDK**```python-task = await client.cancel_task("uuid-xxx")+task = await client.cancel_task(task_id="uuid-xxx")print(task["status"])```diff --git a/docs/zh/api/99-api-doc-writing-guide.md b/docs/zh/api/99-api-doc-writing-guide.mdindex 49188296e..88e88fd98 100644--- a/docs/zh/api/99-api-doc-writing-guide.md+++ b/docs/zh/api/99-api-doc-writing-guide.md@@ -49,7 +49,7 @@ API 文档按模块组织,每个模块一个文件,使用两位数字序号**Python SDK**-```python+```text<SDK 调用示例>```@@ -223,8 +223,8 @@ from openviking_sdk import SyncHTTPClientclient = SyncHTTPClient(url="http://localhost:1933", api_key="your-key")result = client.add_resource(- "./documents/guide.md",- reason="User guide documentation"+ path="./documents/guide.md",+ options={"reason": "User guide documentation"},)print(f"Added: {result['root_uri']}")diff --git a/docs/zh/concepts/02-context-types.md b/docs/zh/concepts/02-context-types.mdindex 751a86382..e5487ef32 100644--- a/docs/zh/concepts/02-context-types.md+++ b/docs/zh/concepts/02-context-types.md@@ -31,14 +31,14 @@```python# 添加资源client.add_resource(- "https://docs.example.com/api.pdf",- reason="API 文档"+ path="https://docs.example.com/api.pdf",+ options={"reason": "API 文档"},)# 搜索资源results = client.find(- "认证方法",- target_uri="viking://resources/"+ query="认证方法",+ target_uri="viking://resources/",)```@@ -73,15 +73,21 @@ Schema 定义的 `memories/tools/` 和 `memories/skills/` 类型已禁用。它### 使用```python+from openviking_sdk import TextPart+# 记忆从会话中自动提取-session = client.session()-await session.add_message("user", [{"type": "text", "text": "我喜欢深色模式"}])+session_info = await client.create_session()+session = client.session(session_id=session_info["session_id"])+await session.add_message(+ role="user",+ parts=[TextPart(text="我喜欢深色模式")],+)commit = await session.commit() # 启动后台记忆提取-task = await client.get_task(commit["task_id"]) # 轮询直到 task["status"] == "completed"+task = await client.get_task(task_id=commit["task_id"]) # 轮询直到 task["status"] == "completed"# 搜索记忆results = await client.find(- "用户界面偏好",+ query="用户界面偏好",target_uri="viking://~/memories/")```@@ -127,25 +133,27 @@ AgentDefinedContextType 包含以下子类型,均存储于 `viking://agent/````python# 添加技能(默认写入 viking://~/skills/)-await client.add_skill({- "name": "search-web",- "description": "搜索网络获取信息",- "content": "# search-web\n..."-})+await client.add_skill(+ data={+ "name": "search-web",+ "description": "搜索网络获取信息",+ "content": "# search-web\n...",+ },+)# 通过 -p 指定写入全局 agent 技能根(公开共享)ov skills add search-web -p viking://agent/skills# 搜索用户技能results = await client.find(- "网络搜索",+ query="网络搜索",target_uri="viking://~/skills/")# 搜索全局 agent 技能results = await client.find(- "网络搜索",- target_uri="viking://agent/skills/"+ query="网络搜索",+ target_uri="viking://agent/skills/",)```@@ -155,14 +163,14 @@ results = await client.find(```python# 跨所有上下文类型搜索-results = await client.find("用户认证")--for ctx in results.memories:- print(f"记忆: {ctx.uri}")-for ctx in results.resources:- print(f"资源: {ctx.uri}")-for ctx in results.skills:- print(f"技能: {ctx.uri}")+results = await client.find(query="用户认证")++for context in results.get("memories", []):+ print(f"记忆: {context['uri']}")+for context in results.get("resources", []):+ print(f"资源: {context['uri']}")+for context in results.get("skills", []):+ print(f"技能: {context['uri']}")```## 相关文档diff --git a/docs/zh/concepts/03-context-layers.md b/docs/zh/concepts/03-context-layers.mdindex 9ee7269e5..737a88775 100644--- a/docs/zh/concepts/03-context-layers.md+++ b/docs/zh/concepts/03-context-layers.md@@ -27,7 +27,7 @@ API 认证指南,涵盖 OAuth 2.0、JWT 令牌和 API 密钥的安全访问方通过语义 accessor 读取时,只返回可见正文:```python-abstract = client.abstract("viking://resources/docs/auth")+abstract = client.abstract(uri="viking://resources/docs/auth")```## L1:概览@@ -47,7 +47,7 @@ L1 提供更完整的目录摘要和导航信息,用于 Rerank 和决定是否``````python-overview = client.overview("viking://resources/docs/auth")+overview = client.overview(uri="viking://resources/docs/auth")```L0 从 L1 正文中提取:取 H1 标题之后、第一个 `##` 标题之前的 Brief Description 段落。YAML frontmatter 不参与提取。@@ -57,7 +57,7 @@ L0 从 L1 正文中提取:取 H1 标题之后、第一个 `##` 标题之前的L2 是原始文件或解析后的完整内容,只在需要时加载,并保留源格式和结构。```python-content = client.read("viking://resources/docs/auth/oauth.md")+content = client.read(uri="viking://resources/docs/auth/oauth.md")```## 目录结构diff --git a/docs/zh/concepts/04-viking-uri.md b/docs/zh/concepts/04-viking-uri.mdindex 298e70d71..5a56e0adc 100644--- a/docs/zh/concepts/04-viking-uri.md+++ b/docs/zh/concepts/04-viking-uri.md@@ -301,25 +301,25 @@ parent = VikingURI(uri).parent.uri # viking://resources/docs```python# 仅在资源中搜索results = client.find(- "认证",- target_uri="viking://resources/"+ query="认证",+ target_uri="viking://resources/",)# 仅在自己的资源中搜索results = client.find(- "私有项目笔记",+ query="私有项目笔记",target_uri="viking://~/resources/")# 仅在自己的记忆中搜索results = client.find(- "编码偏好",+ query="编码偏好",target_uri="viking://~/memories/")# 仅在自己的技能中搜索results = client.find(- "网络搜索",+ query="网络搜索",target_uri="viking://~/skills/")```@@ -328,16 +328,16 @@ results = client.find(```python# 列出目录-entries = await client.ls("viking://resources/")+entries = await client.ls(uri="viking://resources/")# 读取文件-content = await client.read("viking://resources/docs/api.md")+content = await client.read(uri="viking://resources/docs/api.md")# 获取摘要-abstract = await client.abstract("viking://resources/docs/")+abstract = await client.abstract(uri="viking://resources/docs/")# 获取概览-overview = await client.overview("viking://resources/docs/")+overview = await client.overview(uri="viking://resources/docs/")```## 特殊文件diff --git a/docs/zh/concepts/06-extraction.md b/docs/zh/concepts/06-extraction.mdindex c14418c51..fed7f8b6f 100644--- a/docs/zh/concepts/06-extraction.md+++ b/docs/zh/concepts/06-extraction.md@@ -176,8 +176,8 @@ L0/L1 是目录级 sidecar,不是 per-file sidecar。生成父目录摘要时```python# 添加资源await client.add_resource(- "/path/to/doc.pdf",- reason="API 文档"+ path="/path/to/doc.pdf",+ options={"reason": "API 文档"},)# 流程: Parser → TreeBuilder(scope=resources) → SemanticQueue@@ -187,10 +187,12 @@ await client.add_resource(```python# 添加技能-await client.add_skill({- "name": "search-web",- "content": "# search-web\\n..."-})+await client.add_skill(+ data={+ "name": "search-web",+ "content": "# search-web\\n...",+ },+)# 流程: 直接写入 viking://~/skills/{name}/ → SemanticQueue```diff --git a/docs/zh/concepts/07-retrieval.md b/docs/zh/concepts/07-retrieval.mdindex a2b64ae33..f163cc203 100644--- a/docs/zh/concepts/07-retrieval.md+++ b/docs/zh/concepts/07-retrieval.md@@ -25,14 +25,15 @@ OpenViking 采用两阶段检索:意图分析 + 层级检索 + Rerank。```python# find(): 简单查询results = await client.find(- "OAuth 认证",- target_uri="viking://resources/"+ query="OAuth 认证",+ target_uri="viking://resources/",)# search(): 复杂任务(需要会话上下文)+session_info = await client.create_session()results = await client.search(- "帮我创建一个 RFC 文档",- session_info=session+ query="帮我创建一个 RFC 文档",+ session_id=session_info["session_id"],)```diff --git a/docs/zh/concepts/08-session.md b/docs/zh/concepts/08-session.mdindex f910a56f8..34cf5948c 100644--- a/docs/zh/concepts/08-session.md+++ b/docs/zh/concepts/08-session.md@@ -6,11 +6,13 @@ Session 负责管理对话消息、记录上下文使用、提取长期记忆。**生命周期**:创建 → 交互 → 提交-通过 session_id 获取会话时,默认不会自动创建不存在的会话;如果需要自动创建,请显式使用 `client.get_session(..., auto_create=True)`。+通过 session_id 获取会话时不会创建会话。请先创建会话,再通过+`client.session(session_id=...)` 追加消息或提交会话。```python-session = client.session(session_id="chat_001")-session.add_message("user", [TextPart("...")])+session_info = client.create_session(session_id="chat_001")+session = client.session(session_id=session_info["session_id"])+session.add_message(role="user", content="...")session.commit()```@@ -18,51 +20,41 @@ session.commit()| 方法 | 说明 ||------|------|-| `add_message(role, parts)` | 添加消息 |-| `used(contexts, skill)` | 记录使用的上下文/技能 |+| `add_message(role, content=None, parts=None, options=None, peer_id=None)` | 添加消息 || `commit()` | 提交:归档(同步) + 摘要生成和记忆提取(异步后台) || `get_task(task_id)` | 查询后台任务状态 |### add_message```python+from openviking_sdk import ContextPart, ImagePart, TextPart+session.add_message(- "user",- [TextPart("How to configure embedding?")]+ role="user",+ content="How to configure embedding?",)session.add_message(- "assistant",- [- TextPart("Here's how..."),- ContextPart(uri="viking://~/memories/profile.md"),+ role="assistant",+ parts=[+ TextPart(text="Here's how..."),+ ContextPart(+ uri="viking://~/memories/profile.md",+ context_type="memory",+ abstract="User profile",+ ),])session.add_message(- "user",- [- TextPart("Remember this studio layout."),+ role="user",+ parts=[+ TextPart(text="Remember this studio layout."),ImagePart(url="https://example.com/studio.png", detail="auto"),])```-### used--```python-# 记录使用的上下文-session.used(contexts=["viking://~/memories/profile.md"])--# 记录使用的技能-session.used(skill={- "uri": "viking://~/skills/code-search",- "input": "search config",- "output": "found 3 files",- "success": True-})-```-### commit```python@@ -75,7 +67,7 @@ result = session.commit()# }# 查询后台任务进度-task = client.get_task(result["task_id"])+task = client.get_task(task_id=result["task_id"])# task["status"]: "pending" | "running" | "completed" | "failed"# sum(task["result"]["memories_extracted"].values()): 3```diff --git a/docs/zh/faq/faq.md b/docs/zh/faq/faq.mdindex bcb7c06ed..ada8153c2 100644--- a/docs/zh/faq/faq.md+++ b/docs/zh/faq/faq.md@@ -162,15 +162,15 @@ Embedding、VLM、存储等服务配置由 OpenViking Server 通过 `ov.conf````python# 添加单个文件await client.add_resource(- "./document.pdf",- reason="项目技术文档", # 描述资源用途,提升检索质量- to="viking://resources/docs/" # 指定存储位置+ path="./document.pdf",+ to="viking://resources/docs/", # 指定存储位置+ options={"reason": "项目技术文档"}, # 描述资源用途,提升检索质量)# 添加网页await client.add_resource(- "https://example.com/api-docs",- reason="API 参考文档"+ path="https://example.com/api-docs",+ options={"reason": "API 参考文档"},)# 等待处理完成@@ -189,14 +189,14 @@ await client.wait_processed()```python# find(): 简单直接的语义搜索results = await client.find(- "OAuth 认证流程",- target_uri="viking://resources/"+ query="OAuth 认证流程",+ target_uri="viking://resources/",)# search(): 复杂任务,需要意图分析results = await client.search(- "帮我实现用户登录功能",- session_info=session+ query="帮我实现用户登录功能",+ session_id=session.session_id,)```@@ -209,15 +209,21 @@ results = await client.search(会话管理是 OpenViking 的核心能力,支持对话追踪和记忆提取:```python+from openviking_sdk import TextPart+# 创建会话-session = client.session()+session_info = await client.create_session()+session = client.session(session_id=session_info["session_id"])# 添加对话消息-await session.add_message("user", [{"type": "text", "text": "帮我分析这段代码的性能问题"}])-await session.add_message("assistant", [{"type": "text", "text": "我来分析一下..."}])--# 标记使用的上下文(用于追踪)-await session.used(["viking://resources/code/main.py"])+await session.add_message(+ role="user",+ parts=[TextPart(text="帮我分析这段代码的性能问题")],+)+await session.add_message(+ role="assistant",+ parts=[TextPart(text="我来分析一下...")],+)# 提交会话,触发记忆提取await session.commit()@@ -233,16 +239,16 @@ OpenViking 内置 `profile`、`preferences`、`entities`、`events`、`identity````python# 列出目录内容-items = await client.ls("viking://resources/")+items = await client.ls(uri="viking://resources/")# 读取完整内容(L2)-content = await client.read("viking://resources/doc.md")+content = await client.read(uri="viking://resources/doc.md")# 获取摘要(L0)-abstract = await client.abstract("viking://resources")+abstract = await client.abstract(uri="viking://resources")# 获取概览(L1)-overview = await client.overview("viking://resources")+overview = await client.overview(uri="viking://resources")```## 检索优化@@ -285,7 +291,7 @@ OpenViking 使用分数传播机制:1. **未等待处理完成**```python- await client.add_resource("./doc.pdf")+ await client.add_resource(path="./doc.pdf")await client.wait_processed() # 必须等待```@@ -310,7 +316,7 @@ OpenViking 使用分数传播机制:1. **确认资源已处理完成**```python# 检查资源是否存在- items = await client.ls("viking://resources/")+ items = await client.ls(uri="viking://resources/")```2. **检查 `target_uri` 过滤条件**@@ -323,7 +329,7 @@ OpenViking 使用分数传播机制:4. **检查 L0 摘要质量**```python- abstract = await client.abstract("viking://resources/your-doc")+ abstract = await client.abstract(uri="viking://resources/your-doc")print(abstract) # 确认摘要是否准确反映内容```@@ -346,7 +352,10 @@ OpenViking 使用分数传播机制:4. **查看提取的记忆**```python- memories = await client.find("", target_uri="viking://~/memories/")+ memories = await client.find(+ query="",+ target_uri="viking://~/memories/",+ )```### 性能问题diff --git a/docs/zh/getting-started/01-introduction.md b/docs/zh/getting-started/01-introduction.mdindex e764a91e1..2dbb3f0e9 100644--- a/docs/zh/getting-started/01-introduction.md+++ b/docs/zh/getting-started/01-introduction.md@@ -51,11 +51,11 @@ viking://**类 Unix API**:熟悉的命令式操作```python-client.find("用户认证") # 语义搜索-client.ls("viking://resources/") # 列出目录-client.read("viking://resources/doc") # 读取内容-client.abstract("viking://...") # 获取 L0 摘要-client.overview("viking://...") # 获取 L1 概览+client.find(query="用户认证") # 语义搜索+client.ls(uri="viking://resources/") # 列出目录+client.read(uri="viking://resources/doc") # 读取内容+client.abstract(uri="viking://...") # 获取 L0 摘要+client.overview(uri="viking://...") # 获取 L1 概览```### 2. 分层上下文按需加载diff --git a/docs/zh/getting-started/02-quickstart.md b/docs/zh/getting-started/02-quickstart.mdindex 389a3cff3..77ace076b 100644--- a/docs/zh/getting-started/02-quickstart.md+++ b/docs/zh/getting-started/02-quickstart.md@@ -194,22 +194,25 @@ try:root_uri = add_result['root_uri']# Explore the resource tree structure- ls_result = client.ls(root_uri)+ ls_result = client.ls(uri=root_uri)print(f"Directory structure:\n{ls_result}\n")# Use glob to find markdown filesglob_result = client.glob(pattern="**/*.md", uri=root_uri)if glob_result['matches']:- content = client.read(glob_result['matches'][0])+ content = client.read(uri=glob_result["matches"][0])print(f"Content preview: {content[:200]}...\n")# Get abstract and overview of the resource- abstract = client.abstract(root_uri)- overview = client.overview(root_uri)+ abstract = client.abstract(uri=root_uri)+ overview = client.overview(uri=root_uri)print(f"Abstract:\n{abstract}\n\nOverview:\n{overview}\n")# Perform semantic search- results = client.find("what is openviking", target_uri=root_uri)+ results = client.find(+ query="what is openviking",+ target_uri=root_uri,+ )print("Search results:")for result in results.get("resources", []):print(f" {result['uri']} (score: {result.get('score', 0.0):.4f})")diff --git a/docs/zh/getting-started/03-quickstart-server.md b/docs/zh/getting-started/03-quickstart-server.mdindex f324d732d..81eb7b23a 100644--- a/docs/zh/getting-started/03-quickstart-server.md+++ b/docs/zh/getting-started/03-quickstart-server.md@@ -109,7 +109,7 @@ try:# Add a resourceresult = client.add_resource(- "https://raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/README.md"+ path="https://raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/README.md",)root_uri = result["root_uri"]@@ -117,9 +117,12 @@ try:client.wait_processed()# Search- results = client.find("what is openviking", target_uri=root_uri)- for r in results.resources:- print(f" {r.uri} (score: {r.score:.4f})")+ results = client.find(+ query="what is openviking",+ target_uri=root_uri,+ )+ for result in results.get("resources", []):+ print(f" {result['uri']} (score: {result.get('score', 0.0):.4f})")finally:client.close()diff --git a/docs/zh/guides/02-volcengine-purchase-guide.md b/docs/zh/guides/02-volcengine-purchase-guide.mdindex 6ec62791b..ae7622c88 100644--- a/docs/zh/guides/02-volcengine-purchase-guide.md+++ b/docs/zh/guides/02-volcengine-purchase-guide.md@@ -182,8 +182,8 @@ async def test():# 添加简单资源测试result = await client.add_resource(- "https://example.com",- reason="测试连接"+ path="https://example.com",+ options={"reason": "测试连接"},)print(f"✓ 配置成功: {result['root_uri']}")diff --git a/docs/zh/guides/03-deployment.md b/docs/zh/guides/03-deployment.mdindex ed5b463e8..fc924569b 100644--- a/docs/zh/guides/03-deployment.md+++ b/docs/zh/guides/03-deployment.md@@ -150,7 +150,7 @@ import openviking as ovclient = ov.SyncHTTPClient(url="http://localhost:1933", api_key="your-key")client.initialize()-results = client.find("how to use openviking")+results = client.find(query="how to use openviking")client.close()```diff --git a/docs/zh/guides/07-operation-telemetry.md b/docs/zh/guides/07-operation-telemetry.mdindex 7cae5e465..4d667360e 100644--- a/docs/zh/guides/07-operation-telemetry.md+++ b/docs/zh/guides/07-operation-telemetry.md@@ -333,7 +333,10 @@ from openviking_sdk import AsyncHTTPClientclient = AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")await client.initialize()-result = await client.find("memory dedup", telemetry=True)+result = await client.find(+ query="memory dedup",+ options={"telemetry": True},+)print(result["telemetry"]["summary"]["operation"])print(result["telemetry"]["summary"]["duration_ms"])```diff --git a/docs/zh/guides/08-encryption.md b/docs/zh/guides/08-encryption.mdindex 0aefe88f6..f204cecc5 100644--- a/docs/zh/guides/08-encryption.md+++ b/docs/zh/guides/08-encryption.md@@ -68,10 +68,13 @@ async def test():# add_resource 接收文件路径或 URLsample = Path("./encrypted-sample.txt")sample.write_text("Hello, encrypted world!", encoding="utf-8")- await client.add_resource(str(sample), reason="测试加密")+ await client.add_resource(+ path=str(sample),+ options={"reason": "测试加密"},+ )# 读取资源(自动解密)- results = await client.find("encrypted")+ results = await client.find(query="encrypted")print(f"找到 {len(results)} 个结果")await client.close()diff --git a/docs/zh/guides/09-ovpack.md b/docs/zh/guides/09-ovpack.mdindex 3084446a0..2bf623044 100644--- a/docs/zh/guides/09-ovpack.md+++ b/docs/zh/guides/09-ovpack.md@@ -107,7 +107,7 @@ ov system consistency viking://resources/my-projectPython SDK:```python-report = await client.check_consistency("viking://resources/my-project")+report = await client.check_consistency(uri="viking://resources/my-project")print(report["ok"], report["missing_records"])```@@ -178,9 +178,12 @@ async def migrate_project():全量备份:```python-await client.backup_ovpack("./backups/openviking.ovpack", include_vectors=True)+await client.backup_ovpack(+ to="./backups/openviking.ovpack",+ include_vectors=True,+)await client.restore_ovpack(- "./backups/openviking.ovpack",+ file_path="./backups/openviking.ovpack",on_conflict="overwrite",vector_mode="auto",)diff --git a/docs/zh/guides/15-snapshot.md b/docs/zh/guides/15-snapshot.mdindex 5efa4755e..162435756 100644--- a/docs/zh/guides/15-snapshot.md+++ b/docs/zh/guides/15-snapshot.md@@ -137,12 +137,22 @@ client.initialize()root = "viking://resources/my_project"# 1. 写入初始内容并提交 v1-client.write(f"{root}/guide.md", "# Guide\n\nv1 content\n", mode="create", wait=True)+client.write(+ uri=f"{root}/guide.md",+ content="# Guide\n\nv1 content\n",+ mode="create",+ wait=True,+)v1 = client.snapshot.commit(message="v1 initial import")print("v1:", v1["commit_oid"])# 2. 修改后再提交 v2-client.write(f"{root}/guide.md", "# Guide\n\nv2 content\n", mode="replace", wait=True)+client.write(+ uri=f"{root}/guide.md",+ content="# Guide\n\nv2 content\n",+ mode="replace",+ wait=True,+)v2 = client.snapshot.commit(message="v2 update")# 3. 查看历史diff --git a/examples/basic-usage/README.md b/examples/basic-usage/README.mdindex d8c576205..df3ca3b35 100644--- a/examples/basic-usage/README.md+++ b/examples/basic-usage/README.md@@ -104,14 +104,14 @@ Add a URL, local file, or directory:```pythonresult = client.add_resource(path="https://example.com/docs",- wait=False,+ options={"wait": False},)result = client.add_resource(path="/path/to/manual.pdf")result = client.add_resource(path="/path/to/repo",- instruction="This is a Python web application",+ options={"instruction": "This is a Python web application"},)```@@ -123,9 +123,9 @@ asynchronously and call `wait_processed()` when you actually need the indexed reOpenViking organizes context as a virtual filesystem:```python-files = client.ls("viking://resources/")-tree = client.tree("viking://resources/my-project", level_limit=3)-content = client.read("viking://resources/my-project/README.md")+files = client.ls(uri="viking://resources/")+tree = client.tree(uri="viking://resources/my-project", level_limit=3)+content = client.read(uri="viking://resources/my-project/README.md")```This same URI model applies to memories and skills as well:@@ -141,14 +141,12 @@ Use `find` for fast semantic search and `search` for more advanced retrieval:```pythonresults = client.find(query="how does authentication work",- target_uri="viking://resources/my-project",- limit=5,+ options={"target_uri": "viking://resources/my-project", "limit": 5},)results = client.search(query="database configuration and failure handling",- target_uri="viking://resources/",- limit=10,+ options={"target_uri": "viking://resources/", "limit": 10},)```@@ -157,15 +155,19 @@ Use tiered loading after retrieval:```pythonuri = "viking://resources/my-project/docs/api.md"-abstract = client.abstract(uri)-overview = client.overview(uri)-content = client.read(uri)+abstract = client.abstract(uri=uri)+overview = client.overview(uri=uri)+content = client.read(uri=uri)```Use `grep` when you need literal text matching instead of semantic retrieval:```python-result = client.grep("viking://resources/my-project", "Agent", case_insensitive=True)+result = client.grep(+ uri="viking://resources/my-project",+ pattern="Agent",+ case_insensitive=True,+)matches = result.get("matches", [])```@@ -177,14 +179,22 @@ The example script creates a session and appends messages:session_info = client.create_session()session_id = session_info["session_id"]-client.add_message(session_id, "user", "I prefer TypeScript over JavaScript")-client.add_message(session_id, "assistant", "Understood. I will use TypeScript where appropriate.")+client.add_message(+ session_id=session_id,+ role="user",+ content="I prefer TypeScript over JavaScript",+)+client.add_message(+ session_id=session_id,+ role="assistant",+ content="Understood. I will use TypeScript where appropriate.",+)```To extract durable memories from that conversation, commit the session:```python-client.commit_session(session_id)+client.commit_session(session_id=session_id)```After commit, you can retrieve those memories through normal search APIs:diff --git a/examples/basic-usage/README_CN.md b/examples/basic-usage/README_CN.mdindex d072e7fc8..b89f2f94c 100644--- a/examples/basic-usage/README_CN.md+++ b/examples/basic-usage/README_CN.md@@ -105,14 +105,14 @@ client = SyncHTTPClient(```pythonresult = client.add_resource(path="https://example.com/docs",- wait=False,+ options={"wait": False},)result = client.add_resource(path="/path/to/manual.pdf")result = client.add_resource(path="/path/to/repo",- instruction="这是一个 Python Web 应用",+ options={"instruction": "这是一个 Python Web 应用"},)```@@ -124,9 +124,9 @@ result = client.add_resource(OpenViking 的上下文统一组织在虚拟文件系统里:```python-files = client.ls("viking://resources/")-tree = client.tree("viking://resources/my-project", level_limit=3)-content = client.read("viking://resources/my-project/README.md")+files = client.ls(uri="viking://resources/")+tree = client.tree(uri="viking://resources/my-project", level_limit=3)+content = client.read(uri="viking://resources/my-project/README.md")```同样的 URI 模型也适用于记忆和技能:@@ -142,14 +142,12 @@ content = client.read("viking://resources/my-project/README.md")```pythonresults = client.find(query="认证逻辑是怎么做的",- target_uri="viking://resources/my-project",- limit=5,+ options={"target_uri": "viking://resources/my-project", "limit": 5},)results = client.search(query="数据库配置和故障处理",- target_uri="viking://resources/",- limit=10,+ options={"target_uri": "viking://resources/", "limit": 10},)```@@ -158,15 +156,19 @@ results = client.search(```pythonuri = "viking://resources/my-project/docs/api.md"-abstract = client.abstract(uri)-overview = client.overview(uri)-content = client.read(uri)+abstract = client.abstract(uri=uri)+overview = client.overview(uri=uri)+content = client.read(uri=uri)```如果你要的是字面匹配而不是语义检索,用 `grep`:```python-result = client.grep("viking://resources/my-project", "Agent", case_insensitive=True)+result = client.grep(+ uri="viking://resources/my-project",+ pattern="Agent",+ case_insensitive=True,+)matches = result.get("matches", [])```@@ -178,14 +180,22 @@ matches = result.get("matches", [])session_info = client.create_session()session_id = session_info["session_id"]-client.add_message(session_id, "user", "我更喜欢 TypeScript 而不是 JavaScript")-client.add_message(session_id, "assistant", "明白了,在合适场景下我会优先使用 TypeScript。")+client.add_message(+ session_id=session_id,+ role="user",+ content="我更喜欢 TypeScript 而不是 JavaScript",+)+client.add_message(+ session_id=session_id,+ role="assistant",+ content="明白了,在合适场景下我会优先使用 TypeScript。",+)```如果要把这段对话真正提取成长期记忆,需要提交 session:```python-client.commit_session(session_id)+client.commit_session(session_id=session_id)```提交后,记忆可以通过正常检索接口再次找回:diff --git a/examples/basic-usage/basic_usage.py b/examples/basic-usage/basic_usage.pyindex 6bba82c4a..29ca3beba 100644--- a/examples/basic-usage/basic_usage.py+++ b/examples/basic-usage/basic_usage.py@@ -77,7 +77,7 @@ def main():print(f" Root URI: {root_uri}")# Get the file count- files = client.ls(root_uri)+ files = client.ls(uri=root_uri)print(f" Files indexed: {len(files)}")except Exception as e:@@ -96,13 +96,13 @@ def main():try:# List directory contentsprint(" Directory listing:")- files = client.ls(root_uri, simple=True)+ files = client.ls(uri=root_uri, simple=True)for f in files[:5]: # Show first 5 filesprint(f" - {f}")# Show tree structureprint("\n Tree view:")- tree = client.tree(root_uri, level_limit=2)+ tree = client.tree(uri=root_uri, level_limit=2)print_tree(tree, indent=" ")except Exception as e:@@ -136,7 +136,7 @@ def main():try:# L0: Abstract (quick summary ~100 tokens)print(" L0 (Abstract):")- abstract = client.abstract(root_uri)+ abstract = client.abstract(uri=root_uri)if abstract:# Show first 200 characterspreview = abstract[:200] + "..." if len(abstract) > 200 else abstract@@ -148,7 +148,7 @@ def main():# L1: Overview (key points ~2k tokens)print(" L1 (Overview):")- overview = client.overview(root_uri)+ overview = client.overview(uri=root_uri)if overview:preview = overview[:300] + "..." if len(overview) > 300 else overviewprint(f" {preview}")@@ -162,7 +162,7 @@ def main():glob_result = client.glob(pattern="**/*.md", uri=root_uri)matches = glob_result.get("matches", []) if isinstance(glob_result, dict) else []if matches:- content = client.read(matches[0])+ content = client.read(uri=matches[0])preview = content[:500] + "..." if len(content) > 500 else contentprint(f" File: {matches[0]}")print(f" {preview}")@@ -186,7 +186,11 @@ def main():print(f" Query: '{query}'")print(" Results:")- results = client.find(query=query, target_uri=root_uri, limit=5)+ results = client.find(+ query=query,+ target_uri=root_uri,+ limit=5,+ )resources = results.get("resources", [])if resources:@@ -212,7 +216,7 @@ def main():pattern = "Agent"print(f" Pattern: '{pattern}'")- result = client.grep(root_uri, pattern, case_insensitive=True)+ result = client.grep(uri=root_uri, pattern=pattern, case_insensitive=True)matches = result.get("matches", [])print(f" Found {len(matches)} matches")@@ -239,9 +243,15 @@ def main():print(f" Created session: {session_id}")# Add a conversation turn- client.add_message(session_id, "user", "I prefer Python for data science projects")client.add_message(- session_id, "assistant", "Understood! I'll use Python for your data science work."+ session_id=session_id,+ role="user",+ content="I prefer Python for data science projects",+ )+ client.add_message(+ session_id=session_id,+ role="assistant",+ content="Understood! I'll use Python for your data science work.",)print(" Added conversation turn")diff --git a/examples/cloud/alice.py b/examples/cloud/alice.pyindex 5069be79e..0e29ac1c2 100644--- a/examples/cloud/alice.py+++ b/examples/cloud/alice.py@@ -67,7 +67,7 @@ def main():print("\n== 1. 添加资源: OpenViking README ==")result = client.add_resource(path="https://raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/README.md",- reason="项目核心文档",+ options={"reason": "项目核心文档"},)readme_uri = result.get("root_uri", "")print(f" URI: {readme_uri}")@@ -91,14 +91,17 @@ def main():# ── 4. 语义搜索 ──print("\n== 4. 语义搜索: 'context database for AI agent' ==")- results = client.find("context database for AI agent", limit=3)- if hasattr(results, "resources") and results.resources:- for i, r in enumerate(results.resources, 1):- print(f" {i}. [{r.score:.3f}] {r.uri}")+ results = client.find(query="context database for AI agent", limit=3)+ for index, resource in enumerate(results.get("resources", []), 1):+ print(+ f" {index}. [{resource.get('score', 0.0):.3f}] "+ f"{resource['uri']}"+ )# ── 5. 创建会话,模拟技术讨论 ──print("\n== 5. 对话: 技术架构讨论 ==")- session = client.session()+ session_info = client.create_session()+ session = client.session(session_id=session_info["session_id"])print(f" Session: {session.session_id}")messages = [@@ -150,16 +153,25 @@ def main():# ── 8. 搜索回顾记忆 ──print("\n== 8. 回顾记忆: '为什么选择 VikingDB' ==")- results = client.find("为什么选择 VikingDB 作为向量数据库", limit=3)- if hasattr(results, "memories") and results.memories:+ results = client.find(query="为什么选择 VikingDB 作为向量数据库", limit=3)+ memories = results.get("memories", [])+ if memories:print(" 记忆:")- for i, m in enumerate(results.memories, 1):- desc = m.abstract or m.overview or str(m.uri)- print(f" {i}. [{m.score:.3f}] {desc[:150]}")- if hasattr(results, "resources") and results.resources:+ for index, memory in enumerate(memories, 1):+ description = (+ memory.get("abstract")+ or memory.get("overview")+ or memory.get("uri", "")+ )+ print(f" {index}. [{memory.get('score', 0.0):.3f}] {description[:150]}")+ resources = results.get("resources", [])+ if resources:print(" 资源:")- for i, r in enumerate(results.resources, 1):- print(f" {i}. [{r.score:.3f}] {r.uri}")+ for index, resource in enumerate(resources, 1):+ print(+ f" {index}. [{resource.get('score', 0.0):.3f}] "+ f"{resource['uri']}"+ )print("\nAlice 流程完成")diff --git a/examples/cloud/bob.py b/examples/cloud/bob.pyindex aa82709bf..d214f6a3f 100644--- a/examples/cloud/bob.py+++ b/examples/cloud/bob.py@@ -74,26 +74,40 @@ def main():# ── 2. 回顾团队记忆(Alice 沉淀的技术决策) ──print("\n== 2. 回顾团队记忆: '项目技术选型' ==")- results = client.find("项目用了什么技术栈和架构选型", limit=5)- if hasattr(results, "memories") and results.memories:+ results = client.find(query="项目用了什么技术栈和架构选型", limit=5)+ memories = results.get("memories", [])+ if memories:print(" 团队记忆:")- for i, m in enumerate(results.memories, 1):- desc = m.abstract or m.overview or str(m.uri)- print(f" {i}. [{m.score:.3f}] {desc[:150]}")+ for index, memory in enumerate(memories, 1):+ description = (+ memory.get("abstract")+ or memory.get("overview")+ or memory.get("uri", "")+ )+ print(f" {index}. [{memory.get('score', 0.0):.3f}] {description[:150]}")else:print(" 未找到团队记忆(Alice 可能还没执行 commit)")- if hasattr(results, "resources") and results.resources:+ resources = results.get("resources", [])+ if resources:print(" 相关资源:")- for i, r in enumerate(results.resources, 1):- print(f" {i}. [{r.score:.3f}] {r.uri}")+ for index, resource in enumerate(resources, 1):+ print(+ f" {index}. [{resource.get('score', 0.0):.3f}] "+ f"{resource['uri']}"+ )# ── 3. 搜索具体决策 ──print("\n== 3. 搜索: '存储方案 TOS 配置' ==")- results = client.find("文件存储方案 TOS bucket 配置", limit=3)- if hasattr(results, "memories") and results.memories:- for i, m in enumerate(results.memories, 1):- desc = m.abstract or m.overview or str(m.uri)- print(f" {i}. [{m.score:.3f}] {desc[:150]}")+ results = client.find(query="文件存储方案 TOS bucket 配置", limit=3)+ memories = results.get("memories", [])+ if memories:+ for index, memory in enumerate(memories, 1):+ description = (+ memory.get("abstract")+ or memory.get("overview")+ or memory.get("uri", "")+ )+ print(f" {index}. [{memory.get('score', 0.0):.3f}] {description[:150]}")else:print(" 未找到相关记忆")@@ -101,7 +115,7 @@ def main():print("\n== 4. 添加资源: CONTRIBUTING.md ==")result = client.add_resource(path="https://raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/CONTRIBUTING.md",- reason="贡献指南学习笔记",+ options={"reason": "贡献指南学习笔记"},)bob_uri = result.get("root_uri", "")print(f" URI: {bob_uri}")@@ -111,7 +125,8 @@ def main():# ── 5. 创建会话,模拟入职学习 ──print("\n== 5. 对话: 入职学习 ==")- session = client.session()+ session_info = client.create_session()+ session = client.session(session_id=session_info["session_id"])print(f" Session: {session.session_id}")messages = [@@ -153,31 +168,49 @@ def main():# ── 7. 回顾自己的记忆 ──print("\n== 7. 回顾记忆: '本地开发环境搭建' ==")- results = client.find("本地开发环境搭建步骤", limit=3)- if hasattr(results, "memories") and results.memories:+ results = client.find(query="本地开发环境搭建步骤", limit=3)+ memories = results.get("memories", [])+ if memories:print(" 记忆:")- for i, m in enumerate(results.memories, 1):- desc = m.abstract or m.overview or str(m.uri)- print(f" {i}. [{m.score:.3f}] {desc[:150]}")- if hasattr(results, "resources") and results.resources:+ for index, memory in enumerate(memories, 1):+ description = (+ memory.get("abstract")+ or memory.get("overview")+ or memory.get("uri", "")+ )+ print(f" {index}. [{memory.get('score', 0.0):.3f}] {description[:150]}")+ resources = results.get("resources", [])+ if resources:print(" 资源:")- for i, r in enumerate(results.resources, 1):- print(f" {i}. [{r.score:.3f}] {r.uri}")+ for index, resource in enumerate(resources, 1):+ print(+ f" {index}. [{resource.get('score', 0.0):.3f}] "+ f"{resource['uri']}"+ )# ── 8. 带会话上下文的搜索 ──print("\n== 8. 带上下文搜索: '还有什么注意事项' ==")results = client.search(- "还有什么需要注意的事项",+ query="还有什么需要注意的事项",session_id=session.session_id,limit=3,)- if hasattr(results, "resources") and results.resources:- for i, r in enumerate(results.resources, 1):- print(f" {i}. [{r.score:.3f}] {r.uri}")- if hasattr(results, "memories") and results.memories:- for i, m in enumerate(results.memories, 1):- desc = m.abstract or m.overview or str(m.uri)- print(f" {i}. [{m.score:.3f}] {desc[:100]}")+ resources = results.get("resources", [])+ if resources:+ for index, resource in enumerate(resources, 1):+ print(+ f" {index}. [{resource.get('score', 0.0):.3f}] "+ f"{resource['uri']}"+ )+ memories = results.get("memories", [])+ if memories:+ for index, memory in enumerate(memories, 1):+ description = (+ memory.get("abstract")+ or memory.get("overview")+ or memory.get("uri", "")+ )+ print(f" {index}. [{memory.get('score', 0.0):.3f}] {description[:100]}")print("\nBob 流程完成")diff --git a/examples/common/recipe.py b/examples/common/recipe.pyindex 4f6d9f521..998170b95 100644--- a/examples/common/recipe.py+++ b/examples/common/recipe.py@@ -71,7 +71,13 @@ class Recipe:# Search all resources or specific target# `find` has better performance, but not so smart- results = self.client.search(query, target_uri=target_uri, score_threshold=score_threshold)+ results = self.client.search(+ query=query,+ target_uri=target_uri or "",+ options={+ "score_threshold": score_threshold,+ },+ )# Extract top resultssearch_results = []diff --git a/examples/langchain-langgraph/langgraph/agent/live_app.py b/examples/langchain-langgraph/langgraph/agent/live_app.pyindex b9b17ad99..b8c97ec4b 100644--- a/examples/langchain-langgraph/langgraph/agent/live_app.py+++ b/examples/langchain-langgraph/langgraph/agent/live_app.py@@ -16,14 +16,13 @@ import uuidfrom typing import Anyfrom langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage+from langchain_openviking import OpenVikingContextMiddleware+from langchain_openviking.client import extract_message_textfrom langgraph.graph import END, START, StateGraphfrom langgraph.graph.message import add_messagesfrom openai import OpenAIfrom typing_extensions import Annotated, TypedDict-from langchain_openviking import OpenVikingContextMiddleware-from langchain_openviking.client import extract_message_text-class LiveState(TypedDict, total=False):messages: Annotated[list, add_messages]@@ -178,12 +177,12 @@ def main() -> str:print(answer)if code not in answer.lower():raise RuntimeError(f"Expected {code!r} in live answer: {answer!r}")- commit = client.commit_session(session_id)+ commit = client.commit_session(session_id=session_id)wait_for_commit_task(client, commit)return answerfinally:try:- client.delete_session(session_id)+ client.delete_session(session_id=session_id)except Exception:pass@@ -195,7 +194,7 @@ def wait_for_commit_task(client, commit: dict[str, object]) -> None:deadline = time.monotonic() + timeoutlast_task = Nonewhile time.monotonic() < deadline:- task = client.get_task(str(commit["task_id"]))+ task = client.get_task(task_id=str(commit["task_id"]))last_task = taskif task and task.get("status") == "completed":returndiff --git a/examples/quick_start.py b/examples/quick_start.pyindex 325cac675..976557d1d 100644--- a/examples/quick_start.py+++ b/examples/quick_start.py@@ -24,19 +24,22 @@ try:wait=True,)root_uri = res["root_uri"]- res = client.ls(root_uri) # Explore resource tree+ res = client.ls(uri=root_uri) # Explore resource treeprint(f"Directory structure:\n{res}\n")res = client.glob(pattern="**/*.md", uri=root_uri) # use glob to find markdown filesif res["matches"]:- content = client.read(res["matches"][0])+ content = client.read(uri=res["matches"][0])print(f"Content preview: {content[:200]}...\n")- abstract = client.abstract(root_uri) # Get abstract- overview = client.overview(root_uri) # Get overview+ abstract = client.abstract(uri=root_uri) # Get abstract+ overview = client.overview(uri=root_uri) # Get overviewprint(f"Abstract:\n{abstract}\n\nOverview:\n{overview}\n")- results = client.find("what is openviking", target_uri=root_uri) # Semantic search+ results = client.find(+ query="what is openviking",+ target_uri=root_uri,+ ) # Semantic searchprint("Search results:")for result in results.get("resources", []):print(f" {result['uri']} (score: {result.get('score', 0.0):.4f})")diff --git a/examples/snapshot/snapshot_example.py b/examples/snapshot/snapshot_example.pyindex ac20aedcb..ddf888f09 100644--- a/examples/snapshot/snapshot_example.py+++ b/examples/snapshot/snapshot_example.py@@ -32,17 +32,27 @@ def short_oid(commit_oid: str | None) -> str:def write_text(client: Any, uri: str, content: str, mode: str) -> None:- result = client.write(uri, content, mode=mode, wait=True, timeout=WAIT_TIMEOUT)+ result = client.write(+ uri=uri,+ content=content,+ mode=mode,+ wait=True,+ timeout=WAIT_TIMEOUT,+ )print(f"write: {uri} (mode={result.get('mode')}, bytes={result.get('written_bytes')})")def remove_resource(client: Any, uri: str) -> None:- client.rm(uri, wait=True, timeout=WAIT_TIMEOUT)+ client.rm(uri=uri, wait=True, timeout=WAIT_TIMEOUT)print(f"rm: {uri}")def print_find(client: Any, query: str, root_uri: str) -> None:- results = client.find(query, target_uri=root_uri, limit=10)+ results = client.find(+ query=query,+ target_uri=root_uri,+ limit=10,+ )resources = results.get("resources", [])if not resources:print(f"find {query!r}: (no matches)")@@ -53,7 +63,7 @@ def print_find(client: Any, query: str, root_uri: str) -> None:def print_read(client: Any, uri: str) -> None:- content = client.read(uri)+ content = client.read(uri=uri)first_line = content.splitlines()[0] if content else ""print(f"read {uri}: {len(content)} chars | {first_line}")@@ -83,7 +93,7 @@ def wait_for_task(returndeadline = time.time() + timeoutwhile True:- task = client.get_task(task_id) or {}+ task = client.get_task(task_id=task_id) or {}status = task.get("status")if status in ("completed", "failed"):print(f"wait_for_task {task_id[:12]}: {status}")@@ -113,8 +123,8 @@ def main() -> None:print_section("setup")print(f"server: {OPENVIKING_URL}")print(f"workspace: {root_uri}")- client.mkdir(root_uri)- client.mkdir(f"{root_uri}/notes")+ client.mkdir(uri=root_uri)+ client.mkdir(uri=f"{root_uri}/notes")print(f"mkdir: {root_uri}, {root_uri}/notes")print_section("v1 initial import")@@ -139,7 +149,7 @@ def main() -> None:print_find(client, changelog, root_uri)print_section("v3 second changes")- client.mkdir(f"{root_uri}/archive")+ client.mkdir(uri=f"{root_uri}/archive")print(f"mkdir: {root_uri}/archive")write_text(client,@@ -174,7 +184,7 @@ def main() -> None:f"written={len(restore.get('written_paths') or [])} deleted={len(restore.get('deleted_paths') or [])}")wait_for_task(client, restore.get("task_id"))- entries = client.ls(root_uri, recursive=True)+ entries = client.ls(uri=root_uri, recursive=True)print(f"ls after restore: {len(entries)} entry(ies)")for entry in entries:print(f" {entry.get('uri') if isinstance(entry, dict) else entry}")diff --git a/examples/watch_resource_example.py b/examples/watch_resource_example.pyindex 88f945e7d..9239083af 100644--- a/examples/watch_resource_example.py+++ b/examples/watch_resource_example.py@@ -44,9 +44,11 @@ Version: 1.0result = await client.add_resource(path=str(test_file),to=to_uri,- reason="Example: monitoring a document",- instruction="Check for updates and re-index",- watch_interval=60.0,+ options={+ "reason": "Example: monitoring a document",+ "instruction": "Check for updates and re-index",+ "watch_interval": 60.0,+ },)print("Resource added successfully!")@@ -67,13 +69,15 @@ async def example_update_watch_interval():await client.add_resource(path=str(test_file),to=to_uri,- watch_interval=0,+ options={"watch_interval": 0},)await client.add_resource(path=str(test_file),to=to_uri,- reason="Updated: more frequent monitoring",- watch_interval=120.0,+ options={+ "reason": "Updated: more frequent monitoring",+ "watch_interval": 120.0,+ },)print("Watch task updated successfully!")finally:@@ -92,7 +96,7 @@ async def example_cancel_watch():await client.add_resource(path=str(test_file),to=to_uri,- watch_interval=0,+ options={"watch_interval": 0},)print("Watch task cancelled successfully!")finally:@@ -111,7 +115,7 @@ async def example_handle_conflict():await client.add_resource(path=str(test_file),to=to_uri,- watch_interval=30.0,+ options={"watch_interval": 30.0},)print(" First watch task created successfully")@@ -120,7 +124,7 @@ async def example_handle_conflict():await client.add_resource(path=str(test_file),to=to_uri,- watch_interval=60.0,+ options={"watch_interval": 60.0},)print(" ERROR: This should not happen!")except ConflictError as e:diff --git a/integrations/langchain/src/langchain_openviking/client.py b/integrations/langchain/src/langchain_openviking/client.pyindex ce3e09760..29e6bcc0b 100644--- a/integrations/langchain/src/langchain_openviking/client.py+++ b/integrations/langchain/src/langchain_openviking/client.py@@ -714,11 +714,14 @@ def _filter_client_kwargs(method: Any, kwargs: dict[str, Any]) -> dict[str, Any])if accepts_kwargs:return {key: value for key, value in kwargs.items() if value is not None}- return {- key: value- for key, value in kwargs.items()- if value is not None and key in signature.parameters- }+ values = {key: value for key, value in kwargs.items() if value is not None}+ filtered = {key: value for key, value in values.items() if key in signature.parameters}+ extra = {key: value for key, value in values.items() if key not in signature.parameters}+ if "message" in signature.parameters and "message" not in filtered and extra:+ filtered["message"] = extra+ elif "options" in signature.parameters and "options" not in filtered and extra:+ filtered["options"] = extra+ return filtereddef _should_retry_method(method_name: str) -> bool:diff --git a/openviking/eval/ragas/pipeline.py b/openviking/eval/ragas/pipeline.pyindex 84bf8aff2..18ac658be 100644--- a/openviking/eval/ragas/pipeline.py+++ b/openviking/eval/ragas/pipeline.py@@ -86,7 +86,7 @@ class RAGQueryPipeline:logger.info(f"Adding document: {path}")result = client.add_resource(- path=str(path),+ str(path),wait=wait,timeout=timeout,)@@ -141,7 +141,7 @@ class RAGQueryPipeline:# Retrieve contextslogger.debug(f"Searching for: {question}")search_result = client.search(- query=question,+ question,limit=top_k,)diff --git a/openviking/eval/ragas/rag_eval.py b/openviking/eval/ragas/rag_eval.pyindex 3d1466f3f..c6a4c7520 100644--- a/openviking/eval/ragas/rag_eval.py+++ b/openviking/eval/ragas/rag_eval.py@@ -117,7 +117,7 @@ class RAGEvaluator:logger.info(f"Adding document: {path}")try:result = client.add_resource(- path=str(path),+ str(path),wait=True,timeout=300,)@@ -135,7 +135,7 @@ class RAGEvaluator:logger.info(f"Adding code: {path}")try:result = client.add_resource(- path=str(path),+ str(path),wait=True,timeout=300,)diff --git a/sdk/go/README.md b/sdk/go/README.mdindex 4eacf3e73..9385872ac 100644--- a/sdk/go/README.md+++ b/sdk/go/README.md@@ -118,11 +118,12 @@ _, err = client.UpdateSessionConfig(ctx, "demo-session", &openviking.UpdateSessi_, err = client.UpdateSessionConfig(ctx, "demo-session", &openviking.UpdateSessionConfigOptions{AutoCommitPolicy: openviking.Map(nil), // explicit JSON null disables auto-commit})-_, err = client.AddMessage(ctx, "demo-session", "user", openviking.AddMessageOptions{+_, err = client.AddMessage(ctx, "demo-session", openviking.Message{+ Role: "user",Content: openviking.String("remember this deployment decision"),})commit, err := client.CommitSession(ctx, "demo-session", &openviking.CommitSessionOptions{- KeepRecentCount: 2,+ KeepRecentCount: openviking.Int(2),EventTags: []string{"team=search", "channel=web"},})diff --git a/sdk/go/admin.go b/sdk/go/admin.goindex 10186e30a..cf66be805 100644--- a/sdk/go/admin.go+++ b/sdk/go/admin.go@@ -116,3 +116,38 @@ func (c *Client) AdminMigrate(ctx context.Context, opts *AdminMigrateOptions) (merr := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/migrate", nil, map[string]any{"action": action}, &result)return result, err}++// AdminGetAgentEvolution returns the effective Agent Evolution switch for the+// caller's account.+func (c *Client) AdminGetAgentEvolution(ctx context.Context) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/admin/agent-evolution", nil, nil, &result)+ return result, err+}++// AdminSetAgentEvolution persists and hot-reloads Agent Evolution for the+// caller's account.+func (c *Client) AdminSetAgentEvolution(ctx context.Context, enabled bool) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPut, "/api/v1/admin/agent-evolution", nil, map[string]any{"enabled": enabled}, &result)+ return result, err+}++// AdminGetAccountSettings returns the effective and explicitly overridden+// settings for one account.+func (c *Client) AdminGetAccountSettings(ctx context.Context, accountID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/settings", nil, nil, &result)+ return result, err+}++// AdminSetAccountAgentEvolution updates the allowlisted, hot-reloadable Agent+// Evolution setting for one account via PATCH.+func (c *Client) AdminSetAccountAgentEvolution(ctx context.Context, accountID string, enabled bool) (map[string]any, error) {+ payload := map[string]any{+ "agent_evolution": map[string]any{"enabled": enabled},+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPatch, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/settings", nil, payload, &result)+ return result, err+}diff --git a/sdk/go/agent_evolution.go b/sdk/go/agent_evolution.gonew file mode 100644index 000000000..67322e0ef--- /dev/null+++ b/sdk/go/agent_evolution.go@@ -0,0 +1,63 @@+package openviking++import (+ "context"+ "net/http"+ "net/url"+)++// ListExperienceTrajectories lists trajectories that consumed an Experience.+func (c *Client) ListExperienceTrajectories(+ ctx context.Context,+ experienceURI string,+ opts *ExperienceTrajectoryOptions,+) (map[string]any, error) {+ query := url.Values{+ "experience_uri": []string{NormalizeURI(experienceURI)},+ }+ if opts != nil {+ if opts.Limit != nil {+ queryInt(query, "limit", *opts.Limit)+ }+ if opts.Offset != nil {+ queryInt(query, "offset", *opts.Offset)+ }+ setQueryString(query, "start_date", opts.StartDate)+ setQueryString(query, "end_date", opts.EndDate)+ }+ var result map[string]any+ err := c.doJSON(+ ctx,+ http.MethodGet,+ "/api/v1/agent-evolution/experiences/trajectories",+ query,+ nil,+ &result,+ )+ return result, err+}++// GetExperienceOutcomes returns the outcome distribution for an Experience.+func (c *Client) GetExperienceOutcomes(+ ctx context.Context,+ experienceURI string,+ opts *ExperienceOutcomeOptions,+) (map[string]any, error) {+ query := url.Values{+ "experience_uri": []string{NormalizeURI(experienceURI)},+ }+ if opts != nil {+ setQueryString(query, "start_date", opts.StartDate)+ setQueryString(query, "end_date", opts.EndDate)+ }+ var result map[string]any+ err := c.doJSON(+ ctx,+ http.MethodGet,+ "/api/v1/agent-evolution/experiences/outcomes",+ query,+ nil,+ &result,+ )+ return result, err+}diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex c64256eb8..095174018 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -137,7 +137,7 @@ func TestFindSendsHeadersQueryAndBody(t *testing.T) {requireBodyKeysAbsent(t, body, "agent_id", "agent_uri")writeOK(t, w, map[string]any{"resources": []map[string]any{- {"uri": "viking://resources/docs/api.md", "context_type": "resource", "score": 0.9},+ {"uri": "viking://resources/docs/api.md", "context_type": "resource", "score": 0.9, "tags": []string{"topic=docs", "kind=api"}},},})}))@@ -159,6 +159,9 @@ func TestFindSendsHeadersQueryAndBody(t *testing.T) {if len(result.Resources) != 1 || result.Resources[0].URI != "viking://resources/docs/api.md" {t.Fatalf("unexpected result: %#v", result)}+ if got := result.Resources[0].Tags; len(got) != 2 || got[0] != "topic=docs" || got[1] != "kind=api" {+ t.Fatalf("result tags = %#v", got)+ }}func TestFindOmitsSearchFiltersWhenUnset(t *testing.T) {@@ -177,6 +180,30 @@ func TestFindOmitsSearchFiltersWhenUnset(t *testing.T) {}}+func TestFindUsesDefaultLimitAndPreservesEmptyValues(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body := readJSONBody(t, r)+ if got, ok := body["limit"]; !ok || got != float64(10) {+ t.Fatalf("limit = %#v, present = %v", got, ok)+ }+ if tags, ok := body["tags"].([]any); !ok || len(tags) != 0 {+ t.Fatalf("tags = %#v", body["tags"])+ }+ if levels, ok := body["level"].([]any); !ok || len(levels) != 0 {+ t.Fatalf("level = %#v", body["level"])+ }+ writeOK(t, w, map[string]any{"resources": []any{}})+ }))+ defer closeServer()++ if _, err := client.Find(context.Background(), "auth", &FindOptions{+ Tags: []string{},+ Level: []int{},+ }); err != nil {+ t.Fatal(err)+ }+}+func TestListAndTreeSendQueryOptions(t *testing.T) {wantTreeLimits := []string{"0", "3"}client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -268,14 +295,18 @@ func TestReindexSendsDryRun(t *testing.T) {if got := body["dry_run"]; got != true {t.Fatalf("dry_run = %#v", got)}+ if got := body["recursive"]; got != false {+ t.Fatalf("recursive = %#v", got)+ }writeOK(t, w, map[string]any{"status": "completed"})}))defer closeServer()if _, err := client.Reindex(context.Background(), "resources/demo", &ReindexOptions{- Mode: "prune_orphans",- Wait: false,- DryRun: true,+ Mode: "prune_orphans",+ Wait: false,+ DryRun: true,+ Recursive: Bool(false),}); err != nil {t.Fatal(err)}@@ -303,6 +334,28 @@ func TestReindexSendsExplicitEmptyTags(t *testing.T) {}}+func TestReindexSendsExtraAndRejectsOverrides(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body := readJSONBody(t, r)+ if got := body["future_flag"]; got != false {+ t.Fatalf("future_flag = %#v", got)+ }+ writeOK(t, w, map[string]any{"status": "completed"})+ }))+ defer closeServer()++ if _, err := client.Reindex(context.Background(), "resources/demo", &ReindexOptions{+ Extra: map[string]any{"future_flag": false},+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.Reindex(context.Background(), "resources/demo", &ReindexOptions{+ Extra: map[string]any{"tags": []string{"team=search"}},+ }); err == nil {+ t.Fatal("expected formal tags field in extra to fail")+ }+}+func TestAdminCreatePathsAcceptInitialUserConfig(t *testing.T) {var seen []map[string]anyclient, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -489,6 +542,283 @@ func TestSearchOmitsSearchFiltersWhenUnset(t *testing.T) {}}+func TestSearchContextSendsContextOptionsAndRejectsModeOverride(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method+" "+r.URL.Path != "POST /api/v1/search/search" {+ t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)+ }+ body := readJSONBody(t, r)+ if body["mode"] != "context" || body["query"] != "continue refactor" {+ t.Fatalf("body = %#v", body)+ }+ if body["session_id"] != "session-1" || body["purpose"] != "coding" {+ t.Fatalf("context fields = %#v", body)+ }+ if body["max_tokens"] != float64(3000) || body["dedup_turns"] != float64(5) {+ t.Fatalf("budget fields = %#v", body)+ }+ writeOK(t, w, map[string]any{+ "rendered": "<memory />",+ "entries": []any{},+ "stats": map[string]any{"returned": 0},+ })+ }))+ defer closeServer()++ result, err := client.SearchContext(context.Background(), "continue refactor", &SearchContextOptions{+ SessionID: "session-1",+ Purpose: "coding",+ MaxTokens: Int(3000),+ DedupTurns: Int(5),+ })+ if err != nil {+ t.Fatal(err)+ }+ if result.Rendered != "<memory />" {+ t.Fatalf("result = %#v", result)+ }++ if _, err := client.SearchContext(context.Background(), "query", &SearchContextOptions{+ Extra: map[string]any{"mode": "list"},+ }); err == nil || !strings.Contains(err.Error(), "mode") {+ t.Fatalf("expected mode conflict, got %v", err)+ }+}++func TestWriteSendsProcessingModeAndExtra(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body := readJSONBody(t, r)+ if body["processing_mode"] != "vectors_only" || body["future_flag"] != float64(0) || body["wait"] != true {+ t.Fatalf("body = %#v", body)+ }+ writeOK(t, w, map[string]any{"uri": "viking://resources/a.md"})+ }))+ defer closeServer()++ if _, err := client.Write(context.Background(), "resources/a.md", "", &WriteOptions{+ ProcessingMode: "vectors_only",+ Wait: true,+ Extra: map[string]any{"future_flag": 0},+ }); err != nil {+ t.Fatal(err)+ }+}++func TestBatchWriteAndDownloadBytes(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.Method + " " + r.URL.Path {+ case "POST /api/v1/content/batch-write":+ body := readJSONBody(t, r)+ if body["root_uri"] != "viking://resources/project" || body["future_flag"] != float64(0) {+ t.Fatalf("body = %#v", body)+ }+ writeOK(t, w, map[string]any{"updated": 1})+ case "GET /api/v1/content/download":+ if r.URL.Query().Get("uri") != "viking://resources/project/a.txt" {+ t.Fatalf("query = %s", r.URL.RawQuery)+ }+ _, _ = w.Write([]byte{1, 2, 3})+ default:+ t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)+ }+ }))+ defer closeServer()++ if _, err := client.BatchWrite(context.Background(), "resources/project", []BatchWriteOperation{+ {+ URI: "resources/project/a.txt",+ Content: String("hello"),+ Precondition: BatchWritePrecondition{+ Kind: "create_if_absent",+ },+ },+ }, &BatchWriteOptions{Extra: map[string]any{"future_flag": 0}}); err != nil {+ t.Fatal(err)+ }+ data, err := client.DownloadBytes(context.Background(), "resources/project/a.txt")+ if err != nil {+ t.Fatal(err)+ }+ if string(data) != string([]byte{1, 2, 3}) {+ t.Fatalf("data = %v", data)+ }+}++func TestAddResourceExtra(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body := readJSONBody(t, r)+ if body["future_flag"] != false {+ t.Fatalf("body = %#v", body)+ }+ writeOK(t, w, map[string]any{"root_uri": "viking://resources/a"})+ }))+ defer closeServer()++ if _, err := client.AddResource(context.Background(), "https://example.com/a.md", &AddResourceOptions{+ CreateParent: Bool(false),+ Extra: map[string]any{"future_flag": false},+ }); err != nil {+ t.Fatal(err)+ }+}++func TestAddResourceSendsAddTypeAndProcessingMode(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body := readJSONBody(t, r)+ if body["add_type"] != "git" || body["processing_mode"] != "vectors_only" {+ t.Fatalf("body = %#v", body)+ }+ writeOK(t, w, map[string]any{"root_uri": "viking://resources/a"})+ }))+ defer closeServer()++ if _, err := client.AddResource(context.Background(), "https://example.com/a.md", &AddResourceOptions{+ AddType: "git",+ ProcessingMode: "vectors_only",+ }); err != nil {+ t.Fatal(err)+ }+}++func TestSessionSendsLatestMessageAndRetentionFields(t *testing.T) {+ var bodies []map[string]any+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ bodies = append(bodies, readJSONBody(t, r))+ writeOK(t, w, map[string]any{"status": "ok"})+ }))+ defer closeServer()++ if _, err := client.AddMessage(context.Background(), "session-1", "assistant", AddMessageOptions{+ Content: String("done"),+ TurnID: "turn-1",+ MessageKind: "assistant_step",+ SourceMessageIDs: []string{"user-1"},+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.CommitSession(context.Background(), "session-1", &CommitSessionOptions{+ RetentionMode: "turn_budget",+ KeepRecentTurnCount: Int(3),+ RetainedMessageTokenBudget: Int(12000),+ MinRawTailSteps: Int(1),+ }); err != nil {+ t.Fatal(err)+ }++ if bodies[0]["turn_id"] != "turn-1" || bodies[0]["message_kind"] != "assistant_step" {+ t.Fatalf("message = %#v", bodies[0])+ }+ if bodies[1]["retention_mode"] != "turn_budget" ||+ bodies[1]["keep_recent_turn_count"] != float64(3) {+ t.Fatalf("commit = %#v", bodies[1])+ }+}++func TestCreateSessionSendsExtra(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body := readJSONBody(t, r)+ if body["future_flag"] != false {+ t.Fatalf("body = %#v", body)+ }+ writeOK(t, w, map[string]any{"session_id": "session-1"})+ }))+ defer closeServer()++ if _, err := client.CreateSession(context.Background(), &CreateSessionOptions{+ Extra: map[string]any{"future_flag": false},+ }); err != nil {+ t.Fatal(err)+ }+}++func TestAgentEvolutionQueries(t *testing.T) {+ var paths []string+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ paths = append(paths, r.URL.RequestURI())+ writeOK(t, w, map[string]any{"experience_uri": "viking://user/memories/experiences/a.md"})+ }))+ defer closeServer()++ if _, err := client.ListExperienceTrajectories(+ context.Background(),+ "user/memories/experiences/a.md",+ &ExperienceTrajectoryOptions{+ Limit: Int(25),+ Offset: Int(50),+ StartDate: "2026-08-01",+ EndDate: "2026-08-10",+ },+ ); err != nil {+ t.Fatal(err)+ }+ if _, err := client.GetExperienceOutcomes(+ context.Background(),+ "user/memories/experiences/a.md",+ &ExperienceOutcomeOptions{+ StartDate: "2026-08-01",+ EndDate: "2026-08-10",+ },+ ); err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(paths[0], "limit=25") || !strings.Contains(paths[0], "offset=50") {+ t.Fatalf("trajectory path = %s", paths[0])+ }+ if !strings.Contains(paths[0], "start_date=2026-08-01") ||+ !strings.Contains(paths[0], "end_date=2026-08-10") {+ t.Fatalf("trajectory dates = %s", paths[0])+ }+ if !strings.Contains(paths[1], "experiences%2Fa.md") {+ t.Fatalf("outcomes path = %s", paths[1])+ }+ if !strings.Contains(paths[1], "start_date=2026-08-01") ||+ !strings.Contains(paths[1], "end_date=2026-08-10") {+ t.Fatalf("outcome dates = %s", paths[1])+ }+}++func TestOpenVikingAssetsResolveAndPreflight(t *testing.T) {+ var bodies []map[string]any+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ bodies = append(bodies, readJSONBody(t, r))+ writeOK(t, w, map[string]any{"ok": true})+ }))+ defer closeServer()++ if _, err := client.ResolveOpenVikingAssets(+ context.Background(),+ "protocol: openviking-assets/1",+ &ResolveAssetsOptions{+ ManifestLabel: "custom.yaml",+ Extra: map[string]any{"future_flag": false},+ },+ ); err != nil {+ t.Fatal(err)+ }+ if _, err := client.PreflightOpenVikingAsset(+ context.Background(),+ "private-repo",+ "https://github.com/example/private.git",+ &PreflightAssetOptions{+ Branch: "main",+ Commit: "0123456789abcdef",+ AuthConfig: &AssetGitAuth{+ Username: "oauth2",+ Token: "secret",+ },+ },+ ); err != nil {+ t.Fatal(err)+ }++ if bodies[0]["manifest_label"] != "custom.yaml" || bodies[0]["future_flag"] != false {+ t.Fatalf("resolve body = %#v", bodies[0])+ }+ if bodies[1]["commit"] != "0123456789abcdef" {+ t.Fatalf("preflight body = %#v", bodies[1])+ }+}+func TestSearchSendsImageURI(t *testing.T) {client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path != "/api/v1/search/search" {@@ -1303,6 +1633,28 @@ func TestSetTagsDefaultsModeAndOmitsTelemetry(t *testing.T) {}}+func TestSetTagsForwardsExtraAndRejectsOfficialFields(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body := readJSONBody(t, r)+ if got := body["future_flag"]; got != false {+ t.Fatalf("future_flag = %#v", got)+ }+ writeOK(t, w, map[string]any{"updated": 1})+ }))+ defer closeServer()++ if _, err := client.SetTags(context.Background(), "resources/docs", []string{"team=infra"}, &SetTagsOptions{+ Extra: map[string]any{"future_flag": false},+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.SetTags(context.Background(), "resources/docs", []string{"team=infra"}, &SetTagsOptions{+ Extra: map[string]any{"uri": "viking://other"},+ }); err == nil {+ t.Fatal("expected extra to reject uri override")+ }+}+func TestGrepForwardsLevelLimit(t *testing.T) {client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.Method+" "+r.URL.Path != "POST /api/v1/search/grep" {diff --git a/sdk/go/examples/basic_usage/main.go b/sdk/go/examples/basic_usage/main.goindex 116d1b431..2985f363a 100644--- a/sdk/go/examples/basic_usage/main.go+++ b/sdk/go/examples/basic_usage/main.go@@ -292,7 +292,7 @@ func main() {fmt.Printf(" context=%v\n", sessionContext)commit, err := client.CommitSession(ctx, sessionID, &openviking.CommitSessionOptions{- KeepRecentCount: 0,+ KeepRecentCount: openviking.Int(0),})if err != nil {log.Fatal(err)diff --git a/sdk/go/filesystem.go b/sdk/go/filesystem.goindex d9db25fc2..88bc238e9 100644--- a/sdk/go/filesystem.go+++ b/sdk/go/filesystem.go@@ -2,6 +2,7 @@ package openvikingimport ("context"+ "io""net/http""net/url")@@ -132,6 +133,39 @@ func (c *Client) Read(ctx context.Context, uri string, offset int, limit int) (sreturn result, err}+// DownloadBytes downloads raw stored bytes.+func (c *Client) DownloadBytes(ctx context.Context, uri string) ([]byte, error) {+ query := url.Values{"uri": []string{NormalizeURI(uri)}}+ req, err := c.newRequest(ctx, http.MethodGet, "/api/v1/content/download", query, nil)+ if err != nil {+ return nil, err+ }+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ data, err := io.ReadAll(resp.Body)+ if err != nil {+ return nil, err+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ env, decodeErr := decodeEnvelope(resp.StatusCode, data)+ if decodeErr != nil {+ return nil, decodeErr+ }+ if env.Error != nil {+ return nil, apiError(resp.StatusCode, env.Error)+ }+ return nil, &Error{+ Code: "UNKNOWN",+ Message: envelopeDetail(env, resp.StatusCode, data),+ StatusCode: resp.StatusCode,+ }+ }+ return data, nil+}+// Abstract reads L0 abstract content.func (c *Client) Abstract(ctx context.Context, uri string) (string, error) {query := url.Values{"uri": []string{NormalizeURI(uri)}}@@ -151,7 +185,7 @@ func (c *Client) Overview(ctx context.Context, uri string) (string, error) {// Write writes text content and refreshes related semantics/vectors.func (c *Client) Write(ctx context.Context, uri string, content string, opts *WriteOptions) (map[string]any, error) {if opts == nil {- opts = &WriteOptions{Mode: "replace"}+ opts = &WriteOptions{}}mode := opts.Modeif mode == "" {@@ -165,11 +199,44 @@ func (c *Client) Write(ctx context.Context, uri string, content string, opts *Wr}setFloatPtr(payload, "timeout", opts.Timeout)setAny(payload, "telemetry", opts.Telemetry)+ setString(payload, "processing_mode", opts.ProcessingMode)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/content/write", nil, payload, &result)return result, err}+// BatchWrite applies preconditioned file writes in one request.+func (c *Client) BatchWrite(+ ctx context.Context,+ rootURI string,+ operations []BatchWriteOperation,+ opts *BatchWriteOptions,+) (map[string]any, error) {+ normalized := make([]BatchWriteOperation, len(operations))+ copy(normalized, operations)+ for i := range normalized {+ normalized[i].URI = NormalizeURI(normalized[i].URI)+ }+ payload := map[string]any{+ "root_uri": NormalizeURI(rootURI),+ "operations": normalized,+ }+ if opts != nil {+ setAny(payload, "wait", opts.Wait)+ setFloatPtr(payload, "timeout", opts.Timeout)+ setAny(payload, "telemetry", opts.Telemetry)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/content/batch-write", nil, payload, &result)+ return result, err+}+// SetTags sets explicit k=v retrieval tags metadata for a file or directory.// Valid modes are "replace" (default) and "append"; Recursive applies the tags// to every file under a directory URI.@@ -194,6 +261,9 @@ func (c *Client) SetTags(ctx context.Context, uri string, tags []string, opts *S"recursive": opts.Recursive,}setAny(payload, "telemetry", opts.Telemetry)+ if err := mergeExtraProtected(payload, opts.Extra, "uri", "tags", "mode", "recursive", "telemetry"); err != nil {+ return nil, err+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/fs/attrs/set_tags", nil, payload, &result)return result, err@@ -209,10 +279,11 @@ func (c *Client) Reindex(ctx context.Context, uri string, opts *ReindexOptions)mode = "vectors_only"}payload := map[string]any{- "uri": NormalizeURI(uri),- "mode": mode,- "wait": opts.Wait,- "dry_run": opts.DryRun,+ "uri": NormalizeURI(uri),+ "mode": mode,+ "wait": opts.Wait,+ "dry_run": opts.DryRun,+ "recursive": boolValue(opts.Recursive, true),}if opts.Tags != nil {payload["tags"] = opts.Tags@@ -222,6 +293,9 @@ func (c *Client) Reindex(ctx context.Context, uri string, opts *ReindexOptions)}payload["tag_mode"] = tagMode}+ if err := mergeExtraProtected(payload, opts.Extra, "tags", "tag_mode"); err != nil {+ return nil, err+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/content/reindex", nil, payload, &result)return result, errdiff --git a/sdk/go/helpers.go b/sdk/go/helpers.goindex 780799967..3f667e62e 100644--- a/sdk/go/helpers.go+++ b/sdk/go/helpers.go@@ -48,6 +48,33 @@ func setFloatPtr(m map[string]any, key string, value *float64) {}}+func mergeExtra(payload map[string]any, extra map[string]any) error {+ return mergeExtraProtected(payload, extra)+}++func mergeExtraProtected(+ payload map[string]any,+ extra map[string]any,+ protected ...string,+) error {+ protectedFields := make(map[string]struct{}, len(protected))+ for _, key := range protected {+ protectedFields[key] = struct{}{}+ }+ for key, value := range extra {+ if _, exists := payload[key]; exists {+ return fmt.Errorf("openviking: extra cannot override %q", key)+ }+ if _, exists := protectedFields[key]; exists {+ return fmt.Errorf("openviking: extra cannot override %q", key)+ }+ if value != nil {+ payload[key] = value+ }+ }+ return nil+}+func boolValue(ptr *bool, fallback bool) bool {if ptr == nil {return fallbackdiff --git a/sdk/go/openviking_assets.go b/sdk/go/openviking_assets.gonew file mode 100644index 000000000..91f886866--- /dev/null+++ b/sdk/go/openviking_assets.go@@ -0,0 +1,65 @@+package openviking++import (+ "context"+ "net/http"+)++// ResolveOpenVikingAssets parses and validates an OpenViking Assets manifest.+func (c *Client) ResolveOpenVikingAssets(+ ctx context.Context,+ manifestYAML string,+ opts *ResolveAssetsOptions,+) (map[string]any, error) {+ payload := map[string]any{"manifest_yaml": manifestYAML}+ if opts != nil {+ setString(payload, "catalog_yaml", opts.CatalogYAML)+ setString(payload, "manifest_label", opts.ManifestLabel)+ setString(payload, "catalog_label", opts.CatalogLabel)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }+ }+ var result map[string]any+ err := c.doJSON(+ ctx,+ http.MethodPost,+ "/api/v1/openviking-assets/resolve",+ nil,+ payload,+ &result,+ )+ return result, err+}++// PreflightOpenVikingAsset verifies read access to one Git asset.+func (c *Client) PreflightOpenVikingAsset(+ ctx context.Context,+ name string,+ repoURL string,+ opts *PreflightAssetOptions,+) (map[string]any, error) {+ payload := map[string]any{+ "name": name,+ "connector": "git",+ "repo_url": repoURL,+ }+ if opts != nil {+ setString(payload, "branch", opts.Branch)+ setString(payload, "commit", opts.Commit)+ setAny(payload, "auth_config", opts.AuthConfig)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }+ }+ var result map[string]any+ err := c.doJSON(+ ctx,+ http.MethodPost,+ "/api/v1/openviking-assets/preflight",+ nil,+ payload,+ &result,+ )+ return result, err+}diff --git a/sdk/go/resources.go b/sdk/go/resources.goindex 5a1890b1c..0a6d3d523 100644--- a/sdk/go/resources.go+++ b/sdk/go/resources.go@@ -24,6 +24,8 @@ func (c *Client) AddResource(ctx context.Context, path string, opts *AddResource}setString(payload, "to", opts.To)setString(payload, "parent", opts.Parent)+ setAny(payload, "create_parent", opts.CreateParent)+ setString(payload, "add_type", opts.AddType)setString(payload, "ignore_dirs", opts.IgnoreDirs)setString(payload, "include", opts.Include)setString(payload, "exclude", opts.Exclude)@@ -31,6 +33,7 @@ func (c *Client) AddResource(ctx context.Context, path string, opts *AddResourceif opts.PreserveStructure != nil {payload["preserve_structure"] = *opts.PreserveStructure}+ setString(payload, "processing_mode", opts.ProcessingMode)setAny(payload, "telemetry", opts.Telemetry)// Only attach args when arguments were actually provided. Instances that// predate #2549 (which added the args field to the resources route under@@ -49,6 +52,9 @@ func (c *Client) AddResource(ctx context.Context, path string, opts *AddResourceif err := c.addLocalUpload(ctx, payload, path, true); err != nil {return nil, err}+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/resources", nil, payload, &result)return result, errdiff --git a/sdk/go/retrieval.go b/sdk/go/retrieval.goindex 7367b23c5..925368cd0 100644--- a/sdk/go/retrieval.go+++ b/sdk/go/retrieval.go@@ -14,33 +14,36 @@ func (c *Client) Find(ctx context.Context, queryText string, opts *FindOptions)if limit == 0 {limit = 10}- actualLimit := limitif opts.NodeLimit != nil {- actualLimit = *opts.NodeLimit+ limit = *opts.NodeLimit}imageURL, err := normalizeImageInput(opts.Image)if err != nil {return nil, err}- payload := map[string]any{- "query": queryText,- "target_uri": normalizeTarget(opts.TargetURI),- "limit": actualLimit,+ payload := map[string]any{"query": queryText}+ if opts.TargetURI != nil {+ payload["target_uri"] = normalizeTarget(opts.TargetURI)}+ payload["limit"] = limitsetString(payload, "image_url", imageURL)setAny(payload, "score_threshold", opts.ScoreThreshold)setAny(payload, "filter", opts.Filter)setAny(payload, "context_type", opts.ContextType)+ setAny(payload, "include_provenance", opts.IncludeProvenance)setString(payload, "since", opts.Since)setString(payload, "until", opts.Until)setString(payload, "time_field", opts.TimeField)- if len(opts.Level) > 0 {+ if opts.Level != nil {payload["level"] = opts.Level}- if len(opts.Tags) > 0 {+ if opts.Tags != nil {payload["tags"] = opts.Tags}setAny(payload, "telemetry", opts.Telemetry)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }var result FindResulterr = c.doJSON(ctx, http.MethodPost, "/api/v1/search/find", nil, payload, &result)return &result, err@@ -55,39 +58,93 @@ func (c *Client) Search(ctx context.Context, queryText string, opts *SearchOptioif limit == 0 {limit = 10}- actualLimit := limitif opts.NodeLimit != nil {- actualLimit = *opts.NodeLimit+ limit = *opts.NodeLimit}imageURL, err := normalizeImageInput(opts.Image)if err != nil {return nil, err}- payload := map[string]any{- "query": queryText,- "target_uri": normalizeTarget(opts.TargetURI),- "limit": actualLimit,+ payload := map[string]any{"query": queryText}+ if opts.TargetURI != nil {+ payload["target_uri"] = normalizeTarget(opts.TargetURI)}+ payload["limit"] = limitsetString(payload, "image_url", imageURL)setString(payload, "session_id", opts.SessionID)setAny(payload, "score_threshold", opts.ScoreThreshold)setAny(payload, "filter", opts.Filter)setAny(payload, "context_type", opts.ContextType)+ setAny(payload, "include_provenance", opts.IncludeProvenance)setString(payload, "since", opts.Since)setString(payload, "until", opts.Until)setString(payload, "time_field", opts.TimeField)- if len(opts.Level) > 0 {+ if opts.Level != nil {payload["level"] = opts.Level}- if len(opts.Tags) > 0 {+ if opts.Tags != nil {payload["tags"] = opts.Tags}setAny(payload, "telemetry", opts.Telemetry)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }var result FindResulterr = c.doJSON(ctx, http.MethodPost, "/api/v1/search/search", nil, payload, &result)return &result, err}+// SearchContext assembles injection-ready context on the server.+func (c *Client) SearchContext(ctx context.Context, query string, opts *SearchContextOptions) (*SearchContextResult, error) {+ if opts == nil {+ opts = &SearchContextOptions{}+ }+ payload := map[string]any{+ "query": query,+ "mode": "context",+ }+ imageURL, err := normalizeImageInput(opts.Image)+ if err != nil {+ return nil, err+ }+ setString(payload, "image_url", imageURL)+ setString(payload, "session_id", opts.SessionID)+ setAny(payload, "limit", opts.Limit)+ setAny(payload, "node_limit", opts.NodeLimit)+ setAny(payload, "score_threshold", opts.ScoreThreshold)+ setAny(payload, "filter", opts.Filter)+ setAny(payload, "context_type", opts.ContextType)+ setAny(payload, "include_provenance", opts.IncludeProvenance)+ if opts.Tags != nil {+ payload["tags"] = opts.Tags+ }+ setString(payload, "since", opts.Since)+ setString(payload, "until", opts.Until)+ setString(payload, "time_field", opts.TimeField)+ setString(payload, "query_expansion", opts.QueryExpansion)+ setAny(payload, "max_tokens", opts.MaxTokens)+ if opts.Quotas != nil {+ payload["quotas"] = opts.Quotas+ }+ setString(payload, "purpose", opts.Purpose)+ setAny(payload, "detail", opts.Detail)+ setAny(payload, "dedup_turns", opts.DedupTurns)+ if opts.ExcludeURIs != nil {+ payload["exclude_uris"] = opts.ExcludeURIs+ }+ setString(payload, "peer_scope", opts.PeerScope)+ setAny(payload, "other_peer_penalty", opts.OtherPeerPenalty)+ setAny(payload, "rewrite", opts.Rewrite)+ setAny(payload, "rewrite_max_bullets", opts.RewriteMaxBullets)+ setAny(payload, "telemetry", opts.Telemetry)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }+ var result SearchContextResult+ err = c.doJSON(ctx, http.MethodPost, "/api/v1/search/search", nil, payload, &result)+ return &result, err+}+// Grep searches file content by pattern.func (c *Client) Grep(ctx context.Context, uri, pattern string, opts *GrepOptions) (map[string]any, error) {if opts == nil {diff --git a/sdk/go/sessions.go b/sdk/go/sessions.goindex 3a98c6822..ea1a2e958 100644--- a/sdk/go/sessions.go+++ b/sdk/go/sessions.go@@ -23,6 +23,9 @@ func (c *Client) CreateSession(ctx context.Context, opts *CreateSessionOptions)}setAny(payload, "memory_extraction_config", opts.MemoryExtractionConfig)setAny(payload, "telemetry", opts.Telemetry)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions", nil, payload, &result)return result, err@@ -57,6 +60,9 @@ func (c *Client) UpdateSessionConfig(ctx context.Context, sessionID string, optspayload["auto_commit_policy"] = *opts.AutoCommitPolicy}setAny(payload, "telemetry", opts.Telemetry)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPatch, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/config", nil, payload, &result)return result, err@@ -110,7 +116,15 @@ func (c *Client) AddMessage(ctx context.Context, sessionID, role string, opts Ad}setString(payload, "created_at", opts.CreatedAt)setString(payload, "peer_id", opts.PeerID)+ setString(payload, "turn_id", opts.TurnID)+ setString(payload, "message_kind", opts.MessageKind)+ if opts.SourceMessageIDs != nil {+ payload["source_message_ids"] = opts.SourceMessageIDs+ }setAny(payload, "telemetry", opts.Telemetry)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/messages", nil, payload, &result)return result, err@@ -121,6 +135,9 @@ func (c *Client) BatchAddMessages(ctx context.Context, sessionID string, messagepayload := map[string]any{"messages": messages}if opts != nil {setAny(payload, "telemetry", opts.Telemetry)+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }}var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/messages/batch", nil, payload, &result)@@ -132,15 +149,23 @@ func (c *Client) CommitSession(ctx context.Context, sessionID string, opts *Commif opts == nil {opts = &CommitSessionOptions{}}- payload := map[string]any{- "keep_recent_count": opts.KeepRecentCount,+ payload := map[string]any{}+ if opts.KeepRecentCount != nil {+ payload["keep_recent_count"] = *opts.KeepRecentCount}+ setString(payload, "retention_mode", opts.RetentionMode)+ setAny(payload, "keep_recent_turn_count", opts.KeepRecentTurnCount)+ setAny(payload, "retained_message_token_budget", opts.RetainedMessageTokenBudget)+ setAny(payload, "min_raw_tail_steps", opts.MinRawTailSteps)setAny(payload, "telemetry", opts.Telemetry)if opts.EventTags != nil {payload["extraction_metadata"] = map[string]any{"event": map[string]any{"tags": opts.EventTags},}}+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/commit", nil, payload, &result)return result, errdiff --git a/sdk/go/skills.go b/sdk/go/skills.goindex d724cf09f..f19a8923e 100644--- a/sdk/go/skills.go+++ b/sdk/go/skills.go@@ -20,6 +20,9 @@ func (c *Client) AddSkill(ctx context.Context, data any, opts *AddSkillOptions)if err := c.attachSkillData(ctx, payload, data); err != nil {return nil, err}+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/skills", nil, payload, &result)return result, err@@ -121,6 +124,9 @@ func (c *Client) UpdateSkill(ctx context.Context, skillName string, data any, opif err := c.attachSkillData(ctx, payload, data); err != nil {return nil, err}+ if err := mergeExtra(payload, opts.Extra); err != nil {+ return nil, err+ }var result map[string]anyerr := c.doJSON(ctx, http.MethodPut, "/api/v1/skills/"+url.PathEscape(skillName), nil, payload, &result)return result, errdiff --git a/sdk/go/types.go b/sdk/go/types.goindex 4a88cab94..63947a33a 100644--- a/sdk/go/types.go+++ b/sdk/go/types.go@@ -24,6 +24,8 @@ type Config struct {type AddResourceOptions struct {To stringParent string+ CreateParent *bool+ AddType stringReason stringInstruction stringWait bool@@ -35,10 +37,12 @@ type AddResourceOptions struct {DirectlyUploadMedia *boolPreserveStructure *boolWatchInterval float64+ ProcessingMode stringArgs map[string]anyTags []stringTagMode stringTelemetry any+ Extra map[string]any}// AddSkillOptions controls AddSkill.@@ -46,6 +50,7 @@ type AddSkillOptions struct {Wait boolTimeout *float64Telemetry any+ Extra map[string]any// TargetURI scopes the operation to a skills root such as// "viking://agent/skills" (account-shared) or a per-user root. A nil// value omits target_uri and lets the server use its default root.@@ -108,6 +113,7 @@ type UpdateSkillOptions struct {SourceMetadata map[string]anyTelemetry anyTargetURI any+ Extra map[string]any}// DeleteSkillOptions controls DeleteSkill.@@ -172,10 +178,34 @@ type RemoveOptions struct {// WriteOptions controls Write.type WriteOptions struct {- Mode string- Wait bool+ Mode string+ Wait bool+ Timeout *float64+ Telemetry any+ ProcessingMode string+ Extra map[string]any+}++// BatchWritePrecondition protects one batch write operation.+type BatchWritePrecondition struct {+ Kind string `json:"kind"`+ BaseHash *string `json:"base_hash,omitempty"`+}++// BatchWriteOperation is one preconditioned file write.+type BatchWriteOperation struct {+ URI string `json:"uri"`+ Content *string `json:"content,omitempty"`+ ContentBase64 *string `json:"content_base64,omitempty"`+ Precondition BatchWritePrecondition `json:"precondition"`+}++// BatchWriteOptions controls BatchWrite.+type BatchWriteOptions struct {+ Wait *boolTimeout *float64Telemetry any+ Extra map[string]any}// SetTagsOptions controls SetTags.@@ -183,52 +213,88 @@ type SetTagsOptions struct {Mode stringRecursive boolTelemetry any+ Extra map[string]any}// ReindexOptions controls Reindex.// Wait is used as-is when options are provided; set it explicitly to true// when adding optional fields such as Tags and synchronous behavior is desired.type ReindexOptions struct {- Mode string- Wait bool- DryRun bool- Tags []string- TagMode string+ Mode string+ Wait bool+ DryRun bool+ Recursive *bool+ Tags []string+ TagMode string+ Extra map[string]any}// FindOptions controls Find.type FindOptions struct {- TargetURI any- Image string- Limit int- NodeLimit *int- ScoreThreshold *float64- Filter map[string]any- ContextType any- Telemetry any- Since string- Until string- TimeField string- Level []int- Tags []string+ TargetURI any+ Image string+ Limit int+ NodeLimit *int+ ScoreThreshold *float64+ Filter map[string]any+ ContextType any+ IncludeProvenance *bool+ Telemetry any+ Since string+ Until string+ TimeField string+ Level []int+ Tags []string+ Extra map[string]any}// SearchOptions controls Search.type SearchOptions struct {- TargetURI any- Image string- SessionID string- Limit int- NodeLimit *int- ScoreThreshold *float64- Filter map[string]any- ContextType any- Telemetry any- Since string- Until string- TimeField string- Level []int- Tags []string+ TargetURI any+ Image string+ SessionID string+ Limit int+ NodeLimit *int+ ScoreThreshold *float64+ Filter map[string]any+ ContextType any+ IncludeProvenance *bool+ Telemetry any+ Since string+ Until string+ TimeField string+ Level []int+ Tags []string+ Extra map[string]any+}++// SearchContextOptions controls server-side context assembly.+type SearchContextOptions struct {+ Image string+ SessionID string+ Limit *int+ NodeLimit *int+ ScoreThreshold *float64+ Filter map[string]any+ ContextType any+ IncludeProvenance *bool+ Tags []string+ Since string+ Until string+ TimeField string+ QueryExpansion string+ MaxTokens *int+ Quotas map[string]int+ Purpose string+ Detail any+ DedupTurns *int+ ExcludeURIs []string+ PeerScope string+ OtherPeerPenalty any+ Rewrite any+ RewriteMaxBullets *int+ Telemetry any+ Extra map[string]any}// GrepOptions controls Grep.@@ -252,6 +318,7 @@ type CreateSessionOptions struct {DisableAutoCommit boolMemoryExtractionConfig map[string]anyTelemetry any+ Extra map[string]any}// GetSessionOptions controls GetSession.@@ -264,36 +331,87 @@ type UpdateSessionConfigOptions struct {MemoryExtractionConfig map[string]anyAutoCommitPolicy *map[string]anyTelemetry any+ Extra map[string]any}// AddMessageOptions controls AddMessage.type AddMessageOptions struct {- Content *string- Parts []map[string]any- CreatedAt string- PeerID string- Telemetry any+ Content *string+ Parts []map[string]any+ CreatedAt string+ PeerID string+ TurnID string+ MessageKind string+ SourceMessageIDs []string+ Telemetry any+ Extra map[string]any}// Message is one session message payload for BatchAddMessages.type Message struct {- Role string `json:"role"`- Content *string `json:"content,omitempty"`- Parts []map[string]any `json:"parts,omitempty"`- CreatedAt string `json:"created_at,omitempty"`- PeerID string `json:"peer_id,omitempty"`+ Role string `json:"role"`+ Content *string `json:"content,omitempty"`+ Parts []map[string]any `json:"parts,omitempty"`+ CreatedAt string `json:"created_at,omitempty"`+ PeerID string `json:"peer_id,omitempty"`+ TurnID string `json:"turn_id,omitempty"`+ MessageKind string `json:"message_kind,omitempty"`+ SourceMessageIDs []string `json:"source_message_ids,omitempty"`+ Telemetry any `json:"telemetry,omitempty"`}// BatchAddMessagesOptions controls BatchAddMessages.type BatchAddMessagesOptions struct {Telemetry any+ Extra map[string]any}// CommitSessionOptions controls CommitSession.type CommitSessionOptions struct {- KeepRecentCount int- Telemetry any- EventTags []string+ KeepRecentCount *int+ RetentionMode string+ KeepRecentTurnCount *int+ RetainedMessageTokenBudget *int+ MinRawTailSteps *int+ Telemetry any+ EventTags []string+ Extra map[string]any+}++// ExperienceTrajectoryOptions controls trajectory pagination and date filters.+type ExperienceTrajectoryOptions struct {+ Limit *int+ Offset *int+ StartDate string+ EndDate string+}++// ExperienceOutcomeOptions controls outcome date filters.+type ExperienceOutcomeOptions struct {+ StartDate string+ EndDate string+}++// ResolveAssetsOptions controls OpenViking Assets manifest resolution.+type ResolveAssetsOptions struct {+ CatalogYAML string+ ManifestLabel string+ CatalogLabel string+ Extra map[string]any+}++// AssetGitAuth is one-shot Git authentication for asset preflight.+type AssetGitAuth struct {+ Username string `json:"username,omitempty"`+ Token string `json:"token,omitempty"`+}++// PreflightAssetOptions controls Git asset access checks.+type PreflightAssetOptions struct {+ Branch string+ Commit string+ AuthConfig *AssetGitAuth+ Extra map[string]any}// ListTasksOptions controls ListTasks.@@ -330,16 +448,37 @@ type FindResult struct {Total int `json:"total,omitempty"`}-// MatchedContext is one retrieval hit.+// SearchContextEntry is one assembled context entry.+type SearchContextEntry struct {+ URI string `json:"uri,omitempty"`+ Category string `json:"category,omitempty"`+ Score float64 `json:"score,omitempty"`+ Detail string `json:"detail,omitempty"`+ Text string `json:"text,omitempty"`+ Origin string `json:"origin,omitempty"`+}++// SearchContextResult is an injection-ready context response.+type SearchContextResult struct {+ Entries []SearchContextEntry `json:"entries,omitempty"`+ Rendered string `json:"rendered,omitempty"`+ Digest string `json:"digest,omitempty"`+ Stats map[string]any `json:"stats,omitempty"`+}++// MatchedContext is one retrieval hit. Only the fields the retrieval pipeline+// actually populates are exposed; search_tags is surfaced under the "tags" key+// to match the tags filter parameter accepted by Find and Search.type MatchedContext struct {- URI string `json:"uri,omitempty"`- ContextType string `json:"context_type,omitempty"`- Level int `json:"level,omitempty"`- Abstract string `json:"abstract,omitempty"`- Overview string `json:"overview,omitempty"`- Category string `json:"category,omitempty"`- Score float64 `json:"score,omitempty"`- MatchReason string `json:"match_reason,omitempty"`+ URI string `json:"uri,omitempty"`+ ContextType string `json:"context_type,omitempty"`+ Level int `json:"level,omitempty"`+ Abstract string `json:"abstract,omitempty"`+ Overview string `json:"overview,omitempty"`+ Category string `json:"category,omitempty"`+ Score float64 `json:"score,omitempty"`+ MatchReason string `json:"match_reason,omitempty"`+ Tags []string `json:"tags,omitempty"`}// QueryPlan describes search query expansion details when the server returns them.diff --git a/sdk/python/README.md b/sdk/python/README.mdindex 7609046aa..5ae94476c 100644--- a/sdk/python/README.md+++ b/sdk/python/README.md@@ -21,7 +21,7 @@ Requirements:- Python import name: `openviking_sdk````python-from openviking_sdk import AsyncHTTPClient, SyncHTTPClient+from openviking_sdk import AsyncHTTPClient, SyncHTTPClient, TextPart```## Configuration Sources@@ -96,7 +96,7 @@ client = SyncHTTPClient(client.initialize()with use_actor_peer("assistant-a"):- memories = client.find("deployment preference")+ memories = client.find(query="deployment preference")```The scope is isolated with Python `ContextVar`, so concurrent async tasks and@@ -124,11 +124,19 @@ client.initialize()healthy = client.health()print("health:", healthy)-session = client.create_session("demo-session")+session = client.create_session(session_id="demo-session")print("session:", session)-client.session("demo-session").add_message("user", "hello from sdk")-context = client.session("demo-session").get_session_context(token_budget=4096)+client.session(session_id="demo-session").add_message(+ role="user",+ content="hello from sdk",+)+client.session(session_id="demo-session").add_message(+ role="assistant",+ parts=[TextPart(text="hello from a specific peer")],+ peer_id="peer-alice",+)+context = client.session(session_id="demo-session").get_session_context(token_budget=4096)print("context:", context)client.close()@@ -152,11 +160,14 @@ async def main() -> None:healthy = await client.health()print("health:", healthy)- session = await client.create_session("demo-session-async")+ session = await client.create_session(session_id="demo-session-async")print("session:", session)- session_client = client.session("demo-session-async")- await session_client.add_message("user", "hello from async sdk")+ session_client = client.session(session_id="demo-session-async")+ await session_client.add_message(+ role="user",+ content="hello from async sdk",+ )context = await session_client.get_session_context(token_budget=4096)print("context:", context)@@ -181,21 +192,33 @@ event_config = {}}result = client.create_session(- "demo-session",- memory_extraction_config=event_config,+ session_id="demo-session",+ options={+ "memory_extraction_config": event_config,+ },)# Explicit None disables a server-wide auto-commit default at creation time.-client.create_session("manual-session", auto_commit_policy=None)+client.create_session(+ session_id="manual-session",+ options={"auto_commit_policy": None},+)client.update_session_config(- "demo-session",- auto_commit_policy={"message_count_threshold": 25},- memory_extraction_config={- "events": {"tags": ["team=search", "channel=app"]}+ session_id="demo-session",+ options={+ "auto_commit_policy": {"message_count_threshold": 25},+ "memory_extraction_config": {+ "events": {"tags": ["team=search", "channel=app"]}+ },},)# Explicit None disables automatic commits; omitting the argument leaves it unchanged.-client.update_session_config("demo-session", auto_commit_policy=None)-client.session("demo-session").commit(event_tags=["team=search", "channel=web"])+client.update_session_config(+ session_id="demo-session",+ options={"auto_commit_policy": None},+)+client.session(session_id="demo-session").commit(+ options={"event_tags": ["team=search", "channel=web"]}+)# Use event_tags=[] to skip the session defaults for one commit.print(result)```@@ -211,10 +234,12 @@ client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")client.initialize()result = client.add_resource(- "/path/to/notes.md",+ path="/path/to/notes.md",to="viking://resources/demo-notes",- reason="knowledge import",wait=True,+ options={+ "reason": "knowledge import",+ },)print(result)```@@ -225,10 +250,12 @@ or refresh `.abstract.md` / `.overview.md`.```pythonresult = client.add_resource(- "/path/to/notes.md",+ path="/path/to/notes.md",to="viking://resources/demo-notes",- processing_mode="vectors_only",wait=True,+ options={+ "processing_mode": "vectors_only",+ },)```@@ -240,9 +267,9 @@ from openviking_sdk import SyncHTTPClientclient = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")client.initialize()-client.mkdir("viking://resources/demo-dir")-print(client.ls("viking://resources"))-print(client.read("viking://resources/demo-dir/example.md"))+client.mkdir(uri="viking://resources/demo-dir")+print(client.ls(uri="viking://resources"))+print(client.read(uri="viking://resources/demo-dir/example.md"))```### Retrieval@@ -253,15 +280,48 @@ from openviking_sdk import SyncHTTPClientclient = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")client.initialize()-result = client.find("hello", limit=5)+result = client.find(query="hello", limit=5)print(result)```-Image search uses the same methods. Pass a local path, bytes, data URI, HTTP URL, or `viking://` URI with `image`. The server must use a multimodal embedding model.+### Core Parameters and Options++Frequently used fields are explicit parameters. For readability, prefer named+arguments such as `to` and `wait` with `add_resource`; `target_uri`+and `limit` with retrieval; and `role`, `content`, and `parts` with+`add_message`. `add_message` also accepts `peer_id` as an explicit message+field. For batch writes, place `peer_id` in each message dictionary. Positional+calls remain supported.++For structured messages, `parts` accepts either wire-format dictionaries or+the SDK's `TextPart`, `ContextPart`, `ImagePart`, and `ToolPart` objects. The+SDK serializes both forms to the same HTTP JSON payload.++Use the method's typed `options` dictionary for advanced fields, such as+`processing_mode`, retrieval filters, session extraction configuration, or+`telemetry`.+Do not pass advanced fields as bare keyword arguments. A field must be passed+through exactly one entry point; SDK-defined fields in `options` and+`extra` cannot override explicit parameters.++Image search uses the same methods. Pass a local path, bytes, data URI, HTTP URL, or `viking://` URI with the explicit `image` parameter. The server must use a multimodal embedding model.++```python+result = client.find(limit=5, image="/path/to/photo.png")+result = client.search(+ image="viking://resources/poster.png",+)+```++Complex requests use typed Options dictionaries. Use the `extra` key only for+server fields that the installed SDK version does not yet expose:```python-result = client.find(image="/path/to/photo.png", limit=5)-result = client.search("similar poster", image="viking://resources/poster.png")+result = client.find(+ query="authentication",+ limit=10,+ options={"extra": {"future_server_field": False}},+)```## Admin Operations@@ -330,7 +390,7 @@ client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")client.initialize()try:- print(client.read("viking://resources/not-exists.md"))+ print(client.read(uri="viking://resources/not-exists.md"))except OpenVikingError as exc:print(type(exc).__name__, exc)```diff --git a/sdk/python/README_CN.md b/sdk/python/README_CN.mdindex 59beb4cdf..3dfbf46d4 100644--- a/sdk/python/README_CN.md+++ b/sdk/python/README_CN.md@@ -96,7 +96,7 @@ client = SyncHTTPClient(client.initialize()with use_actor_peer("assistant-a"):- memories = client.find("部署偏好")+ memories = client.find(query="部署偏好")```该作用域通过 Python `ContextVar` 隔离,因此并发 async task 以及由 SDK worker loop@@ -121,11 +121,19 @@ client.initialize()healthy = client.health()print("health:", healthy)-session = client.create_session("demo-session")+session = client.create_session(session_id="demo-session")print("session:", session)-client.session("demo-session").add_message("user", "hello from sdk")-context = client.session("demo-session").get_session_context(token_budget=4096)+client.session(session_id="demo-session").add_message(+ role="user",+ content="hello from sdk",+)+client.session(session_id="demo-session").add_message(+ role="assistant",+ content="hello from a specific peer",+ peer_id="peer-alice",+)+context = client.session(session_id="demo-session").get_session_context(token_budget=4096)print("context:", context)client.close()@@ -149,11 +157,14 @@ async def main() -> None:healthy = await client.health()print("health:", healthy)- session = await client.create_session("demo-session-async")+ session = await client.create_session(session_id="demo-session-async")print("session:", session)- session_client = client.session("demo-session-async")- await session_client.add_message("user", "hello from async sdk")+ session_client = client.session(session_id="demo-session-async")+ await session_client.add_message(+ role="user",+ content="hello from async sdk",+ )context = await session_client.get_session_context(token_budget=4096)print("context:", context)@@ -178,21 +189,33 @@ event_config = {}}result = client.create_session(- "demo-session",- memory_extraction_config=event_config,+ session_id="demo-session",+ options={+ "memory_extraction_config": event_config,+ },)# 创建时显式传 None,可覆盖服务端默认并禁用自动提交。-client.create_session("manual-session", auto_commit_policy=None)+client.create_session(+ session_id="manual-session",+ options={"auto_commit_policy": None},+)client.update_session_config(- "demo-session",- auto_commit_policy={"message_count_threshold": 25},- memory_extraction_config={- "events": {"tags": ["team=search", "channel=app"]}+ session_id="demo-session",+ options={+ "auto_commit_policy": {"message_count_threshold": 25},+ "memory_extraction_config": {+ "events": {"tags": ["team=search", "channel=app"]}+ },},)# 显式传 None 会禁用自动 commit;省略参数则保持不变。-client.update_session_config("demo-session", auto_commit_policy=None)-client.session("demo-session").commit(event_tags=["team=search", "channel=web"])+client.update_session_config(+ session_id="demo-session",+ options={"auto_commit_policy": None},+)+client.session(session_id="demo-session").commit(+ options={"event_tags": ["team=search", "channel=web"]}+)# 单次 commit 传 event_tags=[] 可显式跳过 session 默认 tags。print(result)```@@ -208,10 +231,12 @@ client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")client.initialize()result = client.add_resource(- "/path/to/notes.md",+ path="/path/to/notes.md",to="viking://resources/demo-notes",- reason="knowledge import",wait=True,+ options={+ "reason": "knowledge import",+ },)print(result)```@@ -221,10 +246,12 @@ print(result)```pythonresult = client.add_resource(- "/path/to/notes.md",+ path="/path/to/notes.md",to="viking://resources/demo-notes",- processing_mode="vectors_only",wait=True,+ options={+ "processing_mode": "vectors_only",+ },)```@@ -236,9 +263,9 @@ from openviking_sdk import SyncHTTPClientclient = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")client.initialize()-client.mkdir("viking://resources/demo-dir")-print(client.ls("viking://resources"))-print(client.read("viking://resources/demo-dir/example.md"))+client.mkdir(uri="viking://resources/demo-dir")+print(client.ls(uri="viking://resources"))+print(client.read(uri="viking://resources/demo-dir/example.md"))```### 检索@@ -249,15 +276,40 @@ from openviking_sdk import SyncHTTPClientclient = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")client.initialize()-result = client.find("hello", limit=5)+result = client.find(query="hello", limit=5)print(result)```-图片搜索也使用同一组方法。`image` 支持本地路径、bytes、data URI、HTTP URL 或 `viking://` URI;服务端需要使用 multimodal embedding 模型。+### 高频参数与 Options++高频字段使用显式参数。为保证可读性,推荐使用参数名,例如 `add_resource` 的+`to`、`wait`,检索的 `target_uri`、`limit`,以及 `add_message` 的+`role`、`content`、`parts`、`peer_id`;位置参数调用仍然支持。批量写入时,+请在每条消息字典中传入 `peer_id`。++进阶字段统一放入带类型提示的 `options` 字典,例如 `processing_mode`、检索+过滤条件、Session 提取配置和 `telemetry`。不要把进阶字段作为裸关键字参数传入。同一个字段+只能通过一个入口传递;`options` 或 `extra` 中的 SDK 已定义字段不能覆盖显式参数。++图片搜索也使用同一组方法。通过显式的 `image` 参数传入本地路径、bytes、data URI、HTTP URL 或 `viking://` URI;服务端需要使用 multimodal embedding 模型。++```python+result = client.find(query="", limit=5, image="/path/to/photo.png")+result = client.search(+ query="similar poster",+ image="viking://resources/poster.png",+)+```++复杂请求统一使用带类型提示的 Options 字典。只有服务端已经增加、当前 SDK+版本尚未正式暴露的字段才通过 `extra` 临时传递:```python-result = client.find(image="/path/to/photo.png", limit=5)-result = client.search("similar poster", image="viking://resources/poster.png")+result = client.find(+ query="authentication",+ limit=10,+ options={"extra": {"future_server_field": False}},+)```## 管理员操作@@ -323,7 +375,7 @@ client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")client.initialize()try:- print(client.read("viking://resources/not-exists.md"))+ print(client.read(uri="viking://resources/not-exists.md"))except OpenVikingError as exc:print(type(exc).__name__, exc)```diff --git a/sdk/python/openviking_sdk/__init__.py b/sdk/python/openviking_sdk/__init__.pyindex eba322f35..c3e4bdc59 100644--- a/sdk/python/openviking_sdk/__init__.py+++ b/sdk/python/openviking_sdk/__init__.py@@ -7,15 +7,65 @@ from .errors import (ResourceExhaustedError,UnimplementedError,)+from .message import ContextPart, ImagePart, MessagePart, TextPart, ToolPart+from .options import (+ AddMessageOptions,+ AddResourceOptions,+ AddSkillOptions,+ BatchAddMessagesOptions,+ BatchWriteOptions,+ CommitSessionOptions,+ CreateSessionOptions,+ ExperienceOutcomeOptions,+ ExperienceTrajectoryOptions,+ FindOptions,+ Message,+ PreflightAssetOptions,+ ReindexOptions,+ ResolveAssetsOptions,+ SearchContextOptions,+ SearchContextResult,+ SearchOptions,+ SetTagsOptions,+ UpdateSessionConfigOptions,+ UpdateSkillOptions,+ WriteOptions,+)__all__ = ["AbortedError",+ "AddMessageOptions",+ "AddResourceOptions",+ "AddSkillOptions","AsyncHTTPClient",+ "BatchAddMessagesOptions",+ "BatchWriteOptions",+ "CommitSessionOptions","ConflictError",+ "ContextPart",+ "CreateSessionOptions",+ "ExperienceOutcomeOptions",+ "ExperienceTrajectoryOptions",+ "FindOptions","get_actor_peer_id",+ "ImagePart",+ "Message",+ "MessagePart","OpenVikingError",+ "PreflightAssetOptions",+ "ReindexOptions","ResourceExhaustedError",+ "ResolveAssetsOptions",+ "SearchContextOptions",+ "SearchContextResult",+ "SearchOptions",+ "SetTagsOptions","SyncHTTPClient",+ "TextPart",+ "ToolPart","UnimplementedError",+ "UpdateSessionConfigOptions",+ "UpdateSkillOptions","use_actor_peer",+ "WriteOptions",]diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex 6029aa60d..f16e24a96 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -9,7 +9,7 @@ import uuidimport zipfilefrom enum import Enumfrom pathlib import Path-from typing import Any, Callable, Dict, List, Optional, Union+from typing import Any, Callable, Dict, List, Mapping, Optional, Type, Unionfrom urllib.parse import quoteimport httpx@@ -39,6 +39,30 @@ from .errors import (UnimplementedError,VLMFailedError,)+from .message import MessagePart, normalize_part+from .options import (+ AddMessageOptions,+ AddResourceOptions,+ AddSkillOptions,+ BatchAddMessagesOptions,+ BatchWriteOptions,+ CommitSessionOptions,+ CreateSessionOptions,+ ExperienceOutcomeOptions,+ ExperienceTrajectoryOptions,+ FindOptions,+ Message,+ PreflightAssetOptions,+ ReindexOptions,+ ResolveAssetsOptions,+ SearchContextOptions,+ SearchContextResult,+ SearchOptions,+ SetTagsOptions,+ UpdateSessionConfigOptions,+ UpdateSkillOptions,+ WriteOptions,+)ERROR_CODE_TO_EXCEPTION = {"INVALID_ARGUMENT": InvalidArgumentError,@@ -136,32 +160,20 @@ class Session:async def add_message(self,role: str,- content: str | None = None,- parts: list[dict] | None = None,- created_at: str | None = None,- peer_id: str | None = None,- turn_id: str | None = None,- message_kind: str | None = None,- source_message_ids: list[str] | None = None,- ) -> Dict[str, Any]:- semantic_kwargs = {- key: value- for key, value in {- "turn_id": turn_id,- "message_kind": message_kind,- "source_message_ids": source_message_ids,- }.items()- if value is not None+ content: Optional[str] = None,+ parts: Optional[List[Union[Dict[str, Any], MessagePart]]] = None,+ options: Optional[AddMessageOptions] = None,+ peer_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ kwargs: Dict[str, Any] = {+ "role": role,+ "content": content,+ "parts": parts,+ "options": options,}- return await self._client.add_message(- self.session_id,- role=role,- content=content,- parts=parts,- created_at=created_at,- peer_id=peer_id,- **semantic_kwargs,- )+ if peer_id is not None:+ kwargs["peer_id"] = peer_id+ return await self._client.add_message(self.session_id, **kwargs)async def batch_add_messages(self, messages: list[dict]) -> Dict[str, Any]:return await self._client.batch_add_messages(self.session_id, messages)@@ -169,29 +181,12 @@ class Session:async def commit(self,keep_recent_count: int = 0,- *,- retention_mode: str | None = None,- keep_recent_turn_count: int | None = None,- retained_message_token_budget: int | None = None,- min_raw_tail_steps: int | None = None,- event_tags: list[str] | None = None,- ) -> Dict[str, Any]:- optional_retention = {- key: value- for key, value in {- "retention_mode": retention_mode,- "keep_recent_turn_count": keep_recent_turn_count,- "retained_message_token_budget": retained_message_token_budget,- "min_raw_tail_steps": min_raw_tail_steps,- }.items()- if value is not None- }- if event_tags is not None:- optional_retention["event_tags"] = event_tags+ options: Optional[CommitSessionOptions] = None,+ ) -> Dict[str, Any]:return await self._client.commit_session(self.session_id,keep_recent_count=keep_recent_count,- **optional_retention,+ options=options,)async def delete(self) -> None:@@ -215,94 +210,41 @@ class SyncSession:def add_message(self,role: str,- content: str | None = None,- parts: list[dict] | None = None,- created_at: str | None = None,- peer_id: str | None = None,- turn_id: str | None = None,- message_kind: str | None = None,- source_message_ids: list[str] | None = None,- ) -> Dict[str, Any]:- semantic_kwargs = {- key: value- for key, value in {- "turn_id": turn_id,- "message_kind": message_kind,- "source_message_ids": source_message_ids,- }.items()- if value is not None+ content: Optional[str] = None,+ parts: Optional[List[Union[Dict[str, Any], MessagePart]]] = None,+ options: Optional[AddMessageOptions] = None,+ peer_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ kwargs: Dict[str, Any] = {+ "role": role,+ "content": content,+ "parts": parts,+ "options": options,}- return self._client.add_message(- self.session_id,- role=role,- content=content,- parts=parts,- created_at=created_at,- peer_id=peer_id,- **semantic_kwargs,- )+ if peer_id is not None:+ kwargs["peer_id"] = peer_id+ return self._client.add_message(self.session_id, **kwargs)def batch_add_messages(self, messages: list[dict]) -> Dict[str, Any]:return self._client.batch_add_messages(self.session_id, messages)def commit(self,- telemetry: Any = False,- *,keep_recent_count: int = 0,- retention_mode: str | None = None,- keep_recent_turn_count: int | None = None,- retained_message_token_budget: int | None = None,- min_raw_tail_steps: int | None = None,- event_tags: list[str] | None = None,- ) -> Dict[str, Any]:- optional_retention = {- key: value- for key, value in {- "retention_mode": retention_mode,- "keep_recent_turn_count": keep_recent_turn_count,- "retained_message_token_budget": retained_message_token_budget,- "min_raw_tail_steps": min_raw_tail_steps,- }.items()- if value is not None- }- if event_tags is not None:- optional_retention["event_tags"] = event_tags+ options: Optional[CommitSessionOptions] = None,+ ) -> Dict[str, Any]:return self._client.commit_session(self.session_id,- telemetry=telemetry,keep_recent_count=keep_recent_count,- **optional_retention,+ options=options,)def commit_async(self,- telemetry: Any = False,- *,keep_recent_count: int = 0,- retention_mode: str | None = None,- keep_recent_turn_count: int | None = None,- retained_message_token_budget: int | None = None,- min_raw_tail_steps: int | None = None,- event_tags: list[str] | None = None,- ) -> Dict[str, Any]:- optional_retention = {- key: value- for key, value in {- "retention_mode": retention_mode,- "keep_recent_turn_count": keep_recent_turn_count,- "retained_message_token_budget": retained_message_token_budget,- "min_raw_tail_steps": min_raw_tail_steps,- }.items()- if value is not None- }- if event_tags is not None:- optional_retention["event_tags"] = event_tags- return self.commit(- telemetry=telemetry,- keep_recent_count=keep_recent_count,- **optional_retention,- )+ options: Optional[CommitSessionOptions] = None,+ ) -> Dict[str, Any]:+ return self.commit(keep_recent_count=keep_recent_count, options=options)def delete(self) -> None:self._client.delete_session(self.session_id)@@ -568,6 +510,85 @@ class AsyncHTTPClient:compacted[key] = valuereturn compacted+ @classmethod+ def _normalize_message_payload(cls, message: Mapping[str, Any]) -> Dict[str, Any]:+ payload = dict(message)+ if payload.get("parts"):+ payload["parts"] = [normalize_part(part) for part in payload["parts"]]+ payload.pop("content", None)+ else:+ payload.pop("parts", None)+ if payload.get("content") is None:+ raise ValueError("Either content or non-empty parts must be provided")+ return cls._compact_request_body(payload)++ @classmethod+ def _build_options_payload(+ cls,+ options: Optional[Mapping[str, Any]],+ options_type: Type[Any],+ fixed: Optional[Mapping[str, Any]] = None,+ protected: Optional[set[str]] = None,+ ) -> Dict[str, Any]:+ option_values = dict(options or {})+ allowed = set(options_type.__optional_keys__) | set(options_type.__required_keys__)+ unknown = sorted(set(option_values) - allowed)+ if unknown:+ raise TypeError(+ f"Unknown option '{unknown[0]}' for {options_type.__name__}; "+ "use 'extra' for server fields not yet supported by the SDK"+ )++ extra = dict(option_values.pop("extra", {}) or {})+ payload = dict(fixed or {})+ protected_fields = set(payload) | set(protected or ())+ official_fields = allowed - {"extra"}+ conflicts = sorted(set(extra) & (official_fields | protected_fields))+ if conflicts:+ raise ValueError(f"extra cannot override '{conflicts[0]}'")++ payload.update(option_values)+ payload.update(extra)+ return cls._compact_request_body(payload)++ @classmethod+ def _search_options_payload(+ cls,+ query: str,+ options: Optional[Mapping[str, Any]],+ options_type: Type[Any],+ fixed: Optional[Mapping[str, Any]] = None,+ ) -> Dict[str, Any]:+ option_values = dict(options or {})+ if "image" in option_values:+ option_values["image_url"] = _normalize_image_input(option_values.pop("image"))+ if "target_uri" in option_values:+ option_values["target_uri"] = cls._normalize_target_uri(option_values["target_uri"])+ if "context_type" in option_values:+ option_values["context_type"] = cls._normalize_context_type(+ option_values["context_type"]+ )++ allowed = set(options_type.__optional_keys__) | set(options_type.__required_keys__)+ allowed.discard("image")+ allowed.add("image_url")+ proxy_type = type(+ f"_{options_type.__name__}Payload",+ (),+ {+ "__optional_keys__": frozenset(allowed),+ "__required_keys__": frozenset(),+ "__name__": options_type.__name__,+ },+ )+ fixed_payload = {"query": query}+ fixed_payload.update(fixed or {})+ return cls._build_options_payload(+ option_values,+ proxy_type,+ fixed=fixed_payload,+ )+@staticmethoddef _normalize_context_type(context_type: Optional[Any]) -> Optional[Any]:if context_type is None:@@ -678,24 +699,12 @@ class AsyncHTTPClient:path: str,to: Optional[str] = None,parent: Optional[str] = None,- reason: str = "",- instruction: str = "",wait: bool = False,timeout: Optional[float] = None,- strict: bool = False,- ignore_dirs: Optional[str] = None,- include: Optional[str] = None,- exclude: Optional[str] = None,- directly_upload_media: bool = True,- preserve_structure: Optional[bool] = None,- watch_interval: float = 0,- args: Optional[Dict[str, Any]] = None,- telemetry: Any = False,- processing_mode: Optional[str] = None,- add_type: Optional[str] = None,- tags: Optional[List[str]] = None,- tag_mode: str = "replace",+ options: Optional[AddResourceOptions] = None,) -> Dict[str, Any]:+ option_values = dict(options or {})+ add_type = option_values.get("add_type")if add_type is not None:add_type = add_type.strip() or Noneif add_type and parent:@@ -705,30 +714,23 @@ class AsyncHTTPClient:if to and parent:raise ValueError("Cannot specify both 'to' and 'parent' at the same time.")- request_data = {- "add_type": add_type,- "to": to,- "parent": parent,- "reason": reason,- "instruction": instruction,- "wait": wait,- "timeout": timeout,- "strict": strict,- "ignore_dirs": ignore_dirs,- "include": include,- "exclude": exclude,- "directly_upload_media": directly_upload_media,- "watch_interval": watch_interval,- "args": args or {},- "telemetry": telemetry,- }- if processing_mode is not None:- request_data["processing_mode"] = processing_mode- if tags is not None:- request_data["tags"] = tags- request_data["tag_mode"] = tag_mode- if preserve_structure is not None:- request_data["preserve_structure"] = preserve_structure+ if to is not None:+ to = VikingURI.normalize(to)+ if parent is not None:+ parent = VikingURI.normalize(parent)+ if add_type is not None:+ option_values["add_type"] = add_type+ request_data = self._build_options_payload(+ option_values,+ AddResourceOptions,+ fixed={+ "to": to,+ "parent": parent,+ "wait": wait,+ "timeout": timeout,+ },+ protected={"path", "temp_file_id", "source_name"},+ )path_obj = Path(path)if not add_type and path_obj.exists():@@ -754,13 +756,16 @@ class AsyncHTTPClient:async def batch_add_messages(self,session_id: str,- messages: list[dict],- telemetry: Any = False,+ messages: list[Message],+ options: Optional[BatchAddMessagesOptions] = None,) -> Dict[str, Any]:session_path = self._path_segment(session_id)- payload: Dict[str, Any] = {"messages": messages}- if telemetry is not False:- payload["telemetry"] = telemetry+ normalized_messages = [self._normalize_message_payload(message) for message in messages]+ payload = self._build_options_payload(+ options,+ BatchAddMessagesOptions,+ fixed={"messages": normalized_messages},+ )response = await self._request("POST",f"/api/v1/sessions/{session_path}/messages/batch",@@ -773,12 +778,17 @@ class AsyncHTTPClient:data: Any,wait: bool = False,timeout: Optional[float] = None,- telemetry: Any = False,- target_uri: Optional[str] = None,+ options: Optional[AddSkillOptions] = None,) -> Dict[str, Any]:- request_data = {"wait": wait, "timeout": timeout, "telemetry": telemetry}- if target_uri is not None:- request_data["target_uri"] = target_uri+ option_values = dict(options or {})+ if "target_uri" in option_values:+ option_values["target_uri"] = VikingURI.normalize(option_values["target_uri"])+ request_data = self._build_options_payload(+ option_values,+ AddSkillOptions,+ fixed={"wait": wait, "timeout": timeout},+ protected={"data", "temp_file_id"},+ )if isinstance(data, str):path_obj = Path(data)if path_obj.exists():@@ -879,18 +889,17 @@ class AsyncHTTPClient:data: Any,wait: bool = False,timeout: Optional[float] = None,- source_metadata: Optional[Dict[str, Any]] = None,- telemetry: Any = False,- target_uri: Optional[str] = None,+ options: Optional[UpdateSkillOptions] = None,) -> Dict[str, Any]:- request_data: Dict[str, Any] = {- "wait": wait,- "timeout": timeout,- "source_metadata": source_metadata,- "telemetry": telemetry,- }- if target_uri is not None:- request_data["target_uri"] = target_uri+ option_values = dict(options or {})+ if "target_uri" in option_values:+ option_values["target_uri"] = VikingURI.normalize(option_values["target_uri"])+ request_data = self._build_options_payload(+ option_values,+ UpdateSkillOptions,+ fixed={"wait": wait, "timeout": timeout},+ protected={"data", "temp_file_id"},+ )if isinstance(data, str):path_obj = Path(data)if path_obj.exists():@@ -1171,19 +1180,19 @@ class AsyncHTTPClient:mode: str = "replace",wait: bool = False,timeout: Optional[float] = None,- telemetry: Any = False,- processing_mode: Optional[str] = None,+ options: Optional[WriteOptions] = None,) -> Dict[str, Any]:- payload = {- "uri": VikingURI.normalize(uri),- "content": content,- "mode": mode,- "wait": wait,- "timeout": timeout,- "telemetry": telemetry,- }- if processing_mode is not None:- payload["processing_mode"] = processing_mode+ payload = self._build_options_payload(+ options,+ WriteOptions,+ fixed={+ "uri": VikingURI.normalize(uri),+ "content": content,+ "mode": mode,+ "wait": wait,+ "timeout": timeout,+ },+ )response = await self._request("POST","/api/v1/content/write",@@ -1197,7 +1206,7 @@ class AsyncHTTPClient:operations: List[Dict[str, Any]],wait: bool = True,timeout: Optional[float] = None,- telemetry: Any = False,+ options: Optional[BatchWriteOptions] = None,) -> Dict[str, Any]:"""Apply multiple content writes, then refresh semantics once."""normalized_operations = []@@ -1205,16 +1214,20 @@ class AsyncHTTPClient:item = dict(operation)item["uri"] = VikingURI.normalize(str(item.get("uri") or ""))normalized_operations.append(item)- response = await self._request(- "POST",- "/api/v1/content/batch-write",- json={+ payload = self._build_options_payload(+ options,+ BatchWriteOptions,+ fixed={"root_uri": VikingURI.normalize(root_uri),"operations": normalized_operations,"wait": wait,"timeout": timeout,- "telemetry": telemetry,},+ )+ response = await self._request(+ "POST",+ "/api/v1/content/batch-write",+ json=payload,**self._wait_request_kwargs(wait=wait, timeout=timeout),)return self._handle_response_data(response).get("result", {})@@ -1225,19 +1238,23 @@ class AsyncHTTPClient:tags: List[str],mode: str = "replace",recursive: bool = False,- telemetry: Any = False,+ options: Optional[SetTagsOptions] = None,) -> Dict[str, Any]:- response = await self._request(- "POST",- "/api/v1/fs/attrs/set_tags",- json={+ payload = self._build_options_payload(+ options,+ SetTagsOptions,+ fixed={"uri": VikingURI.normalize(uri),"tags": tags,"mode": mode,"recursive": recursive,- "telemetry": telemetry,},)+ response = await self._request(+ "POST",+ "/api/v1/fs/attrs/set_tags",+ json=payload,+ )return self._handle_response_data(response).get("result", {})async def find(@@ -1245,60 +1262,72 @@ class AsyncHTTPClient:query: str = "",target_uri: Union[str, List[str]] = "",limit: int = 10,- node_limit: Optional[int] = None,- score_threshold: Optional[float] = None,- filter: Optional[Dict[str, Any]] = None,- context_type: Optional[Any] = None,- tags: Optional[List[str]] = None,- telemetry: Any = False,image: Any = None,- ) -> Dict[str, Any]:- actual_limit = node_limit if node_limit is not None else limit- payload = {- "query": query,- "image_url": _normalize_image_input(image),- "target_uri": self._normalize_target_uri(target_uri),- "limit": actual_limit,- "score_threshold": score_threshold,- "filter": filter,- "context_type": self._normalize_context_type(context_type),- "tags": tags,- "telemetry": telemetry,- }- payload = self._compact_request_body(payload)+ options: Optional[FindOptions] = None,+ ) -> Dict[str, Any]:+ search_options = dict(options or {})+ if image is not None:+ search_options["image"] = image+ payload = self._search_options_payload(+ query,+ search_options,+ FindOptions,+ fixed={+ "target_uri": self._normalize_target_uri(target_uri),+ "limit": limit,+ },+ )response = await self._request("POST", "/api/v1/search/find", json=payload)return self._handle_response_data(response).get("result", {})async def search(self,query: str = "",+ session_id: Optional[str] = None,target_uri: Union[str, List[str]] = "",- session: Optional[Any] = None,+ limit: int = 10,+ image: Any = None,+ options: Optional[SearchOptions] = None,+ ) -> Dict[str, Any]:+ search_options = dict(options or {})+ if image is not None:+ search_options["image"] = image+ payload = self._search_options_payload(+ query,+ search_options,+ SearchOptions,+ fixed={+ "session_id": session_id,+ "target_uri": self._normalize_target_uri(target_uri),+ "limit": limit,+ },+ )+ response = await self._request("POST", "/api/v1/search/search", json=payload)+ return self._handle_response_data(response).get("result", {})++ async def search_context(+ self,+ query: str = "",session_id: Optional[str] = None,+ target_uri: Union[str, List[str]] = "",limit: int = 10,- node_limit: Optional[int] = None,- score_threshold: Optional[float] = None,- filter: Optional[Dict[str, Any]] = None,- context_type: Optional[Any] = None,- tags: Optional[List[str]] = None,- telemetry: Any = False,image: Any = None,- ) -> Dict[str, Any]:- actual_limit = node_limit if node_limit is not None else limit- sid = session_id or (session.session_id if session else None)- payload = {- "query": query,- "image_url": _normalize_image_input(image),- "target_uri": self._normalize_target_uri(target_uri),- "session_id": sid,- "limit": actual_limit,- "score_threshold": score_threshold,- "filter": filter,- "context_type": self._normalize_context_type(context_type),- "tags": tags,- "telemetry": telemetry,- }- payload = self._compact_request_body(payload)+ options: Optional[SearchContextOptions] = None,+ ) -> SearchContextResult:+ search_options = dict(options or {})+ if image is not None:+ search_options["image"] = image+ payload = self._search_options_payload(+ query,+ search_options,+ SearchContextOptions,+ fixed={+ "mode": "context",+ "session_id": session_id,+ "target_uri": self._normalize_target_uri(target_uri),+ "limit": limit,+ },+ )response = await self._request("POST", "/api/v1/search/search", json=payload)return self._handle_response_data(response).get("result", {})@@ -1341,22 +1370,16 @@ class AsyncHTTPClient:async def create_session(self,session_id: Optional[str] = None,- telemetry: Any = False,- memory_policy: Optional[Dict[str, Any]] = None,- auto_commit_policy: Any = _SESSION_CONFIG_UNSET,- memory_extraction_config: Optional[Dict[str, Any]] = None,- ) -> Dict[str, Any]:- json_body: Dict[str, Any] = {}- if session_id is not None:- json_body["session_id"] = session_id- if memory_policy is not None:- json_body["memory_policy"] = memory_policy- if auto_commit_policy is not _SESSION_CONFIG_UNSET:- json_body["auto_commit_policy"] = auto_commit_policy- if memory_extraction_config is not None:- json_body["memory_extraction_config"] = memory_extraction_config- if telemetry is not False:- json_body["telemetry"] = telemetry+ options: Optional[CreateSessionOptions] = None,+ ) -> Dict[str, Any]:+ option_values = dict(options or {})+ json_body = self._build_options_payload(+ option_values,+ CreateSessionOptions,+ fixed={"session_id": session_id},+ )+ if "auto_commit_policy" in option_values:+ json_body["auto_commit_policy"] = option_values["auto_commit_policy"]response = await self._request("POST", "/api/v1/sessions", json=json_body)return self._handle_response_data(response).get("result", {})@@ -1373,18 +1396,12 @@ class AsyncHTTPClient:async def update_session_config(self,session_id: str,- *,- memory_extraction_config: Optional[Dict[str, Any]] = None,- auto_commit_policy: Any = _SESSION_CONFIG_UNSET,- telemetry: Any = False,+ options: Optional[UpdateSessionConfigOptions] = None,) -> Dict[str, Any]:- payload: Dict[str, Any] = {}- if memory_extraction_config is not None:- payload["memory_extraction_config"] = memory_extraction_config- if auto_commit_policy is not _SESSION_CONFIG_UNSET:- payload["auto_commit_policy"] = auto_commit_policy- if telemetry is not False:- payload["telemetry"] = telemetry+ option_values = dict(options or {})+ payload = self._build_options_payload(option_values, UpdateSessionConfigOptions)+ if "auto_commit_policy" in option_values:+ payload["auto_commit_policy"] = option_values["auto_commit_policy"]session_path = self._path_segment(session_id)response = await self._request("PATCH",@@ -1447,27 +1464,30 @@ class AsyncHTTPClient:async def commit_session(self,session_id: str,- telemetry: Any = False,- *,keep_recent_count: int = 0,- retention_mode: str | None = None,- keep_recent_turn_count: int | None = None,- retained_message_token_budget: int | None = None,- min_raw_tail_steps: int | None = None,- event_tags: list[str] | None = None,- ) -> Dict[str, Any]:- payload: Dict[str, Any] = {- "keep_recent_count": keep_recent_count,- "telemetry": telemetry,- }- optional = {- "retention_mode": retention_mode,- "keep_recent_turn_count": keep_recent_turn_count,- "retained_message_token_budget": retained_message_token_budget,- "min_raw_tail_steps": min_raw_tail_steps,+ options: Optional[CommitSessionOptions] = None,+ ) -> Dict[str, Any]:+ option_values = dict(options or {})+ event_tags = option_values.pop("event_tags", _SESSION_CONFIG_UNSET)+ turn_fields = {+ "keep_recent_turn_count",+ "retained_message_token_budget",+ "min_raw_tail_steps",}- payload.update({key: value for key, value in optional.items() if value is not None})- if event_tags is not None:+ if (+ turn_fields & set(option_values)+ and option_values.get("retention_mode") != "turn_budget"+ ):+ raise ValueError(+ "retention_mode='turn_budget' is required when Turn retention fields are set"+ )+ payload = self._build_options_payload(+ option_values,+ CommitSessionOptions,+ fixed={"keep_recent_count": keep_recent_count},+ protected={"extraction_metadata"},+ )+ if event_tags is not _SESSION_CONFIG_UNSET:payload["extraction_metadata"] = {"event": {"tags": event_tags}}session_path = self._path_segment(session_id)response = await self._request(@@ -1481,32 +1501,27 @@ class AsyncHTTPClient:self,session_id: str,role: str,- content: str | None = None,- parts: list[dict] | None = None,- created_at: str | None = None,- peer_id: str | None = None,- telemetry: Any = False,- turn_id: str | None = None,- message_kind: str | None = None,- source_message_ids: list[str] | None = None,- ) -> Dict[str, Any]:- payload: Dict[str, Any] = {"role": role}- if parts is not None:- payload["parts"] = parts- elif content is not None:- payload["content"] = content- else:- raise ValueError("Either content or parts must be provided")- optional = {- "created_at": created_at,- "peer_id": peer_id,- "turn_id": turn_id,- "message_kind": message_kind,- "source_message_ids": source_message_ids,+ content: Optional[str] = None,+ parts: Optional[List[Union[Dict[str, Any], MessagePart]]] = None,+ options: Optional[AddMessageOptions] = None,+ peer_id: Optional[str] = None,+ ) -> Dict[str, Any]:+ if peer_id is not None and options and "peer_id" in options:+ raise ValueError("options cannot override 'peer_id'")+ fixed = {+ "role": role,+ "content": content,+ "parts": parts,}- payload.update({key: value for key, value in optional.items() if value is not None})- if telemetry is not False:- payload["telemetry"] = telemetry+ if peer_id is not None:+ fixed["peer_id"] = peer_id+ payload = self._build_options_payload(+ options,+ AddMessageOptions,+ fixed=fixed,+ protected={"role", "content", "parts"},+ )+ payload = self._normalize_message_payload(payload)session_path = self._path_segment(session_id)response = await self._request("POST", f"/api/v1/sessions/{session_path}/messages", json=payload@@ -1618,20 +1633,19 @@ class AsyncHTTPClient:wait: bool = True,dry_run: bool = False,recursive: bool = True,- tags: Optional[List[str]] = None,- tag_mode: str = "replace",+ options: Optional[ReindexOptions] = None,) -> Dict[str, Any]:- payload = {- "uri": uri,- "mode": mode,- "wait": wait,- "dry_run": dry_run,- }- if not recursive:- payload["recursive"] = False- if tags is not None:- payload["tags"] = tags- payload["tag_mode"] = tag_mode+ payload = self._build_options_payload(+ options,+ ReindexOptions,+ fixed={+ "uri": VikingURI.normalize(uri),+ "mode": mode,+ "wait": wait,+ "dry_run": dry_run,+ "recursive": recursive,+ },+ )response = await self._request("POST","/api/v1/content/reindex",@@ -1738,6 +1752,101 @@ class AsyncHTTPClient:response = await self._request("POST", "/api/v1/admin/migrate", json={"action": action})return self._handle_response(response)+ async def admin_get_agent_evolution(self) -> Dict[str, Any]:+ """Return the effective Agent Evolution switch for the caller's account."""+ response = await self._request("GET", "/api/v1/admin/agent-evolution")+ return self._handle_response(response)++ async def admin_set_agent_evolution(self, enabled: bool) -> Dict[str, Any]:+ """Persist and hot-reload Agent Evolution for the caller's account."""+ response = await self._request(+ "PUT", "/api/v1/admin/agent-evolution", json={"enabled": enabled}+ )+ return self._handle_response(response)++ async def admin_get_account_settings(self, account_id: str) -> Dict[str, Any]:+ """Return effective and explicitly overridden settings for one account."""+ response = await self._request("GET", f"/api/v1/admin/accounts/{account_id}/settings")+ return self._handle_response(response)++ async def admin_set_account_agent_evolution(+ self, account_id: str, enabled: bool+ ) -> Dict[str, Any]:+ """Update the allowlisted Agent Evolution setting for one account."""+ response = await self._request(+ "PATCH",+ f"/api/v1/admin/accounts/{account_id}/settings",+ json={"agent_evolution": {"enabled": enabled}},+ )+ return self._handle_response(response)++ async def list_experience_trajectories(+ self,+ experience_uri: str,+ options: Optional[ExperienceTrajectoryOptions] = None,+ ) -> Dict[str, Any]:+ params: Dict[str, Any] = {"experience_uri": VikingURI.normalize(experience_uri)}+ params.update(dict(options or {}))+ response = await self._request(+ "GET",+ "/api/v1/agent-evolution/experiences/trajectories",+ params=params,+ )+ return self._handle_response(response)++ async def get_experience_outcomes(+ self,+ experience_uri: str,+ options: Optional[ExperienceOutcomeOptions] = None,+ ) -> Dict[str, Any]:+ params: Dict[str, Any] = {"experience_uri": VikingURI.normalize(experience_uri)}+ params.update(dict(options or {}))+ response = await self._request(+ "GET",+ "/api/v1/agent-evolution/experiences/outcomes",+ params=params,+ )+ return self._handle_response(response)++ async def resolve_openviking_assets(+ self,+ manifest_yaml: str,+ options: Optional[ResolveAssetsOptions] = None,+ ) -> Dict[str, Any]:+ payload = self._build_options_payload(+ options,+ ResolveAssetsOptions,+ fixed={"manifest_yaml": manifest_yaml},+ )+ response = await self._request(+ "POST",+ "/api/v1/openviking-assets/resolve",+ json=payload,+ )+ return self._handle_response(response)++ async def preflight_openviking_asset(+ self,+ name: str,+ repo_url: str,+ options: Optional[PreflightAssetOptions] = None,+ ) -> Dict[str, Any]:+ payload = self._build_options_payload(+ options,+ PreflightAssetOptions,+ fixed={+ "name": name,+ "connector": "git",+ "repo_url": repo_url,+ },+ )+ response = await self._request(+ "POST",+ "/api/v1/openviking-assets/preflight",+ json=payload,+ )+ return self._handle_response(response)+def get_status(self) -> Dict[str, Any]:return run_async(self._get_system_status())@@ -1919,75 +2028,38 @@ class SyncHTTPClient:path: str,to: Optional[str] = None,parent: Optional[str] = None,- reason: str = "",- instruction: str = "",wait: bool = False,timeout: Optional[float] = None,- strict: bool = False,- ignore_dirs: Optional[str] = None,- include: Optional[str] = None,- exclude: Optional[str] = None,- directly_upload_media: bool = True,- preserve_structure: Optional[bool] = None,- watch_interval: float = 0,- args: Optional[Dict[str, Any]] = None,- telemetry: Any = False,- processing_mode: Optional[str] = None,- add_type: Optional[str] = None,- tags: Optional[List[str]] = None,- tag_mode: str = "replace",+ options: Optional[AddResourceOptions] = None,) -> Dict[str, Any]:return run_async(self._async_client.add_resource(- path=path,- add_type=add_type,+ path,to=to,parent=parent,- reason=reason,- instruction=instruction,wait=wait,timeout=timeout,- strict=strict,- ignore_dirs=ignore_dirs,- include=include,- exclude=exclude,- directly_upload_media=directly_upload_media,- preserve_structure=preserve_structure,- watch_interval=watch_interval,- processing_mode=processing_mode,- args=args,- tags=tags,- tag_mode=tag_mode,- telemetry=telemetry,+ options=options,))def batch_add_messages(self,session_id: str,- messages: list[dict],- telemetry: Any = False,+ messages: list[Message],+ options: Optional[BatchAddMessagesOptions] = None,) -> Dict[str, Any]:- if telemetry is False:- return run_async(self._async_client.batch_add_messages(session_id, messages))- return run_async(self._async_client.batch_add_messages(session_id, messages, telemetry))+ return run_async(self._async_client.batch_add_messages(session_id, messages, options))def add_skill(self,data: Any,wait: bool = False,timeout: Optional[float] = None,- telemetry: Any = False,- target_uri: Optional[str] = None,+ options: Optional[AddSkillOptions] = None,) -> Dict[str, Any]:return run_async(- self._async_client.add_skill(- data,- wait=wait,- timeout=timeout,- telemetry=telemetry,- target_uri=target_uri,- )+ self._async_client.add_skill(data, wait=wait, timeout=timeout, options=options))def list_skills(@@ -2065,19 +2137,11 @@ class SyncHTTPClient:data: Any,wait: bool = False,timeout: Optional[float] = None,- source_metadata: Optional[Dict[str, Any]] = None,- telemetry: Any = False,- target_uri: Optional[str] = None,+ options: Optional[UpdateSkillOptions] = None,) -> Dict[str, Any]:return run_async(self._async_client.update_skill(- skill_name,- data,- wait=wait,- timeout=timeout,- source_metadata=source_metadata,- telemetry=telemetry,- target_uri=target_uri,+ skill_name, data, wait=wait, timeout=timeout, options=options))@@ -2231,18 +2295,11 @@ class SyncHTTPClient:mode: str = "replace",wait: bool = False,timeout: Optional[float] = None,- telemetry: Any = False,- processing_mode: Optional[str] = None,+ options: Optional[WriteOptions] = None,) -> Dict[str, Any]:return run_async(self._async_client.write(- uri=uri,- content=content,- mode=mode,- wait=wait,- timeout=timeout,- telemetry=telemetry,- processing_mode=processing_mode,+ uri, content, mode=mode, wait=wait, timeout=timeout, options=options))@@ -2252,15 +2309,11 @@ class SyncHTTPClient:operations: List[Dict[str, Any]],wait: bool = True,timeout: Optional[float] = None,- telemetry: Any = False,+ options: Optional[BatchWriteOptions] = None,) -> Dict[str, Any]:return run_async(self._async_client.batch_write(- root_uri=root_uri,- operations=operations,- wait=wait,- timeout=timeout,- telemetry=telemetry,+ root_uri, operations, wait=wait, timeout=timeout, options=options))@@ -2270,15 +2323,11 @@ class SyncHTTPClient:tags: List[str],mode: str = "replace",recursive: bool = False,- telemetry: Any = False,+ options: Optional[SetTagsOptions] = None,) -> Dict[str, Any]:return run_async(self._async_client.set_tags(- uri=uri,- tags=tags,- mode=mode,- recursive=recursive,- telemetry=telemetry,+ uri, tags, mode=mode, recursive=recursive, options=options))@@ -2287,60 +2336,56 @@ class SyncHTTPClient:query: str = "",target_uri: Union[str, List[str]] = "",limit: int = 10,- node_limit: Optional[int] = None,- score_threshold: Optional[float] = None,- filter: Optional[Dict[str, Any]] = None,- context_type: Optional[Any] = None,- tags: Optional[List[str]] = None,- telemetry: Any = False,image: Any = None,+ options: Optional[FindOptions] = None,) -> Dict[str, Any]:return run_async(self._async_client.find(- query=query,+ query,target_uri=target_uri,limit=limit,- node_limit=node_limit,- score_threshold=score_threshold,- filter=filter,- context_type=context_type,- tags=tags,- telemetry=telemetry,image=image,+ options=options,))def search(self,query: str = "",- target_uri: Union[str, List[str]] = "",- session: Optional[Any] = None,session_id: Optional[str] = None,+ target_uri: Union[str, List[str]] = "",limit: int = 10,- node_limit: Optional[int] = None,- score_threshold: Optional[float] = None,- filter: Optional[Dict[str, Any]] = None,- context_type: Optional[Any] = None,- tags: Optional[List[str]] = None,- telemetry: Any = False,image: Any = None,+ options: Optional[SearchOptions] = None,) -> Dict[str, Any]:- actual_session_id = session_id- if actual_session_id is None and session is not None:- actual_session_id = getattr(session, "session_id", None)return run_async(self._async_client.search(- query=query,+ query,+ session_id=session_id,+ target_uri=target_uri,+ limit=limit,+ image=image,+ options=options,+ )+ )++ def search_context(+ self,+ query: str = "",+ session_id: Optional[str] = None,+ target_uri: Union[str, List[str]] = "",+ limit: int = 10,+ image: Any = None,+ options: Optional[SearchContextOptions] = None,+ ) -> SearchContextResult:+ return run_async(+ self._async_client.search_context(+ query,+ session_id=session_id,target_uri=target_uri,- session_id=actual_session_id,limit=limit,- node_limit=node_limit,- score_threshold=score_threshold,- filter=filter,- context_type=context_type,- tags=tags,- telemetry=telemetry,image=image,+ options=options,))@@ -2373,20 +2418,9 @@ class SyncHTTPClient:def create_session(self,session_id: Optional[str] = None,- telemetry: Any = False,- memory_policy: Optional[Dict[str, Any]] = None,- auto_commit_policy: Any = _SESSION_CONFIG_UNSET,- memory_extraction_config: Optional[Dict[str, Any]] = None,+ options: Optional[CreateSessionOptions] = None,) -> Dict[str, Any]:- kwargs: Dict[str, Any] = {- "session_id": session_id,- "telemetry": telemetry,- "memory_policy": memory_policy,- "memory_extraction_config": memory_extraction_config,- }- if auto_commit_policy is not _SESSION_CONFIG_UNSET:- kwargs["auto_commit_policy"] = auto_commit_policy- return run_async(self._async_client.create_session(**kwargs))+ return run_async(self._async_client.create_session(session_id, options=options))def list_sessions(self) -> List[Any]:return run_async(self._async_client.list_sessions())@@ -2397,18 +2431,9 @@ class SyncHTTPClient:def update_session_config(self,session_id: str,- *,- memory_extraction_config: Optional[Dict[str, Any]] = None,- auto_commit_policy: Any = _SESSION_CONFIG_UNSET,- telemetry: Any = False,+ options: Optional[UpdateSessionConfigOptions] = None,) -> Dict[str, Any]:- kwargs: Dict[str, Any] = {- "memory_extraction_config": memory_extraction_config,- "telemetry": telemetry,- }- if auto_commit_policy is not _SESSION_CONFIG_UNSET:- kwargs["auto_commit_policy"] = auto_commit_policy- return run_async(self._async_client.update_session_config(session_id, **kwargs))+ return run_async(self._async_client.update_session_config(session_id, options))def get_session_context(self, session_id: str, token_budget: int = 128_000) -> Dict[str, Any]:return run_async(self._async_client.get_session_context(session_id, token_budget))@@ -2444,42 +2469,12 @@ class SyncHTTPClient:def commit_session(self,session_id: str,- telemetry: Any = False,- *,keep_recent_count: int = 0,- retention_mode: str | None = None,- keep_recent_turn_count: int | None = None,- retained_message_token_budget: int | None = None,- min_raw_tail_steps: int | None = None,- event_tags: list[str] | None = None,- ) -> Dict[str, Any]:- kwargs = {"keep_recent_count": keep_recent_count}- kwargs.update(- {- key: value- for key, value in {- "retention_mode": retention_mode,- "keep_recent_turn_count": keep_recent_turn_count,- "retained_message_token_budget": retained_message_token_budget,- "min_raw_tail_steps": min_raw_tail_steps,- }.items()- if value is not None- }- )- if event_tags is not None:- kwargs["event_tags"] = event_tags- if telemetry is False:- return run_async(- self._async_client.commit_session(- session_id,- **kwargs,- )- )+ options: Optional[CommitSessionOptions] = None,+ ) -> Dict[str, Any]:return run_async(self._async_client.commit_session(- session_id,- telemetry=telemetry,- **kwargs,+ session_id, keep_recent_count=keep_recent_count, options=options))@@ -2487,41 +2482,20 @@ class SyncHTTPClient:self,session_id: str,role: str,- content: str | None = None,- parts: list[dict] | None = None,- created_at: str | None = None,- peer_id: str | None = None,- telemetry: Any = False,- turn_id: str | None = None,- message_kind: str | None = None,- source_message_ids: list[str] | None = None,+ content: Optional[str] = None,+ parts: Optional[List[Union[Dict[str, Any], MessagePart]]] = None,+ options: Optional[AddMessageOptions] = None,+ peer_id: Optional[str] = None,) -> Dict[str, Any]:- kwargs = {+ kwargs: Dict[str, Any] = {"role": role,"content": content,"parts": parts,- "created_at": created_at,- "peer_id": peer_id,+ "options": options,}- kwargs.update(- {- key: value- for key, value in {- "turn_id": turn_id,- "message_kind": message_kind,- "source_message_ids": source_message_ids,- }.items()- if value is not None- }- )- if telemetry is not False:- kwargs["telemetry"] = telemetry- return run_async(- self._async_client.add_message(- session_id,- **kwargs,- )- )+ if peer_id is not None:+ kwargs["peer_id"] = peer_id+ return run_async(self._async_client.add_message(session_id, **kwargs))def export_ovpack(self,@@ -2577,21 +2551,18 @@ class SyncHTTPClient:wait: bool = True,dry_run: bool = False,recursive: bool = True,- tags: Optional[List[str]] = None,- tag_mode: str = "replace",+ options: Optional[ReindexOptions] = None,) -> Dict[str, Any]:- kwargs = {- "uri": uri,- "mode": mode,- "wait": wait,- "dry_run": dry_run,- }- if not recursive:- kwargs["recursive"] = False- if tags is not None:- kwargs["tags"] = tags- kwargs["tag_mode"] = tag_mode- return run_async(self._async_client.reindex(**kwargs))+ return run_async(+ self._async_client.reindex(+ uri,+ mode=mode,+ wait=wait,+ dry_run=dry_run,+ recursive=recursive,+ options=options,+ )+ )def admin_create_account(self,@@ -2650,6 +2621,49 @@ class SyncHTTPClient:def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:return run_async(self._async_client.admin_migrate(cleanup=cleanup))+ def admin_get_agent_evolution(self) -> Dict[str, Any]:+ return run_async(self._async_client.admin_get_agent_evolution())++ def admin_set_agent_evolution(self, enabled: bool) -> Dict[str, Any]:+ return run_async(self._async_client.admin_set_agent_evolution(enabled))++ def admin_get_account_settings(self, account_id: str) -> Dict[str, Any]:+ return run_async(self._async_client.admin_get_account_settings(account_id))++ def admin_set_account_agent_evolution(self, account_id: str, enabled: bool) -> Dict[str, Any]:+ return run_async(self._async_client.admin_set_account_agent_evolution(account_id, enabled))++ def list_experience_trajectories(+ self,+ experience_uri: str,+ options: Optional[ExperienceTrajectoryOptions] = None,+ ) -> Dict[str, Any]:+ return run_async(+ self._async_client.list_experience_trajectories(experience_uri, options)+ )++ def get_experience_outcomes(+ self,+ experience_uri: str,+ options: Optional[ExperienceOutcomeOptions] = None,+ ) -> Dict[str, Any]:+ return run_async(self._async_client.get_experience_outcomes(experience_uri, options))++ def resolve_openviking_assets(+ self,+ manifest_yaml: str,+ options: Optional[ResolveAssetsOptions] = None,+ ) -> Dict[str, Any]:+ return run_async(self._async_client.resolve_openviking_assets(manifest_yaml, options))++ def preflight_openviking_asset(+ self,+ name: str,+ repo_url: str,+ options: Optional[PreflightAssetOptions] = None,+ ) -> Dict[str, Any]:+ return run_async(self._async_client.preflight_openviking_asset(name, repo_url, options))+def get_status(self) -> Dict[str, Any]:return self._async_client.get_status()diff --git a/sdk/python/openviking_sdk/message.py b/sdk/python/openviking_sdk/message.pynew file mode 100644index 000000000..2238b72d8--- /dev/null+++ b/sdk/python/openviking_sdk/message.py@@ -0,0 +1,127 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Dict, Literal, Optional, Union+++@dataclass+class TextPart:+ text: str = ""+ type: Literal["text"] = "text"+++@dataclass+class ContextPart:+ uri: str = ""+ context_type: Literal["memory", "resource", "skill"] = "memory"+ abstract: str = ""+ type: Literal["context"] = "context"+++@dataclass+class ImagePart:+ url: str = ""+ detail: Optional[str] = None+ type: Literal["image_url"] = "image_url"+++@dataclass+class ToolPart:+ tool_id: str = ""+ tool_name: str = ""+ tool_uri: str = ""+ skill_uri: str = ""+ tool_input: Optional[Dict[str, Any]] = None+ tool_output: str = ""+ tool_status: str = "pending"+ duration_ms: Optional[float] = None+ prompt_tokens: Optional[int] = None+ completion_tokens: Optional[int] = None+ tool_output_ref: str = ""+ tool_output_truncated: bool = False+ tool_output_original_chars: Optional[int] = None+ tool_output_preview_chars: Optional[int] = None+ tool_output_sha256: str = ""+ tool_output_storage_uri: str = ""+ tool_output_mime_type: str = "text/plain"+ tool_output_source_ref: str = ""+ tool_output_source_offset: Optional[int] = None+ tool_output_source_limit: Optional[int] = None+ tool_output_externalization_error: str = ""+ tool_output_group_id: str = ""+ tool_output_externalized_reason: str = ""+ tool_output_group_original_chars: Optional[int] = None+ tool_output_group_budget_chars: Optional[int] = None+ type: Literal["tool"] = "tool"+++MessagePart = Union[TextPart, ContextPart, ImagePart, ToolPart]+++def normalize_part(part: Union[Dict[str, Any], MessagePart, Any]) -> Dict[str, Any]:+ if isinstance(part, dict):+ return dict(part)++ part_type = getattr(part, "type", None)+ if part_type == "text":+ return {"type": "text", "text": getattr(part, "text", "")}+ if part_type == "context":+ return {+ "type": "context",+ "uri": getattr(part, "uri", ""),+ "context_type": getattr(part, "context_type", "memory"),+ "abstract": getattr(part, "abstract", ""),+ }+ if part_type == "image_url":+ image_url = {"url": getattr(part, "url", "")}+ detail = getattr(part, "detail", None)+ if detail is not None:+ image_url["detail"] = detail+ return {"type": "image_url", "image_url": image_url}+ if part_type == "tool":+ payload = {+ "type": "tool",+ "tool_id": getattr(part, "tool_id", ""),+ "tool_name": getattr(part, "tool_name", ""),+ "tool_status": getattr(part, "tool_status", "pending"),+ }+ for field in (+ "tool_uri",+ "skill_uri",+ "tool_input",+ "tool_output",+ "tool_output_ref",+ "tool_output_sha256",+ "tool_output_storage_uri",+ "tool_output_source_ref",+ "tool_output_externalization_error",+ "tool_output_group_id",+ "tool_output_externalized_reason",+ ):+ value = getattr(part, field, None)+ if value:+ payload[field] = value+ for field in (+ "duration_ms",+ "prompt_tokens",+ "completion_tokens",+ "tool_output_original_chars",+ "tool_output_preview_chars",+ "tool_output_source_offset",+ "tool_output_source_limit",+ "tool_output_group_original_chars",+ "tool_output_group_budget_chars",+ ):+ value = getattr(part, field, None)+ if value is not None:+ payload[field] = value+ if getattr(part, "tool_output_truncated", False):+ payload["tool_output_truncated"] = True+ tool_output_mime_type = getattr(part, "tool_output_mime_type", "text/plain")+ if tool_output_mime_type and tool_output_mime_type != "text/plain":+ payload["tool_output_mime_type"] = tool_output_mime_type+ return payload++ raise TypeError(+ "parts must contain dictionaries or TextPart, ContextPart, ImagePart, or ToolPart"+ )diff --git a/sdk/python/openviking_sdk/options.py b/sdk/python/openviking_sdk/options.pynew file mode 100644index 000000000..76ee9e13e--- /dev/null+++ b/sdk/python/openviking_sdk/options.py@@ -0,0 +1,198 @@+from __future__ import annotations++from typing import Any, Dict, List, Literal, Mapping, Optional, TypedDict, Union++ExtraFields = Mapping[str, Any]+TargetURI = Union[str, List[str]]+Level = Union[int, str, List[int]]+TimeField = Literal["updated_at", "created_at"]+ProcessingMode = Literal["semantic_and_vectors", "vectors_only"]+++class _ExtraOptions(TypedDict, total=False):+ extra: ExtraFields+++class FindOptions(_ExtraOptions, total=False):+ image: Any+ node_limit: int+ score_threshold: float+ filter: Dict[str, Any]+ context_type: Any+ include_provenance: bool+ tags: List[str]+ since: str+ until: str+ time_field: TimeField+ level: Level+ telemetry: Any+++class SearchOptions(FindOptions, total=False):+ pass+++class SearchContextOptions(_ExtraOptions, total=False):+ image: Any+ node_limit: int+ score_threshold: float+ filter: Dict[str, Any]+ context_type: Any+ include_provenance: bool+ tags: List[str]+ since: str+ until: str+ time_field: TimeField+ query_expansion: Literal["off", "auto"]+ max_tokens: int+ quotas: Dict[str, int]+ purpose: Literal["chat", "coding"]+ detail: Union[str, Dict[str, str]]+ dedup_turns: int+ exclude_uris: List[str]+ peer_scope: Literal["actor", "all"]+ other_peer_penalty: Union[float, Dict[str, float]]+ rewrite: Union[bool, Literal["auto"]]+ rewrite_max_bullets: int+ telemetry: Any+++class AddResourceOptions(_ExtraOptions, total=False):+ reason: str+ instruction: str+ create_parent: bool+ strict: bool+ ignore_dirs: str+ include: str+ exclude: str+ directly_upload_media: bool+ preserve_structure: bool+ watch_interval: float+ args: Dict[str, Any]+ telemetry: Any+ processing_mode: ProcessingMode+ add_type: str+ tags: List[str]+ tag_mode: Literal["replace", "append"]+++class AddSkillOptions(_ExtraOptions, total=False):+ telemetry: Any+ target_uri: str+++class UpdateSkillOptions(AddSkillOptions, total=False):+ source_metadata: Dict[str, Any]+++class WriteOptions(_ExtraOptions, total=False):+ telemetry: Any+ processing_mode: ProcessingMode+++class BatchWriteOptions(_ExtraOptions, total=False):+ telemetry: Any+++class SetTagsOptions(_ExtraOptions, total=False):+ telemetry: Any+++class ReindexOptions(_ExtraOptions, total=False):+ tags: List[str]+ tag_mode: Literal["replace", "append"]+++class CreateSessionOptions(_ExtraOptions, total=False):+ memory_policy: Dict[str, Any]+ auto_commit_policy: Optional[Dict[str, Any]]+ memory_extraction_config: Dict[str, Any]+ telemetry: Any+++class UpdateSessionConfigOptions(_ExtraOptions, total=False):+ auto_commit_policy: Optional[Dict[str, Any]]+ memory_extraction_config: Dict[str, Any]+ telemetry: Any+++class _RequiredMessage(TypedDict):+ role: str+++class Message(_RequiredMessage, total=False):+ content: str+ parts: List[Any]+ created_at: str+ peer_id: str+ turn_id: str+ message_kind: Literal["user_query", "assistant_step", "tool_transport", "checkpoint"]+ source_message_ids: List[str]+ telemetry: Any+++class AddMessageOptions(_ExtraOptions, total=False):+ created_at: str+ peer_id: str+ turn_id: str+ message_kind: Literal["user_query", "assistant_step", "tool_transport", "checkpoint"]+ source_message_ids: List[str]+ telemetry: Any+++class BatchAddMessagesOptions(_ExtraOptions, total=False):+ telemetry: Any+++class CommitSessionOptions(_ExtraOptions, total=False):+ retention_mode: Literal["turn_budget"]+ keep_recent_turn_count: int+ retained_message_token_budget: int+ min_raw_tail_steps: int+ event_tags: List[str]+ telemetry: Any+++class ExperienceTrajectoryOptions(TypedDict, total=False):+ limit: int+ offset: int+ start_date: str+ end_date: str+++class ExperienceOutcomeOptions(TypedDict, total=False):+ start_date: str+ end_date: str+++class ResolveAssetsOptions(_ExtraOptions, total=False):+ catalog_yaml: str+ manifest_label: str+ catalog_label: str+++class AssetGitAuth(TypedDict, total=False):+ username: str+ token: str+++class PreflightAssetOptions(_ExtraOptions, total=False):+ branch: str+ commit: str+ auth_config: AssetGitAuth+++class SearchContextEntry(TypedDict, total=False):+ uri: str+ category: str+ score: float+ detail: str+ text: str+ origin: str+++class SearchContextResult(TypedDict, total=False):+ entries: List[SearchContextEntry]+ rendered: str+ digest: str+ stats: Dict[str, Any]diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.pyindex f17e34957..17c27224c 100644--- a/sdk/python/tests/test_async_client_behaviors.py+++ b/sdk/python/tests/test_async_client_behaviors.py@@ -1,21 +1,20 @@-import inspectfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, Mock, patchimport pytest-from openviking_sdk import AsyncHTTPClient, SyncHTTPClient+from openviking_sdk import (+ AsyncHTTPClient,+ ContextPart,+ ImagePart,+ SyncHTTPClient,+ TextPart,+ ToolPart,+)from openviking_sdk.client import Session, SyncSessionfrom openviking_sdk.errors import NotFoundError-def test_add_resource_signatures_keep_telemetry_position():- for func in (AsyncHTTPClient.add_resource, SyncHTTPClient.add_resource):- params = list(inspect.signature(func).parameters)- assert params.index("telemetry") < params.index("tags")- assert params.index("telemetry") < params.index("tag_mode")--@pytest.mark.asyncioasync def test_async_http_client_initialize_forwards_event_hooks():async def request_hook(_request):@@ -104,18 +103,22 @@ async def test_async_http_client_sends_message_semantics_and_turn_retention():await client.add_message("demo-session",- "assistant",+ role="assistant",parts=[{"type": "text", "text": "checking"}],- turn_id="turn-1",- message_kind="assistant_step",- source_message_ids=["u1"],+ options={+ "turn_id": "turn-1",+ "message_kind": "assistant_step",+ "source_message_ids": ["u1"],+ },)await client.commit_session("demo-session",- retention_mode="turn_budget",- keep_recent_turn_count=3,- retained_message_token_budget=12_000,- min_raw_tail_steps=1,+ options={+ "retention_mode": "turn_budget",+ "keep_recent_turn_count": 3,+ "retained_message_token_budget": 12_000,+ "min_raw_tail_steps": 1,+ },)assert fake_http.post.await_args_list[0].kwargs["json"] == {@@ -127,7 +130,6 @@ async def test_async_http_client_sends_message_semantics_and_turn_retention():}assert fake_http.post.await_args_list[1].kwargs["json"] == {"keep_recent_count": 0,- "telemetry": False,"retention_mode": "turn_budget","keep_recent_turn_count": 3,"retained_message_token_budget": 12_000,@@ -135,6 +137,123 @@ async def test_async_http_client_sends_message_semantics_and_turn_retention():}+async def test_async_http_client_normalizes_message_part_objects():+ client = AsyncHTTPClient(url="http://localhost:1933")+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))+ client._http = fake_http+ client._handle_response_data = lambda _response: {"result": {"status": "ok"}}++ await client.add_message(+ "demo-session",+ role="assistant",+ parts=[+ TextPart(text="checking"),+ ContextPart(+ uri="viking://resources/guide.md",+ context_type="resource",+ abstract="Guide",+ ),+ ImagePart(url="https://example.com/image.png", detail="high"),+ ToolPart(+ tool_id="call-1",+ tool_name="search",+ tool_input={"query": "OpenViking"},+ tool_status="completed",+ duration_ms=12.5,+ prompt_tokens=42,+ completion_tokens=7,+ tool_output_ref="viking://sessions/demo-session/tool-results/call-1",+ tool_output_truncated=True,+ tool_output_original_chars=1_024,+ tool_output_mime_type="application/json",+ tool_output_source_limit=512,+ ),+ ],+ )++ fake_http.post.assert_awaited_once_with(+ "/api/v1/sessions/demo-session/messages",+ json={+ "role": "assistant",+ "parts": [+ {"type": "text", "text": "checking"},+ {+ "type": "context",+ "uri": "viking://resources/guide.md",+ "context_type": "resource",+ "abstract": "Guide",+ },+ {+ "type": "image_url",+ "image_url": {+ "url": "https://example.com/image.png",+ "detail": "high",+ },+ },+ {+ "type": "tool",+ "tool_id": "call-1",+ "tool_name": "search",+ "tool_input": {"query": "OpenViking"},+ "tool_status": "completed",+ "duration_ms": 12.5,+ "prompt_tokens": 42,+ "completion_tokens": 7,+ "tool_output_ref": "viking://sessions/demo-session/tool-results/call-1",+ "tool_output_truncated": True,+ "tool_output_original_chars": 1_024,+ "tool_output_mime_type": "application/json",+ "tool_output_source_limit": 512,+ },+ ],+ },+ )+++async def test_async_http_client_add_message_serializes_flattened_peer_id():+ client = AsyncHTTPClient(url="http://localhost:1933")+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))+ client._http = fake_http+ client._handle_response_data = lambda _response: {"result": {"status": "ok"}}++ await client.add_message(+ "demo-session",+ role="assistant",+ content="checking",+ peer_id="peer-alice",+ )++ fake_http.post.assert_awaited_once_with(+ "/api/v1/sessions/demo-session/messages",+ json={+ "role": "assistant",+ "content": "checking",+ "peer_id": "peer-alice",+ },+ )+++async def test_async_http_client_add_message_rejects_duplicate_peer_id():+ client = AsyncHTTPClient(url="http://localhost:1933")+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))+ client._http = fake_http+ client._handle_response_data = lambda _response: {"result": {"status": "ok"}}++ with pytest.raises(ValueError, match="peer_id"):+ await client.add_message(+ "demo-session",+ role="assistant",+ content="checking",+ peer_id="peer-alice",+ options={"peer_id": "peer-bob"},+ )++ fake_http.post.assert_not_awaited()++@pytest.mark.asyncioasync def test_async_http_client_sends_event_memory_tag_configuration():client = AsyncHTTPClient(url="http://localhost:1933")@@ -146,15 +265,19 @@ async def test_async_http_client_sends_event_memory_tag_configuration():client._handle_response_data = lambda _response: {"result": {"status": "ok"}}config = {"events": {"tags": ["team=search", "channel=web"]}}- await client.create_session("tagged-session", memory_extraction_config=config)+ await client.create_session(+ "tagged-session", options={"memory_extraction_config": config}+ )await client.update_session_config("tagged-session",- memory_extraction_config=config,- auto_commit_policy={"message_count_threshold": 25},+ {+ "memory_extraction_config": config,+ "auto_commit_policy": {"message_count_threshold": 25},+ },)- await client.commit_session("tagged-session", event_tags=[])- await client.update_session_config("tagged-session", auto_commit_policy=None)- await client.create_session("disabled-session", auto_commit_policy=None)+ await client.commit_session("tagged-session", options={"event_tags": []})+ await client.update_session_config("tagged-session", {"auto_commit_policy": None})+ await client.create_session("disabled-session", options={"auto_commit_policy": None})assert fake_http.post.await_args_list[0].kwargs["json"] == {"session_id": "tagged-session",@@ -167,7 +290,6 @@ async def test_async_http_client_sends_event_memory_tag_configuration():}assert fake_http.post.await_args_list[1].kwargs["json"] == {"keep_recent_count": 0,- "telemetry": False,"extraction_metadata": {"event": {"tags": []}},}assert fake_http.patch.await_args_list[1].args == ("/api/v1/sessions/tagged-session/config",)@@ -190,6 +312,7 @@ async def test_async_http_client_reindex_posts_content_reindex():mode="prune_orphans",wait=False,dry_run=True,+ options=None,)assert result == {"status": "completed"}@@ -200,6 +323,7 @@ async def test_async_http_client_reindex_posts_content_reindex():"mode": "prune_orphans","wait": False,"dry_run": True,+ "recursive": True,},)@@ -213,8 +337,7 @@ async def test_async_http_client_reindex_sends_explicit_empty_tags():await client.reindex("viking://resources/demo",- tags=[],- tag_mode="replace",+ options={"tags": [], "tag_mode": "replace"},)assert fake_http.post.await_args.kwargs["json"]["tags"] == []@@ -233,7 +356,7 @@ async def test_async_http_client_write_forwards_processing_mode():await client.write("viking://resources/demo.md","updated",- processing_mode="vectors_only",+ options={"processing_mode": "vectors_only"},)payload = fake_http.post.await_args.kwargs["json"]@@ -290,10 +413,12 @@ def test_sync_http_client_reindex_forwards_to_async_client():assert result == {"status": "accepted"}assert mock_run.calledmock_reindex.assert_called_once_with(- uri="viking://resources/demo",+ "viking://resources/demo",mode="prune_orphans",wait=False,dry_run=True,+ recursive=True,+ options=None,)@@ -322,7 +447,7 @@ def test_sync_http_client_batch_add_messages_forwards_to_async_client():assert result == {"session_id": "batch-session", "message_count": 2, "added": 2}assert mock_run.called- mock_batch.assert_called_once_with("batch-session", messages)+ mock_batch.assert_called_once_with("batch-session", messages, None)def test_sync_http_client_session_returns_sync_session_wrapper():@@ -347,7 +472,11 @@ def test_sync_session_add_message_wraps_async_client():"openviking_sdk.client.run_async",return_value={"message_id": "msg-1"},) as mock_run:- result = session.add_message("user", content="hello")+ result = session.add_message(+ role="user",+ content="hello",+ peer_id="peer-alice",+ )assert result == {"message_id": "msg-1"}assert mock_run.called@@ -356,8 +485,8 @@ def test_sync_session_add_message_wraps_async_client():role="user",content="hello",parts=None,- created_at=None,- peer_id=None,+ options=None,+ peer_id="peer-alice",)@@ -385,7 +514,11 @@ def test_sync_session_commit_and_context_are_sync():assert commit_result == {"status": "completed"}assert context_result == {"messages": []}assert mock_run.call_count == 2- mock_commit.assert_called_once_with("demo-session", keep_recent_count=1)+ mock_commit.assert_called_once_with(+ "demo-session",+ keep_recent_count=1,+ options=None,+ )mock_context.assert_called_once_with("demo-session", 2048)@@ -462,7 +595,7 @@ def test_sync_session_commit_async_and_repr_match_sync_usage():result = session.commit_async(keep_recent_count=3)assert result == {"status": "completed"}- mock_commit.assert_called_once_with(telemetry=False, keep_recent_count=3)+ mock_commit.assert_called_once_with(keep_recent_count=3, options=None)assert "demo-session" in repr(session)@@ -500,12 +633,124 @@ async def test_write_omits_removed_semantic_flags_from_http_payload():"content": "updated","mode": "replace","wait": True,- "timeout": None,- "telemetry": False,},)+async def test_find_forwards_level_and_time_filters_when_provided():+ client = AsyncHTTPClient(url="http://localhost:1933")+ client._request = AsyncMock(return_value=object())+ client._handle_response_data = lambda _response: {"result": {}}++ await client.find(+ "hello",+ options={+ "level": [0, 1],+ "since": "2026-01-01",+ "until": "2026-02-01",+ "time_field": "updated_at",+ },+ )++ payload = client._request.await_args.kwargs["json"]+ assert payload["level"] == [0, 1]+ assert payload["since"] == "2026-01-01"+ assert payload["until"] == "2026-02-01"+ assert payload["time_field"] == "updated_at"+++ ("method_name", "extra_kwargs", "expected_path"),+ [+ ("find", {}, "/api/v1/search/find"),+ ("search", {"session_id": "session-1"}, "/api/v1/search/search"),+ (+ "search_context",+ {"session_id": "session-1"},+ "/api/v1/search/search",+ ),+ ],+)+async def test_retrieval_accepts_image_as_explicit_parameter(+ method_name, extra_kwargs, expected_path+):+ client = AsyncHTTPClient(url="http://localhost:1933")+ client._request = AsyncMock(return_value=object())+ client._handle_response_data = lambda _response: {"result": {}}++ await getattr(client, method_name)(+ query="",+ image="viking://resources/query.png",+ **extra_kwargs,+ )++ assert client._request.await_args.args == ("POST", expected_path)+ payload = client._request.await_args.kwargs["json"]+ assert payload["image_url"] == "viking://resources/query.png"+++async def test_find_omits_level_and_time_filters_when_absent():+ client = AsyncHTTPClient(url="http://localhost:1933")+ client._request = AsyncMock(return_value=object())+ client._handle_response_data = lambda _response: {"result": {}}++ await client.find("hello")++ payload = client._request.await_args.kwargs["json"]+ for key in ("level", "since", "until", "time_field"):+ assert key not in payload+++async def test_search_forwards_level_zero_and_omits_unset_time_filters():+ client = AsyncHTTPClient(url="http://localhost:1933")+ client._request = AsyncMock(return_value=object())+ client._handle_response_data = lambda _response: {"result": {}}++ # level=0 is a valid level and must survive compaction (is-None check, not falsy).+ await client.search("hello", session_id="s1", options={"level": 0})++ payload = client._request.await_args.kwargs["json"]+ assert payload["level"] == 0+ assert payload["session_id"] == "s1"+ for key in ("since", "until", "time_field"):+ assert key not in payload+++async def test_find_extra_forwards_unknown_fields_to_payload():+ client = AsyncHTTPClient(url="http://localhost:1933")+ client._request = AsyncMock(return_value=object())+ client._handle_response_data = lambda _response: {"result": {}}++ # The escape hatch lets callers reach server fields the SDK does not yet+ # model, without waiting for an SDK release.+ await client.find("hello", options={"include_provenance": True})++ payload = client._request.await_args.kwargs["json"]+ assert payload["include_provenance"] is True+++async def test_write_extra_forwards_unknown_fields_to_payload():+ client = AsyncHTTPClient(url="http://localhost:1933")+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))+ client._http = fake_http+ client._handle_response_data = lambda _response: {"result": {}}++ await client.write(+ "viking://resources/demo.md",+ "body",+ options={"extra": {"future_flag": 1}},+ )++ payload = fake_http.post.await_args.kwargs["json"]+ assert payload["future_flag"] == 1++@pytest.mark.asyncioasync def test_add_skill_uploads_local_file_even_when_url_is_localhost(tmp_path):skill_file = tmp_path / "SKILL.md"@@ -544,7 +789,10 @@ async def test_add_resource_uploads_local_file_even_when_url_is_localhost(tmp_pa"result": {"root_uri": "viking://resources/demo"}}- await client.add_resource(str(resource_file), reason="test", watch_interval=60)+ await client.add_resource(+ str(resource_file),+ options={"reason": "test", "watch_interval": 60},+ )fake_http.post.assert_awaited_once()payload = fake_http.post.await_args.kwargs["json"]@@ -564,7 +812,7 @@ async def test_add_resource_forwards_processing_mode():await client.add_resource("https://example.com/demo.md",- processing_mode="vectors_only",+ options={"processing_mode": "vectors_only"},)fake_http.post.assert_awaited_once()@@ -583,8 +831,8 @@ async def test_add_resource_forwards_declared_add_type_with_exact_target():await client.add_resource("space:home",- add_type=" feishu ",to="viking://resources/feishu",+ options={"add_type": " feishu "},)payload = fake_http.post.await_args.kwargs["json"]@@ -598,7 +846,7 @@ async def test_add_resource_declared_add_type_requires_exact_target():client = AsyncHTTPClient(url="http://127.0.0.1:1933")with pytest.raises(ValueError, match="exact 'to'"):- await client.add_resource("space:home", add_type="feishu")+ await client.add_resource("space:home", options={"add_type": "feishu"})@pytest.mark.asyncio@@ -608,9 +856,11 @@ async def test_add_resource_declared_add_type_rejects_parent():with pytest.raises(ValueError, match="'parent'"):await client.add_resource("space:home",- add_type="feishu",to="viking://resources/feishu",parent="viking://resources/imports",+ options={+ "add_type": "feishu",+ },)@@ -629,8 +879,8 @@ async def test_add_resource_declared_add_type_skips_local_file_upload(tmp_path):await client.add_resource(str(source),- add_type="feishu",to="viking://resources/feishu",+ options={"add_type": "feishu"},)client._upload_temp_file.assert_not_awaited()@@ -650,13 +900,18 @@ def test_sync_add_resource_accepts_and_forwards_declared_add_type():) as mock_add_resource:result = client.add_resource("space:home",- add_type="feishu",to="viking://resources/feishu",+ options={"add_type": "feishu"},)assert result["root_uri"] == "viking://resources/feishu"- assert mock_add_resource.await_args.kwargs["add_type"] == "feishu"- assert mock_add_resource.await_args.kwargs["to"] == "viking://resources/feishu"+ assert mock_add_resource.await_args.kwargs == {+ "to": "viking://resources/feishu",+ "parent": None,+ "wait": False,+ "timeout": None,+ "options": {"add_type": "feishu"},+ }@pytest.mark.asyncio@@ -675,42 +930,6 @@ async def test_add_resource_omits_default_processing_mode_for_legacy_servers():assert "processing_mode" not in payload-async def test_add_resource_preserves_positional_watch_args_for_legacy_callers():- client = AsyncHTTPClient(url="http://127.0.0.1:1933")- fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))- client._http = fake_http- client._handle_response_data = lambda _response: {- "result": {"root_uri": "viking://resources/demo"}- }-- await client.add_resource(- "https://example.com/demo.md",- None,- None,- "",- "",- False,- None,- False,- None,- None,- None,- True,- None,- 1440,- {"site": True},- False,- )-- fake_http.post.assert_awaited_once()- payload = fake_http.post.await_args.kwargs["json"]- assert payload["watch_interval"] == 1440- assert payload["args"] == {"site": True}- assert payload["telemetry"] is False- assert "processing_mode" not in payload--@pytest.mark.asyncioasync def test_admin_create_paths_accept_initial_user_config():client = AsyncHTTPClient(url="http://localhost:1933")@@ -799,22 +1018,15 @@ async def test_add_resource_sends_tags_and_tag_mode():}await client.add_resource(- path="https://example.com/demo.md",- tags=["team=search"],- tag_mode="append",+ "https://example.com/demo.md",+ options={"tags": ["team=search"], "tag_mode": "append"},)fake_http.post.assert_awaited_once_with("/api/v1/resources",json={- "path": "https://example.com/demo.md",- "reason": "",- "instruction": "","wait": False,- "strict": False,- "directly_upload_media": True,- "watch_interval": 0,- "telemetry": False,+ "path": "https://example.com/demo.md","tags": ["team=search"],"tag_mode": "append",},@@ -829,15 +1041,17 @@ async def test_find_uses_node_limit_as_http_limit_and_normalizes_target_uri_listclient._handle_response_data = lambda _response: {"result": {"total": 0, "resources": []}}await client.find(- query="sample",+ "sample",target_uri=["/resources/demo", "viking://resources/kept"],limit=3,- node_limit=9,- score_threshold=0.4,- filter={"type": "resource"},- context_type="resource",- tags=["k:v"],- telemetry={"enabled": True},+ options={+ "node_limit": 9,+ "score_threshold": 0.4,+ "filter": {"type": "resource"},+ "context_type": "resource",+ "tags": ["k:v"],+ "telemetry": {"enabled": True},+ },)fake_http.post.assert_awaited_once_with(@@ -845,7 +1059,8 @@ async def test_find_uses_node_limit_as_http_limit_and_normalizes_target_uri_listjson={"query": "sample","target_uri": ["viking://resources/demo", "viking://resources/kept"],- "limit": 9,+ "limit": 3,+ "node_limit": 9,"score_threshold": 0.4,"filter": {"type": "resource"},"context_type": "resource",@@ -862,8 +1077,12 @@ async def test_search_uses_session_wrapper_session_id_in_payload():client._http = fake_httpclient._handle_response_data = lambda _response: {"result": {"total": 0, "resources": []}}- session = Session(client, "thread-123")- await client.search(query="sample", target_uri="/resources/demo", session=session, limit=5)+ await client.search(+ "sample",+ session_id="thread-123",+ target_uri="/resources/demo",+ limit=5,+ )fake_http.post.assert_awaited_once_with("/api/v1/search/search",@@ -872,7 +1091,6 @@ async def test_search_uses_session_wrapper_session_id_in_payload():"target_uri": "viking://resources/demo","session_id": "thread-123","limit": 5,- "telemetry": False,},)@@ -918,7 +1136,11 @@ async def test_glob_normalizes_scope_uri():fake_http.post.assert_awaited_once_with("/api/v1/search/glob",- json={"pattern": "**/*.md", "uri": "viking://resources/"},+ json={+ "pattern": "**/*.md",+ "uri": "viking://resources/",+ "node_limit": 256,+ },)@@ -1085,7 +1307,11 @@ async def test_session_wrapper_forwards_commit_context_and_archive_operations():assert commit_result == {"status": "completed"}assert context_result == {"messages": []}assert archive_result == {"archive_id": "arc-1"}- client.commit_session.assert_awaited_once_with("thread-1", keep_recent_count=2)+ client.commit_session.assert_awaited_once_with(+ "thread-1",+ keep_recent_count=2,+ options=None,+ )client.get_session_context.assert_awaited_once_with("thread-1", 2048)client.get_session_archive.assert_awaited_once_with("thread-1", "arc-1")client.delete_session.assert_awaited_once_with("thread-1")diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 49dc0d139..3350e3543 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -51,8 +51,11 @@ await client.updateSessionConfig("s1", {},});await client.updateSessionConfig("s1", { autoCommitPolicy: null });-await client.commitSession("s1", 0, undefined, ["team=search", "channel=web"]);-await client.commitSession("s1", 0, undefined, []);+await client.commitSession("s1", {+ keepRecentCount: 0,+ eventTags: ["team=search", "channel=web"],+});+await client.commitSession("s1", { keepRecentCount: 0, eventTags: [] });```Deployments using shared temporary storage can set `uploadMode: "shared"`; the server also accepts `"local"` (the default).diff --git a/sdk/typescript/README_CN.md b/sdk/typescript/README_CN.mdindex 86fd3211d..17d0e3bef 100644--- a/sdk/typescript/README_CN.md+++ b/sdk/typescript/README_CN.md@@ -51,8 +51,11 @@ await client.updateSessionConfig("s1", {},});await client.updateSessionConfig("s1", { autoCommitPolicy: null });-await client.commitSession("s1", 0, undefined, ["team=search", "channel=web"]);-await client.commitSession("s1", 0, undefined, []);+await client.commitSession("s1", {+ keepRecentCount: 0,+ eventTags: ["team=search", "channel=web"],+});+await client.commitSession("s1", { keepRecentCount: 0, eventTags: [] });```使用共享临时存储的部署可设置 `uploadMode: "shared"`;服务端也接受 `"local"`(默认值)。diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.tsindex e441d6f3c..ab98f4349 100644--- a/sdk/typescript/src/client.ts+++ b/sdk/typescript/src/client.ts@@ -8,8 +8,15 @@ import {import { OpenVikingTransport, type TransportOptions } from "./transport.js";import type {AddResourceOptions,+ BatchAddMessagesOptions,+ BatchWriteOperation,+ BatchWriteOptions,ClientConfig,+ CommitSessionOptions,CreateSessionOptions,+ ExperienceOutcomeOptions,+ ExperienceTrajectoryOptions,+ FindOptions,FindResult,GitBlob,GitCommitOptions,@@ -20,8 +27,14 @@ import type {GrepOptions,ImportPackOptions,Message,+ PreflightAssetOptions,+ ReindexOptions,RequestOptions,+ ResolveAssetsOptions,+ SearchContextOptions,+ SearchContextResult,SearchOptions,+ SetTagsOptions,TaskListOptions,TreeOptions,UpdateSessionConfigOptions,@@ -36,6 +49,19 @@ const compact = (value: JsonObject): JsonObject =>([, item]) => item !== undefined && item !== null,),);+const mergeExtra = (+ body: JsonObject,+ extra: JsonObject | undefined,+ protectedKeys: readonly string[] = [],+): JsonObject => {+ const protectedFields = new Set(protectedKeys);+ for (const [key, value] of Object.entries(extra ?? {})) {+ if (key in body || protectedFields.has(key))+ throw new TypeError(`OpenViking: extra cannot override ${key}`);+ if (value !== undefined && value !== null) body[key] = value;+ }+ return body;+};const pathPart = (value: string): string => encodeURIComponent(value);/** Normalize a short OpenViking URI to the canonical `viking://` form. */@@ -110,17 +136,18 @@ export class OpenVikingClient {const body: JsonObject = compact({to: options.to,parent: options.parent,+ create_parent: options.createParent,reason: options.reason,instruction: options.instruction,- wait: options.wait ?? false,+ wait: options.wait,timeout: options.timeout,- strict: options.strict ?? false,+ strict: options.strict,ignore_dirs: options.ignoreDirs,include: options.include,exclude: options.exclude,- directly_upload_media: options.directlyUploadMedia ?? true,+ directly_upload_media: options.directlyUploadMedia,preserve_structure: options.preserveStructure,- watch_interval: options.watchInterval ?? 0,+ watch_interval: options.watchInterval,processing_mode: options.processingMode,args:options.args && Object.keys(options.args).length@@ -135,13 +162,15 @@ export class OpenVikingClient {body.temp_file_id = await this.upload(local.blob, local.filename);body.source_name = local.sourceName;} else body.path = source;- return this.request("POST", "/api/v1/resources", { body });+ return this.request("POST", "/api/v1/resources", {+ body: mergeExtra(body, options.extra),+ });}/** Install a skill from inline data or an existing Node.js path. */async addSkill(source: unknown,- options: WaitOptions & { targetUri?: string } = {},+ options: WaitOptions & { targetUri?: string; extra?: JsonObject } = {},): Promise<JsonObject> {const body: JsonObject = compact({wait: options.wait ?? false,@@ -154,7 +183,9 @@ export class OpenVikingClient {if (local)body.temp_file_id = await this.upload(local.blob, local.filename);else body.data = source;- return this.request("POST", "/api/v1/skills", { body });+ return this.request("POST", "/api/v1/skills", {+ body: mergeExtra(body, options.extra),+ });}/** List installed skills. */listSkills(@@ -228,6 +259,7 @@ export class OpenVikingClient {options: WaitOptions & {sourceMetadata?: JsonObject;targetUri?: string;+ extra?: JsonObject;} = {},): Promise<JsonObject> {const body: JsonObject = compact({@@ -242,7 +274,9 @@ export class OpenVikingClient {if (local)body.temp_file_id = await this.upload(local.blob, local.filename);else body.data = source;- return this.request("PUT", `/api/v1/skills/${pathPart(name)}`, { body });+ return this.request("PUT", `/api/v1/skills/${pathPart(name)}`, {+ body: mergeExtra(body, options.extra),+ });}/** Delete an installed skill. */deleteSkill(name: string, targetUri?: string): Promise<JsonObject> {@@ -317,7 +351,7 @@ export class OpenVikingClient {}/** Find relevant content without session context. */- async find(query: string, options: SearchOptions = {}): Promise<FindResult> {+ async find(query: string, options: FindOptions = {}): Promise<FindResult> {return this.searchRequest("find", query, options);}/** Search relevant content with optional session context. */@@ -330,29 +364,73 @@ export class OpenVikingClient {private async searchRequest(kind: "find" | "search",query: string,- options: SearchOptions,+ options: FindOptions | SearchOptions,): Promise<FindResult> {let imageUrl: string | undefined;if (typeof options.image === "string") {imageUrl = (await nodeImagePathToDataURI(options.image)) ?? options.image;}+ const body = compact({+ query,+ target_uri: options.targetUri,+ image_url: imageUrl,+ session_id:+ kind === "search" ? (options as SearchOptions).sessionId : undefined,+ limit: options.limit,+ node_limit: options.nodeLimit,+ score_threshold: options.scoreThreshold,+ filter: options.filter,+ context_type: options.contextType,+ telemetry: options.telemetry,+ since: options.since,+ until: options.until,+ time_field: options.timeField,+ level: options.level,+ tags: options.tags,+ include_provenance: options.includeProvenance,+ });return this.request("POST", `/api/v1/search/${kind}`, {- body: compact({- query,- target_uri: options.targetUri ?? "",- image_url: imageUrl,- session_id: kind === "search" ? options.sessionId : undefined,- limit: options.nodeLimit ?? options.limit ?? 10,- score_threshold: options.scoreThreshold,- filter: options.filter,- context_type: options.contextType,- telemetry: options.telemetry,- since: options.since,- until: options.until,- time_field: options.timeField,- level: options.level,- tags: options.tags,- }),+ body: mergeExtra(body, options.extra),+ });+ }+ /** Assemble injection-ready context on the server. */+ async searchContext(+ query: string,+ options: SearchContextOptions = {},+ ): Promise<SearchContextResult> {+ let imageUrl: string | undefined;+ if (typeof options.image === "string")+ imageUrl = (await nodeImagePathToDataURI(options.image)) ?? options.image;+ const body = compact({+ query,+ mode: "context",+ image_url: imageUrl,+ session_id: options.sessionId,+ limit: options.limit,+ node_limit: options.nodeLimit,+ score_threshold: options.scoreThreshold,+ filter: options.filter,+ context_type: options.contextType,+ include_provenance: options.includeProvenance,+ tags: options.tags,+ since: options.since,+ until: options.until,+ time_field: options.timeField,+ query_expansion: options.queryExpansion,+ max_tokens: options.maxTokens,+ quotas: options.quotas,+ purpose: options.purpose,+ detail: options.detail,+ dedup_turns: options.dedupTurns,+ exclude_uris: options.excludeUris,+ peer_scope: options.peerScope,+ other_peer_penalty: options.otherPeerPenalty,+ rewrite: options.rewrite,+ rewrite_max_bullets: options.rewriteMaxBullets,+ telemetry: options.telemetry,+ });+ return this.request("POST", "/api/v1/search/search", {+ body: mergeExtra(body, options.extra),});}/** Search file contents by pattern. */@@ -457,6 +535,22 @@ export class OpenVikingClient {query: { uri: normalizeURI(uri), offset, limit },});}+ /** Download raw stored bytes. */+ downloadBytes(uri: string): Promise<Uint8Array> {+ return this.transport.consume(+ "GET",+ "/api/v1/content/download",+ { query: { uri: normalizeURI(uri) } },+ async (response) => {+ if (+ !response.ok ||+ response.headers.get("content-type")?.includes("json")+ )+ return this.transport.parseResponse<never>(response);+ return new Uint8Array(await response.arrayBuffer());+ },+ );+ }/** Read L0 abstract content. */abstract(uri: string): Promise<string> {return this.request("GET", "/api/v1/content/abstract", {@@ -475,54 +569,83 @@ export class OpenVikingClient {content: string,options: WriteOptions = {},): Promise<JsonObject> {+ const body = compact({+ uri: normalizeURI(uri),+ content,+ mode: options.mode,+ processing_mode: options.processingMode,+ wait: options.wait,+ timeout: options.timeout,+ telemetry: options.telemetry,+ });return this.request("POST", "/api/v1/content/write", {- body: compact({- uri: normalizeURI(uri),- content,- mode: options.mode ?? "replace",- processing_mode: options.processingMode,- wait: options.wait ?? false,- timeout: options.timeout,- telemetry: options.telemetry,- }),+ body: mergeExtra(body, options.extra),+ });+ }+ /** Apply preconditioned file writes in one request. */+ batchWrite(+ rootUri: string,+ operations: BatchWriteOperation[],+ options: BatchWriteOptions = {},+ ): Promise<JsonObject> {+ const body = compact({+ root_uri: normalizeURI(rootUri),+ operations: operations.map((operation) =>+ compact({+ uri: normalizeURI(operation.uri),+ content: operation.content,+ content_base64: operation.contentBase64,+ precondition: compact({+ kind: operation.precondition.kind,+ base_hash: operation.precondition.baseHash,+ }),+ }),+ ),+ wait: options.wait,+ timeout: options.timeout,+ telemetry: options.telemetry,+ });+ return this.request("POST", "/api/v1/content/batch-write", {+ body: mergeExtra(body, options.extra),});}/** Set retrieval tags. */setTags(uri: string,tags: string[],- options: { mode?: string; recursive?: boolean; telemetry?: unknown } = {},+ options: SetTagsOptions = {},): Promise<JsonObject> {+ const body = compact({+ uri: normalizeURI(uri),+ tags,+ mode: options.mode ?? "replace",+ recursive: options.recursive ?? false,+ telemetry: options.telemetry,+ });return this.request("POST", "/api/v1/fs/attrs/set_tags", {- body: compact({- uri: normalizeURI(uri),- tags,- mode: options.mode ?? "replace",- recursive: options.recursive ?? false,- telemetry: options.telemetry,- }),+ body: mergeExtra(body, options.extra, [+ "uri",+ "tags",+ "mode",+ "recursive",+ "telemetry",+ ]),});}/** Rebuild indexes for a URI. */- reindex(- uri: string,- options: {- mode?: string;- wait?: boolean;- dryRun?: boolean;- tags?: string[];- tagMode?: "replace" | "append";- } = {},- ): Promise<JsonObject> {+ reindex(uri: string, options: ReindexOptions = {}): Promise<JsonObject> {+ const body = compact({+ uri: normalizeURI(uri),+ mode: options.mode ?? "vectors_only",+ wait: options.wait ?? true,+ dry_run: options.dryRun ?? false,+ recursive: options.recursive ?? true,+ tags: options.tags,+ tag_mode:+ options.tags === undefined ? undefined : (options.tagMode ?? "replace"),+ });return this.request("POST", "/api/v1/content/reindex", {- body: compact({- uri: normalizeURI(uri),- mode: options.mode ?? "vectors_only",- wait: options.wait ?? true,- dry_run: options.dryRun ?? false,- tags: options.tags,- tag_mode: options.tags === undefined ? undefined : options.tagMode ?? "replace",- }),+ body: mergeExtra(body, options.extra, ["tags", "tag_mode"]),});}@@ -537,7 +660,7 @@ export class OpenVikingClient {if ("autoCommitPolicy" in options)body.auto_commit_policy = options.autoCommitPolicy ?? null;return this.request("POST", "/api/v1/sessions", {- body,+ body: mergeExtra(body, options.extra),});}/** List sessions visible to the caller. */@@ -565,7 +688,7 @@ export class OpenVikingClient {"PATCH",`/api/v1/sessions/${pathPart(sessionId)}/config`,{- body,+ body: mergeExtra(body, options.extra),},);}@@ -618,6 +741,9 @@ export class OpenVikingClient {parts: message.parts?.length ? message.parts : undefined,created_at: message.createdAt,peer_id: message.peerId,+ turn_id: message.turnId,+ message_kind: message.messageKind,+ source_message_ids: message.sourceMessageIds,telemetry: message.telemetry,}),},@@ -628,50 +754,90 @@ export class OpenVikingClient {sessionId: string,messages: Message[],telemetry?: unknown,+ ): Promise<JsonObject>;+ batchAddMessages(+ sessionId: string,+ messages: Message[],+ options?: BatchAddMessagesOptions,): Promise<JsonObject> {+ const normalizedOptions =+ options !== null &&+ typeof options === "object" &&+ ("telemetry" in options || "extra" in options)+ ? options+ : { telemetry: options };return this.request("POST",`/api/v1/sessions/${pathPart(sessionId)}/messages/batch`,{- body: compact({- messages: messages.map((message) => {- if (message.content === undefined && !message.parts?.length) {- throw new TypeError(- "OpenViking: each message requires content or parts",- );- }- const parts = message.parts?.length ? message.parts : undefined;- return compact({- role: message.role,- content: parts ? undefined : message.content,- parts,- created_at: message.createdAt,- peer_id: message.peerId,- });+ body: mergeExtra(+ compact({+ messages: messages.map((message) => {+ if (message.content === undefined && !message.parts?.length) {+ throw new TypeError(+ "OpenViking: each message requires content or parts",+ );+ }+ const parts = message.parts?.length ? message.parts : undefined;+ return compact({+ role: message.role,+ content: parts ? undefined : message.content,+ parts,+ created_at: message.createdAt,+ peer_id: message.peerId,+ turn_id: message.turnId,+ message_kind: message.messageKind,+ source_message_ids: message.sourceMessageIds,+ });+ }),+ telemetry: normalizedOptions.telemetry,}),- telemetry,- }),+ normalizedOptions.extra,+ ),},);}/** Commit a session and extract memories. */commitSession(sessionId: string,- keepRecentCount = 0,+ keepRecentCount?: number,+ telemetry?: unknown,+ eventTags?: string[],+ ): Promise<JsonObject>;+ commitSession(+ sessionId: string,+ options?: CommitSessionOptions,+ ): Promise<JsonObject>;+ commitSession(+ sessionId: string,+ optionsOrKeepRecentCount: CommitSessionOptions | number = {},telemetry?: unknown,eventTags?: string[],): Promise<JsonObject> {+ let options: CommitSessionOptions;+ if (typeof optionsOrKeepRecentCount === "number") {+ options = { keepRecentCount: optionsOrKeepRecentCount };+ if (telemetry !== undefined) options.telemetry = telemetry;+ if (eventTags !== undefined) options.eventTags = eventTags;+ } else {+ options = optionsOrKeepRecentCount;+ }+ const body = compact({+ keep_recent_count: options.keepRecentCount,+ retention_mode: options.retentionMode,+ keep_recent_turn_count: options.keepRecentTurnCount,+ retained_message_token_budget: options.retainedMessageTokenBudget,+ min_raw_tail_steps: options.minRawTailSteps,+ extraction_metadata:+ options.eventTags === undefined+ ? undefined+ : { event: { tags: options.eventTags } },+ telemetry: options.telemetry,+ });return this.request("POST",`/api/v1/sessions/${pathPart(sessionId)}/commit`,- {- body: compact({- keep_recent_count: keepRecentCount,- telemetry,- extraction_metadata:- eventTags === undefined ? undefined : { event: { tags: eventTags } },- }),- },+ { body: mergeExtra(body, options.extra) },);}/** Export a resource subtree to a local OVPack file. */@@ -1002,4 +1168,97 @@ export class OpenVikingClient {body: { action: cleanup ? "cleanup" : "migrate" },});}+ /** Return the effective Agent Evolution switch for the caller's account. */+ adminGetAgentEvolution(): Promise<JsonObject> {+ return this.request("GET", "/api/v1/admin/agent-evolution");+ }+ /** Persist and hot-reload Agent Evolution for the caller's account. */+ adminSetAgentEvolution(enabled: boolean): Promise<JsonObject> {+ return this.request("PUT", "/api/v1/admin/agent-evolution", {+ body: { enabled },+ });+ }+ /** Return effective and explicitly overridden settings for one account. */+ adminGetAccountSettings(accountId: string): Promise<JsonObject> {+ return this.request(+ "GET",+ `/api/v1/admin/accounts/${pathPart(accountId)}/settings`,+ );+ }+ /** Update the allowlisted Agent Evolution setting for one account. */+ adminSetAccountAgentEvolution(+ accountId: string,+ enabled: boolean,+ ): Promise<JsonObject> {+ return this.request(+ "PATCH",+ `/api/v1/admin/accounts/${pathPart(accountId)}/settings`,+ { body: { agent_evolution: { enabled } } },+ );+ }+ /** List trajectories that consumed an Experience. */+ listExperienceTrajectories(+ experienceUri: string,+ options: ExperienceTrajectoryOptions = {},+ ): Promise<JsonObject> {+ return this.request(+ "GET",+ "/api/v1/agent-evolution/experiences/trajectories",+ {+ query: {+ experience_uri: normalizeURI(experienceUri),+ limit: options.limit,+ offset: options.offset,+ start_date: options.startDate,+ end_date: options.endDate,+ },+ },+ );+ }+ /** Return the outcome distribution for an Experience. */+ getExperienceOutcomes(+ experienceUri: string,+ options: ExperienceOutcomeOptions = {},+ ): Promise<JsonObject> {+ return this.request("GET", "/api/v1/agent-evolution/experiences/outcomes", {+ query: {+ experience_uri: normalizeURI(experienceUri),+ start_date: options.startDate,+ end_date: options.endDate,+ },+ });+ }+ /** Parse and validate an OpenViking Assets manifest. */+ resolveOpenVikingAssets(+ manifestYaml: string,+ options: ResolveAssetsOptions = {},+ ): Promise<JsonObject> {+ const body = compact({+ manifest_yaml: manifestYaml,+ catalog_yaml: options.catalogYaml,+ manifest_label: options.manifestLabel,+ catalog_label: options.catalogLabel,+ });+ return this.request("POST", "/api/v1/openviking-assets/resolve", {+ body: mergeExtra(body, options.extra),+ });+ }+ /** Verify read access to one Git asset. */+ preflightOpenVikingAsset(+ name: string,+ repoUrl: string,+ options: PreflightAssetOptions = {},+ ): Promise<JsonObject> {+ const body = compact({+ name,+ connector: "git",+ repo_url: repoUrl,+ branch: options.branch,+ commit: options.commit,+ auth_config: options.authConfig,+ });+ return this.request("POST", "/api/v1/openviking-assets/preflight", {+ body: mergeExtra(body, options.extra),+ });+ }}diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsindex fcd70cc3f..ffdfddd83 100644--- a/sdk/typescript/src/types.ts+++ b/sdk/typescript/src/types.ts@@ -76,6 +76,7 @@ export interface WaitOptions {export interface AddResourceOptions extends WaitOptions {to?: string;parent?: string;+ createParent?: boolean;reason?: string;instruction?: string;strict?: boolean;@@ -89,17 +90,51 @@ export interface AddResourceOptions extends WaitOptions {args?: JsonObject;tags?: string[];tagMode?: "replace" | "append";+ extra?: JsonObject;}/** Content write options. */export interface WriteOptions extends WaitOptions {mode?: string;processingMode?: ProcessingMode;+ extra?: JsonObject;}-/** Semantic retrieval options. */-export interface SearchOptions {+/** One batch-write precondition. */+export interface BatchWritePrecondition {+ kind: "create_if_absent" | "replace_if_hash";+ baseHash?: string;+}+/** One preconditioned batch-write operation. */+export interface BatchWriteOperation {+ uri: string;+ content?: string;+ contentBase64?: string;+ precondition: BatchWritePrecondition;+}+/** Batch-write request options. */+export interface BatchWriteOptions extends WaitOptions {+ extra?: JsonObject;+}+/** Retrieval tag update options. */+export interface SetTagsOptions {+ mode?: "replace" | "append";+ recursive?: boolean;+ telemetry?: unknown;+ extra?: JsonObject;+}+/** Reindex request options. */+export interface ReindexOptions {+ mode?: string;+ wait?: boolean;+ dryRun?: boolean;+ recursive?: boolean;+ tags?: string[];+ tagMode?: "replace" | "append";+ extra?: JsonObject;+}+/** Semantic retrieval options shared by find and search. */+export interface FindOptions {targetUri?: TargetURI;image?: string;- sessionId?: string;limit?: number;nodeLimit?: number;scoreThreshold?: number;@@ -111,6 +146,40 @@ export interface SearchOptions {timeField?: string;level?: number[];tags?: string[];+ includeProvenance?: boolean;+ extra?: JsonObject;+}+/** Session-aware semantic retrieval options. */+export interface SearchOptions extends FindOptions {+ sessionId?: string;+}+/** Server-side context assembly options. */+export interface SearchContextOptions {+ image?: string;+ sessionId?: string;+ limit?: number;+ nodeLimit?: number;+ scoreThreshold?: number;+ filter?: JsonObject;+ contextType?: unknown;+ includeProvenance?: boolean;+ tags?: string[];+ since?: string;+ until?: string;+ timeField?: string;+ queryExpansion?: "off" | "auto";+ maxTokens?: number;+ quotas?: Record<string, number>;+ purpose?: "chat" | "coding";+ detail?: string | Record<string, string>;+ dedupTurns?: number;+ excludeUris?: string[];+ peerScope?: "actor" | "all";+ otherPeerPenalty?: number | Record<string, number>;+ rewrite?: boolean | "auto";+ rewriteMaxBullets?: number;+ telemetry?: unknown;+ extra?: JsonObject;}/** Content grep options. */export interface GrepOptions {@@ -145,6 +214,10 @@ export interface Message {parts?: JsonObject[];createdAt?: string;peerId?: string;+ turnId?: string;+ messageKind?:+ "user_query" | "assistant_step" | "tool_transport" | "checkpoint";+ sourceMessageIds?: string[];telemetry?: unknown;}/** Session creation options. */@@ -154,6 +227,7 @@ export interface CreateSessionOptions {autoCommitPolicy?: JsonObject | null;memoryExtractionConfig?: MemoryExtractionConfig;telemetry?: unknown;+ extra?: JsonObject;}/** Event-memory extraction settings shared by session create and update. */export interface MemoryExtractionConfig {@@ -166,6 +240,54 @@ export interface UpdateSessionConfigOptions {memoryExtractionConfig?: MemoryExtractionConfig;autoCommitPolicy?: JsonObject | null;telemetry?: unknown;+ extra?: JsonObject;+}+/** Batch message request options. */+export interface BatchAddMessagesOptions {+ telemetry?: unknown;+ extra?: JsonObject;+}+/** Session commit and turn-retention options. */+export interface CommitSessionOptions {+ keepRecentCount?: number;+ retentionMode?: "turn_budget";+ keepRecentTurnCount?: number;+ retainedMessageTokenBudget?: number;+ minRawTailSteps?: number;+ eventTags?: string[];+ telemetry?: unknown;+ extra?: JsonObject;+}+/** Pagination options for Experience trajectories. */+export interface ExperienceTrajectoryOptions {+ limit?: number;+ offset?: number;+ startDate?: string;+ endDate?: string;+}+/** Date filters for Experience outcome aggregation. */+export interface ExperienceOutcomeOptions {+ startDate?: string;+ endDate?: string;+}+/** Manifest resolver options. */+export interface ResolveAssetsOptions {+ catalogYaml?: string;+ manifestLabel?: string;+ catalogLabel?: string;+ extra?: JsonObject;+}+/** One-shot Git credentials for asset preflight. */+export interface AssetGitAuth {+ username?: string;+ token?: string;+}+/** Git asset preflight options. */+export interface PreflightAssetOptions {+ branch?: string;+ commit?: string;+ authConfig?: AssetGitAuth;+ extra?: JsonObject;}/** Background task filters. */export interface TaskListOptions {@@ -189,13 +311,40 @@ export interface UpdateWatchOptions {reason?: string;instruction?: string;}+/** One retrieval hit. Only fields the retrieval pipeline populates are typed;+ * `search_tags` is surfaced under `tags` to match the tags filter parameter. */+export interface MatchedContext {+ uri?: string;+ context_type?: string;+ level?: number;+ abstract?: string;+ score?: number;+ tags?: string[];+ [key: string]: unknown;+}/** Grouped semantic retrieval results. */export interface FindResult {- memories?: unknown[];- resources?: unknown[];- skills?: unknown[];+ memories?: MatchedContext[];+ resources?: MatchedContext[];+ skills?: MatchedContext[];[key: string]: unknown;}+/** One assembled context entry. */+export interface SearchContextEntry {+ uri?: string;+ category?: string;+ score?: number;+ detail?: string;+ text?: string;+ origin?: string;+}+/** Injection-ready server-side context. */+export interface SearchContextResult {+ entries?: SearchContextEntry[];+ rendered?: string;+ digest?: string;+ stats?: JsonObject;+}/** Error payload returned by OpenViking. */export interface APIErrorInfo {code?: string;diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.tsindex bcbc408f7..8e702d3d9 100644--- a/sdk/typescript/tests/client.test.ts+++ b/sdk/typescript/tests/client.test.ts@@ -58,7 +58,188 @@ describe("OpenVikingClient", () => {});});- it("uses the Python/Go empty default retrieval target", async () => {+ it("assembles context with dedicated options and rejects mode override", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValue(+ ok({ rendered: "<memory />", entries: [], stats: {} }),+ );+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await expect(+ client.searchContext("continue refactor", {+ sessionId: "session-1",+ purpose: "coding",+ maxTokens: 3000,+ dedupTurns: 5,+ }),+ ).resolves.toMatchObject({ rendered: "<memory />" });++ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({+ query: "continue refactor",+ mode: "context",+ session_id: "session-1",+ purpose: "coding",+ max_tokens: 3000,+ dedup_turns: 5,+ });+ await expect(+ client.searchContext("query", { extra: { mode: "list" } }),+ ).rejects.toThrow(/mode/);+ });++ it("sends latest session message and retention fields", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockImplementation(async () => ok({}));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.addMessage("session-1", {+ role: "assistant",+ content: "done",+ turnId: "turn-1",+ messageKind: "assistant_step",+ sourceMessageIds: ["user-1"],+ });+ await client.commitSession("session-1", {+ retentionMode: "turn_budget",+ keepRecentTurnCount: 3,+ retainedMessageTokenBudget: 12_000,+ minRawTailSteps: 1,+ });++ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({+ role: "assistant",+ content: "done",+ turn_id: "turn-1",+ message_kind: "assistant_step",+ source_message_ids: ["user-1"],+ });+ expect(JSON.parse(String(fetcher.mock.calls[1]![1]?.body))).toEqual({+ retention_mode: "turn_budget",+ keep_recent_turn_count: 3,+ retained_message_token_budget: 12_000,+ min_raw_tail_steps: 1,+ });+ });++ it("supports legacy batch and commit session arguments", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockImplementation(async () => ok({}));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });+ const telemetry = { trace_id: "trace-1" };++ await client.batchAddMessages(+ "session-1",+ [{ role: "user", content: "hello" }],+ telemetry,+ );+ await client.commitSession(+ "session-1",+ 2,+ telemetry,+ ["team=platform"],+ );++ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({+ messages: [{ role: "user", content: "hello" }],+ telemetry,+ });+ expect(JSON.parse(String(fetcher.mock.calls[1]![1]?.body))).toEqual({+ keep_recent_count: 2,+ extraction_metadata: { event: { tags: ["team=platform"] } },+ telemetry,+ });+ });++ it("queries Agent Evolution trajectories and outcomes", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockImplementation(async () => ok({}));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.listExperienceTrajectories("user/memories/experiences/a.md", {+ limit: 25,+ offset: 50,+ startDate: "2026-08-01",+ endDate: "2026-08-10",+ });+ await client.getExperienceOutcomes("user/memories/experiences/a.md", {+ startDate: "2026-08-01",+ endDate: "2026-08-10",+ });++ const first = new URL(String(fetcher.mock.calls[0]![0]));+ const second = new URL(String(fetcher.mock.calls[1]![0]));+ expect(first.pathname).toBe(+ "/api/v1/agent-evolution/experiences/trajectories",+ );+ expect(first.searchParams.get("experience_uri")).toBe(+ "viking://user/memories/experiences/a.md",+ );+ expect(first.searchParams.get("limit")).toBe("25");+ expect(first.searchParams.get("offset")).toBe("50");+ expect(first.searchParams.get("start_date")).toBe("2026-08-01");+ expect(first.searchParams.get("end_date")).toBe("2026-08-10");+ expect(second.pathname).toBe(+ "/api/v1/agent-evolution/experiences/outcomes",+ );+ expect(second.searchParams.get("start_date")).toBe("2026-08-01");+ expect(second.searchParams.get("end_date")).toBe("2026-08-10");+ });++ it("resolves and preflights OpenViking Assets with latest Git fields", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockImplementation(async () => ok({}));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.resolveOpenVikingAssets("protocol: openviking-assets/1", {+ manifestLabel: "custom.yaml",+ extra: { future_flag: false },+ });+ await client.preflightOpenVikingAsset(+ "private-repo",+ "https://github.com/example/private.git",+ {+ branch: "main",+ commit: "0123456789abcdef",+ authConfig: { username: "oauth2", token: "secret" },+ },+ );++ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({+ manifest_yaml: "protocol: openviking-assets/1",+ manifest_label: "custom.yaml",+ future_flag: false,+ });+ expect(JSON.parse(String(fetcher.mock.calls[1]![1]?.body))).toEqual({+ name: "private-repo",+ connector: "git",+ repo_url: "https://github.com/example/private.git",+ branch: "main",+ commit: "0123456789abcdef",+ auth_config: { username: "oauth2", token: "secret" },+ });+ });++ it("omits unset retrieval options and uses server defaults", async () => {const fetcher = vi.fn<typeof fetch>().mockResolvedValue(ok({ resources: [] }));@@ -69,8 +250,27 @@ describe("OpenVikingClient", () => {await client.search("hello");- expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toMatchObject({- target_uri: "",+ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({+ query: "hello",+ });+ });++ it("preserves explicit zero and empty retrieval options", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValue(ok({ resources: [] }));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.find("hello", { limit: 0, tags: [], level: [] });++ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({+ query: "hello",+ limit: 0,+ tags: [],+ level: [],});});@@ -87,6 +287,7 @@ describe("OpenVikingClient", () => {mode: "prune_orphans",wait: true,dryRun: true,+ recursive: false,});const [url, init] = fetcher.mock.calls[0]!;@@ -96,6 +297,7 @@ describe("OpenVikingClient", () => {mode: "prune_orphans",wait: true,dry_run: true,+ recursive: false,});});@@ -119,6 +321,29 @@ describe("OpenVikingClient", () => {});});+ it("sends reindex extra fields and rejects official-field overrides", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValue(ok({ status: "completed" }));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.reindex("resources", {+ extra: { future_flag: false },+ });++ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toMatchObject({+ future_flag: false,+ });+ expect(() =>+ client.reindex("resources", {+ extra: { tags: ["team=search"] },+ }),+ ).toThrow("extra cannot override tags");+ });+it("sends processing_mode for addResource requests", async () => {const fetcher = vi.fn<typeof fetch>().mockResolvedValue(ok({}));const client = new OpenVikingClient({@@ -156,15 +381,63 @@ describe("OpenVikingClient", () => {const [url, init] = fetcher.mock.calls[0]!;expect(String(url)).toBe("https://example.com/api/v1/content/write");- expect(JSON.parse(String(init?.body))).toMatchObject({+ expect(JSON.parse(String(init?.body))).toEqual({uri: "viking://resources/demo.md",content: "updated",- mode: "replace",processing_mode: "vectors_only",wait: true,});});+ it("supports batch write, byte download, and resource extra", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockImplementationOnce(async () => ok({}))+ .mockImplementationOnce(+ async () =>+ new Response(new Uint8Array([1, 2, 3]), {+ status: 200,+ headers: { "Content-Type": "application/octet-stream" },+ }),+ )+ .mockImplementationOnce(async () => ok({}));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.batchWrite(+ "resources/project",+ [+ {+ uri: "resources/project/a.txt",+ content: "hello",+ precondition: { kind: "create_if_absent" },+ },+ ],+ { extra: { future_flag: 0 } },+ );+ await expect(+ client.downloadBytes("resources/project/a.txt"),+ ).resolves.toEqual(new Uint8Array([1, 2, 3]));+ await client.addResource("https://example.com/a.md", {+ createParent: false,+ extra: { future_flag: false },+ });++ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toMatchObject({+ root_uri: "viking://resources/project",+ future_flag: 0,+ });+ expect(+ new URL(String(fetcher.mock.calls[1]![0])).searchParams.get("uri"),+ ).toBe("viking://resources/project/a.txt");+ expect(JSON.parse(String(fetcher.mock.calls[2]![1]?.body))).toMatchObject({+ create_parent: false,+ future_flag: false,+ });+ });+it("maps response envelopes to typed errors", async () => {const fetcher = vi.fn<typeof fetch>().mockResolvedValue(new Response(@@ -250,6 +523,31 @@ describe("OpenVikingClient", () => {});});+ it("forwards setTags extra and rejects official-field overrides", async () => {+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(ok({ updated: 1 }));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.setTags("resources/demo.md", ["team=search"], {+ extra: { future_flag: false },+ });++ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({+ uri: "viking://resources/demo.md",+ tags: ["team=search"],+ mode: "replace",+ recursive: false,+ future_flag: false,+ });+ expect(() =>+ client.setTags("resources/demo.md", ["team=search"], {+ extra: { uri: "viking://other" },+ }),+ ).toThrow("extra cannot override uri");+ });+it("converts an existing Node.js image path to a data URI", async () => {const directory = await mkdtemp(join(tmpdir(), "openviking-sdk-image-"));const path = join(directory, "photo.png");@@ -331,7 +629,9 @@ describe("OpenVikingClient", () => {});it("sends event memory tag configuration for session APIs", async () => {- const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => ok({}));+ const fetcher = vi+ .fn<typeof fetch>()+ .mockImplementation(async () => ok({}));const client = new OpenVikingClient({baseUrl: "https://example.com",fetch: fetcher,@@ -345,7 +645,10 @@ describe("OpenVikingClient", () => {memoryExtractionConfig,autoCommitPolicy: { message_count_threshold: 25 },});- await client.commitSession("tagged", 0, undefined, []);+ await client.commitSession("tagged", {+ keepRecentCount: 0,+ eventTags: [],+ });expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({session_id: "tagged",diff --git a/tests/client/test_http_client_local_upload.py b/tests/client/test_http_client_local_upload.pyindex 5bed45efa..882fe2c96 100644--- a/tests/client/test_http_client_local_upload.py+++ b/tests/client/test_http_client_local_upload.py@@ -45,8 +45,6 @@ async def test_write_omits_removed_semantic_flags_from_http_payload(tmp_path, mo"content": "updated","mode": "replace","wait": True,- "timeout": None,- "telemetry": False,}@@ -90,7 +88,10 @@ async def test_add_resource_uploads_local_file_even_when_url_is_localhost(tmp_pa"result": {"root_uri": "viking://resources/demo"}}- await client.add_resource(str(resource_file), reason="test", watch_interval=60)+ await client.add_resource(+ str(resource_file),+ options={"reason": "test", "watch_interval": 60},+ )call = fake_http.calls[-1]assert call["path"] == "/api/v1/resources"diff --git a/tests/client/test_write_signature_compat.py b/tests/client/test_write_signature_compat.pyindex a64c3e2bc..3355e2a1e 100644--- a/tests/client/test_write_signature_compat.py+++ b/tests/client/test_write_signature_compat.py@@ -1,33 +1,52 @@import inspect-from openviking_sdk.client import AsyncHTTPClient, SyncHTTPClient+from openviking_sdk.client import (+ AsyncHTTPClient,+ Session,+ SyncHTTPClient,+ SyncSession,+)-def test_async_http_client_write_preserves_positional_telemetry():- bound = inspect.signature(AsyncHTTPClient.write).bind_partial(- object(),- "viking://resources/demo.md",- "updated",- "append",- True,- 3.0,- False,+def test_async_http_client_core_methods_allow_positional_options():+ inspect.signature(AsyncHTTPClient.add_resource).bind_partial(+ object(), "source.md", "viking://resources/", None, True, 60, {}+ )+ inspect.signature(AsyncHTTPClient.find).bind_partial(+ object(), "query", "viking://resources/", 5, {"level": [1]}+ )+ inspect.signature(AsyncHTTPClient.search).bind_partial(+ object(), "query", "session-1", "viking://resources/", 5, {}+ )+ inspect.signature(AsyncHTTPClient.write).bind_partial(+ object(), "viking://resources/demo.md", "updated", "append", True, 60, {}+ )+ inspect.signature(AsyncHTTPClient.add_message).bind_partial(+ object(), "session-1", "user", "hello", None, {})- assert bound.arguments["telemetry"] is False- assert "processing_mode" not in bound.arguments+def test_sync_http_client_core_methods_allow_positional_options():+ inspect.signature(SyncHTTPClient.add_resource).bind_partial(+ object(), "source.md", "viking://resources/", None, True, 60, {}+ )+ inspect.signature(SyncHTTPClient.find).bind_partial(+ object(), "query", "viking://resources/", 5, {"level": [1]}+ )+ inspect.signature(SyncHTTPClient.search).bind_partial(+ object(), "query", "session-1", "viking://resources/", 5, {}+ )+ inspect.signature(SyncHTTPClient.write).bind_partial(+ object(), "viking://resources/demo.md", "updated", "append", True, 60, {}+ )+ inspect.signature(SyncHTTPClient.add_message).bind_partial(+ object(), "session-1", "user", "hello", None, {}+ )-def test_sync_http_client_write_preserves_positional_telemetry():- bound = inspect.signature(SyncHTTPClient.write).bind_partial(- object(),- "viking://resources/demo.md",- "updated",- "append",- True,- 3.0,- False,+def test_session_message_methods_allow_positional_options():+ inspect.signature(Session.add_message).bind_partial(+ object(), "user", "hello", None, {}+ )+ inspect.signature(SyncSession.add_message).bind_partial(+ object(), "user", "hello", None, {})-- assert bound.arguments["telemetry"] is False- assert "processing_mode" not in bound.argumentsdiff --git a/tests/unit/test_langchain_async_integration.py b/tests/unit/test_langchain_async_integration.pyindex c444b935b..38a99faf8 100644--- a/tests/unit/test_langchain_async_integration.py+++ b/tests/unit/test_langchain_async_integration.py@@ -205,6 +205,37 @@ async def test_injected_async_client_is_initialized_only_once_across_adapters():assert client.initialize_calls == 1+async def test_acall_openviking_adapts_flat_kwargs_to_sdk_options():+ calls = []++ class OptionsClient:+ async def search(self, query, options=None):+ calls.append((query, options))+ return {"query": query}++ result = await acall_openviking(+ OptionsClient(),+ "search",+ query="recover",+ session_id="session-1",+ limit=5,+ include_provenance=False,+ )++ assert result == {"query": "recover"}+ assert calls == [+ (+ "recover",+ {+ "session_id": "session-1",+ "limit": 5,+ "include_provenance": False,+ },+ )+ ]++@pytest.mark.asyncioasync def test_shared_injected_async_client_initializes_once_across_real_adapters():class SharedAsyncClient:diff --git a/tests/unit/test_langchain_integration.py b/tests/unit/test_langchain_integration.pyindex 424b70bb1..d63cc62ba 100644--- a/tests/unit/test_langchain_integration.py+++ b/tests/unit/test_langchain_integration.py@@ -518,6 +518,73 @@ def test_openviking_client_handle_filters_kwargs_for_direct_calls(monkeypatch):assert result == {"query": "recover"}+def test_call_openviking_adapts_flat_kwargs_to_sdk_options():+ calls = []++ class OptionsClient:+ def find(self, query, options=None):+ calls.append(("find", query, options))+ return {"query": query}++ def create_session(self, options=None):+ calls.append(("create_session", options))+ return {"session_id": options["session_id"]}++ def add_message(self, session_id, message):+ calls.append(("add_message", session_id, message))+ return {"ok": True}++ def write(self, uri, content, options=None):+ calls.append(("write", uri, content, options))+ return {"ok": True}++ client = OptionsClient()++ call_openviking(+ client,+ "find",+ query="recover",+ target_uri="viking://resources",+ limit=5,+ )+ call_openviking(client, "create_session", session_id="session-1")+ call_openviking(+ client,+ "add_message",+ session_id="session-1",+ role="user",+ content="hello",+ )+ call_openviking(+ client,+ "write",+ uri="viking://resources/a.md",+ content="hello",+ mode="replace",+ wait=False,+ )++ assert calls == [+ (+ "find",+ "recover",+ {"target_uri": "viking://resources", "limit": 5},+ ),+ ("create_session", {"session_id": "session-1"}),+ (+ "add_message",+ "session-1",+ {"role": "user", "content": "hello"},+ ),+ (+ "write",+ "viking://resources/a.md",+ "hello",+ {"mode": "replace", "wait": False},+ ),+ ]++def test_openviking_client_evicts_but_does_not_retry_mutating_call(monkeypatch):instances = []