Skip to content

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

126 KB
Raw Blame
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0

from __future__ import annotations

import base64
import inspect
import mimetypes
import os
import tempfile
from enum import Enum
from pathlib import Path
from typing import Any, Callable, Dict, List, Literal, Mapping, Optional, Type, TypeVar, Union, cast
from urllib.parse import quote

import httpx

from ._utils import run_async
from .actor_peer import _request_actor_peer_headers
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,
)
from .message import MessagePart, normalize_part
from .options import (
    AddMessageOptions,
    AddResourceOptions,
    AddSkillOptions,
    BatchAddMessagesOptions,
    BatchWriteOptions,
    CommitSessionOptions,
    CompileOptions,
    CreateSessionOptions,
    ExperienceOutcomeOptions,
    ExperienceTrajectoryOptions,
    FindOptions,
    ListPage,
    Message,
    PreflightAssetOptions,
    ReindexOptions,
    ResolveAssetsOptions,
    RuleCompileOptions,
    RuleSearchOptions,
    SearchContextOptions,
    SearchContextResult,
    SearchOptions,
    SetTagsOptions,
    TreePage,
    UpdateSessionConfigOptions,
    UpdateSkillOptions,
    WriteOptions,
)
from .uploads import zip_directory

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,
}

GATEWAY_MARKER_HEADER = "X-VikingBot-Gateway"
GATEWAY_TOKEN_HEADER = "X-Gateway-Token"
_SESSION_CONFIG_UNSET = object()
_OptionsT = TypeVar("_OptionsT", bound=Mapping[str, Any])


def _option_keys(options_type: Type[Any]) -> set[str]:
    optional_keys = getattr(options_type, "__optional_keys__", None)
    required_keys = getattr(options_type, "__required_keys__", None)
    if optional_keys is not None and required_keys is not None:
        return set(optional_keys) | set(required_keys)
    return set(getattr(options_type, "__annotations__", {}))


def _normalize_timeout_options(timeout: Any, options: Optional[_OptionsT]) -> Optional[_OptionsT]:
    """Accept options in the positional slot used after timeout was removed.

    Timeout values are deprecated and ignored. A mapping in that slot is treated
    as options; supplying options in both slots is an error.
    """
    if isinstance(timeout, Mapping):
        if options is not None:
            raise TypeError("options were provided in both the timeout and options slots")
        return cast(_OptionsT, timeout)
    return options


def _image_mime_type(file_name: str = "") -> str:
    mime_type, _ = mimetypes.guess_type(file_name or "")
    if mime_type and mime_type.startswith("image/"):
        return mime_type
    return "image/png"


def _image_to_data_uri(data: bytes | bytearray | memoryview, file_name: str = "") -> str:
    encoded = base64.b64encode(bytes(data)).decode("ascii")
    return f"data:{_image_mime_type(file_name)};base64,{encoded}"


def _atomic_write_bytes(path: Path, data: bytes) -> None:
    temporary = tempfile.NamedTemporaryFile(
        mode="wb",
        dir=path.parent,
        prefix=f".{path.name}-",
        suffix=".tmp",
        delete=False,
    )
    temporary_path = Path(temporary.name)
    try:
        with temporary:
            temporary.write(data)
        os.replace(temporary_path, path)
    except BaseException:
        temporary.close()
        temporary_path.unlink(missing_ok=True)
        raise


