Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat: extract standalone python http sdk (#2736)

Jiahui Zhou02f06488f3a2
diff --git a/.github/workflows/python-sdk-release.yml b/.github/workflows/python-sdk-release.yml
new file mode 100644
index 000000000..2aef3ec66
--- /dev/null
+++ b/.github/workflows/python-sdk-release.yml
@@ -0,0 +1,137 @@
+name: Python SDK Release
+
+on:
+ push:
+ tags:
+ - "python-sdk/v*"
+ workflow_dispatch:
+ inputs:
+ target:
+ description: "Publish target"
+ required: true
+ type: choice
+ default: "testpypi"
+ options:
+ - testpypi
+ - pypi
+ - both
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ build-sdk:
+ name: Build openviking-sdk
+ runs-on: ubuntu-24.04
+ outputs:
+ sdk_version: ${{ steps.version.outputs.sdk_version }}
+ publish_target: ${{ steps.target.outputs.publish_target }}
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+
+ - name: Fetch all tags
+ run: git fetch --force --tags
+
+ - name: Set publish target
+ id: target
+ run: |
+ if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
+ echo "publish_target=${{ inputs.target }}" >> "$GITHUB_OUTPUT"
+ else
+ echo "publish_target=pypi" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ with:
+ python-version: "3.12"
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@v7
+ with:
+ enable-cache: true
+
+ - name: Install build dependencies
+ working-directory: sdk/python
+ run: uv pip install --system build setuptools setuptools-scm wheel
+
+ - name: Resolve SDK version
+ id: version
+ working-directory: sdk/python
+ run: |
+ SDK_VERSION=$(python -m setuptools_scm)
+ echo "sdk_version=$SDK_VERSION" >> "$GITHUB_OUTPUT"
+ echo "Resolved SDK version: $SDK_VERSION"
+
+ - name: Validate tag matches SDK version
+ if: github.event_name == 'push'
+ env:
+ TAG_NAME: ${{ github.ref_name }}
+ SDK_VERSION: ${{ steps.version.outputs.sdk_version }}
+ run: |
+ EXPECTED_TAG="python-sdk/v${SDK_VERSION}"
+ if [ "$TAG_NAME" != "$EXPECTED_TAG" ]; then
+ echo "Tag $TAG_NAME does not match resolved SDK version $SDK_VERSION"
+ exit 1
+ fi
+
+ - name: Build SDK distributions
+ working-directory: sdk/python
+ run: python -m build
+
+ - name: Upload SDK distributions
+ uses: actions/upload-artifact@v7
+ with:
+ name: python-sdk-distributions
+ path: sdk/python/dist/*
+
+ publish-testpypi:
+ name: Publish SDK to TestPyPI
+ needs: [build-sdk]
+ if: needs.build-sdk.outputs.publish_target == 'testpypi' || needs.build-sdk.outputs.publish_target == 'both'
+ runs-on: ubuntu-24.04
+ environment:
+ name: testpypi
+ url: https://test.pypi.org/p/openviking-sdk
+ permissions:
+ id-token: write
+ steps:
+ - name: Download SDK distributions
+ uses: actions/download-artifact@v8
+ with:
+ name: python-sdk-distributions
+ path: dist/
+
+ - name: Publish SDK to TestPyPI
+ uses: pypa/gh-action-pypi-publish@release/v1
+ with:
+ repository-url: https://test.pypi.org/legacy/
+ skip-existing: true
+ verbose: true
+
+ publish-pypi:
+ name: Publish SDK to PyPI
+ needs: [build-sdk]
+ if: needs.build-sdk.outputs.publish_target == 'pypi' || needs.build-sdk.outputs.publish_target == 'both'
+ runs-on: ubuntu-24.04
+ environment:
+ name: pypi
+ url: https://pypi.org/p/openviking-sdk
+ permissions:
+ id-token: write
+ steps:
+ - name: Download SDK distributions
+ uses: actions/download-artifact@v8
+ with:
+ name: python-sdk-distributions
+ path: dist/
+
+ - name: Publish SDK to PyPI
+ uses: pypa/gh-action-pypi-publish@release/v1
+ with:
+ skip-existing: true
+ verbose: true
diff --git a/openviking/_sdk_import.py b/openviking/_sdk_import.py
new file mode 100644
index 000000000..1c12f78db
--- /dev/null
+++ b/openviking/_sdk_import.py
@@ -0,0 +1,24 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+from __future__ import annotations
+
+import sys
+from importlib import import_module
+from pathlib import Path
+
+
+def import_openviking_sdk():
+ try:
+ return import_module("openviking_sdk")
+ except ImportError as exc:
+ sdk_root = Path(__file__).resolve().parents[1] / "sdk" / "python"
+ if str(sdk_root) not in sys.path:
+ sys.path.insert(0, str(sdk_root))
+ try:
+ return import_module("openviking_sdk")
+ except ImportError:
+ raise ImportError(
+ "openviking-sdk is required for HTTP client usage. "
+ "Install it with the main package or run 'pip install -e sdk/python' "
+ "when developing from the repository."
+ ) from exc
diff --git a/openviking/client.py b/openviking/client.py
index 21d9839d4..9492911ef 100644
--- a/openviking/client.py
+++ b/openviking/client.py
@@ -5,9 +5,34 @@ OpenViking client.
This module provides both synchronous and asynchronous clients.
"""
-from openviking.async_client import AsyncOpenViking
-from openviking.sync_client import SyncOpenViking
-from openviking_cli.client.http import AsyncHTTPClient
-from openviking_cli.client.sync_http import SyncHTTPClient
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from openviking.async_client import AsyncOpenViking
+ from openviking.sync_client import SyncOpenViking
+ from openviking_cli.client.http import AsyncHTTPClient
+ from openviking_cli.client.sync_http import SyncHTTPClient
__all__ = ["SyncOpenViking", "AsyncOpenViking", "SyncHTTPClient", "AsyncHTTPClient"]
+
+
+def __getattr__(name: str):
+ if name == "AsyncOpenViking":
+ from openviking.async_client import AsyncOpenViking
+
+ return AsyncOpenViking
+ if name == "SyncOpenViking":
+ from openviking.sync_client import SyncOpenViking
+
+ return SyncOpenViking
+ if name == "AsyncHTTPClient":
+ from openviking_cli.client.http import AsyncHTTPClient
+
+ return AsyncHTTPClient
+ if name == "SyncHTTPClient":
+ from openviking_cli.client.sync_http import SyncHTTPClient
+
+ return SyncHTTPClient
+ raise AttributeError(name)
diff --git a/openviking/client/__init__.py b/openviking/client/__init__.py
index f12af9d3c..c6ccc08f8 100644
--- a/openviking/client/__init__.py
+++ b/openviking/client/__init__.py
@@ -5,11 +5,16 @@
Provides client implementations for embedded (LocalClient) and HTTP (AsyncHTTPClient/SyncHTTPClient) modes.
"""
-from openviking.client.local import LocalClient
-from openviking.client.session import Session
-from openviking_cli.client.base import BaseClient
-from openviking_cli.client.http import AsyncHTTPClient
-from openviking_cli.client.sync_http import SyncHTTPClient
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from openviking.client.local import LocalClient
+ from openviking.client.session import Session
+ from openviking_cli.client.base import BaseClient
+ from openviking_cli.client.http import AsyncHTTPClient
+ from openviking_cli.client.sync_http import SyncHTTPClient
__all__ = [
"BaseClient",
@@ -18,3 +23,27 @@ __all__ = [
"LocalClient",
"Session",
]
+
+
+def __getattr__(name: str):
+ if name == "AsyncHTTPClient":
+ from openviking_cli.client.http import AsyncHTTPClient
+
+ return AsyncHTTPClient
+ if name == "SyncHTTPClient":
+ from openviking_cli.client.sync_http import SyncHTTPClient
+
+ return SyncHTTPClient
+ if name == "LocalClient":
+ from openviking.client.local import LocalClient
+
+ return LocalClient
+ if name == "Session":
+ from openviking.client.session import Session
+
+ return Session
+ if name == "BaseClient":
+ from openviking_cli.client.base import BaseClient
+
+ return BaseClient
+ raise AttributeError(name)
diff --git a/openviking_cli/_sdk_import.py b/openviking_cli/_sdk_import.py
new file mode 100644
index 000000000..1c12f78db
--- /dev/null
+++ b/openviking_cli/_sdk_import.py
@@ -0,0 +1,24 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+from __future__ import annotations
+
+import sys
+from importlib import import_module
+from pathlib import Path
+
+
+def import_openviking_sdk():
+ try:
+ return import_module("openviking_sdk")
+ except ImportError as exc:
+ sdk_root = Path(__file__).resolve().parents[1] / "sdk" / "python"
+ if str(sdk_root) not in sys.path:
+ sys.path.insert(0, str(sdk_root))
+ try:
+ return import_module("openviking_sdk")
+ except ImportError:
+ raise ImportError(
+ "openviking-sdk is required for HTTP client usage. "
+ "Install it with the main package or run 'pip install -e sdk/python' "
+ "when developing from the repository."
+ ) from exc
diff --git a/openviking_cli/client/_http_compat.py b/openviking_cli/client/_http_compat.py
new file mode 100644
index 000000000..7d6376858
--- /dev/null
+++ b/openviking_cli/client/_http_compat.py
@@ -0,0 +1,96 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Compatibility bridge for legacy HTTP client entry points."""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from openviking_cli._sdk_import import import_openviking_sdk
+from openviking_cli.exceptions import (
+ AbortedError,
+ AlreadyExistsError,
+ ConflictError,
+ DeadlineExceededError,
+ EmbeddingFailedError,
+ FailedPreconditionError,
+ InternalError,
+ InvalidArgumentError,
+ InvalidURIError,
+ NotFoundError,
+ NotInitializedError,
+ OpenVikingError,
+ PermissionDeniedError,
+ ProcessingError,
+ ResourceExhaustedError,
+ SessionExpiredError,
+ UnauthenticatedError,
+ UnavailableError,
+ UnimplementedError,
+ VLMFailedError,
+)
+
+ERROR_CODE_TO_EXCEPTION = {
+ "INVALID_ARGUMENT": InvalidArgumentError,
+ "INVALID_URI": InvalidURIError,
+ "NOT_FOUND": NotFoundError,
+ "ALREADY_EXISTS": AlreadyExistsError,
+ "CONFLICT": ConflictError,
+ "FAILED_PRECONDITION": FailedPreconditionError,
+ "ABORTED": AbortedError,
+ "UNAUTHENTICATED": UnauthenticatedError,
+ "PERMISSION_DENIED": PermissionDeniedError,
+ "RESOURCE_EXHAUSTED": ResourceExhaustedError,
+ "UNAVAILABLE": UnavailableError,
+ "INTERNAL": InternalError,
+ "DEADLINE_EXCEEDED": DeadlineExceededError,
+ "UNIMPLEMENTED": UnimplementedError,
+ "NOT_INITIALIZED": NotInitializedError,
+ "PROCESSING_ERROR": ProcessingError,
+ "EMBEDDING_FAILED": EmbeddingFailedError,
+ "VLM_FAILED": VLMFailedError,
+ "SESSION_EXPIRED": SessionExpiredError,
+ "UNKNOWN": OpenVikingError,
+}
+
+
+def _raise_legacy_exception(error: Dict[str, Any]) -> None:
+ code = error.get("code", "UNKNOWN")
+ message = error.get("message", "Unknown error")
+ details = error.get("details")
+ exc_class = ERROR_CODE_TO_EXCEPTION.get(code, OpenVikingError)
+
+ if exc_class == OpenVikingError:
+ raise exc_class(message, code=code, details=details)
+ if exc_class in (
+ InvalidArgumentError,
+ FailedPreconditionError,
+ ResourceExhaustedError,
+ AbortedError,
+ UnimplementedError,
+ ):
+ raise exc_class(message, details=details)
+ if exc_class == InvalidURIError:
+ uri = details.get("uri", "") if details else ""
+ reason = details.get("reason", "") if details else ""
+ raise exc_class(uri, reason)
+ if exc_class == NotFoundError:
+ resource = details.get("resource", "") if details else ""
+ resource_type = details.get("type", "resource") if details else "resource"
+ raise exc_class(resource, resource_type)
+ if exc_class == AlreadyExistsError:
+ resource = details.get("resource", "") if details else ""
+ resource_type = details.get("type", "resource") if details else "resource"
+ raise exc_class(resource, resource_type)
+ raise exc_class(message)
+
+
+class AsyncHTTPClient(import_openviking_sdk().AsyncHTTPClient):
+ def _raise_exception(self, error: Dict[str, Any]) -> None:
+ _raise_legacy_exception(error)
+
+
+class SyncHTTPClient(import_openviking_sdk().SyncHTTPClient):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._async_client = AsyncHTTPClient(*args, **kwargs)
diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.py
index ed7bcecfa..b0b57206b 100644
--- a/openviking_cli/client/http.py
+++ b/openviking_cli/client/http.py
@@ -1,1608 +1,7 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-"""Async HTTP Client for OpenViking.
+"""Compatibility shim for the legacy HTTP client import path."""
-Implements BaseClient interface using HTTP calls to OpenViking Server.
-"""
+from openviking_cli.client._http_compat import ERROR_CODE_TO_EXCEPTION, AsyncHTTPClient
-import tempfile
-import uuid
-import zipfile
-from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
-from urllib.parse import quote
-
-import httpx
-
-from openviking.core.peer_id import normalize_peer_selector
-from openviking.telemetry import TelemetryRequest, normalize_telemetry_request
-from openviking.utils.search_filters import SearchContextTypeInput
-from openviking_cli.client.base import BaseClient
-from openviking_cli.exceptions import (
- AbortedError,
- AlreadyExistsError,
- ConflictError,
- DeadlineExceededError,
- EmbeddingFailedError,
- FailedPreconditionError,
- InternalError,
- InvalidArgumentError,
- InvalidURIError,
- NotFoundError,
- NotInitializedError,
- OpenVikingError,
- PermissionDeniedError,
- ProcessingError,
- ResourceExhaustedError,
- SessionExpiredError,
- UnauthenticatedError,
- UnavailableError,
- UnimplementedError,
- VLMFailedError,
-)
-from openviking_cli.retrieve.types import FindResult
-from openviking_cli.session.user_id import UserIdentifier
-from openviking_cli.utils import get_logger, run_async
-from openviking_cli.utils.config.ovcli_config import load_ovcli_config
-from openviking_cli.utils.uri import VikingURI
-
-# Error code to exception class mapping
-ERROR_CODE_TO_EXCEPTION = {
- "INVALID_ARGUMENT": InvalidArgumentError,
- "INVALID_URI": InvalidURIError,
- "NOT_FOUND": NotFoundError,
- "ALREADY_EXISTS": AlreadyExistsError,
- "CONFLICT": ConflictError,
- "FAILED_PRECONDITION": FailedPreconditionError,
- "ABORTED": AbortedError,
- "UNAUTHENTICATED": UnauthenticatedError,
- "PERMISSION_DENIED": PermissionDeniedError,
- "RESOURCE_EXHAUSTED": ResourceExhaustedError,
- "UNAVAILABLE": UnavailableError,
- "INTERNAL": InternalError,
- "DEADLINE_EXCEEDED": DeadlineExceededError,
- "UNIMPLEMENTED": UnimplementedError,
- "NOT_INITIALIZED": NotInitializedError,
- "PROCESSING_ERROR": ProcessingError,
- "EMBEDDING_FAILED": EmbeddingFailedError,
- "VLM_FAILED": VLMFailedError,
- "SESSION_EXPIRED": SessionExpiredError,
- "UNKNOWN": OpenVikingError,
-}
-
-logger = get_logger(__name__)
-
-
-class _HTTPObserver:
- """Observer proxy for HTTP mode.
-
- Provides the same interface as the local observer but fetches data via HTTP.
- """
-
- def __init__(self, client: "AsyncHTTPClient"):
- self._client = client
- self._cache = {}
-
- async def _fetch_queue_status(self) -> Dict[str, Any]:
- """Fetch queue status asynchronously."""
- return await self._client._get_queue_status()
-
- async def _fetch_vikingdb_status(self) -> Dict[str, Any]:
- """Fetch VikingDB status asynchronously."""
- return await self._client._get_vikingdb_status()
-
- async def _fetch_models_status(self) -> Dict[str, Any]:
- """Fetch models status asynchronously."""
- return await self._client._get_models_status()
-
- async def _fetch_system_status(self) -> Dict[str, Any]:
- """Fetch system status asynchronously."""
- return await self._client._get_system_status()
-
- @property
- def queue(self) -> Dict[str, Any]:
- """Get queue system status (sync wrapper)."""
- return run_async(self._fetch_queue_status())
-
- @property
- def vikingdb(self) -> Dict[str, Any]:
- """Get VikingDB status (sync wrapper)."""
- return run_async(self._fetch_vikingdb_status())
-
- @property
- def models(self) -> Dict[str, Any]:
- """Get models status (VLM, Embedding, Rerank) (sync wrapper)."""
- return run_async(self._fetch_models_status())
-
- @property
- def system(self) -> Dict[str, Any]:
- """Get system overall status (sync wrapper)."""
- return run_async(self._fetch_system_status())
-
- def is_healthy(self) -> bool:
- """Check if system is healthy."""
- status = self.system
- return status.get("is_healthy", False)
-
-
-class AsyncHTTPClient(BaseClient):
- """Async HTTP Client for OpenViking Server.
-
- Implements BaseClient interface using HTTP calls.
- Supports auto-loading url/api_key from ovcli.conf when not provided.
-
- Examples:
- # Explicit url
- client = AsyncHTTPClient(url="http://localhost:1933", api_key="key")
-
- # Auto-load from ~/.openviking/ovcli.conf
- client = AsyncHTTPClient()
- """
-
- def __init__(
- self,
- url: Optional[str] = None,
- api_key: Optional[str] = None,
- user_id: Optional[str] = None,
- account: Optional[str] = None,
- user: Optional[str] = None,
- actor_peer_id: Optional[str] = None,
- agent_id: Optional[str] = None,
- timeout: float = 60.0,
- extra_headers: Optional[Dict[str, str]] = None,
- profile_enabled: Optional[bool] = None,
- ):
- """Initialize AsyncHTTPClient.
-
- Args:
- url: OpenViking Server URL. If not provided, reads from ovcli.conf.
- api_key: API key for authentication. If not provided, reads from ovcli.conf.
- user_id: User identifier. If not provided, defaults to "default".
- account: Optional account identity header for trusted deployments.
- user: Optional user identity header for trusted deployments.
- actor_peer_id: Optional peer actor scope header.
- agent_id: Legacy alias for actor_peer_id.
- timeout: HTTP request timeout in seconds. Default 60.0.
- extra_headers: Additional HTTP headers to send with requests. If not provided, reads from ovcli.conf.
- """
- effective_user = user if user is not None else user_id
- profile_load_requested = profile_enabled is None
- should_load_cli_config = profile_enabled is not False and (
- url is None
- or api_key is None
- or account is None
- or effective_user is None
- or (actor_peer_id is None and agent_id is None)
- or timeout == 60.0
- or extra_headers is None
- )
- cli_config = None
- if should_load_cli_config:
- cli_config = load_ovcli_config()
- if cli_config is not None:
- url = url or cli_config.url
- api_key = api_key or cli_config.api_key
- account = account or cli_config.account
- effective_user = effective_user or cli_config.user
- if actor_peer_id is None and agent_id is None:
- actor_peer_id = cli_config.actor_peer_id
- agent_id = cli_config.agent_id
- if timeout == 60.0: # only override default with config value
- timeout = cli_config.timeout
- if extra_headers is None:
- extra_headers = cli_config.extra_headers
- if profile_load_requested:
- if cli_config is None:
- cli_config = load_ovcli_config()
- if cli_config is not None:
- profile_enabled = cli_config.profile
- if not url:
- raise ValueError(
- "url is required. Pass it explicitly or configure in "
- '~/.openviking/ovcli.conf (key: "url").'
- )
- self._url = url.rstrip("/")
- self._api_key = api_key
- self._account = account
- self._user_id = effective_user
- if actor_peer_id and agent_id:
- raise ValueError("actor_peer_id cannot be used with legacy agent_id")
- self._legacy_agent_id = normalize_peer_selector(None, agent_id=agent_id)
- self._actor_peer_id = normalize_peer_selector(actor_peer_id, agent_id=agent_id)
- self._user = UserIdentifier.the_default_user()
- self._timeout = timeout
- self._extra_headers = extra_headers
- self._profile_enabled = bool(profile_enabled)
- self._upload_mode = None
- if should_load_cli_config and cli_config is not None and cli_config.upload is not None:
- self._upload_mode = cli_config.upload.mode
- self._http: Optional[httpx.AsyncClient] = None
- self._observer: Optional[_HTTPObserver] = None
-
- # ============= Lifecycle =============
-
- async def initialize(self) -> None:
- """Initialize the HTTP client."""
- headers = {}
- if self._api_key:
- headers["X-API-Key"] = self._api_key
- if self._account:
- headers["X-OpenViking-Account"] = self._account
- if self._user_id:
- headers["X-OpenViking-User"] = self._user_id
- if self._actor_peer_id:
- headers["X-OpenViking-Actor-Peer"] = self._actor_peer_id
- if self._extra_headers:
- headers.update(self._extra_headers)
- self._http = httpx.AsyncClient(
- base_url=self._url,
- headers=headers,
- timeout=self._timeout,
- params={"profile": "1"} if self._profile_enabled else None,
- )
- self._observer = _HTTPObserver(self)
-
- async def close(self) -> None:
- """Close the HTTP client."""
- if self._http:
- try:
- await self._http.aclose()
- except RuntimeError:
- pass
- self._http = None
-
- # ============= Internal Helpers =============
-
- def _handle_response_data(self, response: httpx.Response) -> Dict[str, Any]:
- """Handle HTTP response and return the decoded response envelope."""
- try:
- data = response.json()
- except Exception:
- if not response.is_success:
- raise OpenVikingError(
- f"HTTP {response.status_code}: {response.text or 'empty response'}",
- code="INTERNAL",
- )
- return {}
- if data.get("status") == "error":
- self._raise_exception(data.get("error", {}))
- if not response.is_success:
- raise OpenVikingError(
- data.get("detail", f"HTTP {response.status_code}"),
- code="UNKNOWN",
- )
- return data
-
- def _handle_response(self, response: httpx.Response) -> Any:
- """Handle HTTP response and extract result or raise exception."""
- return self._handle_response_data(response).get("result")
-
- @staticmethod
- def _validate_telemetry(telemetry: TelemetryRequest) -> TelemetryRequest:
- normalize_telemetry_request(telemetry)
- return telemetry
-
- @staticmethod
- def _path_segment(value: str) -> str:
- """Encode a value for safe use as one URL path segment."""
- return quote(value, safe="")
-
- @staticmethod
- def _normalize_target_uri(
- target_uri: Union[str, List[str]],
- ) -> Union[str, List[str]]:
- """Normalize target_uri for the search endpoints.
-
- Accepts either a single string or a list of strings and applies
- ``VikingURI.normalize`` to each non-empty entry.
- """
- if isinstance(target_uri, list):
- return [VikingURI.normalize(u) if u else u for u in target_uri]
- if target_uri:
- return VikingURI.normalize(target_uri)
- return target_uri
-
- @staticmethod
- def _attach_telemetry(result: Any, response_data: Dict[str, Any]) -> Any:
- telemetry = response_data.get("telemetry")
- if telemetry is None:
- return result
-
- if result is None:
- payload: Dict[str, Any] = {}
- payload["telemetry"] = telemetry
- return payload
-
- if isinstance(result, dict):
- result["telemetry"] = telemetry
- return result
-
- return result
-
- def _attach_legacy_agent_scope(self, payload: Dict[str, Any]) -> Dict[str, Any]:
- if self._legacy_agent_id:
- payload["agent_id"] = self._legacy_agent_id
- return payload
-
- def _attach_legacy_message_scope(self, payload: Dict[str, Any]) -> Dict[str, Any]:
- if not self._legacy_agent_id:
- return payload
- if payload.get("peer_id") is not None:
- raise InvalidArgumentError(
- "peer_id cannot be used when client is configured with legacy agent_id"
- )
- if payload.get("role") == "assistant":
- payload["agent_id"] = self._legacy_agent_id
- return payload
-
- def _batch_message_payloads(self, messages: list[dict]) -> list[dict]:
- if not self._legacy_agent_id:
- return messages
- scoped_messages = []
- for message in messages:
- payload = dict(message)
- scoped_messages.append(self._attach_legacy_message_scope(payload))
- return scoped_messages
-
- def _raise_exception(self, error: Dict[str, Any]) -> None:
- """Raise appropriate exception based on error code."""
- code = error.get("code", "UNKNOWN")
- message = error.get("message", "Unknown error")
- details = error.get("details")
-
- exc_class = ERROR_CODE_TO_EXCEPTION.get(code, OpenVikingError)
-
- # Handle different exception constructors
- if exc_class == OpenVikingError:
- raise exc_class(message, code=code, details=details)
- elif exc_class in (
- InvalidArgumentError,
- FailedPreconditionError,
- ResourceExhaustedError,
- AbortedError,
- UnimplementedError,
- ):
- raise exc_class(message, details=details)
- elif exc_class == InvalidURIError:
- uri = details.get("uri", "") if details else ""
- reason = details.get("reason", "") if details else ""
- raise exc_class(uri, reason)
- elif exc_class == NotFoundError:
- resource = details.get("resource", "") if details else ""
- resource_type = details.get("type", "resource") if details else "resource"
- raise exc_class(resource, resource_type)
- elif exc_class == AlreadyExistsError:
- resource = details.get("resource", "") if details else ""
- resource_type = details.get("type", "resource") if details else "resource"
- raise exc_class(resource, resource_type)
- else:
- raise exc_class(message)
-
- def _zip_directory(self, dir_path: str) -> str:
- """Create a temporary zip file from a directory."""
- dir_path = Path(dir_path)
- if not dir_path.is_dir():
- raise ValueError(f"Path {dir_path} is not a directory")
-
- root = dir_path.resolve()
- temp_dir = tempfile.gettempdir()
- zip_path = Path(temp_dir) / f"temp_upload_{uuid.uuid4().hex}.zip"
-
- entry_count = 0
- with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
- for file_path in dir_path.rglob("*"):
- if file_path.is_symlink():
- continue
- if file_path.is_file():
- # Defense-in-depth: drop files whose real path escapes the selected root
- # if traversal behavior changes or this walk implementation is replaced.
- if not file_path.resolve().is_relative_to(root):
- continue
- arcname = str(file_path.relative_to(dir_path)).replace("\\", "/")
- zipf.write(file_path, arcname=arcname)
- entry_count += 1
-
- if entry_count == 0:
- logger.warning("Created empty directory upload archive for %s", dir_path)
-
- return str(zip_path)
-
- async def _upload_temp_file(self, file_path: str) -> str:
- """Upload a file to /api/v1/resources/temp_upload and return the temp_file_id."""
- with open(file_path, "rb") as f:
- files = {"file": (Path(file_path).name, f, "application/octet-stream")}
- data = None
- if self._upload_mode:
- data = {"upload_mode": self._upload_mode}
- response = await self._http.post(
- "/api/v1/resources/temp_upload",
- files=files,
- data=data,
- )
- result = self._handle_response(response)
- return result.get("temp_file_id", "")
-
- # ============= Resource Management =============
-
- async def add_resource(
- self,
- 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: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Add resource to OpenViking."""
- telemetry = self._validate_telemetry(telemetry)
- if to and parent:
- raise ValueError("Cannot specify both 'to' and 'parent' at the same time.")
-
- request_data = {
- "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 preserve_structure is not None:
- request_data["preserve_structure"] = preserve_structure
-
- path_obj = Path(path)
- if path_obj.exists():
- if path_obj.is_dir():
- source_name = path_obj.name
- request_data["source_name"] = source_name
- zip_path = self._zip_directory(path)
- try:
- temp_file_id = await self._upload_temp_file(zip_path)
- request_data["temp_file_id"] = temp_file_id
- finally:
- Path(zip_path).unlink(missing_ok=True)
- elif path_obj.is_file():
- request_data["source_name"] = path_obj.name
- temp_file_id = await self._upload_temp_file(path)
- request_data["temp_file_id"] = temp_file_id
- else:
- request_data["path"] = path
- else:
- request_data["path"] = path
-
- response = await self._http.post(
- "/api/v1/resources",
- json=request_data,
- )
- response_data = self._handle_response_data(response)
- return self._attach_telemetry(response_data.get("result"), response_data)
-
- async def batch_add_messages(
- self,
- session_id: str,
- messages: list[dict],
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Add multiple messages to a session in a single request.
-
- Args:
- session_id: Session ID
- messages: List of message dicts, each with "role" and optionally
- "content", "parts", "created_at", "peer_id".
- telemetry: Whether to attach operation telemetry data to the result.
-
- Returns:
- Result dict with session_id, message_count, and added count.
- """
- telemetry = self._validate_telemetry(telemetry)
- payload: Dict[str, Any] = {"messages": self._batch_message_payloads(messages)}
- if telemetry is not False:
- payload["telemetry"] = telemetry
-
- session_path = self._path_segment(session_id)
- response = await self._http.post(
- f"/api/v1/sessions/{session_path}/messages/batch",
- json=payload,
- )
- response_data = self._handle_response_data(response)
- return self._attach_telemetry(response_data.get("result"), response_data)
-
- async def add_skill(
- self,
- data: Any,
- wait: bool = False,
- timeout: Optional[float] = None,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Add skill to OpenViking."""
- telemetry = self._validate_telemetry(telemetry)
- request_data = {
- "wait": wait,
- "timeout": timeout,
- }
-
- if isinstance(data, str):
- path_obj = Path(data)
- if path_obj.exists():
- if path_obj.is_dir():
- zip_path = self._zip_directory(data)
- try:
- temp_file_id = await self._upload_temp_file(zip_path)
- request_data["temp_file_id"] = temp_file_id
- finally:
- Path(zip_path).unlink(missing_ok=True)
- elif path_obj.is_file():
- temp_file_id = await self._upload_temp_file(data)
- request_data["temp_file_id"] = temp_file_id
- else:
- request_data["data"] = data
- else:
- request_data["data"] = data
- else:
- request_data["data"] = data
-
- response = await self._http.post(
- "/api/v1/skills",
- json={**request_data, "telemetry": telemetry},
- )
- response_data = self._handle_response_data(response)
- return self._attach_telemetry(response_data.get("result"), response_data)
-
- # ============= Skill Management =============
-
- async def list_skills(self, node_limit: int = 1000) -> Dict[str, Any]:
- """List installed agent skills."""
- response = await self._http.get(
- "/api/v1/skills",
- params={"node_limit": node_limit},
- )
- return self._handle_response(response)
-
- async def find_skills(
- self,
- query: str,
- limit: int = 10,
- score_threshold: Optional[float] = None,
- level: Optional[List[int]] = None,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Find installed agent skills by semantic search."""
- telemetry = self._validate_telemetry(telemetry)
- payload: Dict[str, Any] = {
- "query": query,
- "limit": limit,
- "score_threshold": score_threshold,
- "level": level,
- "telemetry": telemetry,
- }
- response = await self._http.post("/api/v1/skills/find", json=payload)
- response_data = self._handle_response_data(response)
- return self._attach_telemetry(response_data.get("result"), response_data)
-
- async def validate_skill(
- self,
- data: Any,
- strict: bool = False,
- source_path: Optional[str] = None,
- skill_dir_name: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Validate a skill payload without installing it."""
- payload: Dict[str, Any] = {"data": data, "strict": strict}
- if source_path is not None:
- payload["source_path"] = source_path
- if skill_dir_name is not None:
- payload["skill_dir_name"] = skill_dir_name
- response = await self._http.post("/api/v1/skills/validate", json=payload)
- return self._handle_response(response)
-
- async def get_skill(
- self,
- skill_name: str,
- include_content: Optional[bool] = None,
- include_files: bool = True,
- include_source: bool = False,
- level: Optional[int] = None,
- ) -> Dict[str, Any]:
- """Get one installed agent skill."""
- params: Dict[str, Any] = {
- "include_files": include_files,
- "include_source": include_source,
- }
- if include_content is not None:
- params["include_content"] = include_content
- if level is not None:
- params["level"] = level
- response = await self._http.get(f"/api/v1/skills/{skill_name}", params=params)
- return self._handle_response(response)
-
- async def update_skill(
- self,
- skill_name: str,
- data: Any,
- wait: bool = False,
- timeout: Optional[float] = None,
- source_metadata: Optional[Dict[str, Any]] = None,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Replace an installed agent skill."""
- telemetry = self._validate_telemetry(telemetry)
- request_data: Dict[str, Any] = {
- "wait": wait,
- "timeout": timeout,
- "source_metadata": source_metadata,
- "telemetry": telemetry,
- }
-
- if isinstance(data, str):
- path_obj = Path(data)
- if path_obj.exists():
- if path_obj.is_dir():
- zip_path = self._zip_directory(data)
- try:
- request_data["temp_file_id"] = await self._upload_temp_file(zip_path)
- finally:
- Path(zip_path).unlink(missing_ok=True)
- elif path_obj.is_file():
- request_data["temp_file_id"] = await self._upload_temp_file(data)
- else:
- request_data["data"] = data
- else:
- request_data["data"] = data
- else:
- request_data["data"] = data
-
- response = await self._http.put(
- f"/api/v1/skills/{skill_name}",
- json=request_data,
- )
- response_data = self._handle_response_data(response)
- return self._attach_telemetry(response_data.get("result"), response_data)
-
- async def delete_skill(self, skill_name: str) -> Dict[str, Any]:
- """Remove an installed agent skill."""
- response = await self._http.delete(f"/api/v1/skills/{skill_name}")
- return self._handle_response(response)
-
- # ============= Watch Management =============
-
- async def list_watches(
- self,
- active_only: bool = False,
- to_uri: Optional[str] = None,
- ) -> Dict[str, Any]:
- """List watch tasks, or get one by target URI."""
- params: Dict[str, Any] = {"active_only": active_only}
- if to_uri is not None:
- params["to_uri"] = VikingURI.normalize(to_uri)
- response = await self._http.get("/api/v1/watches", params=params)
- return self._handle_response(response)
-
- async def get_watch(
- self,
- task_id: str,
- to_uri: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Get one watch task by task ID, optionally cross-checking the target URI."""
- params = {}
- if to_uri is not None:
- params["to_uri"] = VikingURI.normalize(to_uri)
- response = await self._http.get(f"/api/v1/watches/{task_id}", params=params)
- return self._handle_response(response)
-
- async def update_watch(
- self,
- task_id: Optional[str] = None,
- *,
- to_uri: Optional[str] = None,
- watch_interval: Optional[float] = None,
- is_active: Optional[bool] = None,
- reason: Optional[str] = None,
- instruction: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Partially update a watch task by task ID or target URI."""
- if not task_id and not to_uri:
- raise ValueError("Either task_id or to_uri is required")
- payload: Dict[str, Any] = {}
- if watch_interval is not None:
- payload["watch_interval"] = watch_interval
- if is_active is not None:
- payload["is_active"] = is_active
- if reason is not None:
- payload["reason"] = reason
- if instruction is not None:
- payload["instruction"] = instruction
- if task_id:
- params = {}
- if to_uri is not None:
- params["to_uri"] = VikingURI.normalize(to_uri)
- response = await self._http.patch(
- f"/api/v1/watches/{task_id}",
- params=params,
- json=payload,
- )
- else:
- response = await self._http.patch(
- "/api/v1/watches",
- params={"to_uri": VikingURI.normalize(to_uri)},
- json=payload,
- )
- return self._handle_response(response)
-
- async def delete_watch(
- self,
- task_id: Optional[str] = None,
- *,
- to_uri: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Delete a watch task by task ID or target URI."""
- if not task_id and not to_uri:
- raise ValueError("Either task_id or to_uri is required")
- if task_id:
- params = {}
- if to_uri is not None:
- params["to_uri"] = VikingURI.normalize(to_uri)
- response = await self._http.delete(f"/api/v1/watches/{task_id}", params=params)
- else:
- response = await self._http.delete(
- "/api/v1/watches",
- params={"to_uri": VikingURI.normalize(to_uri)},
- )
- return self._handle_response(response)
-
- async def trigger_watch(
- self,
- task_id: Optional[str] = None,
- *,
- to_uri: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Schedule a watch task for immediate background execution."""
- if not task_id and not to_uri:
- raise ValueError("Either task_id or to_uri is required")
- if task_id:
- params = {}
- if to_uri is not None:
- params["to_uri"] = VikingURI.normalize(to_uri)
- response = await self._http.post(
- f"/api/v1/watches/{task_id}/trigger",
- params=params,
- )
- else:
- response = await self._http.post(
- "/api/v1/watches/trigger",
- params={"to_uri": VikingURI.normalize(to_uri)},
- )
- return self._handle_response(response)
-
- async def wait_processed(self, timeout: Optional[float] = None) -> Dict[str, Any]:
- """Wait for all processing to complete."""
- http_timeout = timeout if timeout else 600.0
- response = await self._http.post(
- "/api/v1/system/wait",
- json={"timeout": timeout},
- timeout=http_timeout,
- )
- return self._handle_response(response)
-
- # ============= File System =============
-
- async def ls(
- self,
- uri: str,
- simple: bool = False,
- recursive: bool = False,
- output: str = "original",
- abs_limit: int = 256,
- show_all_hidden: bool = False,
- node_limit: int = 1000,
- ) -> List[Any]:
- """List directory contents."""
- uri = VikingURI.normalize(uri)
- response = await self._http.get(
- "/api/v1/fs/ls",
- params={
- "uri": uri,
- "simple": simple,
- "recursive": recursive,
- "output": output,
- "abs_limit": abs_limit,
- "show_all_hidden": show_all_hidden,
- "node_limit": node_limit,
- },
- )
- return self._handle_response(response)
-
- async def tree(
- self,
- uri: str,
- output: str = "original",
- abs_limit: int = 128,
- show_all_hidden: bool = False,
- node_limit: int = 1000,
- ) -> List[Dict[str, Any]]:
- """Get directory tree."""
- uri = VikingURI.normalize(uri)
- response = await self._http.get(
- "/api/v1/fs/tree",
- params={
- "uri": uri,
- "output": output,
- "abs_limit": abs_limit,
- "show_all_hidden": show_all_hidden,
- "node_limit": node_limit,
- },
- )
- return self._handle_response(response)
-
- async def stat(self, uri: str) -> Dict[str, Any]:
- """Get resource status."""
- uri = VikingURI.normalize(uri)
- response = await self._http.get(
- "/api/v1/fs/stat",
- params={"uri": uri},
- )
- return self._handle_response(response)
-
- async def mkdir(self, uri: str, description: Optional[str] = None) -> None:
- """Create directory."""
- uri = VikingURI.normalize(uri)
- payload = {"uri": uri}
- if description is not None:
- payload["description"] = description
- response = await self._http.post(
- "/api/v1/fs/mkdir",
- json=payload,
- )
- self._handle_response(response)
-
- async def rm(
- self,
- uri: str,
- recursive: bool = False,
- wait: bool = False,
- timeout: Optional[float] = None,
- ) -> None:
- """Remove resource."""
- uri = VikingURI.normalize(uri)
- params = {"uri": uri, "recursive": recursive, "wait": wait}
- if timeout is not None:
- params["timeout"] = timeout
- response = await self._http.request(
- "DELETE",
- "/api/v1/fs",
- params=params,
- )
- self._handle_response(response)
-
- async def mv(self, from_uri: str, to_uri: str) -> None:
- """Move resource."""
- from_uri = VikingURI.normalize(from_uri)
- to_uri = VikingURI.normalize(to_uri)
- response = await self._http.post(
- "/api/v1/fs/mv",
- json={"from_uri": from_uri, "to_uri": to_uri},
- )
- self._handle_response(response)
-
- # ============= Content Reading =============
-
- async def read(self, uri: str, offset: int = 0, limit: int = -1) -> str:
- """Read file content.
-
- Args:
- uri: Viking URI
- offset: Starting line number (0-indexed). Default 0.
- limit: Number of lines to read. -1 means read to end. Default -1.
- """
- uri = VikingURI.normalize(uri)
- response = await self._http.get(
- "/api/v1/content/read",
- params={"uri": uri, "offset": offset, "limit": limit},
- )
- return self._handle_response(response)
-
- async def abstract(self, uri: str) -> str:
- """Read L0 abstract."""
- uri = VikingURI.normalize(uri)
- response = await self._http.get(
- "/api/v1/content/abstract",
- params={"uri": uri},
- )
- return self._handle_response(response)
-
- async def overview(self, uri: str) -> str:
- """Read L1 overview."""
- uri = VikingURI.normalize(uri)
- response = await self._http.get(
- "/api/v1/content/overview",
- params={"uri": uri},
- )
- return self._handle_response(response)
-
- async def write(
- self,
- uri: str,
- content: str,
- mode: str = "replace",
- wait: bool = False,
- timeout: Optional[float] = None,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Write text content to an existing file and refresh semantics/vectors."""
- telemetry = self._validate_telemetry(telemetry)
- uri = VikingURI.normalize(uri)
- response = await self._http.post(
- "/api/v1/content/write",
- json={
- "uri": uri,
- "content": content,
- "mode": mode,
- "wait": wait,
- "timeout": timeout,
- "telemetry": telemetry,
- },
- )
- response_data = self._handle_response_data(response)
- return self._attach_telemetry(response_data.get("result") or {}, response_data)
-
- async def set_tags(
- self,
- uri: str,
- tags: List[str],
- mode: str = "replace",
- recursive: bool = False,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Update explicit retrieval tags metadata for a file or directory."""
- telemetry = self._validate_telemetry(telemetry)
- uri = VikingURI.normalize(uri)
- response = await self._http.post(
- "/api/v1/content/set_tags",
- json={
- "uri": uri,
- "tags": tags,
- "mode": mode,
- "recursive": recursive,
- "telemetry": telemetry,
- },
- )
- response_data = self._handle_response_data(response)
- return self._attach_telemetry(response_data.get("result") or {}, response_data)
-
- # ============= Search =============
-
- async def find(
- self,
- 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[SearchContextTypeInput] = None,
- tags: Optional[List[str]] = None,
- telemetry: TelemetryRequest = False,
- ) -> FindResult:
- """Semantic search without session context."""
- telemetry = self._validate_telemetry(telemetry)
- normalized_target = self._normalize_target_uri(target_uri)
- actual_limit = node_limit if node_limit is not None else limit
- payload = self._attach_legacy_agent_scope(
- {
- "query": query,
- "target_uri": normalized_target,
- "limit": actual_limit,
- "score_threshold": score_threshold,
- "filter": filter,
- "context_type": context_type,
- "tags": tags,
- "telemetry": telemetry,
- }
- )
- response = await self._http.post("/api/v1/search/find", json=payload)
- response_data = self._handle_response_data(response)
- return FindResult.from_dict(response_data.get("result") or {})
-
- async def search(
- self,
- query: str,
- target_uri: Union[str, List[str]] = "",
- session: Optional[Any] = None,
- session_id: Optional[str] = None,
- limit: int = 10,
- node_limit: Optional[int] = None,
- score_threshold: Optional[float] = None,
- filter: Optional[Dict[str, Any]] = None,
- context_type: Optional[SearchContextTypeInput] = None,
- tags: Optional[List[str]] = None,
- telemetry: TelemetryRequest = False,
- ) -> FindResult:
- """Semantic search with optional session context."""
- telemetry = self._validate_telemetry(telemetry)
- normalized_target = self._normalize_target_uri(target_uri)
- actual_limit = node_limit if node_limit is not None else limit
- sid = session_id or (session.session_id if session else None)
- payload = self._attach_legacy_agent_scope(
- {
- "query": query,
- "target_uri": normalized_target,
- "session_id": sid,
- "limit": actual_limit,
- "score_threshold": score_threshold,
- "filter": filter,
- "context_type": context_type,
- "tags": tags,
- "telemetry": telemetry,
- }
- )
- response = await self._http.post("/api/v1/search/search", json=payload)
- response_data = self._handle_response_data(response)
- return FindResult.from_dict(response_data.get("result") or {})
-
- async def grep(
- self,
- uri: str,
- pattern: str,
- case_insensitive: bool = False,
- node_limit: Optional[int] = None,
- exclude_uri: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Content search with pattern."""
- uri = VikingURI.normalize(uri)
- request_json = {
- "uri": uri,
- "pattern": pattern,
- "case_insensitive": case_insensitive,
- }
- if node_limit is not None:
- request_json["node_limit"] = node_limit
- if exclude_uri is not None:
- request_json["exclude_uri"] = VikingURI.normalize(exclude_uri)
- response = await self._http.post(
- "/api/v1/search/grep",
- json=request_json,
- )
- return self._handle_response(response)
-
- async def glob(self, pattern: str, uri: str = "viking://") -> Dict[str, Any]:
- """File pattern matching."""
- uri = VikingURI.normalize(uri)
- response = await self._http.post(
- "/api/v1/search/glob",
- json={"pattern": pattern, "uri": uri},
- )
- return self._handle_response(response)
-
- # ============= Relations =============
-
- async def relations(self, uri: str) -> List[Any]:
- """Get relations for a resource."""
- uri = VikingURI.normalize(uri)
- response = await self._http.get(
- "/api/v1/relations",
- params={"uri": uri},
- )
- return self._handle_response(response)
-
- async def link(self, from_uri: str, to_uris: Union[str, List[str]], reason: str = "") -> None:
- """Create link between resources."""
- from_uri = VikingURI.normalize(from_uri)
- if isinstance(to_uris, str):
- to_uris = VikingURI.normalize(to_uris)
- else:
- to_uris = [VikingURI.normalize(u) for u in to_uris]
- response = await self._http.post(
- "/api/v1/relations/link",
- json={"from_uri": from_uri, "to_uris": to_uris, "reason": reason},
- )
- self._handle_response(response)
-
- async def unlink(self, from_uri: str, to_uri: str) -> None:
- """Remove link between resources."""
- from_uri = VikingURI.normalize(from_uri)
- to_uri = VikingURI.normalize(to_uri)
- response = await self._http.request(
- "DELETE",
- "/api/v1/relations/link",
- json={"from_uri": from_uri, "to_uri": to_uri},
- )
- self._handle_response(response)
-
- # ============= Sessions =============
-
- async def create_session(
- self,
- session_id: Optional[str] = None,
- telemetry: TelemetryRequest = False,
- memory_policy: Optional[Dict[str, Any]] = None,
- ) -> Dict[str, Any]:
- """Create a new session.
-
- Args:
- session_id: Optional session ID. If provided, creates a session with the given ID.
- If None, creates a new session with auto-generated ID.
- """
- telemetry = self._validate_telemetry(telemetry)
- 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 telemetry is not False:
- json_body["telemetry"] = telemetry
- response = await self._http.post(
- "/api/v1/sessions",
- json=json_body,
- )
- response_data = self._handle_response_data(response)
- return self._attach_telemetry(response_data.get("result"), response_data)
-
- async def list_sessions(self) -> List[Any]:
- """List all sessions."""
- response = await self._http.get("/api/v1/sessions")
- return self._handle_response(response)
-
- async def get_session(self, session_id: str, *, auto_create: bool = False) -> Dict[str, Any]:
- """Get session details."""
- params = {}
- if auto_create:
- params["auto_create"] = "true"
- session_path = self._path_segment(session_id)
- response = await self._http.get(f"/api/v1/sessions/{session_path}", params=params)
- return self._handle_response(response)
-
- async def get_session_context(
- self, session_id: str, token_budget: int = 128_000
- ) -> Dict[str, Any]:
- """Get assembled session context."""
- session_path = self._path_segment(session_id)
- response = await self._http.get(
- f"/api/v1/sessions/{session_path}/context",
- params={"token_budget": token_budget},
- )
- return self._handle_response(response)
-
- async def get_session_archive(self, session_id: str, archive_id: str) -> Dict[str, Any]:
- """Get one completed archive for a session."""
- session_path = self._path_segment(session_id)
- archive_path = self._path_segment(archive_id)
- response = await self._http.get(
- f"/api/v1/sessions/{session_path}/archives/{archive_path}",
- )
- return self._handle_response(response)
-
- async def delete_session(self, session_id: str) -> None:
- """Delete a session."""
- session_path = self._path_segment(session_id)
- response = await self._http.delete(f"/api/v1/sessions/{session_path}")
- self._handle_response(response)
-
- async def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:
- """Query background task status.
-
- Args:
- task_id: Task ID (returned by commit)
-
- Returns:
- Task info dict, or None if not found
- """
- response = await self._http.get(f"/api/v1/tasks/{task_id}")
- if response.status_code == 404:
- return None
- return self._handle_response(response)
-
- async def list_tasks(
- self,
- task_type: Optional[str] = None,
- status: Optional[str] = None,
- resource_id: Optional[str] = None,
- limit: int = 50,
- ) -> list[dict[str, Any]]:
- """List background tasks visible to the current caller."""
- params: Dict[str, Any] = {"limit": limit}
- if task_type is not None:
- params["task_type"] = task_type
- if status is not None:
- params["status"] = status
- if resource_id is not None:
- params["resource_id"] = resource_id
- response = await self._http.get("/api/v1/tasks", params=params)
- return self._handle_response(response)
-
- async def commit_session(
- self,
- session_id: str,
- telemetry: TelemetryRequest = False,
- *,
- keep_recent_count: int = 0,
- ) -> Dict[str, Any]:
- """Commit a session (archive and extract memories)."""
- telemetry = self._validate_telemetry(telemetry)
- payload: Dict[str, Any] = {
- "keep_recent_count": keep_recent_count,
- "telemetry": telemetry,
- }
- session_path = self._path_segment(session_id)
- response = await self._http.post(
- f"/api/v1/sessions/{session_path}/commit",
- json=payload,
- )
- response_data = self._handle_response_data(response)
- return self._attach_telemetry(response_data.get("result"), response_data)
-
- async def add_message(
- 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: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Add a message to a session.
-
- Args:
- session_id: Session ID
- role: Message role ("user" or "assistant")
- content: Text content (simple mode, backward compatible)
- parts: Parts array (full Part support mode)
- created_at: Message creation time (ISO format string)
- peer_id: Optional stable interaction peer identity.
-
- If both content and parts are provided, parts takes precedence.
- """
- telemetry = self._validate_telemetry(telemetry)
- 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")
-
- if created_at is not None:
- payload["created_at"] = created_at
- if peer_id is not None:
- payload["peer_id"] = peer_id
- if telemetry is not False:
- payload["telemetry"] = telemetry
- payload = self._attach_legacy_message_scope(payload)
-
- session_path = self._path_segment(session_id)
- response = await self._http.post(
- f"/api/v1/sessions/{session_path}/messages",
- json=payload,
- )
- response_data = self._handle_response_data(response)
- return self._attach_telemetry(response_data.get("result"), response_data)
-
- # ============= Pack =============
-
- async def export_ovpack(
- self,
- uri: str,
- to: str,
- include_vectors: bool = False,
- ) -> str:
- """Export context as .ovpack file and save to local path.
-
- Args:
- uri: Viking URI to export
- to: Local file path where to save the .ovpack file
-
- Returns:
- Local file path where the .ovpack was saved
- """
- uri = VikingURI.normalize(uri)
-
- # Determine target path
- to_path = Path(to)
- if to_path.is_dir():
- base_name = uri.strip().rstrip("/").split("/")[-1]
- if not base_name:
- base_name = "export"
- to_path = to_path / f"{base_name}.ovpack"
- elif not str(to_path).endswith(".ovpack"):
- to_path = Path(str(to_path) + ".ovpack")
-
- # Ensure parent directory exists
- to_path.parent.mkdir(parents=True, exist_ok=True)
-
- # Request export and stream response
- response = await self._http.post(
- "/api/v1/pack/export",
- json={"uri": uri, "include_vectors": include_vectors},
- )
-
- # Check for errors
- if not response.is_success:
- self._handle_response(response)
-
- # Save streamed content to local file
- with open(to_path, "wb") as f:
- f.write(response.content)
-
- return str(to_path)
-
- async def backup_ovpack(self, to: str, include_vectors: bool = False) -> str:
- """Back up public scopes as a restore-only .ovpack file."""
- to_path = Path(to)
- if to_path.is_dir():
- to_path = to_path / "openviking-backup.ovpack"
- elif not str(to_path).endswith(".ovpack"):
- to_path = Path(str(to_path) + ".ovpack")
-
- to_path.parent.mkdir(parents=True, exist_ok=True)
-
- response = await self._http.post(
- "/api/v1/pack/backup",
- json={"include_vectors": include_vectors},
- )
- if not response.is_success:
- self._handle_response(response)
-
- with open(to_path, "wb") as f:
- f.write(response.content)
-
- return str(to_path)
-
- async def import_ovpack(
- self,
- file_path: str,
- parent: str,
- on_conflict: Optional[str] = None,
- vector_mode: Optional[str] = None,
- ) -> str:
- """Import .ovpack file."""
- parent = VikingURI.normalize(parent)
- request_data = {
- "parent": parent,
- }
- if on_conflict is not None:
- request_data["on_conflict"] = on_conflict
- if vector_mode is not None:
- request_data["vector_mode"] = vector_mode
-
- file_path_obj = Path(file_path)
- if not file_path_obj.exists():
- raise FileNotFoundError(f"Local ovpack file not found: {file_path}")
- if not file_path_obj.is_file():
- raise ValueError(f"Path {file_path} is not a file")
-
- temp_file_id = await self._upload_temp_file(file_path)
- request_data["temp_file_id"] = temp_file_id
-
- response = await self._http.post(
- "/api/v1/pack/import",
- json=request_data,
- )
- result = self._handle_response(response)
- return result.get("uri", "")
-
- async def restore_ovpack(
- self,
- file_path: str,
- on_conflict: Optional[str] = None,
- vector_mode: Optional[str] = None,
- ) -> str:
- """Restore backup .ovpack file."""
- request_data = {}
- if on_conflict is not None:
- request_data["on_conflict"] = on_conflict
- if vector_mode is not None:
- request_data["vector_mode"] = vector_mode
-
- file_path_obj = Path(file_path)
- if not file_path_obj.exists():
- raise FileNotFoundError(f"Local ovpack file not found: {file_path}")
- if not file_path_obj.is_file():
- raise ValueError(f"Path {file_path} is not a file")
-
- temp_file_id = await self._upload_temp_file(file_path)
- request_data["temp_file_id"] = temp_file_id
-
- response = await self._http.post(
- "/api/v1/pack/restore",
- json=request_data,
- )
- result = self._handle_response(response)
- return result.get("uri", "")
-
- # ============= Debug =============
-
- async def check_consistency(self, uri: str) -> Dict[str, Any]:
- """Check filesystem/vector-index consistency for a URI subtree."""
- response = await self._http.post(
- "/api/v1/system/consistency",
- json={"uri": VikingURI.normalize(uri)},
- )
- return self._handle_response(response)
-
- async def health(self) -> bool:
- """Check server health."""
- try:
- response = await self._http.get("/health")
- data = response.json()
- return data.get("status") == "ok"
- except Exception:
- return False
-
- async def reindex(
- self,
- uri: str,
- mode: str = "vectors_only",
- wait: bool = True,
- ) -> Dict[str, Any]:
- """Trigger reindex for a URI."""
- response = await self._http.post(
- "/api/v1/content/reindex",
- json={
- "uri": uri,
- "mode": mode,
- "wait": wait,
- },
- )
- return self._handle_response(response)
-
- # ============= Observer (Internal) =============
-
- async def _get_queue_status(self) -> Dict[str, Any]:
- """Get queue system status (internal for _HTTPObserver)."""
- response = await self._http.get("/api/v1/observer/queue")
- return self._handle_response(response)
-
- async def _get_vikingdb_status(self) -> Dict[str, Any]:
- """Get VikingDB status (internal for _HTTPObserver)."""
- response = await self._http.get("/api/v1/observer/vikingdb")
- return self._handle_response(response)
-
- async def _get_models_status(self) -> Dict[str, Any]:
- """Get models status (VLM, Embedding, Rerank) (internal for _HTTPObserver)."""
- response = await self._http.get("/api/v1/observer/models")
- return self._handle_response(response)
-
- async def _get_system_status(self) -> Dict[str, Any]:
- """Get system overall status (internal for _HTTPObserver)."""
- response = await self._http.get("/api/v1/observer/system")
- return self._handle_response(response)
-
- # ============= Admin =============
-
- async def admin_create_account(self, account_id: str, admin_user_id: str) -> Dict[str, Any]:
- """Create a new account with its first admin user."""
- response = await self._http.post(
- "/api/v1/admin/accounts",
- json={"account_id": account_id, "admin_user_id": admin_user_id},
- )
- return self._handle_response(response)
-
- async def admin_list_accounts(self) -> List[Any]:
- """List all accounts."""
- response = await self._http.get("/api/v1/admin/accounts")
- return self._handle_response(response)
-
- async def admin_delete_account(self, account_id: str) -> Dict[str, Any]:
- """Delete an account and all associated users."""
- response = await self._http.delete(f"/api/v1/admin/accounts/{account_id}")
- return self._handle_response(response)
-
- async def admin_register_user(
- self, account_id: str, user_id: str, role: str = "user"
- ) -> Dict[str, Any]:
- """Register a new user in an account."""
- response = await self._http.post(
- f"/api/v1/admin/accounts/{account_id}/users",
- json={"user_id": user_id, "role": role},
- )
- return self._handle_response(response)
-
- async def admin_list_users(self, account_id: str) -> List[Any]:
- """List all users in an account."""
- response = await self._http.get(f"/api/v1/admin/accounts/{account_id}/users")
- return self._handle_response(response)
-
- async def admin_remove_user(self, account_id: str, user_id: str) -> Dict[str, Any]:
- """Remove a user from an account."""
- response = await self._http.delete(f"/api/v1/admin/accounts/{account_id}/users/{user_id}")
- return self._handle_response(response)
-
- async def admin_set_role(self, account_id: str, user_id: str, role: str) -> Dict[str, Any]:
- """Change a user's role."""
- response = await self._http.put(
- f"/api/v1/admin/accounts/{account_id}/users/{user_id}/role",
- json={"role": role},
- )
- return self._handle_response(response)
-
- async def admin_regenerate_key(self, account_id: str, user_id: str) -> Dict[str, Any]:
- """Regenerate a user's API key. Old key is immediately invalidated."""
- response = await self._http.post(
- f"/api/v1/admin/accounts/{account_id}/users/{user_id}/key",
- )
- return self._handle_response(response)
-
- async def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:
- """Start legacy data migration or legacy namespace cleanup."""
- action = "cleanup" if cleanup else "migrate"
- response = await self._http.post("/api/v1/admin/migrate", json={"action": action})
- return self._handle_response(response)
-
- # ============= New methods for BaseClient interface =============
-
- def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> Any:
- """Create a new session or load an existing one.
-
- Args:
- session_id: Session ID, creates a new session if None
- must_exist: If True and session_id is provided, raises NotFoundError
- when the session does not exist.
- If session_id is None, must_exist is ignored.
-
- Returns:
- Session object
-
- Raises:
- NotFoundError: If must_exist=True and the session does not exist.
- """
- from openviking.client.session import Session
-
- if not session_id:
- result = run_async(self.create_session())
- session_id = result.get("session_id", "")
- elif must_exist:
- # get_session() raises NotFoundError (via _handle_response) for 404.
- run_async(self.get_session(session_id))
- return Session(self, session_id, self._user)
-
- async def session_exists(self, session_id: str) -> bool:
- """Check whether a session exists in storage.
-
- Args:
- session_id: Session ID to check
-
- Returns:
- True if the session exists, False otherwise
- """
- try:
- await self.get_session(session_id)
- return True
- except NotFoundError:
- return False
-
- def get_status(self) -> Dict[str, Any]:
- """Get system status.
-
- Returns:
- Dict containing health status of all components.
- """
- return self._observer.system
-
- def is_healthy(self) -> bool:
- """Quick health check (synchronous).
-
- Returns:
- True if all components are healthy, False otherwise.
- """
- return self._observer.is_healthy()
-
- @property
- def observer(self) -> _HTTPObserver:
- """Get observer service for component status."""
- return self._observer
+__all__ = ["AsyncHTTPClient", "ERROR_CODE_TO_EXCEPTION"]
diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.py
index 726a38dc1..680d07ba3 100644
--- a/openviking_cli/client/sync_http.py
+++ b/openviking_cli/client/sync_http.py
@@ -1,771 +1,7 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-"""Synchronous HTTP Client for OpenViking.
+"""Compatibility shim for the legacy sync HTTP client import path."""
-Wraps AsyncHTTPClient with synchronous methods.
-"""
+from openviking_cli.client._http_compat import SyncHTTPClient
-from typing import Any, Dict, List, Optional, Union
-
-from openviking.telemetry import TelemetryRequest
-from openviking.utils.search_filters import SearchContextTypeInput
-from openviking_cli.client.http import AsyncHTTPClient
-from openviking_cli.utils import run_async
-
-
-class SyncHTTPClient:
- """Synchronous HTTP Client for OpenViking Server.
-
- Wraps AsyncHTTPClient with synchronous methods.
- Supports auto-loading url/api_key from ovcli.conf when not provided.
-
- Examples:
- # Explicit url
- client = SyncHTTPClient(url="http://localhost:1933", api_key="key")
- client.initialize()
-
- # Auto-load from ~/.openviking/ovcli.conf
- client = SyncHTTPClient()
- client.initialize()
- """
-
- def __init__(
- self,
- url: Optional[str] = None,
- api_key: Optional[str] = None,
- user_id: Optional[str] = None,
- account: Optional[str] = None,
- user: Optional[str] = None,
- actor_peer_id: Optional[str] = None,
- agent_id: Optional[str] = None,
- timeout: float = 60.0,
- extra_headers: Optional[Dict[str, str]] = None,
- profile_enabled: Optional[bool] = None,
- ):
- self._async_client = AsyncHTTPClient(
- url=url,
- api_key=api_key,
- user_id=user_id,
- account=account,
- user=user,
- actor_peer_id=actor_peer_id,
- agent_id=agent_id,
- timeout=timeout,
- extra_headers=extra_headers,
- profile_enabled=profile_enabled,
- )
- self._initialized = False
-
- # ============= Lifecycle =============
-
- def initialize(self) -> None:
- """Initialize the HTTP client."""
- run_async(self._async_client.initialize())
- self._initialized = True
-
- def close(self) -> None:
- """Close the HTTP client and release resources."""
- run_async(self._async_client.close())
- self._initialized = False
-
- # ============= session =============
-
- def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> Any:
- """Create a new session or load an existing one.
-
- Args:
- session_id: Session ID, creates a new session if None
- must_exist: If True and session_id is provided, raises NotFoundError
- when the session does not exist.
-
- Returns:
- Session object
- """
- return self._async_client.session(session_id, must_exist=must_exist)
-
- def session_exists(self, session_id: str) -> bool:
- """Check whether a session exists in storage."""
- return run_async(self._async_client.session_exists(session_id))
-
- def create_session(
- self,
- session_id: Optional[str] = None,
- telemetry: TelemetryRequest = False,
- memory_policy: Optional[Dict[str, Any]] = None,
- ) -> Dict[str, Any]:
- """Create a new session.
-
- Args:
- session_id: Optional session ID. If provided, creates a session with the given ID.
- If None, creates a new session with auto-generated ID.
- """
- return run_async(
- self._async_client.create_session(
- session_id,
- telemetry=telemetry,
- memory_policy=memory_policy,
- )
- )
-
- def list_sessions(self) -> List[Any]:
- """List all sessions."""
- return run_async(self._async_client.list_sessions())
-
- def get_session(self, session_id: str, *, auto_create: bool = False) -> Dict[str, Any]:
- """Get session details."""
- return run_async(self._async_client.get_session(session_id, auto_create=auto_create))
-
- def get_session_context(self, session_id: str, token_budget: int = 128_000) -> Dict[str, Any]:
- """Get assembled session context."""
- return run_async(self._async_client.get_session_context(session_id, token_budget))
-
- def get_session_archive(self, session_id: str, archive_id: str) -> Dict[str, Any]:
- """Get one completed archive for a session."""
- return run_async(self._async_client.get_session_archive(session_id, archive_id))
-
- def delete_session(self, session_id: str) -> None:
- """Delete a session."""
- run_async(self._async_client.delete_session(session_id))
-
- def add_message(
- 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: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Add a message to a session.
-
- Args:
- session_id: Session ID
- role: Message role ("user" or "assistant")
- content: Text content (simple mode)
- parts: Parts array (full Part support: TextPart, ContextPart, ImagePart, ToolPart)
- created_at: Message creation time (ISO format string)
- peer_id: Optional stable interaction peer identity.
-
- If both content and parts are provided, parts takes precedence.
- """
- return run_async(
- self._async_client.add_message(
- session_id,
- role,
- content,
- parts,
- created_at,
- peer_id,
- telemetry,
- )
- )
-
- def batch_add_messages(
- self,
- session_id: str,
- messages: list[dict],
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Add multiple messages to a session in a single request.
-
- Args:
- session_id: Session ID
- messages: List of message dicts, each with "role" and optionally
- "content", "parts", "created_at", "peer_id".
- telemetry: Whether to attach operation telemetry data to the result.
-
- Returns:
- Result dict with session_id, message_count, and added count.
- """
- return run_async(
- self._async_client.batch_add_messages(
- session_id,
- messages,
- telemetry,
- )
- )
-
- def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:
- """Query background task status."""
- return run_async(self._async_client.get_task(task_id))
-
- def list_tasks(
- self,
- task_type: Optional[str] = None,
- status: Optional[str] = None,
- resource_id: Optional[str] = None,
- limit: int = 50,
- ) -> list[dict[str, Any]]:
- """List background tasks visible to the current caller."""
- return run_async(
- self._async_client.list_tasks(
- task_type=task_type,
- status=status,
- resource_id=resource_id,
- limit=limit,
- )
- )
-
- def reindex(
- self,
- uri: str,
- mode: str = "vectors_only",
- wait: bool = True,
- ) -> Dict[str, Any]:
- """Trigger reindex for a URI."""
- return run_async(
- self._async_client.reindex(
- uri=uri,
- mode=mode,
- wait=wait,
- )
- )
-
- def commit_session(
- self,
- session_id: str,
- telemetry: TelemetryRequest = False,
- *,
- keep_recent_count: int = 0,
- ) -> Dict[str, Any]:
- """Commit a session (archive and extract memories)."""
- return run_async(
- self._async_client.commit_session(
- session_id,
- telemetry=telemetry,
- keep_recent_count=keep_recent_count,
- )
- )
-
- # ============= Resource =============
-
- def add_resource(
- self,
- path: str,
- to: Optional[str] = None,
- parent: Optional[str] = None,
- reason: str = "",
- instruction: str = "",
- wait: bool = False,
- timeout: Optional[float] = None,
- strict: bool = True,
- ignore_dirs: Optional[str] = None,
- include: Optional[str] = None,
- exclude: Optional[str] = None,
- directly_upload_media: bool = True,
- watch_interval: float = 0,
- args: Optional[Dict[str, Any]] = None,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Add resource to OpenViking."""
- if to and parent:
- raise ValueError("Cannot specify both 'to' and 'parent' at the same time.")
- return run_async(
- self._async_client.add_resource(
- path=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,
- watch_interval=watch_interval,
- args=args,
- telemetry=telemetry,
- )
- )
-
- def add_skill(
- self,
- data: Any,
- wait: bool = False,
- timeout: Optional[float] = None,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Add skill to OpenViking."""
- return run_async(
- self._async_client.add_skill(data, wait=wait, timeout=timeout, telemetry=telemetry)
- )
-
- # ============= Skill Management =============
-
- def list_skills(self, node_limit: int = 1000) -> Dict[str, Any]:
- """List installed agent skills."""
- return run_async(self._async_client.list_skills(node_limit=node_limit))
-
- def find_skills(
- self,
- query: str,
- limit: int = 10,
- score_threshold: Optional[float] = None,
- level: Optional[List[int]] = None,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Find installed agent skills by semantic search."""
- return run_async(
- self._async_client.find_skills(
- query=query,
- limit=limit,
- score_threshold=score_threshold,
- level=level,
- telemetry=telemetry,
- )
- )
-
- def validate_skill(
- self,
- data: Any,
- strict: bool = False,
- source_path: Optional[str] = None,
- skill_dir_name: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Validate a skill payload without installing it."""
- return run_async(
- self._async_client.validate_skill(
- data=data,
- strict=strict,
- source_path=source_path,
- skill_dir_name=skill_dir_name,
- )
- )
-
- def get_skill(
- self,
- skill_name: str,
- include_content: Optional[bool] = None,
- include_files: bool = True,
- include_source: bool = False,
- level: Optional[int] = None,
- ) -> Dict[str, Any]:
- """Get one installed agent skill."""
- return run_async(
- self._async_client.get_skill(
- skill_name,
- include_content=include_content,
- include_files=include_files,
- include_source=include_source,
- level=level,
- )
- )
-
- def update_skill(
- self,
- skill_name: str,
- data: Any,
- wait: bool = False,
- timeout: Optional[float] = None,
- source_metadata: Optional[Dict[str, Any]] = None,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Replace an installed agent skill."""
- return run_async(
- self._async_client.update_skill(
- skill_name,
- data,
- wait=wait,
- timeout=timeout,
- source_metadata=source_metadata,
- telemetry=telemetry,
- )
- )
-
- def delete_skill(self, skill_name: str) -> Dict[str, Any]:
- """Remove an installed agent skill."""
- return run_async(self._async_client.delete_skill(skill_name))
-
- # ============= Watch Management =============
-
- def list_watches(
- self,
- active_only: bool = False,
- to_uri: Optional[str] = None,
- ) -> Dict[str, Any]:
- """List watch tasks, or get one by target URI."""
- return run_async(self._async_client.list_watches(active_only=active_only, to_uri=to_uri))
-
- def get_watch(
- self,
- task_id: str,
- to_uri: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Get one watch task by task ID, optionally cross-checking the target URI."""
- return run_async(self._async_client.get_watch(task_id, to_uri=to_uri))
-
- def update_watch(
- self,
- task_id: Optional[str] = None,
- *,
- to_uri: Optional[str] = None,
- watch_interval: Optional[float] = None,
- is_active: Optional[bool] = None,
- reason: Optional[str] = None,
- instruction: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Partially update a watch task by task ID or target URI."""
- return run_async(
- self._async_client.update_watch(
- task_id,
- to_uri=to_uri,
- watch_interval=watch_interval,
- is_active=is_active,
- reason=reason,
- instruction=instruction,
- )
- )
-
- def delete_watch(
- self,
- task_id: Optional[str] = None,
- *,
- to_uri: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Delete a watch task by task ID or target URI."""
- return run_async(self._async_client.delete_watch(task_id, to_uri=to_uri))
-
- def trigger_watch(
- self,
- task_id: Optional[str] = None,
- *,
- to_uri: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Schedule a watch task for immediate background execution."""
- return run_async(self._async_client.trigger_watch(task_id, to_uri=to_uri))
-
- def wait_processed(self, timeout: Optional[float] = None) -> Dict[str, Any]:
- """Wait for all processing to complete."""
- return run_async(self._async_client.wait_processed(timeout))
-
- # ============= Search =============
-
- def search(
- self,
- query: str,
- target_uri: Union[str, List[str]] = "",
- session: Optional[Any] = None,
- session_id: Optional[str] = None,
- limit: int = 10,
- node_limit: Optional[int] = None,
- score_threshold: Optional[float] = None,
- filter: Optional[Dict] = None,
- context_type: Optional[SearchContextTypeInput] = None,
- tags: Optional[List[str]] = None,
- telemetry: TelemetryRequest = False,
- ):
- """Semantic search with optional session context."""
- return run_async(
- self._async_client.search(
- query=query,
- target_uri=target_uri,
- session=session,
- session_id=session_id,
- limit=limit,
- node_limit=node_limit,
- score_threshold=score_threshold,
- filter=filter,
- context_type=context_type,
- tags=tags,
- telemetry=telemetry,
- )
- )
-
- def find(
- self,
- query: str,
- target_uri: Union[str, List[str]] = "",
- limit: int = 10,
- node_limit: Optional[int] = None,
- score_threshold: Optional[float] = None,
- filter: Optional[Dict] = None,
- context_type: Optional[SearchContextTypeInput] = None,
- tags: Optional[List[str]] = None,
- telemetry: TelemetryRequest = False,
- ):
- """Semantic search without session context."""
- return run_async(
- self._async_client.find(
- query,
- target_uri,
- limit,
- node_limit,
- score_threshold,
- filter,
- context_type,
- tags,
- telemetry=telemetry,
- )
- )
-
- def grep(
- self,
- uri: str,
- pattern: str,
- case_insensitive: bool = False,
- node_limit: Optional[int] = None,
- exclude_uri: Optional[str] = None,
- ) -> Dict:
- """Content search with pattern."""
- return run_async(
- self._async_client.grep(uri, pattern, case_insensitive, node_limit, exclude_uri)
- )
-
- def glob(self, pattern: str, uri: str = "viking://") -> Dict:
- """File pattern matching."""
- return run_async(self._async_client.glob(pattern, uri))
-
- # ============= File System =============
-
- def ls(
- self,
- uri: str,
- simple: bool = False,
- recursive: bool = False,
- output: str = "original",
- abs_limit: int = 256,
- show_all_hidden: bool = False,
- node_limit: int = 1000,
- ) -> List[Any]:
- """List directory contents."""
- return run_async(
- self._async_client.ls(
- uri,
- simple=simple,
- recursive=recursive,
- output=output,
- abs_limit=abs_limit,
- show_all_hidden=show_all_hidden,
- node_limit=node_limit,
- )
- )
-
- def tree(
- self,
- uri: str,
- output: str = "original",
- abs_limit: int = 128,
- show_all_hidden: bool = False,
- node_limit: int = 1000,
- ) -> List[Dict[str, Any]]:
- """Get directory tree."""
- return run_async(
- self._async_client.tree(
- uri,
- output=output,
- abs_limit=abs_limit,
- show_all_hidden=show_all_hidden,
- node_limit=node_limit,
- )
- )
-
- def stat(self, uri: str) -> Dict:
- """Get resource status."""
- return run_async(self._async_client.stat(uri))
-
- def mkdir(self, uri: str, description: Optional[str] = None) -> None:
- """Create directory."""
- run_async(self._async_client.mkdir(uri, description=description))
-
- def rm(
- self,
- uri: str,
- recursive: bool = False,
- wait: bool = False,
- timeout: Optional[float] = None,
- ) -> None:
- """Remove resource."""
- run_async(self._async_client.rm(uri, recursive, wait=wait, timeout=timeout))
-
- def mv(self, from_uri: str, to_uri: str) -> None:
- """Move resource."""
- run_async(self._async_client.mv(from_uri, to_uri))
-
- # ============= Content =============
-
- def read(self, uri: str, offset: int = 0, limit: int = -1) -> str:
- """Read file content."""
- return run_async(self._async_client.read(uri, offset=offset, limit=limit))
-
- def abstract(self, uri: str) -> str:
- """Read L0 abstract."""
- return run_async(self._async_client.abstract(uri))
-
- def overview(self, uri: str) -> str:
- """Read L1 overview."""
- return run_async(self._async_client.overview(uri))
-
- def write(
- self,
- uri: str,
- content: str,
- mode: str = "replace",
- wait: bool = False,
- timeout: Optional[float] = None,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Write text content to an existing file and refresh semantics/vectors."""
- return run_async(
- self._async_client.write(
- uri=uri,
- content=content,
- mode=mode,
- wait=wait,
- timeout=timeout,
- telemetry=telemetry,
- )
- )
-
- def set_tags(
- self,
- uri: str,
- tags: List[str],
- mode: str = "replace",
- recursive: bool = False,
- telemetry: TelemetryRequest = False,
- ) -> Dict[str, Any]:
- """Update explicit retrieval tags metadata for a file or directory."""
- return run_async(
- self._async_client.set_tags(
- uri=uri,
- tags=tags,
- mode=mode,
- recursive=recursive,
- telemetry=telemetry,
- )
- )
-
- # ============= Relations =============
-
- def relations(self, uri: str) -> List[Dict[str, Any]]:
- """Get relations for a resource."""
- return run_async(self._async_client.relations(uri))
-
- def link(self, from_uri: str, uris: Union[str, List[str]], reason: str = "") -> None:
- """Create link between resources."""
- run_async(self._async_client.link(from_uri, uris, reason))
-
- def unlink(self, from_uri: str, uri: str) -> None:
- """Remove link between resources."""
- run_async(self._async_client.unlink(from_uri, uri))
-
- # ============= Pack =============
-
- def export_ovpack(
- self,
- uri: str,
- to: str,
- include_vectors: bool = False,
- ) -> str:
- """Export context as .ovpack file and save to local path.
-
- Args:
- uri: Viking URI to export
- to: Local file path where to save the .ovpack file
-
- Returns:
- Local file path where the .ovpack was saved
- """
- return run_async(self._async_client.export_ovpack(uri, to, include_vectors=include_vectors))
-
- def backup_ovpack(self, to: str, include_vectors: bool = False) -> str:
- """Back up public scopes as a restore-only .ovpack file."""
- return run_async(self._async_client.backup_ovpack(to, include_vectors=include_vectors))
-
- def import_ovpack(
- self,
- file_path: str,
- target: str,
- on_conflict: Optional[str] = None,
- vector_mode: Optional[str] = None,
- ) -> str:
- """Import .ovpack file."""
- return run_async(
- self._async_client.import_ovpack(
- file_path,
- target,
- on_conflict=on_conflict,
- vector_mode=vector_mode,
- )
- )
-
- def restore_ovpack(
- self,
- file_path: str,
- on_conflict: Optional[str] = None,
- vector_mode: Optional[str] = None,
- ) -> str:
- """Restore backup .ovpack file."""
- return run_async(
- self._async_client.restore_ovpack(
- file_path,
- on_conflict=on_conflict,
- vector_mode=vector_mode,
- )
- )
-
- def check_consistency(self, uri: str) -> Dict[str, Any]:
- """Check filesystem/vector-index consistency for a URI subtree."""
- return run_async(self._async_client.check_consistency(uri))
-
- # ============= Admin =============
-
- def admin_create_account(self, account_id: str, admin_user_id: str) -> Dict[str, Any]:
- """Create a new account with its first admin user."""
- return run_async(self._async_client.admin_create_account(account_id, admin_user_id))
-
- def admin_list_accounts(self) -> List[Any]:
- """List all accounts."""
- return run_async(self._async_client.admin_list_accounts())
-
- def admin_delete_account(self, account_id: str) -> Dict[str, Any]:
- """Delete an account and all associated users."""
- return run_async(self._async_client.admin_delete_account(account_id))
-
- def admin_register_user(
- self, account_id: str, user_id: str, role: str = "user"
- ) -> Dict[str, Any]:
- """Register a new user in an account."""
- return run_async(self._async_client.admin_register_user(account_id, user_id, role))
-
- def admin_list_users(self, account_id: str) -> List[Any]:
- """List all users in an account."""
- return run_async(self._async_client.admin_list_users(account_id))
-
- def admin_remove_user(self, account_id: str, user_id: str) -> Dict[str, Any]:
- """Remove a user from an account."""
- return run_async(self._async_client.admin_remove_user(account_id, user_id))
-
- def admin_set_role(self, account_id: str, user_id: str, role: str) -> Dict[str, Any]:
- """Change a user's role."""
- return run_async(self._async_client.admin_set_role(account_id, user_id, role))
-
- def admin_regenerate_key(self, account_id: str, user_id: str) -> Dict[str, Any]:
- """Regenerate a user's API key. Old key is immediately invalidated."""
- return run_async(self._async_client.admin_regenerate_key(account_id, user_id))
-
- def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:
- """Start legacy data migration or legacy namespace cleanup."""
- return run_async(self._async_client.admin_migrate(cleanup=cleanup))
-
- # ============= Debug =============
-
- def health(self) -> bool:
- """Check server health."""
- return run_async(self._async_client.health())
-
- def get_status(self) -> Dict[str, Any]:
- """Get system status."""
- return self._async_client.get_status()
-
- def is_healthy(self) -> bool:
- """Quick health check."""
- return self._async_client.is_healthy()
-
- @property
- def observer(self):
- """Get observer service for component status."""
- return self._async_client.observer
+__all__ = ["SyncHTTPClient"]
diff --git a/pyproject.toml b/pyproject.toml
index 2710df788..3c5924960 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -30,6 +30,7 @@ classifiers = [
"Programming Language :: Python :: 3.14",
]
dependencies = [
+ "openviking-sdk>=0.1.1",
"pydantic>=2.0.0",
"typing-extensions>=4.5.0",
"pyyaml>=6.0",
@@ -209,7 +210,7 @@ vikingbot = "vikingbot.cli.commands:app"
[tool.setuptools_scm]
write_to = "openviking/_version.py"
local_scheme = "no-local-version"
-tag_regex = "^(?:v)?(?:[a-zA-Z0-9_]+@)?(?P<version>[0-9]+(?:\\.[0-9]+)*)$"
+tag_regex = "^v(?P<version>[0-9]+(?:\\.[0-9]+)*)$"
[tool.setuptools.packages.find]
where = [".", "bot"]
diff --git a/sdk/python/README.md b/sdk/python/README.md
new file mode 100644
index 000000000..80f7d15c1
--- /dev/null
+++ b/sdk/python/README.md
@@ -0,0 +1,280 @@
+# openviking-sdk
+
+Lightweight Python HTTP SDK for OpenViking.
+
+`openviking-sdk` is the small package for users who only need to call an existing OpenViking server over HTTP. It avoids the heavier local-runtime, server, and CLI dependencies from the main `openviking` package.
+
+## Installation
+
+```bash
+pip install openviking-sdk
+```
+
+Requirements:
+
+- Python 3.10+
+- A reachable OpenViking HTTP server, for example `http://127.0.0.1:1933`
+
+## Package Name vs Import Name
+
+- PyPI package name: `openviking-sdk`
+- Python import name: `openviking_sdk`
+
+```python
+from openviking_sdk import AsyncHTTPClient, SyncHTTPClient
+```
+
+## Configuration Sources
+
+You can configure the SDK in three ways, with this precedence:
+
+1. Explicit constructor arguments
+2. Environment variables such as `OPENVIKING_URL`, `OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_ACTOR_PEER_ID`, and `OPENVIKING_TIMEOUT`
+3. `ovcli.conf`, either from `OPENVIKING_CLI_CONFIG_FILE` or the default path `~/.openviking/ovcli.conf`
+
+This means existing setups that relied on `ovcli.conf` continue to work after the SDK split.
+
+## Authentication Model
+
+Most deployments use API key authentication.
+
+Common client fields:
+
+- `url`: OpenViking server base URL
+- `api_key`: root key or user key
+- `account`: optional account override, usually only needed with a root key
+- `user`: optional user override, usually only needed with a root key
+- `user_id`: legacy alias for `user`
+- `actor_peer_id`: optional actor peer override
+- `agent_id`: legacy alias for `actor_peer_id`
+
+Compatibility notes:
+
+- `user_id` and `agent_id` are still accepted for legacy callers
+- `actor_peer_id` and `agent_id` cannot be passed together
+
+Example:
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(
+ url="http://127.0.0.1:1933",
+ api_key="your-user-or-root-key",
+)
+```
+
+If you are using a root key and want to act as a specific tenant user:
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(
+ url="http://127.0.0.1:1933",
+ api_key="your-root-key",
+ account="demo-account",
+ user="demo-user",
+)
+```
+
+## Quick Start: Sync Client
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(
+ url="http://127.0.0.1:1933",
+ api_key="your-user-key",
+)
+
+healthy = client.health()
+print("health:", healthy)
+
+session = client.create_session("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)
+print("context:", context)
+```
+
+## Quick Start: Async Client
+
+```python
+import asyncio
+
+from openviking_sdk import AsyncHTTPClient
+
+
+async def main() -> None:
+ client = AsyncHTTPClient(
+ url="http://127.0.0.1:1933",
+ api_key="your-user-key",
+ )
+
+ healthy = await client.health()
+ print("health:", healthy)
+
+ session = await client.create_session("demo-session-async")
+ print("session:", session)
+
+ session_client = client.session("demo-session-async")
+ await session_client.add_message("user", "hello from async sdk")
+ context = await session_client.get_session_context(token_budget=4096)
+ print("context:", context)
+
+ await client.close()
+
+
+asyncio.run(main())
+```
+
+## Common Operations
+
+### Create a Session
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+result = client.create_session("demo-session")
+print(result)
+```
+
+### Add a Resource from a Local File
+
+`add_resource` handles file upload for local paths automatically.
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+
+result = client.add_resource(
+ "/path/to/notes.md",
+ to="viking://resources/demo-notes",
+ reason="knowledge import",
+ wait=True,
+)
+print(result)
+```
+
+### Filesystem Operations
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+
+client.mkdir("viking://resources/demo-dir")
+print(client.ls("viking://resources"))
+print(client.read("viking://resources/demo-dir/example.md"))
+```
+
+### Retrieval
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+
+result = client.find("hello", limit=5)
+print(result)
+```
+
+## Admin Operations
+
+If you connect with a root key, the SDK also exposes admin APIs such as:
+
+- `admin_create_account`
+- `admin_register_user`
+- `admin_list_accounts`
+- `admin_list_users`
+- `admin_regenerate_key`
+- `admin_delete_account`
+
+Example:
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+root_client = SyncHTTPClient(
+ url="http://127.0.0.1:1933",
+ api_key="your-root-key",
+)
+
+result = root_client.admin_create_account(
+ account_id="demo-account",
+ admin_user_id="demo-admin",
+)
+print(result)
+```
+
+## Error Handling
+
+The SDK maps server-side error codes to Python exceptions.
+
+```python
+from openviking_sdk import OpenVikingError, SyncHTTPClient
+
+client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+
+try:
+ print(client.read("viking://resources/not-exists.md"))
+except OpenVikingError as exc:
+ print(type(exc).__name__, exc)
+```
+
+## Relationship to `openviking`
+
+Use `openviking-sdk` when you want:
+
+- the HTTP client only
+- the smallest dependency footprint
+- a package suitable for application-side integration
+
+Use `openviking` when you want:
+
+- the full Python package
+- local runtime integrations
+- server entrypoints
+- compatibility imports that re-export the HTTP clients
+
+## Development
+
+Install from source:
+
+```bash
+cd sdk/python
+pip install -e .
+```
+
+Build distributions:
+
+```bash
+cd sdk/python
+python -m build
+```
+
+The SDK version is derived from git tags with this format:
+
+```text
+python-sdk/v0.1.3
+```
+
+That tag namespace is independent from the main package release tags such as:
+
+```text
+v0.3.26
+```
+
+## Release
+
+The repository is configured so SDK releases can be driven by SDK-only tags.
+
+Typical flow:
+
+1. Merge SDK changes.
+2. Create and push a tag like `python-sdk/v0.1.3`.
+3. GitHub Actions builds `sdk/python`.
+4. GitHub Actions publishes `openviking-sdk` to PyPI.
diff --git a/sdk/python/README_CN.md b/sdk/python/README_CN.md
new file mode 100644
index 000000000..1f0ec1a5e
--- /dev/null
+++ b/sdk/python/README_CN.md
@@ -0,0 +1,280 @@
+# openviking-sdk
+
+OpenViking 的轻量级 Python HTTP SDK。
+
+`openviking-sdk` 面向只需要通过 HTTP 调用现有 OpenViking 服务的用户。它避免了主包 `openviking` 中较重的本地运行时、服务端和 CLI 依赖。
+
+## 安装
+
+```bash
+pip install openviking-sdk
+```
+
+要求:
+
+- Python 3.10+
+- 一个可访问的 OpenViking HTTP 服务,例如 `http://127.0.0.1:1933`
+
+## 包名与导入名
+
+- PyPI 包名:`openviking-sdk`
+- Python 导入名:`openviking_sdk`
+
+```python
+from openviking_sdk import AsyncHTTPClient, SyncHTTPClient
+```
+
+## 配置来源
+
+SDK 支持三种配置方式,优先级从高到低如下:
+
+1. 显式构造参数
+2. 环境变量,例如 `OPENVIKING_URL`、`OPENVIKING_API_KEY`、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_ACTOR_PEER_ID` 和 `OPENVIKING_TIMEOUT`
+3. `ovcli.conf`,来源可以是 `OPENVIKING_CLI_CONFIG_FILE` 指定的路径,或者默认路径 `~/.openviking/ovcli.conf`
+
+这意味着之前依赖 `ovcli.conf` 的配置方式,在 SDK 拆分之后仍然可以继续使用。
+
+## 认证模型
+
+大多数部署场景使用 API Key 认证。
+
+常见客户端字段:
+
+- `url`:OpenViking 服务的基础 URL
+- `api_key`:root key 或 user key
+- `account`:可选的 account 覆盖,通常只在使用 root key 时需要
+- `user`:可选的 user 覆盖,通常只在使用 root key 时需要
+- `user_id`:`user` 的兼容旧别名
+- `actor_peer_id`:可选的 actor peer 覆盖
+- `agent_id`:`actor_peer_id` 的兼容旧别名
+
+兼容性说明:
+
+- 旧调用方仍然可以使用 `user_id` 和 `agent_id`
+- `actor_peer_id` 和 `agent_id` 不能同时传入
+
+示例:
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(
+ url="http://127.0.0.1:1933",
+ api_key="your-user-or-root-key",
+)
+```
+
+如果你使用的是 root key,并且希望以某个租户用户身份执行:
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(
+ url="http://127.0.0.1:1933",
+ api_key="your-root-key",
+ account="demo-account",
+ user="demo-user",
+)
+```
+
+## 快速开始:同步客户端
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(
+ url="http://127.0.0.1:1933",
+ api_key="your-user-key",
+)
+
+healthy = client.health()
+print("health:", healthy)
+
+session = client.create_session("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)
+print("context:", context)
+```
+
+## 快速开始:异步客户端
+
+```python
+import asyncio
+
+from openviking_sdk import AsyncHTTPClient
+
+
+async def main() -> None:
+ client = AsyncHTTPClient(
+ url="http://127.0.0.1:1933",
+ api_key="your-user-key",
+ )
+
+ healthy = await client.health()
+ print("health:", healthy)
+
+ session = await client.create_session("demo-session-async")
+ print("session:", session)
+
+ session_client = client.session("demo-session-async")
+ await session_client.add_message("user", "hello from async sdk")
+ context = await session_client.get_session_context(token_budget=4096)
+ print("context:", context)
+
+ await client.close()
+
+
+asyncio.run(main())
+```
+
+## 常见操作
+
+### 创建 Session
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+result = client.create_session("demo-session")
+print(result)
+```
+
+### 从本地文件添加资源
+
+`add_resource` 会自动处理本地路径对应的文件上传。
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+
+result = client.add_resource(
+ "/path/to/notes.md",
+ to="viking://resources/demo-notes",
+ reason="knowledge import",
+ wait=True,
+)
+print(result)
+```
+
+### 文件系统操作
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+
+client.mkdir("viking://resources/demo-dir")
+print(client.ls("viking://resources"))
+print(client.read("viking://resources/demo-dir/example.md"))
+```
+
+### 检索
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+
+result = client.find("hello", limit=5)
+print(result)
+```
+
+## 管理员操作
+
+如果你使用 root key 连接,SDK 也暴露了管理员 API,例如:
+
+- `admin_create_account`
+- `admin_register_user`
+- `admin_list_accounts`
+- `admin_list_users`
+- `admin_regenerate_key`
+- `admin_delete_account`
+
+示例:
+
+```python
+from openviking_sdk import SyncHTTPClient
+
+root_client = SyncHTTPClient(
+ url="http://127.0.0.1:1933",
+ api_key="your-root-key",
+)
+
+result = root_client.admin_create_account(
+ account_id="demo-account",
+ admin_user_id="demo-admin",
+)
+print(result)
+```
+
+## 错误处理
+
+SDK 会把服务端错误码映射为 Python 异常。
+
+```python
+from openviking_sdk import OpenVikingError, SyncHTTPClient
+
+client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
+
+try:
+ print(client.read("viking://resources/not-exists.md"))
+except OpenVikingError as exc:
+ print(type(exc).__name__, exc)
+```
+
+## 与 `openviking` 的关系
+
+在以下场景中使用 `openviking-sdk`:
+
+- 只需要 HTTP 客户端
+- 希望依赖体积尽可能小
+- 作为业务应用侧集成包使用
+
+在以下场景中使用 `openviking`:
+
+- 需要完整 Python 主包
+- 需要本地运行时集成
+- 需要服务端入口
+- 需要重新导出 HTTP client 的兼容导入路径
+
+## 开发
+
+从源码安装:
+
+```bash
+cd sdk/python
+pip install -e .
+```
+
+构建发行包:
+
+```bash
+cd sdk/python
+python -m build
+```
+
+SDK 版本号来自以下格式的 git tag:
+
+```text
+python-sdk/v0.1.3
+```
+
+这个 tag 命名空间独立于主包的发布 tag,例如:
+
+```text
+v0.3.26
+```
+
+## 发布
+
+仓库已经配置为支持通过 SDK 专用 tag 触发 SDK 发布。
+
+典型流程:
+
+1. 合并 SDK 相关改动
+2. 创建并推送类似 `python-sdk/v0.1.3` 的 tag
+3. GitHub Actions 构建 `sdk/python`
+4. GitHub Actions 将 `openviking-sdk` 发布到 PyPI
diff --git a/sdk/python/openviking_sdk/__init__.py b/sdk/python/openviking_sdk/__init__.py
new file mode 100644
index 000000000..a91100d05
--- /dev/null
+++ b/sdk/python/openviking_sdk/__init__.py
@@ -0,0 +1,18 @@
+from .client import AsyncHTTPClient, SyncHTTPClient
+from .errors import (
+ AbortedError,
+ ConflictError,
+ OpenVikingError,
+ ResourceExhaustedError,
+ UnimplementedError,
+)
+
+__all__ = [
+ "AbortedError",
+ "AsyncHTTPClient",
+ "ConflictError",
+ "OpenVikingError",
+ "ResourceExhaustedError",
+ "SyncHTTPClient",
+ "UnimplementedError",
+]
diff --git a/sdk/python/openviking_sdk/_utils.py b/sdk/python/openviking_sdk/_utils.py
new file mode 100644
index 000000000..dd84ac74c
--- /dev/null
+++ b/sdk/python/openviking_sdk/_utils.py
@@ -0,0 +1,20 @@
+from __future__ import annotations
+
+import asyncio
+from typing import Any, Coroutine
+
+
+def run_async(coro: Coroutine[Any, Any, Any]) -> Any:
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+
+ if loop.is_running():
+ new_loop = asyncio.new_event_loop()
+ try:
+ return new_loop.run_until_complete(coro)
+ finally:
+ new_loop.close()
+ return loop.run_until_complete(coro)
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
new file mode 100644
index 000000000..fa907092c
--- /dev/null
+++ b/sdk/python/openviking_sdk/client.py
@@ -0,0 +1,1834 @@
+from __future__ import annotations
+
+import inspect
+import tempfile
+import uuid
+import zipfile
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+from urllib.parse import quote
+
+import httpx
+
+from ._utils import run_async
+from .config import resolve_client_config
+from .errors import (
+ AbortedError,
+ AlreadyExistsError,
+ ConflictError,
+ DeadlineExceededError,
+ EmbeddingFailedError,
+ FailedPreconditionError,
+ InternalError,
+ InvalidArgumentError,
+ InvalidURIError,
+ NotFoundError,
+ NotInitializedError,
+ OpenVikingError,
+ PermissionDeniedError,
+ ProcessingError,
+ ResourceExhaustedError,
+ SessionExpiredError,
+ UnauthenticatedError,
+ UnavailableError,
+ UnimplementedError,
+ VLMFailedError,
+)
+
+ERROR_CODE_TO_EXCEPTION = {
+ "INVALID_ARGUMENT": InvalidArgumentError,
+ "INVALID_URI": InvalidURIError,
+ "NOT_FOUND": NotFoundError,
+ "ALREADY_EXISTS": AlreadyExistsError,
+ "CONFLICT": ConflictError,
+ "FAILED_PRECONDITION": FailedPreconditionError,
+ "ABORTED": AbortedError,
+ "UNAUTHENTICATED": UnauthenticatedError,
+ "PERMISSION_DENIED": PermissionDeniedError,
+ "RESOURCE_EXHAUSTED": ResourceExhaustedError,
+ "UNAVAILABLE": UnavailableError,
+ "INTERNAL": InternalError,
+ "DEADLINE_EXCEEDED": DeadlineExceededError,
+ "UNIMPLEMENTED": UnimplementedError,
+ "NOT_INITIALIZED": NotInitializedError,
+ "PROCESSING_ERROR": ProcessingError,
+ "EMBEDDING_FAILED": EmbeddingFailedError,
+ "VLM_FAILED": VLMFailedError,
+ "SESSION_EXPIRED": SessionExpiredError,
+ "UNKNOWN": OpenVikingError,
+}
+
+
+class VikingURI:
+ @staticmethod
+ def normalize(uri: str) -> str:
+ if not uri:
+ return uri
+ if uri.startswith("viking://"):
+ return uri
+ if uri == "/":
+ return "viking://"
+ cleaned = uri.strip()
+ if cleaned.startswith("/"):
+ cleaned = cleaned[1:]
+ return f"viking://{cleaned}"
+
+
+class Session:
+ def __init__(self, client: "AsyncHTTPClient", session_id: str):
+ self._client = client
+ self.session_id = session_id
+
+ 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,
+ ) -> Dict[str, Any]:
+ return await self._client.add_message(
+ self.session_id,
+ role=role,
+ content=content,
+ parts=parts,
+ created_at=created_at,
+ peer_id=peer_id,
+ )
+
+ async def batch_add_messages(self, messages: list[dict]) -> Dict[str, Any]:
+ return await self._client.batch_add_messages(self.session_id, messages)
+
+ async def commit(self, keep_recent_count: int = 0) -> Dict[str, Any]:
+ return await self._client.commit_session(
+ self.session_id, keep_recent_count=keep_recent_count
+ )
+
+ async def delete(self) -> None:
+ await self._client.delete_session(self.session_id)
+
+ async def load(self) -> Dict[str, Any]:
+ return await self._client.get_session(self.session_id)
+
+ async def get_session_context(self, token_budget: int = 128_000) -> Dict[str, Any]:
+ return await self._client.get_session_context(self.session_id, token_budget)
+
+ async def get_archive(self, archive_id: str) -> Dict[str, Any]:
+ return await self._client.get_session_archive(self.session_id, archive_id)
+
+
+class SyncSession:
+ def __init__(self, client: "SyncHTTPClient", session_id: str):
+ self._client = client
+ self.session_id = session_id
+
+ 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,
+ ) -> Dict[str, Any]:
+ return self._client.add_message(
+ self.session_id,
+ role=role,
+ content=content,
+ parts=parts,
+ created_at=created_at,
+ peer_id=peer_id,
+ )
+
+ 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,
+ ) -> Dict[str, Any]:
+ return self._client.commit_session(
+ self.session_id,
+ telemetry=telemetry,
+ keep_recent_count=keep_recent_count,
+ )
+
+ def commit_async(
+ self,
+ telemetry: Any = False,
+ *,
+ keep_recent_count: int = 0,
+ ) -> Dict[str, Any]:
+ return self.commit(telemetry=telemetry, keep_recent_count=keep_recent_count)
+
+ def delete(self) -> None:
+ self._client.delete_session(self.session_id)
+
+ def load(self) -> Dict[str, Any]:
+ return self._client.get_session(self.session_id)
+
+ def get_session_context(self, token_budget: int = 128_000) -> Dict[str, Any]:
+ return self._client.get_session_context(self.session_id, token_budget)
+
+ def get_archive(self, archive_id: str) -> Dict[str, Any]:
+ return self._client.get_session_archive(self.session_id, archive_id)
+
+ def __repr__(self) -> str:
+ return f"SyncSession(id={self.session_id})"
+
+
+class _HTTPObserver:
+ def __init__(self, client: "AsyncHTTPClient"):
+ self._client = client
+
+ @property
+ def queue(self) -> Dict[str, Any]:
+ return run_async(self._client._get_queue_status())
+
+ @property
+ def vikingdb(self) -> Dict[str, Any]:
+ return run_async(self._client._get_vikingdb_status())
+
+ @property
+ def models(self) -> Dict[str, Any]:
+ return run_async(self._client._get_models_status())
+
+ @property
+ def system(self) -> Dict[str, Any]:
+ return run_async(self._client._get_system_status())
+
+ def is_healthy(self) -> bool:
+ return self.system.get("is_healthy", False)
+
+
+class AsyncHTTPClient:
+ def __init__(
+ self,
+ url: Optional[str] = None,
+ api_key: Optional[str] = None,
+ user_id: Optional[str] = None,
+ account: Optional[str] = None,
+ user: Optional[str] = None,
+ actor_peer_id: Optional[str] = None,
+ agent_id: Optional[str] = None,
+ timeout: float = 60.0,
+ extra_headers: Optional[Dict[str, str]] = None,
+ profile_enabled: Optional[bool] = None,
+ upload_mode: Optional[str] = None,
+ ):
+ if actor_peer_id and agent_id:
+ raise ValueError("actor_peer_id cannot be used with legacy agent_id")
+ effective_user = user if user is not None else user_id
+ effective_actor = actor_peer_id or agent_id
+ config = resolve_client_config(
+ url=url,
+ api_key=api_key,
+ account=account,
+ user=effective_user,
+ actor_peer_id=effective_actor,
+ timeout=timeout,
+ extra_headers=extra_headers,
+ profile_enabled=profile_enabled,
+ upload_mode=upload_mode,
+ )
+ self._url = config.url
+ self._api_key = config.api_key
+ self._account = config.account
+ self._user_id = config.user
+ self._actor_peer_id = config.actor_peer_id
+ self._timeout = config.timeout
+ self._extra_headers = config.extra_headers
+ self._profile_enabled = config.profile_enabled
+ self._upload_mode = config.upload_mode
+ self._http: Optional[httpx.AsyncClient] = None
+ self._observer: Optional[_HTTPObserver] = None
+
+ async def initialize(self) -> None:
+ headers: Dict[str, str] = {}
+ if self._api_key:
+ headers["X-API-Key"] = self._api_key
+ if self._account:
+ headers["X-OpenViking-Account"] = self._account
+ if self._user_id:
+ headers["X-OpenViking-User"] = self._user_id
+ if self._actor_peer_id:
+ headers["X-OpenViking-Actor-Peer"] = self._actor_peer_id
+ headers.update(self._extra_headers)
+ self._http = httpx.AsyncClient(
+ base_url=self._url,
+ headers=headers,
+ timeout=self._timeout,
+ params={"profile": "1"} if self._profile_enabled else None,
+ )
+ self._observer = _HTTPObserver(self)
+
+ async def close(self) -> None:
+ if self._http:
+ try:
+ await self._http.aclose()
+ except RuntimeError:
+ pass
+ self._http = None
+
+ @staticmethod
+ def _path_segment(value: str) -> str:
+ return quote(value, safe="")
+
+ @staticmethod
+ def _normalize_target_uri(
+ target_uri: Union[str, List[str]],
+ ) -> Union[str, List[str]]:
+ if isinstance(target_uri, list):
+ return [VikingURI.normalize(u) if u else u for u in target_uri]
+ if target_uri:
+ return VikingURI.normalize(target_uri)
+ return target_uri
+
+ def _handle_response_data(self, response: httpx.Response) -> Dict[str, Any]:
+ try:
+ data = response.json()
+ except Exception:
+ if hasattr(response, "is_success") and not response.is_success:
+ raise OpenVikingError(
+ f"HTTP {response.status_code}: {response.text or 'empty response'}",
+ code="INTERNAL",
+ )
+ return {}
+ if data.get("status") == "error":
+ self._raise_exception(data.get("error", {}))
+ if hasattr(response, "is_success") and not response.is_success:
+ raise OpenVikingError(
+ data.get("detail", f"HTTP {response.status_code}"),
+ code="UNKNOWN",
+ )
+ return data
+
+ def _handle_response(self, response: httpx.Response) -> Any:
+ return self._handle_response_data(response).get("result")
+
+ def _raise_exception(self, error: Dict[str, Any]) -> None:
+ code = error.get("code", "UNKNOWN")
+ message = error.get("message", "Unknown error")
+ details = error.get("details")
+ exc_class = ERROR_CODE_TO_EXCEPTION.get(code, OpenVikingError)
+
+ if exc_class == OpenVikingError:
+ raise exc_class(message, code=code, details=details)
+ if exc_class in (
+ InvalidArgumentError,
+ FailedPreconditionError,
+ ResourceExhaustedError,
+ AbortedError,
+ UnimplementedError,
+ ):
+ raise exc_class(message, details=details)
+ if exc_class == InvalidURIError:
+ uri = details.get("uri", "") if details else ""
+ reason = details.get("reason", "") if details else ""
+ raise exc_class(uri, reason)
+ if exc_class == NotFoundError:
+ resource = details.get("resource", "") if details else ""
+ resource_type = details.get("type", "resource") if details else "resource"
+ raise exc_class(resource, resource_type)
+ if exc_class == AlreadyExistsError:
+ resource = details.get("resource", "") if details else ""
+ resource_type = details.get("type", "resource") if details else "resource"
+ raise exc_class(resource, resource_type)
+ raise exc_class(message)
+
+ def _zip_directory(self, dir_path: str) -> str:
+ dir_path = Path(dir_path)
+ if not dir_path.is_dir():
+ raise ValueError(f"Path {dir_path} is not a directory")
+
+ root = dir_path.resolve()
+ zip_path = Path(tempfile.gettempdir()) / f"temp_upload_{uuid.uuid4().hex}.zip"
+ entry_count = 0
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
+ for file_path in dir_path.rglob("*"):
+ if file_path.is_symlink():
+ continue
+ if file_path.is_file():
+ if not file_path.resolve().is_relative_to(root):
+ continue
+ arcname = str(file_path.relative_to(dir_path)).replace("\\", "/")
+ zipf.write(file_path, arcname=arcname)
+ entry_count += 1
+ return str(zip_path)
+
+ async def _upload_temp_file(self, file_path: str) -> str:
+ with open(file_path, "rb") as f:
+ files = {"file": (Path(file_path).name, f, "application/octet-stream")}
+ data = {"upload_mode": self._upload_mode} if self._upload_mode else None
+ response = await self._http.post(
+ "/api/v1/resources/temp_upload",
+ files=files,
+ data=data,
+ )
+ result = self._handle_response(response)
+ return result.get("temp_file_id", "")
+
+ def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> Session:
+ return Session(self, session_id or "")
+
+ async def session_exists(self, session_id: str) -> bool:
+ try:
+ await self.get_session(session_id)
+ return True
+ except NotFoundError:
+ return False
+
+ async def add_resource(
+ self,
+ 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,
+ ) -> Dict[str, Any]:
+ if to and parent:
+ raise ValueError("Cannot specify both 'to' and 'parent' at the same time.")
+
+ request_data = {
+ "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 preserve_structure is not None:
+ request_data["preserve_structure"] = preserve_structure
+
+ path_obj = Path(path)
+ if path_obj.exists():
+ if path_obj.is_dir():
+ request_data["source_name"] = path_obj.name
+ zip_path = self._zip_directory(path)
+ try:
+ request_data["temp_file_id"] = await self._upload_temp_file(zip_path)
+ finally:
+ Path(zip_path).unlink(missing_ok=True)
+ elif path_obj.is_file():
+ request_data["source_name"] = path_obj.name
+ request_data["temp_file_id"] = await self._upload_temp_file(path)
+ else:
+ request_data["path"] = path
+ else:
+ request_data["path"] = path
+
+ response = await self._http.post("/api/v1/resources", json=request_data)
+ return self._handle_response_data(response).get("result", {})
+
+ async def batch_add_messages(
+ self,
+ session_id: str,
+ messages: list[dict],
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ session_path = self._path_segment(session_id)
+ payload: Dict[str, Any] = {"messages": messages}
+ if telemetry is not False:
+ payload["telemetry"] = telemetry
+ response = await self._http.post(
+ f"/api/v1/sessions/{session_path}/messages/batch",
+ json=payload,
+ )
+ return self._handle_response_data(response).get("result", {})
+
+ async def add_skill(
+ self,
+ data: Any,
+ wait: bool = False,
+ timeout: Optional[float] = None,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ request_data = {"wait": wait, "timeout": timeout, "telemetry": telemetry}
+ if isinstance(data, str):
+ path_obj = Path(data)
+ if path_obj.exists():
+ if path_obj.is_dir():
+ zip_path = self._zip_directory(data)
+ try:
+ request_data["temp_file_id"] = await self._upload_temp_file(zip_path)
+ finally:
+ Path(zip_path).unlink(missing_ok=True)
+ elif path_obj.is_file():
+ request_data["temp_file_id"] = await self._upload_temp_file(data)
+ else:
+ request_data["data"] = data
+ else:
+ request_data["data"] = data
+ else:
+ request_data["data"] = data
+ response = await self._http.post("/api/v1/skills", json=request_data)
+ return self._handle_response_data(response).get("result", {})
+
+ async def list_skills(self, node_limit: int = 1000) -> Dict[str, Any]:
+ response = await self._http.get("/api/v1/skills", params={"node_limit": node_limit})
+ return self._handle_response(response)
+
+ async def find_skills(
+ self,
+ query: str,
+ limit: int = 10,
+ score_threshold: Optional[float] = None,
+ level: Optional[List[int]] = None,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ payload = {
+ "query": query,
+ "limit": limit,
+ "score_threshold": score_threshold,
+ "level": level,
+ "telemetry": telemetry,
+ }
+ response = await self._http.post("/api/v1/skills/find", json=payload)
+ return self._handle_response_data(response).get("result", {})
+
+ async def validate_skill(
+ self,
+ data: Any,
+ strict: bool = False,
+ source_path: Optional[str] = None,
+ skill_dir_name: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ payload: Dict[str, Any] = {"data": data, "strict": strict}
+ if source_path is not None:
+ payload["source_path"] = source_path
+ if skill_dir_name is not None:
+ payload["skill_dir_name"] = skill_dir_name
+ response = await self._http.post("/api/v1/skills/validate", json=payload)
+ return self._handle_response(response)
+
+ async def get_skill(
+ self,
+ skill_name: str,
+ include_content: Optional[bool] = None,
+ include_files: bool = True,
+ include_source: bool = False,
+ level: Optional[int] = None,
+ ) -> Dict[str, Any]:
+ params: Dict[str, Any] = {
+ "include_files": include_files,
+ "include_source": include_source,
+ }
+ if include_content is not None:
+ params["include_content"] = include_content
+ if level is not None:
+ params["level"] = level
+ response = await self._http.get(f"/api/v1/skills/{skill_name}", params=params)
+ return self._handle_response(response)
+
+ async def update_skill(
+ self,
+ skill_name: str,
+ data: Any,
+ wait: bool = False,
+ timeout: Optional[float] = None,
+ source_metadata: Optional[Dict[str, Any]] = None,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ request_data: Dict[str, Any] = {
+ "wait": wait,
+ "timeout": timeout,
+ "source_metadata": source_metadata,
+ "telemetry": telemetry,
+ }
+ if isinstance(data, str):
+ path_obj = Path(data)
+ if path_obj.exists():
+ if path_obj.is_dir():
+ zip_path = self._zip_directory(data)
+ try:
+ request_data["temp_file_id"] = await self._upload_temp_file(zip_path)
+ finally:
+ Path(zip_path).unlink(missing_ok=True)
+ elif path_obj.is_file():
+ request_data["temp_file_id"] = await self._upload_temp_file(data)
+ else:
+ request_data["data"] = data
+ else:
+ request_data["data"] = data
+ else:
+ request_data["data"] = data
+ response = await self._http.put(f"/api/v1/skills/{skill_name}", json=request_data)
+ return self._handle_response_data(response).get("result", {})
+
+ async def delete_skill(self, skill_name: str) -> Dict[str, Any]:
+ response = await self._http.delete(f"/api/v1/skills/{skill_name}")
+ return self._handle_response(response)
+
+ async def list_watches(
+ self,
+ active_only: bool = False,
+ to_uri: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ params: Dict[str, Any] = {"active_only": active_only}
+ if to_uri is not None:
+ params["to_uri"] = VikingURI.normalize(to_uri)
+ response = await self._http.get("/api/v1/watches", params=params)
+ return self._handle_response(response)
+
+ async def get_watch(
+ self,
+ task_id: str,
+ to_uri: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ params = {}
+ if to_uri is not None:
+ params["to_uri"] = VikingURI.normalize(to_uri)
+ response = await self._http.get(f"/api/v1/watches/{task_id}", params=params)
+ return self._handle_response(response)
+
+ async def update_watch(
+ self,
+ task_id: Optional[str] = None,
+ *,
+ to_uri: Optional[str] = None,
+ watch_interval: Optional[float] = None,
+ is_active: Optional[bool] = None,
+ reason: Optional[str] = None,
+ instruction: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ if not task_id and not to_uri:
+ raise ValueError("Either task_id or to_uri is required")
+ payload: Dict[str, Any] = {}
+ if watch_interval is not None:
+ payload["watch_interval"] = watch_interval
+ if is_active is not None:
+ payload["is_active"] = is_active
+ if reason is not None:
+ payload["reason"] = reason
+ if instruction is not None:
+ payload["instruction"] = instruction
+ if task_id:
+ params = {}
+ if to_uri is not None:
+ params["to_uri"] = VikingURI.normalize(to_uri)
+ response = await self._http.patch(
+ f"/api/v1/watches/{task_id}", params=params, json=payload
+ )
+ else:
+ response = await self._http.patch(
+ "/api/v1/watches",
+ params={"to_uri": VikingURI.normalize(to_uri)},
+ json=payload,
+ )
+ return self._handle_response(response)
+
+ async def delete_watch(
+ self, task_id: Optional[str] = None, *, to_uri: Optional[str] = None
+ ) -> Dict[str, Any]:
+ if not task_id and not to_uri:
+ raise ValueError("Either task_id or to_uri is required")
+ if task_id:
+ params = {}
+ if to_uri is not None:
+ params["to_uri"] = VikingURI.normalize(to_uri)
+ response = await self._http.delete(f"/api/v1/watches/{task_id}", params=params)
+ else:
+ response = await self._http.delete(
+ "/api/v1/watches", params={"to_uri": VikingURI.normalize(to_uri)}
+ )
+ return self._handle_response(response)
+
+ async def trigger_watch(
+ self, task_id: Optional[str] = None, *, to_uri: Optional[str] = None
+ ) -> Dict[str, Any]:
+ if not task_id and not to_uri:
+ raise ValueError("Either task_id or to_uri is required")
+ if task_id:
+ params = {}
+ if to_uri is not None:
+ params["to_uri"] = VikingURI.normalize(to_uri)
+ response = await self._http.post(f"/api/v1/watches/{task_id}/trigger", params=params)
+ else:
+ response = await self._http.post(
+ "/api/v1/watches/trigger", params={"to_uri": VikingURI.normalize(to_uri)}
+ )
+ return self._handle_response(response)
+
+ async def wait_processed(self, timeout: Optional[float] = None) -> Dict[str, Any]:
+ http_timeout = timeout if timeout else 600.0
+ response = await self._http.post(
+ "/api/v1/system/wait",
+ json={"timeout": timeout},
+ timeout=http_timeout,
+ )
+ return self._handle_response(response)
+
+ async def ls(
+ self,
+ uri: str,
+ simple: bool = False,
+ recursive: bool = False,
+ output: str = "original",
+ abs_limit: int = 256,
+ show_all_hidden: bool = False,
+ node_limit: int = 1000,
+ ) -> List[Any]:
+ response = await self._http.get(
+ "/api/v1/fs/ls",
+ params={
+ "uri": VikingURI.normalize(uri),
+ "simple": simple,
+ "recursive": recursive,
+ "output": output,
+ "abs_limit": abs_limit,
+ "show_all_hidden": show_all_hidden,
+ "node_limit": node_limit,
+ },
+ )
+ return self._handle_response(response)
+
+ async def tree(
+ self,
+ uri: str,
+ output: str = "original",
+ abs_limit: int = 128,
+ show_all_hidden: bool = False,
+ node_limit: int = 1000,
+ ) -> List[Dict[str, Any]]:
+ response = await self._http.get(
+ "/api/v1/fs/tree",
+ params={
+ "uri": VikingURI.normalize(uri),
+ "output": output,
+ "abs_limit": abs_limit,
+ "show_all_hidden": show_all_hidden,
+ "node_limit": node_limit,
+ },
+ )
+ return self._handle_response(response)
+
+ async def stat(self, uri: str) -> Dict[str, Any]:
+ response = await self._http.get("/api/v1/fs/stat", params={"uri": VikingURI.normalize(uri)})
+ return self._handle_response(response)
+
+ async def mkdir(self, uri: str, description: Optional[str] = None) -> None:
+ payload = {"uri": VikingURI.normalize(uri)}
+ if description is not None:
+ payload["description"] = description
+ response = await self._http.post("/api/v1/fs/mkdir", json=payload)
+ self._handle_response(response)
+
+ async def rm(
+ self,
+ uri: str,
+ recursive: bool = False,
+ wait: bool = False,
+ timeout: Optional[float] = None,
+ ) -> None:
+ params = {"uri": VikingURI.normalize(uri), "recursive": recursive, "wait": wait}
+ if timeout is not None:
+ params["timeout"] = timeout
+ response = await self._http.request("DELETE", "/api/v1/fs", params=params)
+ self._handle_response(response)
+
+ async def mv(self, from_uri: str, to_uri: str) -> None:
+ response = await self._http.post(
+ "/api/v1/fs/mv",
+ json={"from_uri": VikingURI.normalize(from_uri), "to_uri": VikingURI.normalize(to_uri)},
+ )
+ self._handle_response(response)
+
+ async def read(self, uri: str, offset: int = 0, limit: int = -1) -> str:
+ response = await self._http.get(
+ "/api/v1/content/read",
+ params={"uri": VikingURI.normalize(uri), "offset": offset, "limit": limit},
+ )
+ return self._handle_response(response)
+
+ async def abstract(self, uri: str) -> str:
+ response = await self._http.get(
+ "/api/v1/content/abstract", params={"uri": VikingURI.normalize(uri)}
+ )
+ return self._handle_response(response)
+
+ async def overview(self, uri: str) -> str:
+ response = await self._http.get(
+ "/api/v1/content/overview", params={"uri": VikingURI.normalize(uri)}
+ )
+ return self._handle_response(response)
+
+ async def write(
+ self,
+ uri: str,
+ content: str,
+ mode: str = "replace",
+ wait: bool = False,
+ timeout: Optional[float] = None,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ response = await self._http.post(
+ "/api/v1/content/write",
+ json={
+ "uri": VikingURI.normalize(uri),
+ "content": content,
+ "mode": mode,
+ "wait": wait,
+ "timeout": timeout,
+ "telemetry": telemetry,
+ },
+ )
+ return self._handle_response_data(response).get("result", {})
+
+ async def set_tags(
+ self,
+ uri: str,
+ tags: List[str],
+ mode: str = "replace",
+ recursive: bool = False,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ response = await self._http.post(
+ "/api/v1/content/set_tags",
+ json={
+ "uri": VikingURI.normalize(uri),
+ "tags": tags,
+ "mode": mode,
+ "recursive": recursive,
+ "telemetry": telemetry,
+ },
+ )
+ return self._handle_response_data(response).get("result", {})
+
+ async def find(
+ self,
+ 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,
+ ) -> Dict[str, Any]:
+ actual_limit = node_limit if node_limit is not None else limit
+ payload = {
+ "query": query,
+ "target_uri": self._normalize_target_uri(target_uri),
+ "limit": actual_limit,
+ "score_threshold": score_threshold,
+ "filter": filter,
+ "context_type": context_type,
+ "tags": tags,
+ "telemetry": telemetry,
+ }
+ response = await self._http.post("/api/v1/search/find", json=payload)
+ return self._handle_response_data(response).get("result", {})
+
+ async def search(
+ self,
+ query: str,
+ target_uri: Union[str, List[str]] = "",
+ session: Optional[Any] = None,
+ session_id: Optional[str] = None,
+ limit: int = 10,
+ node_limit: Optional[int] = None,
+ score_threshold: Optional[float] = None,
+ filter: Optional[Dict[str, Any]] = None,
+ context_type: Optional[Any] = None,
+ tags: Optional[List[str]] = None,
+ telemetry: Any = False,
+ ) -> 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,
+ "target_uri": self._normalize_target_uri(target_uri),
+ "session_id": sid,
+ "limit": actual_limit,
+ "score_threshold": score_threshold,
+ "filter": filter,
+ "context_type": context_type,
+ "tags": tags,
+ "telemetry": telemetry,
+ }
+ response = await self._http.post("/api/v1/search/search", json=payload)
+ return self._handle_response_data(response).get("result", {})
+
+ async def grep(
+ self,
+ uri: str,
+ pattern: str,
+ case_insensitive: bool = False,
+ node_limit: Optional[int] = None,
+ exclude_uri: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ request_json = {
+ "uri": VikingURI.normalize(uri),
+ "pattern": pattern,
+ "case_insensitive": case_insensitive,
+ }
+ if node_limit is not None:
+ request_json["node_limit"] = node_limit
+ if exclude_uri is not None:
+ request_json["exclude_uri"] = VikingURI.normalize(exclude_uri)
+ response = await self._http.post("/api/v1/search/grep", json=request_json)
+ return self._handle_response(response)
+
+ async def glob(self, pattern: str, uri: str = "viking://") -> Dict[str, Any]:
+ response = await self._http.post(
+ "/api/v1/search/glob",
+ json={"pattern": pattern, "uri": VikingURI.normalize(uri)},
+ )
+ return self._handle_response(response)
+
+ async def relations(self, uri: str) -> List[Any]:
+ response = await self._http.get(
+ "/api/v1/relations", params={"uri": VikingURI.normalize(uri)}
+ )
+ return self._handle_response(response)
+
+ async def link(self, from_uri: str, to_uris: Union[str, List[str]], reason: str = "") -> None:
+ if isinstance(to_uris, str):
+ to_uris = VikingURI.normalize(to_uris)
+ else:
+ to_uris = [VikingURI.normalize(u) for u in to_uris]
+ response = await self._http.post(
+ "/api/v1/relations/link",
+ json={
+ "from_uri": VikingURI.normalize(from_uri),
+ "to_uris": to_uris,
+ "reason": reason,
+ },
+ )
+ self._handle_response(response)
+
+ async def unlink(self, from_uri: str, to_uri: str) -> None:
+ response = await self._http.request(
+ "DELETE",
+ "/api/v1/relations/link",
+ json={
+ "from_uri": VikingURI.normalize(from_uri),
+ "to_uri": VikingURI.normalize(to_uri),
+ },
+ )
+ self._handle_response(response)
+
+ async def create_session(
+ self,
+ session_id: Optional[str] = None,
+ telemetry: Any = False,
+ memory_policy: 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 telemetry is not False:
+ json_body["telemetry"] = telemetry
+ response = await self._http.post("/api/v1/sessions", json=json_body)
+ return self._handle_response_data(response).get("result", {})
+
+ async def list_sessions(self) -> List[Any]:
+ response = await self._http.get("/api/v1/sessions")
+ return self._handle_response(response)
+
+ async def get_session(self, session_id: str, *, auto_create: bool = False) -> Dict[str, Any]:
+ params = {"auto_create": "true"} if auto_create else {}
+ session_path = self._path_segment(session_id)
+ response = await self._http.get(f"/api/v1/sessions/{session_path}", params=params)
+ return self._handle_response(response)
+
+ async def get_session_context(
+ self, session_id: str, token_budget: int = 128_000
+ ) -> Dict[str, Any]:
+ session_path = self._path_segment(session_id)
+ response = await self._http.get(
+ f"/api/v1/sessions/{session_path}/context",
+ params={"token_budget": token_budget},
+ )
+ return self._handle_response(response)
+
+ async def get_session_archive(self, session_id: str, archive_id: str) -> Dict[str, Any]:
+ session_path = self._path_segment(session_id)
+ archive_path = self._path_segment(archive_id)
+ response = await self._http.get(f"/api/v1/sessions/{session_path}/archives/{archive_path}")
+ return self._handle_response(response)
+
+ async def delete_session(self, session_id: str) -> None:
+ session_path = self._path_segment(session_id)
+ response = await self._http.delete(f"/api/v1/sessions/{session_path}")
+ self._handle_response(response)
+
+ async def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:
+ response = await self._http.get(f"/api/v1/tasks/{task_id}")
+ if response.status_code == 404:
+ return None
+ return self._handle_response(response)
+
+ async def list_tasks(
+ self,
+ task_type: Optional[str] = None,
+ status: Optional[str] = None,
+ resource_id: Optional[str] = None,
+ limit: int = 50,
+ ) -> List[Dict[str, Any]]:
+ params: Dict[str, Any] = {"limit": limit}
+ if task_type is not None:
+ params["task_type"] = task_type
+ if status is not None:
+ params["status"] = status
+ if resource_id is not None:
+ params["resource_id"] = resource_id
+ response = await self._http.get("/api/v1/tasks", params=params)
+ return self._handle_response(response)
+
+ async def commit_session(
+ self,
+ session_id: str,
+ telemetry: Any = False,
+ *,
+ keep_recent_count: int = 0,
+ ) -> Dict[str, Any]:
+ session_path = self._path_segment(session_id)
+ response = await self._http.post(
+ f"/api/v1/sessions/{session_path}/commit",
+ json={"keep_recent_count": keep_recent_count, "telemetry": telemetry},
+ )
+ return self._handle_response_data(response).get("result", {})
+
+ async def add_message(
+ 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,
+ ) -> 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")
+ if created_at is not None:
+ payload["created_at"] = created_at
+ if peer_id is not None:
+ payload["peer_id"] = peer_id
+ if telemetry is not False:
+ payload["telemetry"] = telemetry
+ session_path = self._path_segment(session_id)
+ response = await self._http.post(f"/api/v1/sessions/{session_path}/messages", json=payload)
+ return self._handle_response_data(response).get("result", {})
+
+ async def export_ovpack(
+ self,
+ uri: str,
+ to: str,
+ include_vectors: bool = False,
+ ) -> str:
+ uri = VikingURI.normalize(uri)
+ to_path = Path(to)
+ if to_path.is_dir():
+ base_name = uri.strip().rstrip("/").split("/")[-1] or "export"
+ to_path = to_path / f"{base_name}.ovpack"
+ elif not str(to_path).endswith(".ovpack"):
+ to_path = Path(str(to_path) + ".ovpack")
+ to_path.parent.mkdir(parents=True, exist_ok=True)
+ response = await self._http.post(
+ "/api/v1/pack/export",
+ json={"uri": uri, "include_vectors": include_vectors},
+ )
+ if not response.is_success:
+ self._handle_response(response)
+ with open(to_path, "wb") as f:
+ f.write(response.content)
+ return str(to_path)
+
+ async def backup_ovpack(self, to: str, include_vectors: bool = False) -> str:
+ to_path = Path(to)
+ if to_path.is_dir():
+ to_path = to_path / "openviking-backup.ovpack"
+ elif not str(to_path).endswith(".ovpack"):
+ to_path = Path(str(to_path) + ".ovpack")
+ to_path.parent.mkdir(parents=True, exist_ok=True)
+ response = await self._http.post(
+ "/api/v1/pack/backup", json={"include_vectors": include_vectors}
+ )
+ if not response.is_success:
+ self._handle_response(response)
+ with open(to_path, "wb") as f:
+ f.write(response.content)
+ return str(to_path)
+
+ async def import_ovpack(
+ self,
+ file_path: str,
+ parent: str,
+ on_conflict: Optional[str] = None,
+ vector_mode: Optional[str] = None,
+ ) -> str:
+ request_data = {"parent": VikingURI.normalize(parent)}
+ if on_conflict is not None:
+ request_data["on_conflict"] = on_conflict
+ if vector_mode is not None:
+ request_data["vector_mode"] = vector_mode
+ file_path_obj = Path(file_path)
+ if not file_path_obj.exists():
+ raise FileNotFoundError(f"Local ovpack file not found: {file_path}")
+ if not file_path_obj.is_file():
+ raise ValueError(f"Path {file_path} is not a file")
+ request_data["temp_file_id"] = await self._upload_temp_file(file_path)
+ response = await self._http.post("/api/v1/pack/import", json=request_data)
+ result = self._handle_response(response)
+ return result.get("uri", "")
+
+ async def restore_ovpack(
+ self,
+ file_path: str,
+ on_conflict: Optional[str] = None,
+ vector_mode: Optional[str] = None,
+ ) -> str:
+ request_data = {}
+ if on_conflict is not None:
+ request_data["on_conflict"] = on_conflict
+ if vector_mode is not None:
+ request_data["vector_mode"] = vector_mode
+ file_path_obj = Path(file_path)
+ if not file_path_obj.exists():
+ raise FileNotFoundError(f"Local ovpack file not found: {file_path}")
+ if not file_path_obj.is_file():
+ raise ValueError(f"Path {file_path} is not a file")
+ request_data["temp_file_id"] = await self._upload_temp_file(file_path)
+ response = await self._http.post("/api/v1/pack/restore", json=request_data)
+ result = self._handle_response(response)
+ return result.get("uri", "")
+
+ async def check_consistency(self, uri: str) -> Dict[str, Any]:
+ response = await self._http.post(
+ "/api/v1/system/consistency",
+ json={"uri": VikingURI.normalize(uri)},
+ )
+ return self._handle_response(response)
+
+ async def health(self) -> bool:
+ try:
+ response = await self._http.get("/health")
+ data = response.json()
+ return data.get("status") == "ok"
+ except Exception:
+ return False
+
+ async def reindex(
+ self,
+ uri: str,
+ mode: str = "vectors_only",
+ wait: bool = True,
+ ) -> Dict[str, Any]:
+ response = await self._http.post(
+ "/api/v1/content/reindex",
+ json={"uri": uri, "mode": mode, "wait": wait},
+ )
+ return self._handle_response(response)
+
+ async def _get_queue_status(self) -> Dict[str, Any]:
+ response = await self._http.get("/api/v1/observer/queue")
+ return self._handle_response(response)
+
+ async def _get_vikingdb_status(self) -> Dict[str, Any]:
+ response = await self._http.get("/api/v1/observer/vikingdb")
+ return self._handle_response(response)
+
+ async def _get_models_status(self) -> Dict[str, Any]:
+ response = await self._http.get("/api/v1/observer/models")
+ return self._handle_response(response)
+
+ async def _get_system_status(self) -> Dict[str, Any]:
+ response = await self._http.get("/api/v1/observer/system")
+ return self._handle_response(response)
+
+ async def admin_create_account(self, account_id: str, admin_user_id: str) -> Dict[str, Any]:
+ response = await self._http.post(
+ "/api/v1/admin/accounts",
+ json={"account_id": account_id, "admin_user_id": admin_user_id},
+ )
+ return self._handle_response(response)
+
+ async def admin_list_accounts(self) -> List[Any]:
+ response = await self._http.get("/api/v1/admin/accounts")
+ return self._handle_response(response)
+
+ async def admin_delete_account(self, account_id: str) -> Dict[str, Any]:
+ response = await self._http.delete(f"/api/v1/admin/accounts/{account_id}")
+ return self._handle_response(response)
+
+ async def admin_register_user(
+ self, account_id: str, user_id: str, role: str = "user"
+ ) -> Dict[str, Any]:
+ response = await self._http.post(
+ f"/api/v1/admin/accounts/{account_id}/users",
+ json={"user_id": user_id, "role": role},
+ )
+ return self._handle_response(response)
+
+ async def admin_list_users(self, account_id: str) -> List[Any]:
+ response = await self._http.get(f"/api/v1/admin/accounts/{account_id}/users")
+ return self._handle_response(response)
+
+ async def admin_remove_user(self, account_id: str, user_id: str) -> Dict[str, Any]:
+ response = await self._http.delete(f"/api/v1/admin/accounts/{account_id}/users/{user_id}")
+ return self._handle_response(response)
+
+ async def admin_set_role(self, account_id: str, user_id: str, role: str) -> Dict[str, Any]:
+ response = await self._http.put(
+ f"/api/v1/admin/accounts/{account_id}/users/{user_id}/role",
+ json={"role": role},
+ )
+ return self._handle_response(response)
+
+ async def admin_regenerate_key(self, account_id: str, user_id: str) -> Dict[str, Any]:
+ response = await self._http.post(f"/api/v1/admin/accounts/{account_id}/users/{user_id}/key")
+ return self._handle_response(response)
+
+ async def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:
+ response = await self._http.post("/api/v1/admin/migrate", json={"cleanup": cleanup})
+ return self._handle_response(response)
+
+ def get_status(self) -> Dict[str, Any]:
+ return run_async(self._get_system_status())
+
+ def is_healthy(self) -> bool:
+ return self.observer.is_healthy()
+
+ @property
+ def observer(self) -> _HTTPObserver:
+ if self._observer is None:
+ self._observer = _HTTPObserver(self)
+ return self._observer
+
+
+class SyncHTTPClient:
+ def __init__(self, *args, **kwargs):
+ self._async_client = AsyncHTTPClient(*args, **kwargs)
+ self._initialized = False
+
+ def initialize(self) -> None:
+ run_async(self._async_client.initialize())
+ self._initialized = True
+
+ def close(self) -> None:
+ run_async(self._async_client.close())
+ self._initialized = False
+
+ def session(self, session_id: Optional[str] = None, must_exist: bool = False) -> SyncSession:
+ if session_id and must_exist:
+ self.get_session(session_id)
+ return SyncSession(self, session_id or "")
+
+ def session_exists(self, session_id: str) -> bool:
+ return run_async(self._async_client.session_exists(session_id))
+
+ def add_resource(
+ self,
+ 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,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.add_resource(
+ path=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,
+ args=args,
+ telemetry=telemetry,
+ )
+ )
+
+ def batch_add_messages(
+ self,
+ session_id: str,
+ messages: list[dict],
+ telemetry: Any = False,
+ ) -> 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))
+
+ def add_skill(
+ self,
+ data: Any,
+ wait: bool = False,
+ timeout: Optional[float] = None,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.add_skill(data, wait=wait, timeout=timeout, telemetry=telemetry)
+ )
+
+ def list_skills(self, node_limit: int = 1000) -> Dict[str, Any]:
+ return run_async(self._async_client.list_skills(node_limit=node_limit))
+
+ def find_skills(
+ self,
+ query: str,
+ limit: int = 10,
+ score_threshold: Optional[float] = None,
+ level: Optional[List[int]] = None,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.find_skills(
+ query=query,
+ limit=limit,
+ score_threshold=score_threshold,
+ level=level,
+ telemetry=telemetry,
+ )
+ )
+
+ def validate_skill(
+ self,
+ data: Any,
+ strict: bool = False,
+ source_path: Optional[str] = None,
+ skill_dir_name: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.validate_skill(
+ data=data,
+ strict=strict,
+ source_path=source_path,
+ skill_dir_name=skill_dir_name,
+ )
+ )
+
+ def get_skill(
+ self,
+ skill_name: str,
+ include_content: Optional[bool] = None,
+ include_files: bool = True,
+ include_source: bool = False,
+ level: Optional[int] = None,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.get_skill(
+ skill_name,
+ include_content=include_content,
+ include_files=include_files,
+ include_source=include_source,
+ level=level,
+ )
+ )
+
+ def update_skill(
+ self,
+ skill_name: str,
+ data: Any,
+ wait: bool = False,
+ timeout: Optional[float] = None,
+ source_metadata: Optional[Dict[str, Any]] = None,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.update_skill(
+ skill_name,
+ data,
+ wait=wait,
+ timeout=timeout,
+ source_metadata=source_metadata,
+ telemetry=telemetry,
+ )
+ )
+
+ def delete_skill(self, skill_name: str) -> Dict[str, Any]:
+ return run_async(self._async_client.delete_skill(skill_name))
+
+ def list_watches(
+ self,
+ active_only: bool = False,
+ to_uri: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ return run_async(self._async_client.list_watches(active_only=active_only, to_uri=to_uri))
+
+ def get_watch(
+ self,
+ task_id: str,
+ to_uri: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ return run_async(self._async_client.get_watch(task_id, to_uri=to_uri))
+
+ def update_watch(
+ self,
+ task_id: Optional[str] = None,
+ *,
+ to_uri: Optional[str] = None,
+ watch_interval: Optional[float] = None,
+ is_active: Optional[bool] = None,
+ reason: Optional[str] = None,
+ instruction: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.update_watch(
+ task_id,
+ to_uri=to_uri,
+ watch_interval=watch_interval,
+ is_active=is_active,
+ reason=reason,
+ instruction=instruction,
+ )
+ )
+
+ def delete_watch(
+ self,
+ task_id: Optional[str] = None,
+ *,
+ to_uri: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ return run_async(self._async_client.delete_watch(task_id, to_uri=to_uri))
+
+ def trigger_watch(
+ self,
+ task_id: Optional[str] = None,
+ *,
+ to_uri: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ return run_async(self._async_client.trigger_watch(task_id, to_uri=to_uri))
+
+ def wait_processed(self, timeout: Optional[float] = None) -> Dict[str, Any]:
+ return run_async(self._async_client.wait_processed(timeout))
+
+ def ls(
+ self,
+ uri: str,
+ simple: bool = False,
+ recursive: bool = False,
+ output: str = "original",
+ abs_limit: int = 256,
+ show_all_hidden: bool = False,
+ node_limit: int = 1000,
+ ) -> List[Any]:
+ return run_async(
+ self._async_client.ls(
+ uri,
+ simple=simple,
+ recursive=recursive,
+ output=output,
+ abs_limit=abs_limit,
+ show_all_hidden=show_all_hidden,
+ node_limit=node_limit,
+ )
+ )
+
+ def tree(
+ self,
+ uri: str,
+ output: str = "original",
+ abs_limit: int = 128,
+ show_all_hidden: bool = False,
+ node_limit: int = 1000,
+ ) -> List[Dict[str, Any]]:
+ return run_async(
+ self._async_client.tree(
+ uri,
+ output=output,
+ abs_limit=abs_limit,
+ show_all_hidden=show_all_hidden,
+ node_limit=node_limit,
+ )
+ )
+
+ def stat(self, uri: str) -> Dict[str, Any]:
+ return run_async(self._async_client.stat(uri))
+
+ def mkdir(self, uri: str, description: Optional[str] = None) -> None:
+ run_async(self._async_client.mkdir(uri, description=description))
+
+ def rm(
+ self,
+ uri: str,
+ recursive: bool = False,
+ wait: bool = False,
+ timeout: Optional[float] = None,
+ ) -> None:
+ run_async(self._async_client.rm(uri, recursive=recursive, wait=wait, timeout=timeout))
+
+ def mv(self, from_uri: str, to_uri: str) -> None:
+ run_async(self._async_client.mv(from_uri, to_uri))
+
+ def read(self, uri: str, offset: int = 0, limit: int = -1) -> str:
+ return run_async(self._async_client.read(uri, offset=offset, limit=limit))
+
+ def abstract(self, uri: str) -> str:
+ return run_async(self._async_client.abstract(uri))
+
+ def overview(self, uri: str) -> str:
+ return run_async(self._async_client.overview(uri))
+
+ def write(
+ self,
+ uri: str,
+ content: str,
+ mode: str = "replace",
+ wait: bool = False,
+ timeout: Optional[float] = None,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.write(
+ uri=uri,
+ content=content,
+ mode=mode,
+ wait=wait,
+ timeout=timeout,
+ telemetry=telemetry,
+ )
+ )
+
+ def set_tags(
+ self,
+ uri: str,
+ tags: List[str],
+ mode: str = "replace",
+ recursive: bool = False,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.set_tags(
+ uri=uri,
+ tags=tags,
+ mode=mode,
+ recursive=recursive,
+ telemetry=telemetry,
+ )
+ )
+
+ def find(
+ self,
+ 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,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.find(
+ 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,
+ )
+ )
+
+ def search(
+ self,
+ query: str,
+ target_uri: Union[str, List[str]] = "",
+ session: Optional[Any] = None,
+ session_id: Optional[str] = None,
+ limit: int = 10,
+ node_limit: Optional[int] = None,
+ score_threshold: Optional[float] = None,
+ filter: Optional[Dict[str, Any]] = None,
+ context_type: Optional[Any] = None,
+ tags: Optional[List[str]] = None,
+ telemetry: Any = False,
+ ) -> 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,
+ 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,
+ )
+ )
+
+ def grep(
+ self,
+ uri: str,
+ pattern: str,
+ case_insensitive: bool = False,
+ node_limit: Optional[int] = None,
+ exclude_uri: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.grep(
+ uri=uri,
+ pattern=pattern,
+ case_insensitive=case_insensitive,
+ node_limit=node_limit,
+ exclude_uri=exclude_uri,
+ )
+ )
+
+ def glob(self, pattern: str, uri: str = "viking://") -> Dict[str, Any]:
+ return run_async(self._async_client.glob(pattern, uri=uri))
+
+ def relations(self, uri: str) -> List[Any]:
+ return run_async(self._async_client.relations(uri))
+
+ def link(self, from_uri: str, to_uris: Union[str, List[str]], reason: str = "") -> None:
+ run_async(self._async_client.link(from_uri, to_uris, reason=reason))
+
+ def unlink(self, from_uri: str, to_uri: str) -> None:
+ run_async(self._async_client.unlink(from_uri, to_uri))
+
+ def create_session(
+ self,
+ session_id: Optional[str] = None,
+ telemetry: Any = False,
+ memory_policy: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.create_session(
+ session_id=session_id,
+ telemetry=telemetry,
+ memory_policy=memory_policy,
+ )
+ )
+
+ def list_sessions(self) -> List[Any]:
+ return run_async(self._async_client.list_sessions())
+
+ def get_session(self, session_id: str, *, auto_create: bool = False) -> Dict[str, Any]:
+ return run_async(self._async_client.get_session(session_id, auto_create=auto_create))
+
+ 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))
+
+ def get_session_archive(self, session_id: str, archive_id: str) -> Dict[str, Any]:
+ return run_async(self._async_client.get_session_archive(session_id, archive_id))
+
+ def delete_session(self, session_id: str) -> None:
+ run_async(self._async_client.delete_session(session_id))
+
+ def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:
+ return run_async(self._async_client.get_task(task_id))
+
+ def list_tasks(
+ self,
+ task_type: Optional[str] = None,
+ status: Optional[str] = None,
+ resource_id: Optional[str] = None,
+ limit: int = 50,
+ ) -> List[Dict[str, Any]]:
+ return run_async(
+ self._async_client.list_tasks(
+ task_type=task_type,
+ status=status,
+ resource_id=resource_id,
+ limit=limit,
+ )
+ )
+
+ def commit_session(
+ self,
+ session_id: str,
+ telemetry: Any = False,
+ *,
+ keep_recent_count: int = 0,
+ ) -> Dict[str, Any]:
+ if telemetry is False:
+ return run_async(
+ self._async_client.commit_session(
+ session_id,
+ keep_recent_count=keep_recent_count,
+ )
+ )
+ return run_async(
+ self._async_client.commit_session(
+ session_id,
+ telemetry=telemetry,
+ keep_recent_count=keep_recent_count,
+ )
+ )
+
+ def add_message(
+ 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,
+ ) -> Dict[str, Any]:
+ kwargs = {
+ "role": role,
+ "content": content,
+ "parts": parts,
+ "created_at": created_at,
+ "peer_id": peer_id,
+ }
+ if telemetry is not False:
+ kwargs["telemetry"] = telemetry
+ return run_async(
+ self._async_client.add_message(
+ session_id,
+ **kwargs,
+ )
+ )
+
+ def export_ovpack(
+ self,
+ uri: str,
+ to: str,
+ include_vectors: bool = False,
+ ) -> str:
+ return run_async(self._async_client.export_ovpack(uri, to, include_vectors=include_vectors))
+
+ def backup_ovpack(self, to: str, include_vectors: bool = False) -> str:
+ return run_async(self._async_client.backup_ovpack(to, include_vectors=include_vectors))
+
+ def import_ovpack(
+ self,
+ file_path: str,
+ parent: str,
+ on_conflict: Optional[str] = None,
+ vector_mode: Optional[str] = None,
+ ) -> str:
+ return run_async(
+ self._async_client.import_ovpack(
+ file_path,
+ parent,
+ on_conflict=on_conflict,
+ vector_mode=vector_mode,
+ )
+ )
+
+ def restore_ovpack(
+ self,
+ file_path: str,
+ on_conflict: Optional[str] = None,
+ vector_mode: Optional[str] = None,
+ ) -> str:
+ return run_async(
+ self._async_client.restore_ovpack(
+ file_path,
+ on_conflict=on_conflict,
+ vector_mode=vector_mode,
+ )
+ )
+
+ def check_consistency(self, uri: str) -> Dict[str, Any]:
+ return run_async(self._async_client.check_consistency(uri))
+
+ def health(self) -> bool:
+ return run_async(self._async_client.health())
+
+ def reindex(
+ self,
+ uri: str,
+ mode: str = "vectors_only",
+ wait: bool = True,
+ ) -> Dict[str, Any]:
+ return run_async(self._async_client.reindex(uri=uri, mode=mode, wait=wait))
+
+ def admin_create_account(self, account_id: str, admin_user_id: str) -> Dict[str, Any]:
+ return run_async(self._async_client.admin_create_account(account_id, admin_user_id))
+
+ def admin_list_accounts(self) -> List[Any]:
+ return run_async(self._async_client.admin_list_accounts())
+
+ def admin_delete_account(self, account_id: str) -> Dict[str, Any]:
+ return run_async(self._async_client.admin_delete_account(account_id))
+
+ def admin_register_user(
+ self, account_id: str, user_id: str, role: str = "user"
+ ) -> Dict[str, Any]:
+ return run_async(self._async_client.admin_register_user(account_id, user_id, role))
+
+ def admin_list_users(self, account_id: str) -> List[Any]:
+ return run_async(self._async_client.admin_list_users(account_id))
+
+ def admin_remove_user(self, account_id: str, user_id: str) -> Dict[str, Any]:
+ return run_async(self._async_client.admin_remove_user(account_id, user_id))
+
+ def admin_set_role(self, account_id: str, user_id: str, role: str) -> Dict[str, Any]:
+ return run_async(self._async_client.admin_set_role(account_id, user_id, role))
+
+ def admin_regenerate_key(self, account_id: str, user_id: str) -> Dict[str, Any]:
+ return run_async(self._async_client.admin_regenerate_key(account_id, user_id))
+
+ def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:
+ return run_async(self._async_client.admin_migrate(cleanup=cleanup))
+
+ def get_status(self) -> Dict[str, Any]:
+ return self._async_client.get_status()
+
+ def is_healthy(self) -> bool:
+ return self._async_client.is_healthy()
+
+ @property
+ def observer(self) -> _HTTPObserver:
+ return self._async_client.observer
+
+ def __getattr__(self, name: str):
+ attr = getattr(self._async_client, name)
+ if inspect.iscoroutinefunction(attr):
+
+ def wrapper(*args, **kwargs):
+ return run_async(attr(*args, **kwargs))
+
+ return wrapper
+ return attr
diff --git a/sdk/python/openviking_sdk/config.py b/sdk/python/openviking_sdk/config.py
new file mode 100644
index 000000000..51affa268
--- /dev/null
+++ b/sdk/python/openviking_sdk/config.py
@@ -0,0 +1,232 @@
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+
+OPENVIKING_CLI_CONFIG_ENV = "OPENVIKING_CLI_CONFIG_FILE"
+DEFAULT_OVCLI_CONF = Path.home() / ".openviking" / "ovcli.conf"
+
+
+@dataclass(frozen=True)
+class ClientConfig:
+ url: str
+ api_key: Optional[str]
+ account: Optional[str]
+ user: Optional[str]
+ actor_peer_id: Optional[str]
+ timeout: float
+ profile_enabled: bool
+ extra_headers: dict[str, str]
+ upload_mode: Optional[str]
+
+
+@dataclass(frozen=True)
+class OVCLIConfig:
+ url: Optional[str]
+ api_key: Optional[str]
+ account: Optional[str]
+ user: Optional[str]
+ actor_peer_id: Optional[str]
+ agent_id: Optional[str]
+ timeout: float
+ profile: bool
+ extra_headers: dict[str, str]
+ upload_mode: Optional[str]
+ output: Optional[str]
+
+
+def _resolve_ovcli_config_path() -> Optional[Path]:
+ config_path = os.getenv(OPENVIKING_CLI_CONFIG_ENV)
+ if config_path:
+ return Path(config_path).expanduser()
+ if DEFAULT_OVCLI_CONF.exists():
+ return DEFAULT_OVCLI_CONF
+ return None
+
+
+def _require_mapping(value: object, *, path: str) -> dict:
+ if not isinstance(value, dict):
+ raise ValueError(f"Invalid value for '{path}': expected object")
+ return value
+
+
+def _optional_string(value: object, *, path: str) -> Optional[str]:
+ if value is None:
+ return None
+ if not isinstance(value, str):
+ raise ValueError(f"Invalid value for '{path}': expected string")
+ return value
+
+
+def _optional_bool(value: object, *, path: str) -> Optional[bool]:
+ if value is None:
+ return None
+ if not isinstance(value, bool):
+ raise ValueError(f"Invalid value for '{path}': expected boolean")
+ return value
+
+
+def _optional_float(value: object, *, path: str) -> Optional[float]:
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ raise ValueError(f"Invalid value for '{path}': expected number")
+ if not isinstance(value, (int, float)):
+ raise ValueError(f"Invalid value for '{path}': expected number")
+ return float(value)
+
+
+def _parse_extra_headers(value: object, *, path: str) -> dict[str, str]:
+ if value is None:
+ return {}
+ data = _require_mapping(value, path=path)
+ parsed: dict[str, str] = {}
+ for key, header_value in data.items():
+ if not isinstance(key, str):
+ raise ValueError(f"Invalid value for '{path}': expected string keys")
+ if not isinstance(header_value, str):
+ raise ValueError(f"Invalid value for '{path}.{key}': expected string")
+ parsed[key] = header_value
+ return parsed
+
+
+def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfig]:
+ path = Path(config_path).expanduser() if config_path else _resolve_ovcli_config_path()
+ if path is None or not path.exists():
+ return None
+
+ try:
+ raw = json.loads(path.read_text())
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"Invalid CLI config in {path}: {exc.msg}") from exc
+
+ try:
+ data = _require_mapping(raw, path="ovcli")
+
+ allowed_keys = {
+ "url",
+ "api_key",
+ "account",
+ "user",
+ "actor_peer_id",
+ "agent_id",
+ "timeout",
+ "profile",
+ "upload",
+ "extra_headers",
+ "extra_header",
+ "output",
+ "root_api_key",
+ }
+ unknown_keys = sorted(set(data) - allowed_keys)
+ if unknown_keys:
+ raise ValueError(f"Unknown field 'ovcli.{unknown_keys[0]}'")
+
+ extra_header_alias = data.get("extra_header")
+ extra_headers_value = data.get("extra_headers", extra_header_alias)
+
+ upload_data = data.get("upload")
+ upload_mode = None
+ if upload_data is not None:
+ upload = _require_mapping(upload_data, path="ovcli.upload")
+ allowed_upload_keys = {"mode", "ignore_dirs", "include", "exclude"}
+ unknown_upload_keys = sorted(set(upload) - allowed_upload_keys)
+ if unknown_upload_keys:
+ raise ValueError(f"Unknown field 'ovcli.upload.{unknown_upload_keys[0]}'")
+ upload_mode = _optional_string(upload.get("mode"), path="ovcli.upload.mode")
+
+ actor_peer_id = _optional_string(data.get("actor_peer_id"), path="ovcli.actor_peer_id")
+ agent_id = _optional_string(data.get("agent_id"), path="ovcli.agent_id")
+ if actor_peer_id is not None and agent_id is not None:
+ raise ValueError("actor_peer_id cannot be used with legacy agent_id")
+
+ timeout = _optional_float(data.get("timeout"), path="ovcli.timeout")
+ profile = _optional_bool(data.get("profile"), path="ovcli.profile")
+
+ return OVCLIConfig(
+ url=_optional_string(data.get("url"), path="ovcli.url"),
+ api_key=_optional_string(data.get("api_key"), path="ovcli.api_key"),
+ account=_optional_string(data.get("account"), path="ovcli.account"),
+ user=_optional_string(data.get("user"), path="ovcli.user"),
+ actor_peer_id=actor_peer_id,
+ agent_id=agent_id,
+ timeout=60.0 if timeout is None else timeout,
+ profile=False if profile is None else profile,
+ extra_headers=_parse_extra_headers(extra_headers_value, path="ovcli.extra_headers"),
+ upload_mode=upload_mode,
+ output=_optional_string(data.get("output"), path="ovcli.output"),
+ )
+ except ValueError as exc:
+ raise ValueError(f"Invalid CLI config in {path}: {exc}") from exc
+
+
+def resolve_client_config(
+ *,
+ url: Optional[str] = None,
+ api_key: Optional[str] = None,
+ account: Optional[str] = None,
+ user: Optional[str] = None,
+ actor_peer_id: Optional[str] = None,
+ timeout: float = 60.0,
+ extra_headers: Optional[dict[str, str]] = None,
+ profile_enabled: Optional[bool] = None,
+ upload_mode: Optional[str] = None,
+) -> ClientConfig:
+ cli_config = load_ovcli_config()
+
+ resolved_url = url or os.getenv("OPENVIKING_URL") or (cli_config.url if cli_config else None)
+ resolved_api_key = (
+ api_key or os.getenv("OPENVIKING_API_KEY") or (cli_config.api_key if cli_config else None)
+ )
+ resolved_account = (
+ account or os.getenv("OPENVIKING_ACCOUNT") or (cli_config.account if cli_config else None)
+ )
+ resolved_user = (
+ user or os.getenv("OPENVIKING_USER") or (cli_config.user if cli_config else None)
+ )
+ resolved_actor_peer_id = (
+ actor_peer_id
+ or os.getenv("OPENVIKING_ACTOR_PEER_ID")
+ or (cli_config.actor_peer_id if cli_config else None)
+ or (cli_config.agent_id if cli_config else None)
+ )
+
+ resolved_timeout = timeout
+ if timeout == 60.0:
+ env_timeout = os.getenv("OPENVIKING_TIMEOUT")
+ if env_timeout:
+ resolved_timeout = float(env_timeout)
+ elif cli_config is not None:
+ resolved_timeout = cli_config.timeout
+
+ resolved_profile_enabled = bool(profile_enabled)
+ if profile_enabled is None and cli_config is not None:
+ resolved_profile_enabled = cli_config.profile
+
+ resolved_extra_headers = dict(extra_headers) if extra_headers is not None else {}
+ if extra_headers is None and cli_config is not None:
+ resolved_extra_headers = dict(cli_config.extra_headers)
+
+ resolved_upload_mode = upload_mode
+ if resolved_upload_mode is None and cli_config is not None:
+ resolved_upload_mode = cli_config.upload_mode
+
+ if not resolved_url:
+ raise ValueError(
+ "url is required. Pass it explicitly, set OPENVIKING_URL, or configure ovcli.conf."
+ )
+
+ return ClientConfig(
+ url=resolved_url.rstrip("/"),
+ api_key=resolved_api_key,
+ account=resolved_account,
+ user=resolved_user,
+ actor_peer_id=resolved_actor_peer_id,
+ timeout=resolved_timeout,
+ profile_enabled=resolved_profile_enabled,
+ extra_headers=resolved_extra_headers,
+ upload_mode=resolved_upload_mode,
+ )
diff --git a/sdk/python/openviking_sdk/errors.py b/sdk/python/openviking_sdk/errors.py
new file mode 100644
index 000000000..14075c8cc
--- /dev/null
+++ b/sdk/python/openviking_sdk/errors.py
@@ -0,0 +1,148 @@
+from __future__ import annotations
+
+from typing import Optional
+
+
+class OpenVikingError(Exception):
+ def __init__(self, message: str, code: str = "UNKNOWN", details: Optional[dict] = None):
+ super().__init__(message)
+ self.message = message
+ self.code = code
+ self.details = details or {}
+
+
+class InvalidArgumentError(OpenVikingError):
+ def __init__(self, message: str, details: Optional[dict] = None):
+ super().__init__(message, code="INVALID_ARGUMENT", details=details)
+
+
+class InvalidURIError(InvalidArgumentError):
+ def __init__(self, uri: str, reason: str = ""):
+ message = f"Invalid URI: {uri}"
+ if reason:
+ message += f" ({reason})"
+ super().__init__(message, details={"uri": uri, "reason": reason})
+ self.code = "INVALID_URI"
+
+
+class NotFoundError(OpenVikingError):
+ def __init__(self, resource: str, resource_type: str = "resource"):
+ details = {"type": resource_type}
+ if resource:
+ details["resource"] = resource
+ message = f"{resource_type.capitalize()} not found: {resource}"
+ else:
+ message = f"{resource_type.capitalize()} not found"
+ super().__init__(message, code="NOT_FOUND", details=details)
+
+
+class AlreadyExistsError(OpenVikingError):
+ def __init__(self, resource: str, resource_type: str = "resource"):
+ super().__init__(
+ f"{resource_type.capitalize()} already exists: {resource}",
+ code="ALREADY_EXISTS",
+ details={"resource": resource, "type": resource_type},
+ )
+
+
+class ConflictError(OpenVikingError):
+ def __init__(self, message: str, resource: Optional[str] = None):
+ super().__init__(
+ message, code="CONFLICT", details={"resource": resource} if resource else {}
+ )
+
+
+class FailedPreconditionError(OpenVikingError):
+ def __init__(self, message: str, details: Optional[dict] = None):
+ super().__init__(message, code="FAILED_PRECONDITION", details=details)
+
+
+class AbortedError(OpenVikingError):
+ def __init__(self, message: str = "Operation aborted", details: Optional[dict] = None):
+ super().__init__(message, code="ABORTED", details=details)
+
+
+class UnauthenticatedError(OpenVikingError):
+ def __init__(self, message: str = "Authentication required"):
+ super().__init__(message, code="UNAUTHENTICATED")
+
+
+class PermissionDeniedError(OpenVikingError):
+ def __init__(self, message: str = "Permission denied", resource: Optional[str] = None):
+ super().__init__(
+ message, code="PERMISSION_DENIED", details={"resource": resource} if resource else {}
+ )
+
+
+class UnavailableError(OpenVikingError):
+ def __init__(self, service: str = "service", reason: str = ""):
+ message = f"{service.capitalize()} unavailable"
+ if reason:
+ message += f": {reason}"
+ super().__init__(
+ message, code="UNAVAILABLE", details={"service": service, "reason": reason}
+ )
+
+
+class ResourceExhaustedError(OpenVikingError):
+ def __init__(self, message: str = "Resource exhausted", details: Optional[dict] = None):
+ super().__init__(message, code="RESOURCE_EXHAUSTED", details=details)
+
+
+class InternalError(OpenVikingError):
+ def __init__(self, message: str = "Internal error", cause: Optional[Exception] = None):
+ super().__init__(message, code="INTERNAL", details={"cause": str(cause)} if cause else {})
+
+
+class DeadlineExceededError(OpenVikingError):
+ def __init__(self, operation: str = "operation", timeout: Optional[float] = None):
+ message = f"{operation.capitalize()} timed out"
+ if timeout:
+ message += f" after {timeout}s"
+ super().__init__(
+ message,
+ code="DEADLINE_EXCEEDED",
+ details={"operation": operation, "timeout": timeout},
+ )
+
+
+class UnimplementedError(OpenVikingError):
+ def __init__(self, message: str = "Operation not implemented", details: Optional[dict] = None):
+ super().__init__(message, code="UNIMPLEMENTED", details=details)
+
+
+class ProcessingError(OpenVikingError):
+ def __init__(self, message: str, source: Optional[str] = None):
+ super().__init__(
+ message, code="PROCESSING_ERROR", details={"source": source} if source else {}
+ )
+
+
+class EmbeddingFailedError(ProcessingError):
+ def __init__(self, message: str = "Embedding generation failed", source: Optional[str] = None):
+ super().__init__(message, source=source)
+ self.code = "EMBEDDING_FAILED"
+
+
+class VLMFailedError(ProcessingError):
+ def __init__(self, message: str = "VLM processing failed", source: Optional[str] = None):
+ super().__init__(message, source=source)
+ self.code = "VLM_FAILED"
+
+
+class SessionExpiredError(OpenVikingError):
+ def __init__(self, session_id: str):
+ super().__init__(
+ f"Session expired: {session_id}",
+ code="SESSION_EXPIRED",
+ details={"session_id": session_id},
+ )
+
+
+class NotInitializedError(OpenVikingError):
+ def __init__(self, component: str = "service"):
+ super().__init__(
+ f"{component.capitalize()} not initialized. Call initialize() first.",
+ code="NOT_INITIALIZED",
+ details={"component": component},
+ )
diff --git a/sdk/python/openviking_sdk/uploads.py b/sdk/python/openviking_sdk/uploads.py
new file mode 100644
index 000000000..083df3d9a
--- /dev/null
+++ b/sdk/python/openviking_sdk/uploads.py
@@ -0,0 +1,27 @@
+from __future__ import annotations
+
+import tempfile
+import uuid
+import zipfile
+from pathlib import Path
+
+
+def zip_directory(dir_path: str) -> str:
+ path = Path(dir_path)
+ if not path.is_dir():
+ raise ValueError(f"Path {path} is not a directory")
+
+ root = path.resolve()
+ zip_path = Path(tempfile.gettempdir()) / f"temp_upload_{uuid.uuid4().hex}.zip"
+
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
+ for file_path in path.rglob("*"):
+ if file_path.is_symlink():
+ continue
+ if file_path.is_file():
+ if not file_path.resolve().is_relative_to(root):
+ continue
+ arcname = str(file_path.relative_to(path)).replace("\\", "/")
+ zipf.write(file_path, arcname=arcname)
+
+ return str(zip_path)
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
new file mode 100644
index 000000000..c28f9a5b4
--- /dev/null
+++ b/sdk/python/pyproject.toml
@@ -0,0 +1,26 @@
+[build-system]
+requires = ["setuptools>=61.0", "setuptools-scm>=8.0", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "openviking-sdk"
+dynamic = ["version"]
+description = "Lightweight Python HTTP SDK for OpenViking"
+readme = "README.md"
+requires-python = ">=3.10"
+dependencies = [
+ "httpx>=0.25.0",
+]
+
+[tool.setuptools]
+package-dir = {"" = "."}
+
+[tool.setuptools.packages.find]
+where = ["."]
+include = ["openviking_sdk*"]
+
+[tool.setuptools_scm]
+root = "../.."
+local_scheme = "no-local-version"
+tag_regex = "^python-sdk/v(?P<version>[0-9]+(?:\\.[0-9]+)*)$"
+git_describe_command = "git describe --dirty --tags --long --match python-sdk/v*"
diff --git a/sdk/python/tests/conftest.py b/sdk/python/tests/conftest.py
new file mode 100644
index 000000000..9ce859ef4
--- /dev/null
+++ b/sdk/python/tests/conftest.py
@@ -0,0 +1,16 @@
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+SDK_ROOT = Path(__file__).resolve().parents[1]
+
+if str(SDK_ROOT) not in sys.path:
+ sys.path.insert(0, str(SDK_ROOT))
+
+
[email protected](autouse=True)
+def _isolate_sdk_tests_from_default_ovcli_config(monkeypatch):
+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(SDK_ROOT / ".missing-ovcli.conf"))
diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.py
new file mode 100644
index 000000000..a78751c3b
--- /dev/null
+++ b/sdk/python/tests/test_async_client_behaviors.py
@@ -0,0 +1,699 @@
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from openviking_sdk import AsyncHTTPClient, SyncHTTPClient
+from openviking_sdk.client import Session, SyncSession
+from openviking_sdk.errors import NotFoundError
+
+
+async def test_async_http_client_batch_add_messages_posts_batch_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": {"session_id": "batch-session", "message_count": 2, "added": 2}
+ }
+
+ messages = [
+ {
+ "role": "user",
+ "content": "hello",
+ "peer_id": "explicit-user",
+ "created_at": "2026-05-28T00:00:00+00:00",
+ },
+ {"role": "assistant", "parts": [{"type": "text", "text": "hi"}]},
+ ]
+
+ result = await client.batch_add_messages("batch-session", messages)
+
+ assert result == {"session_id": "batch-session", "message_count": 2, "added": 2}
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/sessions/batch-session/messages/batch",
+ json={"messages": messages},
+ )
+
+
+async def test_async_http_client_batch_add_messages_url_encodes_session_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": {"session_id": "encoded-session", "message_count": 1, "added": 1}
+ }
+
+ session_id = (
+ "feishu__cli_a938e530eb7c9bd9__"
+ "oc_aa9e08fddf5727f9c53400a07ff505cd#om_x100b6ff6c3df48ace10030ac68d3eb4"
+ )
+
+ await client.batch_add_messages(session_id, [{"role": "user", "content": "hello"}])
+
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/sessions/"
+ "feishu__cli_a938e530eb7c9bd9__"
+ "oc_aa9e08fddf5727f9c53400a07ff505cd%23om_x100b6ff6c3df48ace10030ac68d3eb4"
+ "/messages/batch",
+ json={"messages": [{"role": "user", "content": "hello"}]},
+ )
+
+
+async def test_async_http_client_reindex_posts_content_reindex():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+ client._handle_response = lambda _response: {"status": "completed"}
+
+ result = await client.reindex(
+ "viking://resources/demo",
+ mode="vectors_only",
+ wait=False,
+ )
+
+ assert result == {"status": "completed"}
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/content/reindex",
+ json={
+ "uri": "viking://resources/demo",
+ "mode": "vectors_only",
+ "wait": False,
+ },
+ )
+
+
+def test_sync_http_client_reindex_forwards_to_async_client():
+ client = SyncHTTPClient(url="http://localhost:1933")
+ with patch.object(
+ client._async_client,
+ "reindex",
+ return_value={"status": "accepted"},
+ ) as mock_reindex:
+ with patch(
+ "openviking_sdk.client.run_async",
+ return_value={"status": "accepted"},
+ ) as mock_run:
+ result = client.reindex(
+ "viking://resources/demo",
+ mode="vectors_only",
+ wait=False,
+ )
+
+ assert result == {"status": "accepted"}
+ assert mock_run.called
+ assert mock_reindex.called
+
+
+def test_sync_http_client_batch_add_messages_forwards_to_async_client():
+ client = SyncHTTPClient(url="http://localhost:1933")
+ messages = [
+ {
+ "role": "user",
+ "content": "hello",
+ "peer_id": "explicit-user",
+ "created_at": "2026-05-28T00:00:00+00:00",
+ },
+ {"role": "assistant", "parts": [{"type": "text", "text": "hi"}]},
+ ]
+
+ with patch.object(
+ client._async_client,
+ "batch_add_messages",
+ return_value={"session_id": "batch-session", "message_count": 2, "added": 2},
+ ) as mock_batch:
+ with patch(
+ "openviking_sdk.client.run_async",
+ return_value={"session_id": "batch-session", "message_count": 2, "added": 2},
+ ) as mock_run:
+ result = client.batch_add_messages("batch-session", messages)
+
+ assert result == {"session_id": "batch-session", "message_count": 2, "added": 2}
+ assert mock_run.called
+ mock_batch.assert_called_once_with("batch-session", messages)
+
+
+def test_sync_http_client_session_returns_sync_session_wrapper():
+ client = SyncHTTPClient(url="http://localhost:1933")
+
+ session = client.session("demo-session")
+
+ assert isinstance(session, SyncSession)
+ assert session.session_id == "demo-session"
+
+
+def test_sync_session_add_message_wraps_async_client():
+ client = SyncHTTPClient(url="http://localhost:1933")
+ session = client.session("demo-session")
+
+ with patch.object(
+ client._async_client,
+ "add_message",
+ return_value={"message_id": "msg-1"},
+ ) as mock_add_message:
+ with patch(
+ "openviking_sdk.client.run_async",
+ return_value={"message_id": "msg-1"},
+ ) as mock_run:
+ result = session.add_message("user", content="hello")
+
+ assert result == {"message_id": "msg-1"}
+ assert mock_run.called
+ mock_add_message.assert_called_once_with(
+ "demo-session",
+ role="user",
+ content="hello",
+ parts=None,
+ created_at=None,
+ peer_id=None,
+ )
+
+
+def test_sync_session_commit_and_context_are_sync():
+ client = SyncHTTPClient(url="http://localhost:1933")
+ session = client.session("demo-session")
+
+ with patch.object(
+ client._async_client,
+ "commit_session",
+ return_value={"status": "completed"},
+ ) as mock_commit:
+ with patch.object(
+ client._async_client,
+ "get_session_context",
+ return_value={"messages": []},
+ ) as mock_context:
+ with patch(
+ "openviking_sdk.client.run_async",
+ side_effect=[{"status": "completed"}, {"messages": []}],
+ ) as mock_run:
+ commit_result = session.commit(keep_recent_count=1)
+ context_result = session.get_session_context(2048)
+
+ 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_context.assert_called_once_with("demo-session", 2048)
+
+
+def test_sync_http_client_declares_common_sync_methods_explicitly():
+ explicit_methods = SyncHTTPClient.__dict__
+
+ for method_name in [
+ "add_message",
+ "create_session",
+ "list_sessions",
+ "get_session",
+ "get_session_context",
+ "delete_session",
+ "search",
+ "find",
+ "grep",
+ "glob",
+ "ls",
+ "tree",
+ "read",
+ "write",
+ "add_resource",
+ "add_skill",
+ "import_ovpack",
+ "export_ovpack",
+ "list_watches",
+ "get_watch",
+ "update_watch",
+ "delete_watch",
+ "trigger_watch",
+ "list_skills",
+ "get_skill",
+ "update_skill",
+ "delete_skill",
+ "get_task",
+ "list_tasks",
+ "admin_list_accounts",
+ ]:
+ assert method_name in explicit_methods, method_name
+
+
+def test_sync_http_client_session_must_exist_checks_existence():
+ client = SyncHTTPClient(url="http://localhost:1933")
+
+ with patch.object(
+ client, "get_session", return_value={"session_id": "demo-session"}
+ ) as mock_get:
+ session = client.session("demo-session", must_exist=True)
+
+ assert isinstance(session, SyncSession)
+ assert session.session_id == "demo-session"
+ mock_get.assert_called_once_with("demo-session")
+
+
+def test_sync_http_client_session_must_exist_propagates_not_found():
+ client = SyncHTTPClient(url="http://localhost:1933")
+
+ with patch.object(
+ client,
+ "get_session",
+ side_effect=NotFoundError("missing-session", "session"),
+ ) as mock_get:
+ with pytest.raises(NotFoundError):
+ client.session("missing-session", must_exist=True)
+
+ mock_get.assert_called_once_with("missing-session")
+
+
+def test_sync_session_commit_async_and_repr_match_sync_usage():
+ client = SyncHTTPClient(url="http://localhost:1933")
+ session = client.session("demo-session")
+
+ with patch.object(session, "commit", return_value={"status": "completed"}) as mock_commit:
+ result = session.commit_async(keep_recent_count=3)
+
+ assert result == {"status": "completed"}
+ mock_commit.assert_called_once_with(telemetry=False, keep_recent_count=3)
+ assert "demo-session" in repr(session)
+
+
+def test_sync_http_client_get_status_does_not_require_run_async():
+ client = SyncHTTPClient(url="http://localhost:1933")
+ client._async_client._get_system_status = AsyncMock(return_value={"is_healthy": True})
+
+ status = client.get_status()
+
+ assert status == {"is_healthy": True}
+
+
+def test_sync_http_client_health_wraps_async_coroutine():
+ client = SyncHTTPClient(url="http://localhost:1933")
+ client._async_client.health = AsyncMock(return_value=True)
+
+ assert client.health() is True
+
+
+async def test_write_omits_removed_semantic_flags_from_http_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": {"uri": "viking://resources/demo.md"}
+ }
+
+ await client.write("viking://resources/demo.md", "updated", wait=True)
+
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/content/write",
+ json={
+ "uri": "viking://resources/demo.md",
+ "content": "updated",
+ "mode": "replace",
+ "wait": True,
+ "timeout": None,
+ "telemetry": False,
+ },
+ )
+
+
+async def test_add_skill_uploads_local_file_even_when_url_is_localhost(tmp_path):
+ skill_file = tmp_path / "SKILL.md"
+ skill_file.write_text("---\nname: demo\ndescription: demo\n---\n\n# Demo\n")
+
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+
+ async def fake_upload(_path: str) -> str:
+ return "upload_skill.md"
+
+ client._upload_temp_file = fake_upload
+ client._handle_response_data = lambda _response: {"result": {"status": "ok"}}
+
+ await client.add_skill(str(skill_file))
+
+ fake_http.post.assert_awaited_once()
+ assert fake_http.post.await_args.kwargs["json"]["temp_file_id"] == "upload_skill.md"
+
+
+async def test_add_resource_uploads_local_file_even_when_url_is_localhost(tmp_path):
+ resource_file = tmp_path / "demo.md"
+ resource_file.write_text("# Demo\n")
+
+ client = AsyncHTTPClient(url="http://127.0.0.1:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+
+ async def fake_upload(_path: str) -> str:
+ return "upload_resource.md"
+
+ client._upload_temp_file = fake_upload
+ client._handle_response_data = lambda _response: {
+ "result": {"root_uri": "viking://resources/demo"}
+ }
+
+ await client.add_resource(str(resource_file), reason="test", watch_interval=60)
+
+ fake_http.post.assert_awaited_once()
+ payload = fake_http.post.await_args.kwargs["json"]
+ assert payload["temp_file_id"] == "upload_resource.md"
+ assert payload["watch_interval"] == 60
+ assert "path" not in payload
+
+
+async def test_import_ovpack_uploads_local_file_even_when_url_is_localhost(tmp_path):
+ pack_file = tmp_path / "demo.ovpack"
+ pack_file.write_bytes(b"ovpack")
+
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+
+ async def fake_upload(_path: str) -> str:
+ return "upload_pack.ovpack"
+
+ client._upload_temp_file = fake_upload
+ client._handle_response = lambda _response: {"uri": "viking://resources/imported"}
+
+ await client.import_ovpack(
+ str(pack_file),
+ parent="viking://resources/",
+ on_conflict="skip",
+ )
+
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/pack/import",
+ json={
+ "parent": "viking://resources/",
+ "on_conflict": "skip",
+ "temp_file_id": "upload_pack.ovpack",
+ },
+ )
+
+
+async def test_find_uses_node_limit_as_http_limit_and_normalizes_target_uri_list():
+ 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": {"total": 0, "resources": []}}
+
+ await client.find(
+ query="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},
+ )
+
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/search/find",
+ json={
+ "query": "sample",
+ "target_uri": ["viking://resources/demo", "viking://resources/kept"],
+ "limit": 9,
+ "score_threshold": 0.4,
+ "filter": {"type": "resource"},
+ "context_type": "resource",
+ "tags": ["k:v"],
+ "telemetry": {"enabled": True},
+ },
+ )
+
+
+async def test_search_uses_session_wrapper_session_id_in_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": {"total": 0, "resources": []}}
+
+ session = Session(client, "thread-123")
+ await client.search(query="sample", target_uri="/resources/demo", session=session, limit=5)
+
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/search/search",
+ json={
+ "query": "sample",
+ "target_uri": "viking://resources/demo",
+ "session_id": "thread-123",
+ "limit": 5,
+ "score_threshold": None,
+ "filter": None,
+ "context_type": None,
+ "tags": None,
+ "telemetry": False,
+ },
+ )
+
+
+async def test_grep_normalizes_uri_and_exclude_uri():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+ client._handle_response = lambda _response: {"count": 0, "matches": []}
+
+ await client.grep(
+ "/resources/demo",
+ pattern="Sample",
+ case_insensitive=True,
+ node_limit=12,
+ exclude_uri="/resources/demo/tmp",
+ )
+
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/search/grep",
+ json={
+ "uri": "viking://resources/demo",
+ "pattern": "Sample",
+ "case_insensitive": True,
+ "node_limit": 12,
+ "exclude_uri": "viking://resources/demo/tmp",
+ },
+ )
+
+
+async def test_glob_normalizes_scope_uri():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+ client._handle_response = lambda _response: {
+ "count": 1,
+ "matches": ["viking://resources/demo.md"],
+ }
+
+ await client.glob("*.md", uri="/resources/")
+
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/search/glob",
+ json={"pattern": "*.md", "uri": "viking://resources/"},
+ )
+
+
+async def test_ls_passes_full_query_params():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(get=AsyncMock(return_value=object()))
+ client._http = fake_http
+ client._handle_response = lambda _response: []
+
+ await client.ls(
+ "/resources/",
+ simple=True,
+ recursive=True,
+ output="agent",
+ abs_limit=32,
+ show_all_hidden=True,
+ node_limit=44,
+ )
+
+ fake_http.get.assert_awaited_once_with(
+ "/api/v1/fs/ls",
+ params={
+ "uri": "viking://resources/",
+ "simple": True,
+ "recursive": True,
+ "output": "agent",
+ "abs_limit": 32,
+ "show_all_hidden": True,
+ "node_limit": 44,
+ },
+ )
+
+
+async def test_rm_uses_delete_request_with_timeout_when_provided():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(request=AsyncMock(return_value=object()))
+ client._http = fake_http
+ client._handle_response = lambda _response: None
+
+ await client.rm("/resources/demo.md", recursive=True, wait=True, timeout=5.0)
+
+ fake_http.request.assert_awaited_once_with(
+ "DELETE",
+ "/api/v1/fs",
+ params={
+ "uri": "viking://resources/demo.md",
+ "recursive": True,
+ "wait": True,
+ "timeout": 5.0,
+ },
+ )
+
+
+async def test_link_normalizes_single_and_multiple_target_uris():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+ client._handle_response = lambda _response: None
+
+ await client.link("/resources/from", ["/resources/a", "viking://resources/b"], reason="demo")
+
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/relations/link",
+ json={
+ "from_uri": "viking://resources/from",
+ "to_uris": ["viking://resources/a", "viking://resources/b"],
+ "reason": "demo",
+ },
+ )
+
+
+async def test_watch_routes_support_uri_lookup_and_normalization():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(
+ get=AsyncMock(return_value=object()),
+ patch=AsyncMock(return_value=object()),
+ delete=AsyncMock(return_value=object()),
+ post=AsyncMock(return_value=object()),
+ )
+ client._http = fake_http
+ client._handle_response = lambda _response: {"ok": True}
+
+ await client.list_watches(active_only=True, to_uri="/resources/demo")
+ await client.get_watch("task-1", to_uri="/resources/demo")
+ await client.update_watch(
+ to_uri="/resources/demo",
+ watch_interval=30,
+ is_active=False,
+ reason="adjust",
+ instruction="refresh",
+ )
+ await client.delete_watch(to_uri="/resources/demo")
+ await client.trigger_watch(to_uri="/resources/demo")
+
+ fake_http.get.assert_any_await(
+ "/api/v1/watches",
+ params={"active_only": True, "to_uri": "viking://resources/demo"},
+ )
+ fake_http.get.assert_any_await(
+ "/api/v1/watches/task-1",
+ params={"to_uri": "viking://resources/demo"},
+ )
+ fake_http.patch.assert_awaited_once_with(
+ "/api/v1/watches",
+ params={"to_uri": "viking://resources/demo"},
+ json={
+ "watch_interval": 30,
+ "is_active": False,
+ "reason": "adjust",
+ "instruction": "refresh",
+ },
+ )
+ fake_http.delete.assert_awaited_once_with(
+ "/api/v1/watches",
+ params={"to_uri": "viking://resources/demo"},
+ )
+ fake_http.post.assert_awaited_once_with(
+ "/api/v1/watches/trigger",
+ params={"to_uri": "viking://resources/demo"},
+ )
+
+
+async def test_session_exists_returns_false_on_not_found():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+
+ async def raise_not_found(_session_id: str, *, auto_create: bool = False):
+ raise NotFoundError("demo", "session")
+
+ client.get_session = raise_not_found
+
+ assert await client.session_exists("missing-session") is False
+
+
+async def test_session_wrapper_forwards_commit_context_and_archive_operations():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ session = Session(client, "thread-1")
+ client.commit_session = AsyncMock(return_value={"status": "completed"})
+ client.get_session_context = AsyncMock(return_value={"messages": []})
+ client.get_session_archive = AsyncMock(return_value={"archive_id": "arc-1"})
+ client.delete_session = AsyncMock(return_value=None)
+
+ commit_result = await session.commit(keep_recent_count=2)
+ context_result = await session.get_session_context(2048)
+ archive_result = await session.get_archive("arc-1")
+ await session.delete()
+
+ 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.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")
+
+
+async def test_export_and_backup_ovpack_append_default_suffixes(tmp_path):
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ export_response = SimpleNamespace(is_success=True, content=b"exported")
+ backup_response = SimpleNamespace(is_success=True, content=b"backup")
+ fake_http = SimpleNamespace(post=AsyncMock(side_effect=[export_response, backup_response]))
+ client._http = fake_http
+
+ export_path = await client.export_ovpack("/resources/demo/", str(tmp_path / "exports" / "demo"))
+ backup_path = await client.backup_ovpack(str(tmp_path / "backup-dir"))
+
+ assert export_path.endswith("demo.ovpack")
+ assert Path(export_path).read_bytes() == b"exported"
+ assert backup_path.endswith("backup-dir.ovpack")
+ assert Path(backup_path).read_bytes() == b"backup"
+
+
+async def test_import_ovpack_fails_fast_when_local_file_is_missing(tmp_path):
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+
+ missing_path = tmp_path / "missing.ovpack"
+
+ with pytest.raises(FileNotFoundError, match="Local ovpack file not found"):
+ await client.import_ovpack(str(missing_path), parent="viking://resources/")
+
+
+async def test_import_ovpack_fails_fast_when_path_is_directory(tmp_path):
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+
+ pack_dir = tmp_path / "pack_dir"
+ pack_dir.mkdir()
+
+ with pytest.raises(ValueError, match="is not a file"):
+ await client.import_ovpack(str(pack_dir), parent="viking://resources/")
diff --git a/sdk/python/tests/test_client_config.py b/sdk/python/tests/test_client_config.py
new file mode 100644
index 000000000..72d632b48
--- /dev/null
+++ b/sdk/python/tests/test_client_config.py
@@ -0,0 +1,52 @@
+import pytest
+from openviking_sdk import AsyncHTTPClient
+
+
+def test_explicit_arguments_win_over_env(monkeypatch):
+ monkeypatch.setenv("OPENVIKING_URL", "http://env-host:1933")
+ monkeypatch.setenv("OPENVIKING_API_KEY", "env-key")
+ monkeypatch.setenv("OPENVIKING_ACCOUNT", "env-account")
+ monkeypatch.setenv("OPENVIKING_USER", "env-user")
+ monkeypatch.setenv("OPENVIKING_ACTOR_PEER_ID", "env-actor")
+ monkeypatch.setenv("OPENVIKING_TIMEOUT", "12.5")
+
+ client = AsyncHTTPClient(
+ url="http://explicit-host:1933",
+ api_key="explicit-key",
+ account="explicit-account",
+ user="explicit-user",
+ actor_peer_id="explicit-actor",
+ timeout=33.0,
+ )
+
+ assert client._url == "http://explicit-host:1933"
+ assert client._api_key == "explicit-key"
+ assert client._account == "explicit-account"
+ assert client._user_id == "explicit-user"
+ assert client._actor_peer_id == "explicit-actor"
+ assert client._timeout == 33.0
+
+
+def test_env_values_fill_missing_fields(monkeypatch):
+ monkeypatch.setenv("OPENVIKING_URL", "http://env-host:1933")
+ monkeypatch.setenv("OPENVIKING_API_KEY", "env-key")
+ monkeypatch.setenv("OPENVIKING_ACCOUNT", "env-account")
+ monkeypatch.setenv("OPENVIKING_USER", "env-user")
+ monkeypatch.setenv("OPENVIKING_ACTOR_PEER_ID", "env-actor")
+ monkeypatch.setenv("OPENVIKING_TIMEOUT", "12.5")
+
+ client = AsyncHTTPClient()
+
+ assert client._url == "http://env-host:1933"
+ assert client._api_key == "env-key"
+ assert client._account == "env-account"
+ assert client._user_id == "env-user"
+ assert client._actor_peer_id == "env-actor"
+ assert client._timeout == 12.5
+
+
+def test_url_is_required_when_missing_everywhere(monkeypatch):
+ monkeypatch.delenv("OPENVIKING_URL", raising=False)
+
+ with pytest.raises(ValueError, match="url is required"):
+ AsyncHTTPClient()
diff --git a/sdk/python/tests/test_error_mapping.py b/sdk/python/tests/test_error_mapping.py
new file mode 100644
index 000000000..7eab36b0b
--- /dev/null
+++ b/sdk/python/tests/test_error_mapping.py
@@ -0,0 +1,43 @@
+import pytest
+from openviking_sdk import AsyncHTTPClient
+from openviking_sdk.errors import (
+ AbortedError,
+ ConflictError,
+ OpenVikingError,
+ ResourceExhaustedError,
+ UnimplementedError,
+)
+
+
+ ("code", "exc_type"),
+ (
+ ("CONFLICT", ConflictError),
+ ("ABORTED", AbortedError),
+ ("RESOURCE_EXHAUSTED", ResourceExhaustedError),
+ ("UNIMPLEMENTED", UnimplementedError),
+ ),
+)
+def test_client_maps_standard_error_codes(code, exc_type):
+ client = AsyncHTTPClient(url="http://127.0.0.1:1933")
+
+ with pytest.raises(exc_type) as exc_info:
+ client._raise_exception({"code": code, "message": "mapped"})
+
+ assert exc_info.value.code == code
+
+
+def test_client_preserves_unknown_error_code():
+ client = AsyncHTTPClient(url="http://127.0.0.1:1933")
+
+ with pytest.raises(OpenVikingError) as exc_info:
+ client._raise_exception(
+ {
+ "code": "PROVIDER_SPECIFIC",
+ "message": "provider-specific failure",
+ "details": {"x": 1},
+ }
+ )
+
+ assert exc_info.value.code == "PROVIDER_SPECIFIC"
+ assert exc_info.value.details == {"x": 1}
diff --git a/sdk/python/tests/test_legacy_shims.py b/sdk/python/tests/test_legacy_shims.py
new file mode 100644
index 000000000..8bd66b300
--- /dev/null
+++ b/sdk/python/tests/test_legacy_shims.py
@@ -0,0 +1,70 @@
+import sys
+from pathlib import Path
+
+import pytest
+
+SDK_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+if str(SDK_ROOT) not in sys.path:
+ sys.path.insert(0, str(SDK_ROOT))
+if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+
+
+def _purge_legacy_modules() -> None:
+ for name in list(sys.modules):
+ if (
+ name == "openviking_sdk"
+ or name.startswith("openviking_sdk.")
+ or name == "openviking_cli"
+ or name.startswith("openviking_cli.")
+ ):
+ sys.modules.pop(name, None)
+
+
+def test_legacy_async_http_client_shim_points_to_sdk():
+ _purge_legacy_modules()
+ from openviking_cli.client.http import AsyncHTTPClient as LegacyAsyncHTTPClient
+
+ client = LegacyAsyncHTTPClient(url="http://localhost:1933")
+ assert client._url == "http://localhost:1933"
+ try:
+ client._raise_exception({"code": "CONFLICT", "message": "boom"})
+ except Exception as exc:
+ assert getattr(exc, "code", None) == "CONFLICT"
+
+
+def test_legacy_async_http_client_shim_imports_from_repo_checkout(monkeypatch):
+ _purge_legacy_modules()
+ monkeypatch.setattr(
+ sys,
+ "path",
+ [path for path in sys.path if path != str(SDK_ROOT)],
+ )
+
+ from openviking_cli.client.http import AsyncHTTPClient as LegacyAsyncHTTPClient
+
+ client = LegacyAsyncHTTPClient(url="http://localhost:1933")
+ assert client._url == "http://localhost:1933"
+
+
+def test_legacy_async_http_client_shim_raises_legacy_exceptions():
+ _purge_legacy_modules()
+ from openviking_cli.client.http import AsyncHTTPClient as LegacyAsyncHTTPClient
+ from openviking_cli.exceptions import ConflictError
+
+ client = LegacyAsyncHTTPClient(url="http://localhost:1933")
+
+ with pytest.raises(ConflictError) as exc_info:
+ client._raise_exception({"code": "CONFLICT", "message": "boom"})
+
+ assert exc_info.value.code == "CONFLICT"
+
+
+def test_legacy_sync_http_client_shim_points_to_sdk():
+ _purge_legacy_modules()
+ from openviking_cli.client.sync_http import SyncHTTPClient as LegacySyncHTTPClient
+
+ client = LegacySyncHTTPClient(url="http://localhost:1933")
+ assert client._async_client._url == "http://localhost:1933"
diff --git a/sdk/python/tests/test_main_package_exports.py b/sdk/python/tests/test_main_package_exports.py
new file mode 100644
index 000000000..ef8c2332d
--- /dev/null
+++ b/sdk/python/tests/test_main_package_exports.py
@@ -0,0 +1,82 @@
+import sys
+from pathlib import Path
+
+SDK_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+if str(SDK_ROOT) not in sys.path:
+ sys.path.insert(0, str(SDK_ROOT))
+if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+
+
+def _purge_openviking_modules() -> None:
+ for name in list(sys.modules):
+ if name == "openviking" or name.startswith("openviking."):
+ sys.modules.pop(name, None)
+ if name == "openviking_sdk" or name.startswith("openviking_sdk."):
+ sys.modules.pop(name, None)
+
+
+def test_openviking_top_level_exports_http_clients():
+ _purge_openviking_modules()
+ import openviking
+ from openviking_cli.client.http import AsyncHTTPClient as LegacyAsyncHTTPClient
+ from openviking_cli.client.sync_http import SyncHTTPClient as LegacySyncHTTPClient
+
+ assert openviking.AsyncHTTPClient is LegacyAsyncHTTPClient
+ assert openviking.SyncHTTPClient is LegacySyncHTTPClient
+
+
+def test_openviking_client_module_exports_http_clients():
+ _purge_openviking_modules()
+ import os
+
+ from openviking_cli.client.http import AsyncHTTPClient as LegacyAsyncHTTPClient
+ from openviking_cli.client.sync_http import SyncHTTPClient as LegacySyncHTTPClient
+
+ os.environ["OPENVIKING_LOG_ROUTING"] = "stdout"
+ import openviking.client as client_module
+
+ assert client_module.AsyncHTTPClient is LegacyAsyncHTTPClient
+ assert client_module.SyncHTTPClient is LegacySyncHTTPClient
+
+
+def test_openviking_client_module_can_fallback_to_repo_local_sdk():
+ _purge_openviking_modules()
+ original_sys_path = list(sys.path)
+ try:
+ sys.path[:] = [p for p in sys.path if p != str(SDK_ROOT)]
+
+ import openviking.client as client_module
+
+ assert client_module.AsyncHTTPClient.__module__ == "openviking_cli.client._http_compat"
+ assert client_module.SyncHTTPClient.__module__ == "openviking_cli.client._http_compat"
+ finally:
+ sys.path[:] = original_sys_path
+
+
+def test_openviking_client_module_import_is_lazy_for_local_client_stack():
+ _purge_openviking_modules()
+
+ import openviking.client as client_module
+
+ assert "openviking.client.local" not in sys.modules
+ assert "openviking.service" not in sys.modules
+ assert client_module.AsyncHTTPClient.__module__ == "openviking_cli.client._http_compat"
+
+
+def test_openviking_http_client_preserves_legacy_exception_types():
+ _purge_openviking_modules()
+ import openviking
+ from openviking_cli.exceptions import ConflictError
+
+ client = openviking.AsyncHTTPClient(url="http://127.0.0.1:1933")
+
+ try:
+ client._raise_exception({"code": "CONFLICT", "message": "mapped"})
+ except Exception as exc:
+ assert isinstance(exc, ConflictError)
+ assert exc.code == "CONFLICT"
+ else:
+ raise AssertionError("expected ConflictError")
diff --git a/sdk/python/tests/test_ovcli_config_compat.py b/sdk/python/tests/test_ovcli_config_compat.py
new file mode 100644
index 000000000..817407dea
--- /dev/null
+++ b/sdk/python/tests/test_ovcli_config_compat.py
@@ -0,0 +1,133 @@
+from __future__ import annotations
+
+import json
+
+import pytest
+from openviking_sdk import AsyncHTTPClient
+
+
+def test_async_http_client_loads_connection_fields_from_ovcli_config(tmp_path, monkeypatch):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text(
+ json.dumps(
+ {
+ "url": "http://config-host:1933",
+ "api_key": "config-key",
+ "account": "config-account",
+ "user": "config-user",
+ "timeout": 12.5,
+ }
+ )
+ )
+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(config_path))
+ monkeypatch.delenv("OPENVIKING_URL", raising=False)
+ monkeypatch.delenv("OPENVIKING_API_KEY", raising=False)
+
+ client = AsyncHTTPClient()
+
+ assert client._url == "http://config-host:1933"
+ assert client._api_key == "config-key"
+ assert client._account == "config-account"
+ assert client._user_id == "config-user"
+ assert client._timeout == 12.5
+
+
+def test_async_http_client_loads_upload_mode_and_extra_headers_from_ovcli_config(
+ tmp_path, monkeypatch
+):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text(
+ json.dumps(
+ {
+ "url": "http://config-host:1933",
+ "upload": {"mode": "shared"},
+ "extra_headers": {
+ "X-Custom-Header": "custom-value",
+ "Authorization": "Bearer token",
+ },
+ }
+ )
+ )
+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(config_path))
+ monkeypatch.delenv("OPENVIKING_URL", raising=False)
+
+ client = AsyncHTTPClient()
+
+ assert client._upload_mode == "shared"
+ assert client._extra_headers == {
+ "X-Custom-Header": "custom-value",
+ "Authorization": "Bearer token",
+ }
+
+
+def test_async_http_client_explicit_arguments_override_ovcli_config(tmp_path, monkeypatch):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text(
+ json.dumps(
+ {
+ "url": "http://config-host:1933",
+ "api_key": "config-key",
+ "account": "config-account",
+ "user": "config-user",
+ "timeout": 12.5,
+ "upload": {"mode": "shared"},
+ "extra_headers": {"X-Custom-Header": "from-config"},
+ }
+ )
+ )
+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(config_path))
+
+ client = AsyncHTTPClient(
+ url="http://explicit-host:1933",
+ api_key="explicit-key",
+ account="explicit-account",
+ user="explicit-user",
+ timeout=33.0,
+ extra_headers={"X-Custom-Header": "from-explicit"},
+ upload_mode="local",
+ )
+
+ assert client._url == "http://explicit-host:1933"
+ assert client._api_key == "explicit-key"
+ assert client._account == "explicit-account"
+ assert client._user_id == "explicit-user"
+ assert client._timeout == 33.0
+ assert client._extra_headers == {"X-Custom-Header": "from-explicit"}
+ assert client._upload_mode == "local"
+
+
+def test_async_http_client_reports_invalid_ovcli_config(tmp_path, monkeypatch):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text(json.dumps({"url": "http://localhost:1933", "timeout": "fast"}))
+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(config_path))
+ monkeypatch.delenv("OPENVIKING_URL", raising=False)
+
+ with pytest.raises(ValueError, match="Invalid CLI config"):
+ AsyncHTTPClient()
+
+
+def test_async_http_client_inherits_profile_enabled_from_ovcli_config(tmp_path, monkeypatch):
+ config_path = tmp_path / "ovcli.conf"
+ config_path.write_text(
+ json.dumps(
+ {
+ "url": "http://config-host:1933",
+ "profile": True,
+ }
+ )
+ )
+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(config_path))
+ monkeypatch.delenv("OPENVIKING_URL", raising=False)
+
+ client = AsyncHTTPClient()
+
+ assert client._profile_enabled is True
+
+
+def test_async_http_client_rejects_explicit_actor_peer_id_and_agent_id_together():
+ with pytest.raises(ValueError, match="actor_peer_id cannot be used with legacy agent_id"):
+ AsyncHTTPClient(
+ url="http://explicit-host:1933",
+ actor_peer_id="actor-a",
+ agent_id="legacy-agent",
+ )
diff --git a/sdk/python/tests/test_packaging_imports.py b/sdk/python/tests/test_packaging_imports.py
new file mode 100644
index 000000000..7bf382921
--- /dev/null
+++ b/sdk/python/tests/test_packaging_imports.py
@@ -0,0 +1,7 @@
+from openviking_sdk import AsyncHTTPClient, OpenVikingError, SyncHTTPClient
+
+
+def test_sdk_top_level_imports():
+ assert AsyncHTTPClient is not None
+ assert SyncHTTPClient is not None
+ assert OpenVikingError is not None
diff --git a/sdk/python/tests/test_uploads.py b/sdk/python/tests/test_uploads.py
new file mode 100644
index 000000000..dd40471e8
--- /dev/null
+++ b/sdk/python/tests/test_uploads.py
@@ -0,0 +1,59 @@
+import tempfile
+import zipfile
+from pathlib import Path
+
+import pytest
+from openviking_sdk import AsyncHTTPClient
+
+
+class _FakeHTTPClient:
+ def __init__(self):
+ self.calls = []
+
+ async def post(self, path, json=None, files=None, data=None):
+ self.calls.append({"path": path, "json": json, "files": files, "data": data})
+ return object()
+
+
+def test_zip_directory_creates_forward_slash_paths():
+ with tempfile.TemporaryDirectory() as tmpdir:
+ tmpdir = Path(tmpdir)
+ root_dir = tmpdir / "test_project"
+ root_dir.mkdir()
+ (root_dir / "file1.txt").write_text("content1")
+ (root_dir / "subdir").mkdir()
+ (root_dir / "subdir" / "file2.txt").write_text("content2")
+
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ zip_path = client._zip_directory(str(root_dir))
+
+ try:
+ with zipfile.ZipFile(zip_path, "r") as zf:
+ names = zf.namelist()
+ assert "file1.txt" in names
+ assert "subdir/file2.txt" in names
+ assert all("\\" not in name for name in names)
+ finally:
+ Path(zip_path).unlink(missing_ok=True)
+
+
+async def test_upload_temp_file_forwards_upload_mode():
+ with tempfile.TemporaryDirectory() as tmpdir:
+ upload_file = Path(tmpdir) / "demo.md"
+ upload_file.write_text("# Demo\n")
+
+ client = AsyncHTTPClient(
+ url="http://localhost:1933",
+ upload_mode="shared",
+ )
+ fake_http = _FakeHTTPClient()
+ client._http = fake_http
+ client._handle_response = lambda _response: {"temp_file_id": "shared_abc"}
+
+ temp_file_id = await client._upload_temp_file(str(upload_file))
+
+ assert temp_file_id == "shared_abc"
+ call = fake_http.calls[-1]
+ assert call["path"] == "/api/v1/resources/temp_upload"
+ assert call["data"] == {"upload_mode": "shared"}