def _normalize_image_input(image: Any) -> str | list[str] | None:
    if image is None:
        return None
    if isinstance(image, list):
        return [_normalize_image_input(item) for item in image]
    if isinstance(image, (bytes, bytearray, memoryview)):
        return _image_to_data_uri(image)
    value = os.fspath(image) if isinstance(image, os.PathLike) else str(image)
    if value.startswith(("data:image/", "http://", "https://", "viking://")):
        return value
    path = Path(value).expanduser()
    if path.is_file():
        return _image_to_data_uri(path.read_bytes(), path.name)
    return value


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}"

    @staticmethod
    def normalize_file_reference(uri_or_id: str) -> str:
        """Normalize a URI while preserving record IDs for read-only file lookup APIs."""
        cleaned = uri_or_id.strip()
        if len(cleaned) == 32 and all(char in "0123456789abcdef" for char in cleaned):
            return cleaned
        return VikingURI.normalize(uri_or_id)


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: Optional[str] = None,
        parts: Optional[List[Union[Dict[str, Any], MessagePart]]] = None,
        options: Optional[AddMessageOptions] = None,
        peer_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        kwargs: Dict[str, Any] = {
            "role": role,
            "content": content,
            "parts": parts,
            "options": options,
        }
        if peer_id is not None:
            kwargs["peer_id"] = peer_id
        return await self._client.add_message(self.session_id, **kwargs)

    async def batch_add_messages(self, messages: list[dict]) -> Dict[str, Any]:
        return await self._client.batch_add_messages(self.session_id, messages)

    async def commit(
        self,
        keep_recent_count: int = 0,
        options: Optional[CommitSessionOptions] = None,
    ) -> Dict[str, Any]:
        return await self._client.commit_session(
            self.session_id,
            keep_recent_count=keep_recent_count,
            options=options,
        )

    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: Optional[str] = None,
        parts: Optional[List[Union[Dict[str, Any], MessagePart]]] = None,
        options: Optional[AddMessageOptions] = None,
        peer_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        kwargs: Dict[str, Any] = {
            "role": role,
            "content": content,
            "parts": parts,
            "options": options,
        }
        if peer_id is not None:
            kwargs["peer_id"] = peer_id
        return self._client.add_message(self.session_id, **kwargs)

    def batch_add_messages(self, messages: list[dict]) -> Dict[str, Any]:
        return self._client.batch_add_messages(self.session_id, messages)

    def commit(
        self,
        keep_recent_count: int = 0,
        options: Optional[CommitSessionOptions] = None,
    ) -> Dict[str, Any]:
        return self._client.commit_session(
            self.session_id,
            keep_recent_count=keep_recent_count,
            options=options,
        )

    def commit_async(
        self,
        keep_recent_count: int = 0,
        options: Optional[CommitSessionOptions] = None,
    ) -> Dict[str, Any]:
        return self.commit(keep_recent_count=keep_recent_count, options=options)

    def delete(self) -> None:
        self._client.delete_session(self.session_id)

    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:
    supports_request_actor_peer = True

    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: Optional[float] = None,
        extra_headers: Optional[Dict[str, str]] = None,
        profile_enabled: Optional[bool] = None,
        upload_mode: Optional[str] = None,
        event_hooks: Optional[Dict[str, List[Callable[..., Any]]]] = None,
        # LDAP parameters
        auth_mode: Optional[str] = None,
        ldap_username: Optional[str] = None,
        ldap_password: Optional[str] = None,
        # OIDC parameters
        oidc_token: Optional[str] = None,
    ):
        if actor_peer_id and agent_id:
            raise ValueError("actor_peer_id cannot be used with agent_id")
        effective_user = user if user is not None else user_id
        effective_actor = actor_peer_id if actor_peer_id is not None else 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,
            auth_mode=auth_mode,
            ldap_username=ldap_username,
            ldap_password=ldap_password,
            oidc_token=oidc_token,
        )
        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._gateway_token = config.gateway_token
        self._timeout = config.timeout
        self._extra_headers = config.extra_headers
        self._profile_enabled = config.profile_enabled
        self._upload_mode = config.upload_mode
        self._auth_mode = config.auth_mode
        self._ldap_username = config.ldap_username
        self._ldap_password = config.ldap_password
        self._oidc_token = config.oidc_token
        self._event_hooks = {event: list(hooks) for event, hooks in (event_hooks or {}).items()}
        self._http_limits: Optional[httpx.Limits] = None
        self._http: Optional[httpx.AsyncClient] = None
        self._observer: Optional[_HTTPObserver] = None
        self._snapshot: Optional["AsyncHTTPSnapshotNamespace"] = 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

        # LDAP Basic Auth
        if self._auth_mode == "ldap" and self._ldap_username and self._ldap_password:
            from .config import get_basic_auth_header

            headers["Authorization"] = get_basic_auth_header(
                self._ldap_username, self._ldap_password
            )

        # OIDC Bearer token. An explicit oidc_token wins; otherwise fall back
        # to api_key when it looks like a JWT (header.payload.signature).
        if self._auth_mode == "oidc":
            token = self._oidc_token
            if not token and self._api_key and self._api_key.count(".") == 2:
                token = self._api_key
            if token:
                headers["Authorization"] = f"Bearer {token}"

        headers.update(self._extra_headers)
        client_kwargs: Dict[str, Any] = {
            "base_url": self._url,
            "headers": headers,
            "timeout": self._timeout,
            "event_hooks": self._event_hooks,
            "params": {"profile": "1"} if self._profile_enabled else None,
        }
        if self._http_limits is not None:
            client_kwargs["limits"] = self._http_limits
        self._http = httpx.AsyncClient(**client_kwargs)
        self._observer = _HTTPObserver(self)

    @staticmethod
    def _has_header(headers: Dict[str, str], name: str) -> bool:
        return any(key.lower() == name.lower() for key in headers)

    @staticmethod
    def _is_gateway_token_challenge(response: httpx.Response) -> bool:
        return (
            getattr(response, "status_code", None) == httpx.codes.UNAUTHORIZED
            and getattr(response, "headers", {}).get(GATEWAY_MARKER_HEADER, "").lower() == "true"
        )

    def _has_explicit_gateway_header(self, headers: Dict[str, str]) -> bool:
        return self._has_header(self._extra_headers, GATEWAY_TOKEN_HEADER) or self._has_header(
            headers, GATEWAY_TOKEN_HEADER
        )

    async def _gateway_token_required(self) -> bool:
        if self._http is None:
            raise RuntimeError("Client is not initialized")
        response = await self._http.get("/health")
        return self._is_gateway_token_challenge(response)

    async def _send_http_request(
        self,
        method: str,
        url: str,
        headers: Dict[str, str],
        request_kwargs: Dict[str, Any],
    ) -> httpx.Response:
        if self._http is None:
            raise RuntimeError("Client is not initialized")
        call_kwargs = dict(request_kwargs)
        if headers:
            call_kwargs["headers"] = headers
        request_method = getattr(self._http, "request", None)
        if callable(request_method):
            return await request_method(method, url, **call_kwargs)
        verb_method = getattr(self._http, method.lower())
        return await verb_method(url, **call_kwargs)

    async def _request(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
        if self._http is None:
            raise RuntimeError("Client is not initialized")

        request_kwargs = dict(kwargs)
        headers = _request_actor_peer_headers()
        headers.update(dict(request_kwargs.pop("headers", {}) or {}))
        has_explicit_gateway_header = self._has_explicit_gateway_header(headers)

        # Multipart streams cannot be replayed safely after the first request. Probe the
        # endpoint before sending them so a Gateway token is attached only when challenged.
        if (
            request_kwargs.get("files") is not None
            and self._gateway_token
            and not has_explicit_gateway_header
            and await self._gateway_token_required()
        ):
            headers[GATEWAY_TOKEN_HEADER] = self._gateway_token

        response = await self._send_http_request(method, url, headers, request_kwargs)
        if (
            not self._is_gateway_token_challenge(response)
            or not self._gateway_token
            or has_explicit_gateway_header
            or request_kwargs.get("files") is not None
        ):
            return response

        retry_headers = dict(headers)
        retry_headers[GATEWAY_TOKEN_HEADER] = self._gateway_token
        return await self._send_http_request(method, url, retry_headers, request_kwargs)

    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

    @staticmethod
    def _compact_request_body(body: Dict[str, Any]) -> Dict[str, Any]:
        """Drop None-valued keys (and an empty ``args`` object) from a request body.

        Older, stricter servers use ``model_config = ConfigDict(extra="forbid")`` and
        reject any field they do not yet define, so unconditionally attaching optional
        fields (even as ``null``/``{}``) breaks against instances that predate that
        field — e.g. ``body.tags`` against a pre-#2706 ``find`` route, or ``body.args``
        against a pre-#2549 ``resources`` route. Omitting them is safe for read/create
        routes where a missing optional field and an explicit ``null`` are equivalent.
        Do NOT use this for update/PATCH bodies where ``null`` may mean "clear this
        field". Mirrors the CLI's ``compact_request_body`` (see PR #2799).
        """
        compacted: Dict[str, Any] = {}
        for key, value in body.items():
            if value is None:
                continue
            # `args` is always attached by callers but absent from pre-#2549 models;
            # only forward it when arguments were actually provided.
            if key == "args" and isinstance(value, dict) and not value:
                continue
            compacted[key] = value
        return compacted

    @classmethod
    def _normalize_message_payload(cls, message: Mapping[str, Any]) -> Dict[str, Any]:
        payload = dict(message)
        if payload.get("parts"):
            payload["parts"] = [normalize_part(part) for part in payload["parts"]]
            payload.pop("content", None)
        else:
            payload.pop("parts", None)
            if payload.get("content") is None:
                raise ValueError("Either content or non-empty parts must be provided")
        return cls._compact_request_body(payload)

    @classmethod
    def _build_options_payload(
        cls,
        options: Optional[Mapping[str, Any]],
        options_type: Type[Any],
        fixed: Optional[Mapping[str, Any]] = None,
        protected: Optional[set[str]] = None,
    ) -> Dict[str, Any]:
        option_values = dict(options or {})
        allowed = _option_keys(options_type)
        unknown = sorted(set(option_values) - allowed)
        if unknown:
            raise TypeError(
                f"Unknown option '{unknown[0]}' for {options_type.__name__}; "
                "use 'extra' for server fields not yet supported by the SDK"
            )

        extra = dict(option_values.pop("extra", {}) or {})
        payload = dict(fixed or {})
        protected_fields = set(payload) | set(protected or ())
        official_fields = allowed - {"extra"}
        conflicts = sorted(set(extra) & (official_fields | protected_fields))
        if conflicts:
            raise ValueError(f"extra cannot override '{conflicts[0]}'")

        payload.update(option_values)
        payload.update(extra)
        return cls._compact_request_body(payload)

    @classmethod
    def _search_options_payload(
        cls,
        query: str,
        options: Optional[Mapping[str, Any]],
        options_type: Type[Any],
        fixed: Optional[Mapping[str, Any]] = None,
    ) -> Dict[str, Any]:
        option_values = dict(options or {})
        if "image" in option_values:
            option_values["image_url"] = _normalize_image_input(option_values.pop("image"))
        if "target_uri" in option_values:
            option_values["target_uri"] = cls._normalize_target_uri(option_values["target_uri"])
        if "context_type" in option_values:
            option_values["context_type"] = cls._normalize_context_type(
                option_values["context_type"]
            )

        allowed = _option_keys(options_type)
        allowed.discard("image")
        allowed.add("image_url")
        proxy_type = type(
            f"_{options_type.__name__}Payload",
            (),
            {
                "__optional_keys__": frozenset(allowed),
                "__required_keys__": frozenset(),
                "__name__": options_type.__name__,
            },
        )
        fixed_payload = {"query": query}
        fixed_payload.update(fixed or {})
        return cls._build_options_payload(
            option_values,
            proxy_type,
            fixed=fixed_payload,
        )

    @staticmethod
    def _normalize_context_type(context_type: Optional[Any]) -> Optional[Any]:
        if context_type is None:
            return None
        if isinstance(context_type, list):
            return [item.value if isinstance(item, Enum) else item for item in context_type]
        if isinstance(context_type, Enum):
            return context_type.value
        return context_type

    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:
            exception = exc_class(message, code=code, details=details)
        elif exc_class in (
            InvalidArgumentError,
            FailedPreconditionError,
            ResourceExhaustedError,
            AbortedError,
            UnimplementedError,
        ):
            exception = exc_class(message, details=details)
        elif exc_class == InvalidURIError:
            uri = details.get("uri", "") if details else ""
            reason = details.get("reason", "") if details else ""
            exception = 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"
            reason = details.get("reason") if details else None
            exception = exc_class(resource, resource_type, reason=reason)
        elif exc_class == AlreadyExistsError:
            resource = details.get("resource", "") if details else ""
            resource_type = details.get("type", "resource") if details else "resource"
            exception = exc_class(resource, resource_type)
        elif exc_class == UnavailableError:
            service = details.get("service", "service") if details else "service"
            reason = details.get("reason", "") if details else message
            exception = exc_class(service, reason)
        else:
            exception = exc_class(message)
        if details is not None:
            exception.details.update(details)
        raise exception

    def _zip_directory(self, dir_path: str) -> str:
        return zip_directory(dir_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._request(
                "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,
        wait: bool = False,
        timeout: Optional[float] = None,  # Deprecated and ignored.
        options: Optional[AddResourceOptions] = None,
    ) -> Dict[str, Any]:
        option_values = dict(_normalize_timeout_options(timeout, options) or {})
        add_type = option_values.get("add_type")
        if add_type is not None:
            add_type = add_type.strip() or None
        if add_type and parent:
            raise ValueError("'add_type' cannot be combined with 'parent'.")
        if add_type and not to:
            raise ValueError("'add_type' requires an exact 'to' target.")
        if to and parent:
            raise ValueError("Cannot specify both 'to' and 'parent' at the same time.")

        if to is not None:
            to = VikingURI.normalize(to)
        if parent is not None:
            parent = VikingURI.normalize(parent)
        if add_type is not None:
            option_values["add_type"] = add_type
        request_data = self._build_options_payload(
            option_values,
            AddResourceOptions,
            fixed={
                "to": to,
                "parent": parent,
                "wait": wait,
            },
            protected={"path", "temp_file_id", "source_name"},
        )

        path_obj = Path(path)
        if not add_type and 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

        request_data = self._compact_request_body(request_data)
        response = await self._request("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[Message],
        options: Optional[BatchAddMessagesOptions] = None,
    ) -> Dict[str, Any]:
        session_path = self._path_segment(session_id)
        normalized_messages = [self._normalize_message_payload(message) for message in messages]
        payload = self._build_options_payload(
            options,
            BatchAddMessagesOptions,
            fixed={"messages": normalized_messages},
        )
        response = await self._request(
            "POST",
            f"/api/v1/sessions/{session_path}/messages/batch",
            json=payload,
        )
        return self._handle_response_data(response).get("result", {})

    async def add_skill(
        self,
        data: Any,
        wait: bool = False,
        timeout: Optional[float] = None,  # Deprecated and ignored.
        options: Optional[AddSkillOptions] = None,
    ) -> Dict[str, Any]:
        option_values = dict(_normalize_timeout_options(timeout, options) or {})
        if "target_uri" in option_values:
            option_values["target_uri"] = VikingURI.normalize(option_values["target_uri"])
        request_data = self._build_options_payload(
            option_values,
            AddSkillOptions,
            fixed={"wait": wait},
            protected={"data", "temp_file_id"},
        )
        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._request("POST", "/api/v1/skills", json=request_data)
        return self._handle_response_data(response).get("result", {})

    async def list_skills(
        self,
        node_limit: int = 1000,
        target_uri: Optional[str] = None,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {"node_limit": node_limit}
        if target_uri is not None:
            params["target_uri"] = target_uri
        response = await self._request("GET", "/api/v1/skills", params=params)
        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,
        target_uri: Optional[str] = None,
    ) -> Dict[str, Any]:
        payload = {
            "query": query,
            "limit": limit,
            "score_threshold": score_threshold,
            "level": level,
            "telemetry": telemetry,
        }
        if target_uri is not None:
            payload["target_uri"] = target_uri
        response = await self._request("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,
        target_uri: 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
        if target_uri is not None:
            payload["target_uri"] = target_uri
        response = await self._request("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,
        target_uri: Optional[str] = None,
        include_integrity: bool = False,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {
            "include_files": include_files,
            "include_integrity": include_integrity,
            "include_source": include_source,
        }
        if include_content is not None:
            params["include_content"] = include_content
        if level is not None:
            params["level"] = level
        if target_uri is not None:
            params["target_uri"] = target_uri
        response = await self._request("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,  # Deprecated and ignored.
        options: Optional[UpdateSkillOptions] = None,
    ) -> Dict[str, Any]:
        option_values = dict(_normalize_timeout_options(timeout, options) or {})
        if "target_uri" in option_values:
            option_values["target_uri"] = VikingURI.normalize(option_values["target_uri"])
        request_data = self._build_options_payload(
            option_values,
            UpdateSkillOptions,
            fixed={"wait": wait},
            protected={"data", "temp_file_id"},
        )
        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._request("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,
        target_uri: Optional[str] = None,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {}
        if target_uri is not None:
            params["target_uri"] = target_uri
        response = await self._request("DELETE", f"/api/v1/skills/{skill_name}", params=params)
        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._request("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._request("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._request(
                "PATCH", f"/api/v1/watches/{task_id}", params=params, json=payload
            )
        else:
            response = await self._request(
                "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._request("DELETE", f"/api/v1/watches/{task_id}", params=params)
        else:
            response = await self._request(
                "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._request(
                "POST", f"/api/v1/watches/{task_id}/trigger", params=params
            )
        else:
            response = await self._request(
                "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 processing; timeout is deprecated and ignored."""
        response = await self._request(
            "POST",
            "/api/v1/system/wait",
            json={},
        )
        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,
        sort_by: Optional[str] = None,
        sort_order: str = "asc",
        extra_fields: Optional[List[str]] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
        offset: int = 0,
        limit: Optional[int] = None,
        include_abstract: Optional[bool] = None,
        include_overview: Optional[bool] = None,
        overview_limit: int = 4000,
    ) -> List[Any]:
        page = await self.ls_page(
            uri,
            simple=simple,
            recursive=recursive,
            output=output,
            abs_limit=abs_limit,
            show_all_hidden=show_all_hidden,
            node_limit=node_limit,
            sort_by=sort_by,
            sort_order=sort_order,
            extra_fields=extra_fields,
            tags=tags,
            include_tags=include_tags,
            offset=offset,
            limit=limit,
            include_abstract=include_abstract,
            include_overview=include_overview,
            overview_limit=overview_limit,
        )
        return page["result"]

    async def ls_page(
        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,
        sort_by: Optional[str] = None,
        sort_order: str = "asc",
        extra_fields: Optional[List[str]] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
        offset: int = 0,
        limit: Optional[int] = None,
        include_abstract: Optional[bool] = None,
        include_overview: Optional[bool] = None,
        overview_limit: int = 4000,
    ) -> ListPage:
        params: Dict[str, Any] = {
            "uri": VikingURI.normalize(uri),
            "simple": simple,
            "recursive": recursive,
            "output": output,
            "abs_limit": abs_limit,
            "show_all_hidden": show_all_hidden,
            "node_limit": node_limit,
            "offset": offset,
            "overview_limit": overview_limit,
        }
        if include_abstract is not None:
            params["include_abstract"] = include_abstract
        if include_overview is not None:
            params["include_overview"] = include_overview
        if sort_by is not None:
            params["sort_by"] = sort_by
            params["sort_order"] = sort_order
        if extra_fields:
            params["extra_fields"] = list(extra_fields)
        if tags is not None:
            params["tags"] = tags
        if include_tags:
            params["include_tags"] = True
        if limit is not None:
            params["limit"] = limit
        response = await self._request(
            "GET",
            "/api/v1/fs/ls",
            params=params,
        )
        data = self._handle_response_data(response)
        return {
            "result": data.get("result") or [],
            "has_more": bool(data.get("has_more", False)),
        }

    async def tree(
        self,
        uri: str,
        output: str = "original",
        abs_limit: int = 128,
        show_all_hidden: bool = False,
        node_limit: int = 1000,
        level_limit: int = 3,
        extra_fields: Optional[List[str]] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
        offset: int = 0,
        limit: Optional[int] = None,
        include_abstract: Optional[bool] = None,
        include_overview: Optional[bool] = None,
        overview_limit: int = 4000,
        directories_only: bool = False,
    ) -> List[Dict[str, Any]]:
        page = await self.tree_page(
            uri,
            output=output,
            abs_limit=abs_limit,
            show_all_hidden=show_all_hidden,
            node_limit=node_limit,
            level_limit=level_limit,
            extra_fields=extra_fields,
            tags=tags,
            include_tags=include_tags,
            offset=offset,
            limit=limit,
            include_abstract=include_abstract,
            include_overview=include_overview,
            overview_limit=overview_limit,
            directories_only=directories_only,
        )
        return page["result"]

    async def tree_page(
        self,
        uri: str,
        output: str = "original",
        abs_limit: int = 128,
        show_all_hidden: bool = False,
        node_limit: int = 1000,
        level_limit: int = 3,
        extra_fields: Optional[List[str]] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
        offset: int = 0,
        limit: Optional[int] = None,
        include_abstract: Optional[bool] = None,
        include_overview: Optional[bool] = None,
        overview_limit: int = 4000,
        directories_only: bool = False,
    ) -> TreePage:
        params: Dict[str, Any] = {
            "uri": VikingURI.normalize(uri),
            "output": output,
            "abs_limit": abs_limit,
            "show_all_hidden": show_all_hidden,
            "node_limit": node_limit,
            "level_limit": level_limit,
            "offset": offset,
            "overview_limit": overview_limit,
        }
        if include_abstract is not None:
            params["include_abstract"] = include_abstract
        if include_overview is not None:
            params["include_overview"] = include_overview
        if directories_only:
            params["directories_only"] = True
        if extra_fields:
            params["extra_fields"] = list(extra_fields)
        if tags is not None:
            params["tags"] = tags
        if include_tags:
            params["include_tags"] = True
        if limit is not None:
            params["limit"] = limit
        response = await self._request(
            "GET",
            "/api/v1/fs/tree",
            params=params,
        )
        data = self._handle_response_data(response)
        return {
            "result": data.get("result") or [],
            "has_more": bool(data.get("has_more", False)),
        }

    async def stat(self, uri: str) -> Dict[str, Any]:
        response = await self._request(
            "GET",
            "/api/v1/fs/stat",
            params={"uri": VikingURI.normalize_file_reference(uri)},
        )
        return self._handle_response(response)

    async def attrs(self, uri: str) -> Dict[str, Any]:
        response = await self._request(
            "GET", "/api/v1/fs/attrs", params={"uri": VikingURI.normalize(uri)}
        )
        return self._handle_response(response)

    async def mkdir(
        self, uri: str, description: Optional[str] = None, *, acl: Optional[Dict[str, Any]] = None
    ) -> None:
        payload = {"uri": VikingURI.normalize(uri)}
        if description is not None:
            payload["description"] = description
        if acl is not None:
            payload["acl"] = acl
        response = await self._request("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,  # Deprecated and ignored.
    ) -> None:
        params = {"uri": VikingURI.normalize(uri), "recursive": recursive, "wait": wait}
        response = await self._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._request(
            "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._request(
            "GET",
            "/api/v1/content/read",
            params={
                "uri": VikingURI.normalize_file_reference(uri),
                "offset": offset,
                "limit": limit,
            },
        )
        return self._handle_response(response)

    async def read_raw(self, uri: str, offset: int = 0, limit: int = -1) -> str:
        """Read the exact UTF-8 content stored for a file, including hidden metadata."""
        response = await self._request(
            "GET",
            "/api/v1/content/read",
            params={
                "uri": VikingURI.normalize_file_reference(uri),
                "offset": offset,
                "limit": limit,
                "raw": True,
            },
        )
        return self._handle_response(response)

    async def download_bytes(self, uri: str) -> bytes:
        """Download an OpenViking file without interpreting its contents."""
        response = await self._request(
            "GET",
            "/api/v1/content/download",
            params={"uri": VikingURI.normalize(uri)},
        )
        if not response.is_success:
            self._handle_response_data(response)
        return bytes(response.content)

    async def abstract(self, uri: str) -> str:
        response = await self._request(
            "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._request(
            "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,  # Deprecated and ignored.
        options: Optional[WriteOptions] = None,
    ) -> Dict[str, Any]:
        payload = self._build_options_payload(
            _normalize_timeout_options(timeout, options),
            WriteOptions,
            fixed={
                "uri": VikingURI.normalize(uri),
                "content": content,
                "mode": mode,
                "wait": wait,
            },
        )
        response = await self._request(
            "POST",
            "/api/v1/content/write",
            json=payload,
        )
        return self._handle_response_data(response).get("result", {})

    async def batch_write(
        self,
        root_uri: str,
        operations: List[Dict[str, Any]],
        wait: bool = True,
        timeout: Optional[float] = None,  # Deprecated and ignored.
        options: Optional[BatchWriteOptions] = None,
    ) -> Dict[str, Any]:
        """Apply multiple content writes, then refresh semantics once."""
        normalized_operations = []
        for operation in operations:
            item = dict(operation)
            item["uri"] = VikingURI.normalize(str(item.get("uri") or ""))
            normalized_operations.append(item)
        payload = self._build_options_payload(
            _normalize_timeout_options(timeout, options),
            BatchWriteOptions,
            fixed={
                "root_uri": VikingURI.normalize(root_uri),
                "operations": normalized_operations,
                "wait": wait,
            },
        )
        response = await self._request(
            "POST",
            "/api/v1/content/batch-write",
            json=payload,
        )
        return self._handle_response_data(response).get("result", {})

    async def set_tags(
        self,
        uri: str,
        tags: Optional[List[str]] = None,
        mode: str = "replace",
        recursive: bool = False,
        options: Optional[SetTagsOptions] = None,
    ) -> Dict[str, Any]:
        fixed: Dict[str, Any] = {
            "uri": VikingURI.normalize(uri),
            "mode": mode,
            "recursive": recursive,
        }
        if tags is not None:
            fixed["tags"] = tags
        payload = self._build_options_payload(
            options,
            SetTagsOptions,
            fixed=fixed,
        )
        response = await self._request(
            "POST",
            "/api/v1/fs/attrs/set_tags",
            json=payload,
        )
        return self._handle_response_data(response).get("result", {})

    async def acl_get(self, uri: str) -> Dict[str, Any]:
        response = await self._http.get("/api/v1/acl", params={"uri": VikingURI.normalize(uri)})
        return self._handle_response_data(response).get("result", {})

    async def acl_set(
        self,
        uri: str,
        entries: Optional[List[Dict[str, str]]] = None,
        *,
        acl_mode: Optional[Literal["inherit", "restricted"]] = None,
    ) -> Dict[str, Any]:
        if entries is None and acl_mode is None:
            raise ValueError("Either entries or acl_mode must be provided")
        payload: Dict[str, Any] = {"uri": VikingURI.normalize(uri)}
        if entries is not None:
            payload["entries"] = entries
        if acl_mode is not None:
            payload["acl_mode"] = acl_mode
        response = await self._http.put(
            "/api/v1/acl",
            json=payload,
        )
        return self._handle_response_data(response).get("result", {})

    async def acl_grant(self, uri: str, principal: str, level: str) -> Dict[str, Any]:
        response = await self._http.post(
            "/api/v1/acl/grant",
            json={
                "uri": VikingURI.normalize(uri),
                "principal": principal,
                "level": level,
            },
        )
        return self._handle_response_data(response).get("result", {})

    async def acl_revoke(self, uri: str, principal: str) -> Dict[str, Any]:
        response = await self._http.post(
            "/api/v1/acl/revoke",
            json={"uri": VikingURI.normalize(uri), "principal": principal},
        )
        return self._handle_response_data(response).get("result", {})

    async def acl_delete(self, uri: str) -> Dict[str, Any]:
        response = await self._http.request(
            "DELETE", "/api/v1/acl", params={"uri": VikingURI.normalize(uri)}
        )
        return self._handle_response_data(response).get("result", {})

    async def find(
        self,
        query: str = "",
        target_uri: Union[str, List[str]] = "",
        limit: int = 10,
        image: Any = None,
        options: Optional[FindOptions] = None,
    ) -> Dict[str, Any]:
        search_options = dict(options or {})
        if image is not None:
            search_options["image"] = image
        payload = self._search_options_payload(
            query,
            search_options,
            FindOptions,
            fixed={
                "target_uri": self._normalize_target_uri(target_uri),
                "limit": limit,
            },
        )
        response = await self._request("POST", "/api/v1/search/find", json=payload)
        return self._handle_response_data(response).get("result", {})

    async def search(
        self,
        query: str = "",
        session_id: Optional[str] = None,
        target_uri: Union[str, List[str]] = "",
        limit: int = 10,
        image: Any = None,
        options: Optional[SearchOptions] = None,
    ) -> Dict[str, Any]:
        search_options = dict(options or {})
        if image is not None:
            search_options["image"] = image
        payload = self._search_options_payload(
            query,
            search_options,
            SearchOptions,
            fixed={
                "session_id": session_id,
                "target_uri": self._normalize_target_uri(target_uri),
                "limit": limit,
            },
        )
        response = await self._request("POST", "/api/v1/search/search", json=payload)
        return self._handle_response_data(response).get("result", {})

    async def search_context(
        self,
        query: str = "",
        session_id: Optional[str] = None,
        target_uri: Union[str, List[str]] = "",
        limit: int = 10,
        image: Any = None,
        options: Optional[SearchContextOptions] = None,
    ) -> SearchContextResult:
        search_options = dict(options or {})
        if image is not None:
            search_options["image"] = image
        payload = self._search_options_payload(
            query,
            search_options,
            SearchContextOptions,
            fixed={
                "mode": "context",
                "session_id": session_id,
                "target_uri": self._normalize_target_uri(target_uri),
                "limit": limit,
            },
        )
        response = await self._request("POST", "/api/v1/search/search", json=payload)
        return self._handle_response_data(response).get("result", {})

    async def grep(
        self,
        uri: str,
        pattern: str,
        case_insensitive: bool = False,
        node_limit: int = 256,
        exclude_uri: Optional[str] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
        level_limit: Optional[int] = None,
    ) -> Dict[str, Any]:
        request_json = {
            "uri": VikingURI.normalize(uri),
            "pattern": pattern,
            "case_insensitive": case_insensitive,
            "node_limit": node_limit,
        }
        if level_limit is not None:
            request_json["level_limit"] = level_limit
        if exclude_uri is not None:
            request_json["exclude_uri"] = VikingURI.normalize(exclude_uri)
        if tags is not None:
            request_json["tags"] = list(tags)
        if include_tags:
            request_json["include_tags"] = True
        response = await self._request("POST", "/api/v1/search/grep", json=request_json)
        return self._handle_response(response)

    async def glob(
        self,
        pattern: str,
        uri: str = "viking://",
        node_limit: int = 256,
        extra_fields: Optional[List[str]] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
    ) -> Dict[str, Any]:
        json_body: Dict[str, Any] = {
            "pattern": pattern,
            "uri": VikingURI.normalize(uri),
            "node_limit": node_limit,
        }
        if extra_fields is not None:
            json_body["extra_fields"] = list(extra_fields)
        if tags is not None:
            json_body["tags"] = list(tags)
        if include_tags:
            json_body["include_tags"] = True
        response = await self._request(
            "POST",
            "/api/v1/search/glob",
            json=json_body,
        )
        return self._handle_response(response)

    async def create_session(
        self,
        session_id: Optional[str] = None,
        options: Optional[CreateSessionOptions] = None,
    ) -> Dict[str, Any]:
        option_values = dict(options or {})
        json_body = self._build_options_payload(
            option_values,
            CreateSessionOptions,
            fixed={"session_id": session_id},
        )
        if "auto_commit_policy" in option_values:
            json_body["auto_commit_policy"] = option_values["auto_commit_policy"]
        response = await self._request("POST", "/api/v1/sessions", json=json_body)
        return self._handle_response_data(response).get("result", {})

    async def list_sessions(self) -> List[Any]:
        response = await self._request("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._request("GET", f"/api/v1/sessions/{session_path}", params=params)
        return self._handle_response(response)

    async def update_session_config(
        self,
        session_id: str,
        options: Optional[UpdateSessionConfigOptions] = None,
    ) -> Dict[str, Any]:
        option_values = dict(options or {})
        payload = self._build_options_payload(option_values, UpdateSessionConfigOptions)
        if "auto_commit_policy" in option_values:
            payload["auto_commit_policy"] = option_values["auto_commit_policy"]
        session_path = self._path_segment(session_id)
        response = await self._request(
            "PATCH",
            f"/api/v1/sessions/{session_path}/config",
            json=payload,
        )
        return self._handle_response_data(response).get("result", {})

    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._request(
            "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._request(
            "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._request("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._request("GET", f"/api/v1/tasks/{task_id}")
        if response.status_code == 404:
            return None
        return self._handle_response(response)

    async def compile(
        self,
        from_uris: List[str],
        to: str,
        skill: str,
        options: Optional[CompileOptions] = None,
    ) -> Dict[str, Any]:
        payload = self._build_options_payload(
            options,
            CompileOptions,
            fixed={"from": list(from_uris), "to": to, "skill": skill},
        )
        response = await self._request("POST", "/api/v1/compile", json=payload)
        return self._handle_response(response)

    async def rule_compile(
        self,
        instruction: Optional[str] = None,
        options: Optional[RuleCompileOptions] = None,
    ) -> Dict[str, Any]:
        """Compile inline instructions and resource-backed files into durable rules."""
        option_values = dict(options or {})
        raw_sources: Any = option_values.pop("sources", [])
        if option_values:
            names = ", ".join(sorted(option_values))
            raise ValueError(f"Unsupported rule compile options: {names}")
        if not isinstance(raw_sources, list):
            raise ValueError("Rule compile sources must be a list")

        sources: List[Dict[str, Any]] = []
        for source in raw_sources:
            if isinstance(source, dict):
                normalized = dict(source)
                if normalized.get("resource_uri"):
                    normalized["resource_uri"] = VikingURI.normalize(
                        str(normalized["resource_uri"])
                    )
                    sources.append(normalized)
                    continue
                for target_field in ("to", "parent"):
                    if normalized.get(target_field):
                        normalized[target_field] = VikingURI.normalize(
                            str(normalized[target_field])
                        )
                path_value = normalized.get("path")
                if isinstance(path_value, str):
                    local_path = Path(path_value).expanduser()
                    if local_path.exists() and not normalized.get("add_type"):
                        normalized.pop("path")
                        normalized.setdefault("source_name", local_path.name)
                        if local_path.is_dir():
                            zip_path = self._zip_directory(str(local_path))
                            try:
                                normalized["temp_file_id"] = await self._upload_temp_file(zip_path)
                            finally:
                                Path(zip_path).unlink(missing_ok=True)
                        else:
                            normalized["temp_file_id"] = await self._upload_temp_file(
                                str(local_path)
                            )
                sources.append(normalized)
                continue

            value = os.fspath(source)
            if value.startswith("viking://"):
                sources.append({"resource_uri": VikingURI.normalize(value)})
                continue
            path = Path(value).expanduser()
            if path.is_dir():
                zip_path = self._zip_directory(str(path))
                try:
                    temp_file_id = await self._upload_temp_file(zip_path)
                finally:
                    Path(zip_path).unlink(missing_ok=True)
                sources.append(
                    {
                        "temp_file_id": temp_file_id,
                        "source_name": path.name,
                    }
                )
            elif path.is_file():
                sources.append(
                    {
                        "temp_file_id": await self._upload_temp_file(str(path)),
                        "source_name": path.name,
                    }
                )
            else:
                sources.append({"path": value})

        payload = {"instruction": instruction, "sources": sources}
        response = await self._request(
            "POST",
            "/api/v1/rules/compile",
            json=self._compact_request_body(payload),
        )
        return self._handle_response(response)

    async def rule_search(
        self,
        task_context: str,
        options: Optional[RuleSearchOptions] = None,
    ) -> Dict[str, Any]:
        payload = self._build_options_payload(
            options,
            RuleSearchOptions,
            fixed={"task_context": task_context},
        )
        response = await self._request("POST", "/api/v1/rules/search", json=payload)
        return self._handle_response(response)

    async def cancel_task(self, task_id: str) -> Dict[str, Any]:
        response = await self._request("POST", f"/api/v1/tasks/{task_id}/cancel")
        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._request("GET", "/api/v1/tasks", params=params)
        return self._handle_response(response)

    async def commit_session(
        self,
        session_id: str,
        keep_recent_count: int = 0,
        options: Optional[CommitSessionOptions] = None,
    ) -> Dict[str, Any]:
        option_values = dict(options or {})
        event_tags = option_values.pop("event_tags", _SESSION_CONFIG_UNSET)
        turn_fields = {
            "keep_recent_turn_count",
            "retained_message_token_budget",
            "min_raw_tail_steps",
        }
        if (
            turn_fields & set(option_values)
            and option_values.get("retention_mode") != "turn_budget"
        ):
            raise ValueError(
                "retention_mode='turn_budget' is required when Turn retention fields are set"
            )
        payload = self._build_options_payload(
            option_values,
            CommitSessionOptions,
            fixed={"keep_recent_count": keep_recent_count},
            protected={"extraction_metadata"},
        )
        if event_tags is not _SESSION_CONFIG_UNSET:
            payload["extraction_metadata"] = {"event": {"tags": event_tags}}
        session_path = self._path_segment(session_id)
        response = await self._request(
            "POST",
            f"/api/v1/sessions/{session_path}/commit",
            json=payload,
        )
        return self._handle_response_data(response).get("result", {})

    async def add_message(
        self,
        session_id: str,
        role: str,
        content: Optional[str] = None,
        parts: Optional[List[Union[Dict[str, Any], MessagePart]]] = None,
        options: Optional[AddMessageOptions] = None,
        peer_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        if peer_id is not None and options and "peer_id" in options:
            raise ValueError("options cannot override 'peer_id'")
        fixed = {
            "role": role,
            "content": content,
            "parts": parts,
        }
        if peer_id is not None:
            fixed["peer_id"] = peer_id
        payload = self._build_options_payload(
            options,
            AddMessageOptions,
            fixed=fixed,
            protected={"role", "content", "parts"},
        )
        payload = self._normalize_message_payload(payload)
        session_path = self._path_segment(session_id)
        response = await self._request(
            "POST", f"/api/v1/sessions/{session_path}/messages", json=payload
        )
        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._request(
            "POST",
            "/api/v1/pack/export",
            json={"uri": uri, "include_vectors": include_vectors},
        )
        if not response.is_success:
            self._handle_response(response)
        _atomic_write_bytes(to_path, 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._request(
            "POST", "/api/v1/pack/backup", json={"include_vectors": include_vectors}
        )
        if not response.is_success:
            self._handle_response(response)
        _atomic_write_bytes(to_path, 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._request("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._request("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._request(
            "POST",
            "/api/v1/system/consistency",
            json={"uri": VikingURI.normalize(uri)},
        )
        return self._handle_response(response)

    async def health(self) -> bool:
        try:
            response = await self._request("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,
        recursive: bool = True,
        force: bool = False,
        options: Optional[ReindexOptions] = None,
    ) -> Dict[str, Any]:
        payload = self._build_options_payload(
            options,
            ReindexOptions,
            fixed={
                "uri": VikingURI.normalize(uri),
                "mode": mode,
                "wait": wait,
                "force": force,
                "recursive": recursive,
            },
        )
        if not payload.get("force"):
            payload.pop("force", None)
        response = await self._request(
            "POST",
            "/api/v1/content/reindex",
            json=payload,
        )
        return self._handle_response(response)

    async def _get_queue_status(
        self, format: Optional[Literal["table", "json"]] = None
    ) -> Dict[str, Any]:
        params = {"format": format} if format is not None else None
        response = await self._request("GET", "/api/v1/observer/queue", params=params)
        return self._handle_response(response)

    async def _get_vikingdb_status(
        self, format: Optional[Literal["table", "json"]] = None
    ) -> Dict[str, Any]:
        params = {"format": format} if format is not None else None
        response = await self._request("GET", "/api/v1/observer/vikingdb", params=params)
        return self._handle_response(response)

    async def _get_models_status(
        self, format: Optional[Literal["table", "json"]] = None
    ) -> Dict[str, Any]:
        params = {"format": format} if format is not None else None
        response = await self._request("GET", "/api/v1/observer/models", params=params)
        return self._handle_response(response)

    async def _get_system_status(
        self, format: Optional[Literal["table", "json"]] = None
    ) -> Dict[str, Any]:
        params = {"format": format} if format is not None else None
        response = await self._request("GET", "/api/v1/observer/system", params=params)
        return self._handle_response(response)

    async def admin_create_account(
        self,
        account_id: str,
        admin_user_id: str,
        user_config: Optional[Dict[str, Any]] = None,
        seed: Optional[str] = None,
    ) -> Dict[str, Any]:
        payload: Dict[str, Any] = {"account_id": account_id, "admin_user_id": admin_user_id}
        if seed is not None:
            payload["seed"] = seed
        if user_config is not None:
            payload["user_config"] = user_config
        response = await self._request(
            "POST",
            "/api/v1/admin/accounts",
            json=payload,
        )
        return self._handle_response(response)

    async def admin_list_accounts(
        self,
        name: Optional[str] = None,
        limit: Optional[int] = None,
        page: int = 1,
        query: Optional[str] = None,
    ) -> List[Any]:
        params: Dict[str, Any] = {}
        if name is not None:
            params["name"] = name
        if limit is not None:
            params["limit"] = limit
            params["page"] = page
        if query is not None:
            params["query"] = query
        response = await self._request("GET", "/api/v1/admin/accounts", params=params)
        return self._handle_response(response)

    async def admin_get_account(self, account_id: str) -> Dict[str, Any]:
        """Return one account's credential-free metadata.

        Raises NotFoundError when the account does not exist.
        """
        response = await self._request("GET", f"/api/v1/admin/accounts/{account_id}")
        return self._handle_response(response)

    async def admin_delete_account(self, account_id: str) -> Dict[str, Any]:
        response = await self._request("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",
        user_config: Optional[Dict[str, Any]] = None,
        seed: Optional[str] = None,
    ) -> Dict[str, Any]:
        payload: Dict[str, Any] = {"user_id": user_id, "role": role}
        if seed is not None:
            payload["seed"] = seed
        if user_config is not None:
            payload["user_config"] = user_config
        response = await self._request(
            "POST",
            f"/api/v1/admin/accounts/{account_id}/users",
            json=payload,
        )
        return self._handle_response(response)

    async def admin_list_users(
        self,
        account_id: str,
        limit: Optional[int] = None,
        name: Optional[str] = None,
        role: Optional[str] = None,
        page: int = 1,
        query: Optional[str] = None,
    ) -> List[Any]:
        params: Dict[str, Any] = {}
        if limit is not None:
            params["limit"] = limit
            params["page"] = page
        if name is not None:
            params["name"] = name
        if role is not None:
            params["role"] = role
        if query is not None:
            params["query"] = query
        response = await self._request(
            "GET", f"/api/v1/admin/accounts/{account_id}/users", params=params
        )
        return self._handle_response(response)

    async def admin_get_user(self, account_id: str, user_id: str) -> Dict[str, Any]:
        """Return one user's credential-free membership info (user_id, role).

        Raises NotFoundError when the user does not exist. Never returns
        api_key or key_prefix.
        """
        response = await self._request(
            "GET",
            f"/api/v1/admin/accounts/{account_id}/users/{user_id}",
        )
        return self._handle_response(response)

    async def admin_remove_user(self, account_id: str, user_id: str) -> Dict[str, Any]:
        response = await self._request(
            "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._request(
            "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, seed: Optional[str] = None
    ) -> Dict[str, Any]:
        payload: Dict[str, Any] = {}
        if seed is not None:
            payload["seed"] = seed
        response = await self._request(
            "POST",
            f"/api/v1/admin/accounts/{account_id}/users/{user_id}/key",
            json=payload,
        )
        return self._handle_response(response)

    async def admin_create_group(self, account_id: str, group_id: str) -> Dict[str, Any]:
        response = await self._http.post(
            f"/api/v1/admin/accounts/{account_id}/groups",
            json={"group_id": group_id},
        )
        return self._handle_response(response)

    async def admin_list_groups(self, account_id: str) -> List[Any]:
        response = await self._http.get(f"/api/v1/admin/accounts/{account_id}/groups")
        return self._handle_response(response)

    async def admin_delete_group(self, account_id: str, group_id: str) -> Dict[str, Any]:
        response = await self._http.delete(f"/api/v1/admin/accounts/{account_id}/groups/{group_id}")
        return self._handle_response(response)

    async def admin_list_group_members(self, account_id: str, group_id: str) -> Dict[str, Any]:
        response = await self._http.get(
            f"/api/v1/admin/accounts/{account_id}/groups/{group_id}/members"
        )
        return self._handle_response(response)

    async def admin_add_group_member(
        self, account_id: str, group_id: str, user_id: str
    ) -> Dict[str, Any]:
        response = await self._http.put(
            f"/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}"
        )
        return self._handle_response(response)

    async def admin_remove_group_member(
        self, account_id: str, group_id: str, user_id: str
    ) -> Dict[str, Any]:
        response = await self._http.delete(
            f"/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}"
        )
        return self._handle_response(response)

    async def admin_get_agent_evolution(self) -> Dict[str, Any]:
        """Return the effective Agent Evolution switch for the caller's account."""
        response = await self._request("GET", "/api/v1/admin/agent-evolution")
        return self._handle_response(response)

    async def admin_set_agent_evolution(self, enabled: bool) -> Dict[str, Any]:
        """Persist and hot-reload Agent Evolution for the caller's account."""
        response = await self._request(
            "PUT", "/api/v1/admin/agent-evolution", json={"enabled": enabled}
        )
        return self._handle_response(response)

    async def admin_get_account_settings(self, account_id: str) -> Dict[str, Any]:
        """Return effective and explicitly overridden settings for one account."""
        response = await self._request("GET", f"/api/v1/admin/accounts/{account_id}/settings")
        return self._handle_response(response)

    async def admin_set_account_agent_evolution(
        self, account_id: str, enabled: bool
    ) -> Dict[str, Any]:
        """Update the allowlisted Agent Evolution setting for one account."""
        response = await self._request(
            "PATCH",
            f"/api/v1/admin/accounts/{account_id}/settings",
            json={"agent_evolution": {"enabled": enabled}},
        )
        return self._handle_response(response)

    async def list_experience_trajectories(
        self,
        experience_uri: str,
        options: Optional[ExperienceTrajectoryOptions] = None,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {"experience_uri": VikingURI.normalize(experience_uri)}
        params.update(dict(options or {}))
        response = await self._request(
            "GET",
            "/api/v1/agent-evolution/experiences/trajectories",
            params=params,
        )
        return self._handle_response(response)

    async def get_experience_outcomes(
        self,
        experience_uri: str,
        options: Optional[ExperienceOutcomeOptions] = None,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {"experience_uri": VikingURI.normalize(experience_uri)}
        params.update(dict(options or {}))
        response = await self._request(
            "GET",
            "/api/v1/agent-evolution/experiences/outcomes",
            params=params,
        )
        return self._handle_response(response)

    async def resolve_openviking_assets(
        self,
        manifest_yaml: str,
        options: Optional[ResolveAssetsOptions] = None,
    ) -> Dict[str, Any]:
        payload = self._build_options_payload(
            options,
            ResolveAssetsOptions,
            fixed={"manifest_yaml": manifest_yaml},
        )
        response = await self._request(
            "POST",
            "/api/v1/openviking-assets/resolve",
            json=payload,
        )
        return self._handle_response(response)

    async def preflight_openviking_asset(
        self,
        name: str,
        repo_url: str,
        options: Optional[PreflightAssetOptions] = None,
    ) -> Dict[str, Any]:
        payload = self._build_options_payload(
            options,
            PreflightAssetOptions,
            fixed={
                "name": name,
                "connector": "git",
                "repo_url": repo_url,
            },
        )
        response = await self._request(
            "POST",
            "/api/v1/openviking-assets/preflight",
            json=payload,
        )
        return self._handle_response(response)

    def queue_status(self, format: Optional[Literal["table", "json"]] = None) -> Dict[str, Any]:
        return run_async(self._get_queue_status(format=format))

    def vikingdb_status(self, format: Optional[Literal["table", "json"]] = None) -> Dict[str, Any]:
        return run_async(self._get_vikingdb_status(format=format))

    def models_status(self, format: Optional[Literal["table", "json"]] = None) -> Dict[str, Any]:
        return run_async(self._get_models_status(format=format))

    def get_status(self, format: Optional[Literal["table", "json"]] = None) -> Dict[str, Any]:
        return run_async(self._get_system_status(format=format))

    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

    # ============= Git Version Control =============

    async def git_commit(
        self,
        *,
        message: str,
        paths: Optional[List[str]] = None,
        branch: str = "main",
        author_name: Optional[str] = None,
        author_email: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Create a snapshot of the current workspace state."""
        body: Dict[str, Any] = {"message": message, "branch": branch}
        if paths is not None:
            body["paths"] = paths
        if author_name is not None:
            body["author_name"] = author_name
        if author_email is not None:
            body["author_email"] = author_email
        response = await self._request("POST", "/api/v1/snapshot/commit", json=body)
        return self._handle_response(response)

    async def git_restore(
        self,
        *,
        project_dir: Optional[str] = None,
        source_commit: str,
        branch: str = "main",
        dry_run: bool = False,
        message: Optional[str] = None,
        author_name: Optional[str] = None,
        author_email: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Forward-commit restore of a subtree, or the full account tree when project_dir is omitted."""
        body: Dict[str, Any] = {
            "source_commit": source_commit,
            "branch": branch,
            "dry_run": dry_run,
        }
        if project_dir is not None:
            body["project_dir"] = project_dir
        if message is not None:
            body["message"] = message
        if author_name is not None:
            body["author_name"] = author_name
        if author_email is not None:
            body["author_email"] = author_email
        response = await self._request("POST", "/api/v1/snapshot/restore", json=body)
        return self._handle_response(response)

    async def git_show(
        self,
        target_ref: str,
        *,
        path: Optional[str] = None,
    ) -> Any:
        """Fetch commit metadata (path=None) or a blob's {oid, size, bytes} (path=<uri>)."""
        params: Dict[str, Any] = {"target_ref": target_ref}
        if path is not None:
            params["path"] = path
        response = await self._request("GET", "/api/v1/snapshot/show", params=params)

        if path is None:
            return self._handle_response(response)

        # Binary branch: server sets application/octet-stream + X-Snapshot-* headers.
        content_type = response.headers.get("content-type", "")
        if content_type.startswith("application/octet-stream"):
            return {
                "oid": response.headers.get("x-snapshot-oid", ""),
                "size": int(response.headers.get("x-snapshot-size", "0")),
                "bytes": response.content,
            }
        # Fallback: server returned a JSON error envelope. Let the standard handler raise.
        return self._handle_response(response)

    async def git_log(
        self,
        *,
        branch: str = "main",
        limit: int = 20,
        paths: Optional[List[str]] = None,
    ) -> List[Dict[str, Any]]:
        """Walk commit history newest-first."""
        params: Dict[str, Any] = {"branch": branch, "limit": limit}
        if paths:
            params["paths"] = paths
        response = await self._request(
            "GET",
            "/api/v1/snapshot/log",
            params=params,
        )
        return self._handle_response(response)

    async def git_diff(
        self,
        path: str,
        *,
        to_ref: str,
        from_ref: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Compare one file between two snapshot refs."""
        params: Dict[str, Any] = {"path": path, "to": to_ref}
        if from_ref is not None:
            params["from"] = from_ref
        response = await self._request(
            "GET",
            "/api/v1/snapshot/diff",
            params=params,
        )
        return self._handle_response(response)

    async def git_diff_paths(
        self,
        paths: List[str],
        *,
        to_ref: str,
        from_ref: Optional[str] = None,
        offset: int = 0,
        limit: int = 100,
    ) -> Dict[str, Any]:
        """Page changed source URIs under directories; a null base means an empty tree."""
        params: Dict[str, Any] = {"paths": paths, "to": to_ref, "offset": offset, "limit": limit}
        if from_ref is not None:
            params["from"] = from_ref
        response = await self._request("GET", "/api/v1/snapshot/diff-paths", params=params)
        return self._handle_response(response)

    async def git_get_ignore(self) -> str:
        """Return the account ``.ovgitignore`` content (empty string if absent)."""
        response = await self._request("GET", "/api/v1/snapshot/ignore")
        result = self._handle_response(response)
        return result if isinstance(result, str) else ""

    async def git_set_ignore(self, *, content: str) -> None:
        """Write the account ``.ovgitignore`` control file."""
        response = await self._request(
            "PUT",
            "/api/v1/snapshot/ignore",
            json={"content": content},
        )
        self._handle_response(response)

    async def git_delete_ignore(self) -> None:
        """Delete the account ``.ovgitignore`` control file (missing is success)."""
        response = await self._request("DELETE", "/api/v1/snapshot/ignore")
        self._handle_response(response)

    @property
    def snapshot(self) -> "AsyncHTTPSnapshotNamespace":
        """Snapshot version control namespace (async HTTP)."""
        if self._snapshot is None:
            self._snapshot = AsyncHTTPSnapshotNamespace(self)
        return self._snapshot


class SyncHTTPClient:
    supports_request_actor_peer = True

    def __init__(self, *args, **kwargs):
        self._async_client = AsyncHTTPClient(*args, **kwargs)
        self._initialized = False
        self._snapshot: Optional["SyncHTTPSnapshotNamespace"] = None

    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,
        wait: bool = False,
        timeout: Optional[float] = None,  # Deprecated and ignored.
        options: Optional[AddResourceOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.add_resource(
                path,
                to=to,
                parent=parent,
                wait=wait,
                options=_normalize_timeout_options(timeout, options),
            )
        )

    def batch_add_messages(
        self,
        session_id: str,
        messages: list[Message],
        options: Optional[BatchAddMessagesOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.batch_add_messages(session_id, messages, options))

    def add_skill(
        self,
        data: Any,
        wait: bool = False,
        timeout: Optional[float] = None,  # Deprecated and ignored.
        options: Optional[AddSkillOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.add_skill(
                data, wait=wait, options=_normalize_timeout_options(timeout, options)
            )
        )

    def list_skills(
        self,
        node_limit: int = 1000,
        target_uri: Optional[str] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.list_skills(node_limit=node_limit, target_uri=target_uri)
        )

    def find_skills(
        self,
        query: str,
        limit: int = 10,
        score_threshold: Optional[float] = None,
        level: Optional[List[int]] = None,
        telemetry: Any = False,
        target_uri: Optional[str] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.find_skills(
                query=query,
                limit=limit,
                score_threshold=score_threshold,
                level=level,
                telemetry=telemetry,
                target_uri=target_uri,
            )
        )

    def validate_skill(
        self,
        data: Any,
        strict: bool = False,
        source_path: Optional[str] = None,
        skill_dir_name: Optional[str] = None,
        target_uri: 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,
                target_uri=target_uri,
            )
        )

    def get_skill(
        self,
        skill_name: str,
        include_content: Optional[bool] = None,
        include_files: bool = True,
        include_source: bool = False,
        level: Optional[int] = None,
        target_uri: Optional[str] = None,
        include_integrity: bool = False,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.get_skill(
                skill_name,
                include_content=include_content,
                include_files=include_files,
                include_integrity=include_integrity,
                include_source=include_source,
                level=level,
                target_uri=target_uri,
            )
        )

    def update_skill(
        self,
        skill_name: str,
        data: Any,
        wait: bool = False,
        timeout: Optional[float] = None,  # Deprecated and ignored.
        options: Optional[UpdateSkillOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.update_skill(
                skill_name, data, wait=wait, options=_normalize_timeout_options(timeout, options)
            )
        )

    def delete_skill(
        self,
        skill_name: str,
        target_uri: Optional[str] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.delete_skill(skill_name, target_uri=target_uri))

    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]:
        """Wait for processing; timeout is deprecated and ignored."""
        return run_async(self._async_client.wait_processed())

    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,
        sort_by: Optional[str] = None,
        sort_order: str = "asc",
        extra_fields: Optional[List[str]] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
        offset: int = 0,
        limit: Optional[int] = None,
        include_abstract: Optional[bool] = None,
        include_overview: Optional[bool] = None,
        overview_limit: int = 4000,
    ) -> List[Any]:
        return self.ls_page(
            uri,
            simple=simple,
            recursive=recursive,
            output=output,
            abs_limit=abs_limit,
            show_all_hidden=show_all_hidden,
            node_limit=node_limit,
            sort_by=sort_by,
            sort_order=sort_order,
            extra_fields=extra_fields,
            tags=tags,
            include_tags=include_tags,
            offset=offset,
            limit=limit,
            include_abstract=include_abstract,
            include_overview=include_overview,
            overview_limit=overview_limit,
        )["result"]

    def ls_page(
        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,
        sort_by: Optional[str] = None,
        sort_order: str = "asc",
        extra_fields: Optional[List[str]] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
        offset: int = 0,
        limit: Optional[int] = None,
        include_abstract: Optional[bool] = None,
        include_overview: Optional[bool] = None,
        overview_limit: int = 4000,
    ) -> ListPage:
        return run_async(
            self._async_client.ls_page(
                uri,
                simple=simple,
                recursive=recursive,
                output=output,
                abs_limit=abs_limit,
                show_all_hidden=show_all_hidden,
                node_limit=node_limit,
                sort_by=sort_by,
                sort_order=sort_order,
                extra_fields=extra_fields,
                tags=tags,
                include_tags=include_tags,
                offset=offset,
                limit=limit,
                include_abstract=include_abstract,
                include_overview=include_overview,
                overview_limit=overview_limit,
            )
        )

    def tree(
        self,
        uri: str,
        output: str = "original",
        abs_limit: int = 128,
        show_all_hidden: bool = False,
        node_limit: int = 1000,
        level_limit: int = 3,
        extra_fields: Optional[List[str]] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
        offset: int = 0,
        limit: Optional[int] = None,
        include_abstract: Optional[bool] = None,
        include_overview: Optional[bool] = None,
        overview_limit: int = 4000,
        directories_only: bool = False,
    ) -> List[Dict[str, Any]]:
        return self.tree_page(
            uri,
            output=output,
            abs_limit=abs_limit,
            show_all_hidden=show_all_hidden,
            node_limit=node_limit,
            level_limit=level_limit,
            extra_fields=extra_fields,
            tags=tags,
            include_tags=include_tags,
            offset=offset,
            limit=limit,
            include_abstract=include_abstract,
            include_overview=include_overview,
            overview_limit=overview_limit,
            directories_only=directories_only,
        )["result"]

    def tree_page(
        self,
        uri: str,
        output: str = "original",
        abs_limit: int = 128,
        show_all_hidden: bool = False,
        node_limit: int = 1000,
        level_limit: int = 3,
        extra_fields: Optional[List[str]] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
        offset: int = 0,
        limit: Optional[int] = None,
        include_abstract: Optional[bool] = None,
        include_overview: Optional[bool] = None,
        overview_limit: int = 4000,
        directories_only: bool = False,
    ) -> TreePage:
        return run_async(
            self._async_client.tree_page(
                uri,
                output=output,
                abs_limit=abs_limit,
                show_all_hidden=show_all_hidden,
                node_limit=node_limit,
                level_limit=level_limit,
                extra_fields=extra_fields,
                tags=tags,
                include_tags=include_tags,
                offset=offset,
                limit=limit,
                include_abstract=include_abstract,
                include_overview=include_overview,
                overview_limit=overview_limit,
                directories_only=directories_only,
            )
        )

    def stat(self, uri: str) -> Dict[str, Any]:
        return run_async(self._async_client.stat(uri))

    def attrs(self, uri: str) -> Dict[str, Any]:
        return run_async(self._async_client.attrs(uri))

    def mkdir(
        self, uri: str, description: Optional[str] = None, *, acl: Optional[Dict[str, Any]] = None
    ) -> None:
        run_async(self._async_client.mkdir(uri, description=description, acl=acl))

    def rm(
        self,
        uri: str,
        recursive: bool = False,
        wait: bool = False,
        timeout: Optional[float] = None,  # Deprecated and ignored.
    ) -> None:
        run_async(self._async_client.rm(uri, recursive=recursive, wait=wait))

    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 read_raw(self, uri: str, offset: int = 0, limit: int = -1) -> str:
        return run_async(self._async_client.read_raw(uri, offset=offset, limit=limit))

    def download_bytes(self, uri: str) -> bytes:
        return run_async(self._async_client.download_bytes(uri))

    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,  # Deprecated and ignored.
        options: Optional[WriteOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.write(
                uri,
                content,
                mode=mode,
                wait=wait,
                options=_normalize_timeout_options(timeout, options),
            )
        )

    def batch_write(
        self,
        root_uri: str,
        operations: List[Dict[str, Any]],
        wait: bool = True,
        timeout: Optional[float] = None,  # Deprecated and ignored.
        options: Optional[BatchWriteOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.batch_write(
                root_uri,
                operations,
                wait=wait,
                options=_normalize_timeout_options(timeout, options),
            )
        )

    def set_tags(
        self,
        uri: str,
        tags: Optional[List[str]] = None,
        mode: str = "replace",
        recursive: bool = False,
        options: Optional[SetTagsOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.set_tags(uri, tags, mode=mode, recursive=recursive, options=options)
        )

    def acl_get(self, uri: str) -> Dict[str, Any]:
        return run_async(self._async_client.acl_get(uri))

    def acl_set(
        self,
        uri: str,
        entries: Optional[List[Dict[str, str]]] = None,
        *,
        acl_mode: Optional[Literal["inherit", "restricted"]] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.acl_set(uri, entries, acl_mode=acl_mode))

    def acl_grant(self, uri: str, principal: str, level: str) -> Dict[str, Any]:
        return run_async(self._async_client.acl_grant(uri, principal, level))

    def acl_revoke(self, uri: str, principal: str) -> Dict[str, Any]:
        return run_async(self._async_client.acl_revoke(uri, principal))

    def acl_delete(self, uri: str) -> Dict[str, Any]:
        return run_async(self._async_client.acl_delete(uri))

    def find(
        self,
        query: str = "",
        target_uri: Union[str, List[str]] = "",
        limit: int = 10,
        image: Any = None,
        options: Optional[FindOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.find(
                query,
                target_uri=target_uri,
                limit=limit,
                image=image,
                options=options,
            )
        )

    def search(
        self,
        query: str = "",
        session_id: Optional[str] = None,
        target_uri: Union[str, List[str]] = "",
        limit: int = 10,
        image: Any = None,
        options: Optional[SearchOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.search(
                query,
                session_id=session_id,
                target_uri=target_uri,
                limit=limit,
                image=image,
                options=options,
            )
        )

    def search_context(
        self,
        query: str = "",
        session_id: Optional[str] = None,
        target_uri: Union[str, List[str]] = "",
        limit: int = 10,
        image: Any = None,
        options: Optional[SearchContextOptions] = None,
    ) -> SearchContextResult:
        return run_async(
            self._async_client.search_context(
                query,
                session_id=session_id,
                target_uri=target_uri,
                limit=limit,
                image=image,
                options=options,
            )
        )

    def grep(
        self,
        uri: str,
        pattern: str,
        case_insensitive: bool = False,
        node_limit: int = 256,
        exclude_uri: Optional[str] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
        level_limit: Optional[int] = 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,
                tags=tags,
                include_tags=include_tags,
                level_limit=level_limit,
            )
        )

    def glob(
        self,
        pattern: str,
        uri: str = "viking://",
        node_limit: int = 256,
        extra_fields: Optional[List[str]] = None,
        tags: Optional[List[str]] = None,
        include_tags: bool = False,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.glob(
                pattern,
                uri=uri,
                node_limit=node_limit,
                extra_fields=extra_fields,
                tags=tags,
                include_tags=include_tags,
            )
        )

    def create_session(
        self,
        session_id: Optional[str] = None,
        options: Optional[CreateSessionOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.create_session(session_id, options=options))

    def list_sessions(self) -> List[Any]:
        return run_async(self._async_client.list_sessions())

    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 update_session_config(
        self,
        session_id: str,
        options: Optional[UpdateSessionConfigOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.update_session_config(session_id, options))

    def get_session_context(self, session_id: str, token_budget: int = 128_000) -> Dict[str, Any]:
        return run_async(self._async_client.get_session_context(session_id, token_budget))

    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 compile(
        self,
        from_uris: List[str],
        to: str,
        skill: str,
        options: Optional[CompileOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.compile(from_uris, to, skill, options))

    def rule_compile(
        self,
        instruction: Optional[str] = None,
        options: Optional[RuleCompileOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.rule_compile(instruction, options))

    def rule_search(
        self,
        task_context: str,
        options: Optional[RuleSearchOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.rule_search(task_context, options))

    def cancel_task(self, task_id: str) -> Dict[str, Any]:
        return run_async(self._async_client.cancel_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,
        keep_recent_count: int = 0,
        options: Optional[CommitSessionOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.commit_session(
                session_id, keep_recent_count=keep_recent_count, options=options
            )
        )

    def add_message(
        self,
        session_id: str,
        role: str,
        content: Optional[str] = None,
        parts: Optional[List[Union[Dict[str, Any], MessagePart]]] = None,
        options: Optional[AddMessageOptions] = None,
        peer_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        kwargs: Dict[str, Any] = {
            "role": role,
            "content": content,
            "parts": parts,
            "options": options,
        }
        if peer_id is not None:
            kwargs["peer_id"] = peer_id
        return run_async(self._async_client.add_message(session_id, **kwargs))

    def export_ovpack(
        self,
        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,
        recursive: bool = True,
        force: bool = False,
        options: Optional[ReindexOptions] = None,
    ) -> Dict[str, Any]:
        kwargs: Dict[str, Any] = {
            "mode": mode,
            "wait": wait,
            "recursive": recursive,
            "options": options,
        }
        if force:
            kwargs["force"] = True
        return run_async(self._async_client.reindex(uri, **kwargs))

    def admin_create_account(
        self,
        account_id: str,
        admin_user_id: str,
        user_config: Optional[Dict[str, Any]] = None,
        seed: Optional[str] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.admin_create_account(
                account_id,
                admin_user_id,
                seed=seed,
                user_config=user_config,
            )
        )

    def admin_list_accounts(
        self,
        name: Optional[str] = None,
        limit: Optional[int] = None,
        page: int = 1,
        query: Optional[str] = None,
    ) -> List[Any]:
        return run_async(
            self._async_client.admin_list_accounts(name=name, limit=limit, page=page, query=query)
        )

    def admin_delete_account(self, account_id: str) -> Dict[str, Any]:
        return run_async(self._async_client.admin_delete_account(account_id))

    def admin_get_account(self, account_id: str) -> Dict[str, Any]:
        return run_async(self._async_client.admin_get_account(account_id))

    def admin_register_user(
        self,
        account_id: str,
        user_id: str,
        role: str = "user",
        user_config: Optional[Dict[str, Any]] = None,
        seed: Optional[str] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.admin_register_user(
                account_id,
                user_id,
                role,
                seed=seed,
                user_config=user_config,
            )
        )

    def admin_list_users(
        self,
        account_id: str,
        limit: Optional[int] = None,
        name: Optional[str] = None,
        role: Optional[str] = None,
        page: int = 1,
        query: Optional[str] = None,
    ) -> List[Any]:
        return run_async(
            self._async_client.admin_list_users(
                account_id, limit=limit, name=name, role=role, page=page, query=query
            )
        )

    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_get_user(self, account_id: str, user_id: str) -> Dict[str, Any]:
        return run_async(self._async_client.admin_get_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, seed: Optional[str] = None
    ) -> Dict[str, Any]:
        return run_async(self._async_client.admin_regenerate_key(account_id, user_id, seed=seed))

    def admin_create_group(self, account_id: str, group_id: str) -> Dict[str, Any]:
        return run_async(self._async_client.admin_create_group(account_id, group_id))

    def admin_list_groups(self, account_id: str) -> List[Any]:
        return run_async(self._async_client.admin_list_groups(account_id))

    def admin_delete_group(self, account_id: str, group_id: str) -> Dict[str, Any]:
        return run_async(self._async_client.admin_delete_group(account_id, group_id))

    def admin_list_group_members(self, account_id: str, group_id: str) -> Dict[str, Any]:
        return run_async(self._async_client.admin_list_group_members(account_id, group_id))

    def admin_add_group_member(
        self, account_id: str, group_id: str, user_id: str
    ) -> Dict[str, Any]:
        return run_async(self._async_client.admin_add_group_member(account_id, group_id, user_id))

    def admin_remove_group_member(
        self, account_id: str, group_id: str, user_id: str
    ) -> Dict[str, Any]:
        return run_async(
            self._async_client.admin_remove_group_member(account_id, group_id, user_id)
        )

    def admin_get_agent_evolution(self) -> Dict[str, Any]:
        return run_async(self._async_client.admin_get_agent_evolution())

    def admin_set_agent_evolution(self, enabled: bool) -> Dict[str, Any]:
        return run_async(self._async_client.admin_set_agent_evolution(enabled))

    def admin_get_account_settings(self, account_id: str) -> Dict[str, Any]:
        return run_async(self._async_client.admin_get_account_settings(account_id))

    def admin_set_account_agent_evolution(self, account_id: str, enabled: bool) -> Dict[str, Any]:
        return run_async(self._async_client.admin_set_account_agent_evolution(account_id, enabled))

    def list_experience_trajectories(
        self,
        experience_uri: str,
        options: Optional[ExperienceTrajectoryOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.list_experience_trajectories(experience_uri, options))

    def get_experience_outcomes(
        self,
        experience_uri: str,
        options: Optional[ExperienceOutcomeOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.get_experience_outcomes(experience_uri, options))

    def resolve_openviking_assets(
        self,
        manifest_yaml: str,
        options: Optional[ResolveAssetsOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.resolve_openviking_assets(manifest_yaml, options))

    def preflight_openviking_asset(
        self,
        name: str,
        repo_url: str,
        options: Optional[PreflightAssetOptions] = None,
    ) -> Dict[str, Any]:
        return run_async(self._async_client.preflight_openviking_asset(name, repo_url, options))

    def queue_status(self, format: Optional[Literal["table", "json"]] = None) -> Dict[str, Any]:
        return self._async_client.queue_status(format=format)

    def vikingdb_status(self, format: Optional[Literal["table", "json"]] = None) -> Dict[str, Any]:
        return self._async_client.vikingdb_status(format=format)

    def models_status(self, format: Optional[Literal["table", "json"]] = None) -> Dict[str, Any]:
        return self._async_client.models_status(format=format)

    def get_status(self, format: Optional[Literal["table", "json"]] = None) -> Dict[str, Any]:
        return self._async_client.get_status(format=format)

    def is_healthy(self) -> bool:
        return self._async_client.is_healthy()

    @property
    def observer(self) -> _HTTPObserver:
        return self._async_client.observer

    @property
    def snapshot(self) -> "SyncHTTPSnapshotNamespace":
        """Snapshot version control namespace (sync HTTP)."""
        if self._snapshot is None:
            self._snapshot = SyncHTTPSnapshotNamespace(self)
        return self._snapshot

    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


class AsyncHTTPSnapshotNamespace:
    """Snapshot version control namespace forwarding to AsyncHTTPClient git_* methods."""

    def __init__(self, client: "AsyncHTTPClient"):
        self._client = client

    async def commit(
        self,
        *,
        message: str,
        paths: Optional[List[str]] = None,
        branch: str = "main",
        author_name: Optional[str] = None,
        author_email: Optional[str] = None,
    ) -> Dict[str, Any]:
        return await self._client.git_commit(
            message=message,
            paths=paths,
            branch=branch,
            author_name=author_name,
            author_email=author_email,
        )

    async def restore(
        self,
        *,
        project_dir: Optional[str] = None,
        source_commit: str,
        branch: str = "main",
        dry_run: bool = False,
        message: Optional[str] = None,
        author_name: Optional[str] = None,
        author_email: Optional[str] = None,
    ) -> Dict[str, Any]:
        return await self._client.git_restore(
            project_dir=project_dir,
            source_commit=source_commit,
            branch=branch,
            dry_run=dry_run,
            message=message,
            author_name=author_name,
            author_email=author_email,
        )

    async def show(
        self,
        target_ref: str,
        *,
        path: Optional[str] = None,
    ) -> Any:
        return await self._client.git_show(target_ref, path=path)

    async def log(
        self,
        *,
        branch: str = "main",
        limit: int = 20,
        paths: Optional[List[str]] = None,
    ) -> List[Dict[str, Any]]:
        return await self._client.git_log(branch=branch, limit=limit, paths=paths)

    async def diff(
        self,
        path: str,
        *,
        to_ref: str,
        from_ref: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Compare one file between two snapshot refs."""
        return await self._client.git_diff(
            path,
            from_ref=from_ref,
            to_ref=to_ref,
        )

    async def diff_paths(
        self,
        paths: List[str],
        *,
        to_ref: str,
        from_ref: Optional[str] = None,
        offset: int = 0,
        limit: int = 100,
    ) -> Dict[str, Any]:
        """Page changed source URIs between snapshots under the supplied directories."""
        return await self._client.git_diff_paths(
            paths, from_ref=from_ref, to_ref=to_ref, offset=offset, limit=limit
        )

    async def get_gitignore(self) -> str:
        return await self._client.git_get_ignore()

    async def set_gitignore(self, *, content: str) -> None:
        await self._client.git_set_ignore(content=content)

    async def delete_gitignore(self) -> None:
        await self._client.git_delete_ignore()


class SyncHTTPSnapshotNamespace:
    """Synchronous wrapper around the HTTP client's snapshot namespace."""

    def __init__(self, client: "SyncHTTPClient"):
        self._client = client

    def _ns(self) -> AsyncHTTPSnapshotNamespace:
        return self._client._async_client.snapshot

    def commit(
        self,
        *,
        message: str,
        paths: Optional[List[str]] = None,
        branch: str = "main",
        author_name: Optional[str] = None,
        author_email: Optional[str] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._ns().commit(
                message=message,
                paths=paths,
                branch=branch,
                author_name=author_name,
                author_email=author_email,
            )
        )

    def restore(
        self,
        *,
        project_dir: Optional[str] = None,
        source_commit: str,
        branch: str = "main",
        dry_run: bool = False,
        message: Optional[str] = None,
        author_name: Optional[str] = None,
        author_email: Optional[str] = None,
    ) -> Dict[str, Any]:
        return run_async(
            self._ns().restore(
                project_dir=project_dir,
                source_commit=source_commit,
                branch=branch,
                dry_run=dry_run,
                message=message,
                author_name=author_name,
                author_email=author_email,
            )
        )

    def show(
        self,
        target_ref: str,
        *,
        path: Optional[str] = None,
    ) -> Any:
        return run_async(self._ns().show(target_ref, path=path))

    def log(
        self,
        *,
        branch: str = "main",
        limit: int = 20,
        paths: Optional[List[str]] = None,
    ) -> List[Dict[str, Any]]:
        return run_async(self._ns().log(branch=branch, limit=limit, paths=paths))

    def diff(
        self,
        path: str,
        *,
        to_ref: str,
        from_ref: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Compare one file between two snapshot refs."""
        return run_async(self._ns().diff(path, from_ref=from_ref, to_ref=to_ref))

    def diff_paths(
        self,
        paths: List[str],
        *,
        to_ref: str,
        from_ref: Optional[str] = None,
        offset: int = 0,
        limit: int = 100,
    ) -> Dict[str, Any]:
        """Page changed source URIs between snapshots under the supplied directories."""
        return run_async(
            self._ns().diff_paths(
                paths, from_ref=from_ref, to_ref=to_ref, offset=offset, limit=limit
            )
        )

    def get_gitignore(self) -> str:
        return run_async(self._ns().get_gitignore())

    def set_gitignore(self, *, content: str) -> None:
        run_async(self._ns().set_gitignore(content=content))

    def delete_gitignore(self) -> None:
        run_async(self._ns().delete_gitignore())