mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
feat(memory): support multi-user and multi-tenant isolation in openviking (#8441)
* docs(openviking): document multi-user and multi-tenant isolation * feat(memory): support multi-user and multi-tenant isolation in openviking (#8420) * fix(memory): fall back to viking://~/ URIs on OpenViking >=0.5.5 * fix(memory): address OpenViking multi-user PR review findings * fix(memory): reject single-user client_pool and scope static tenant errors * fix(memory): normalize provider MemoryManagerError to honor read failure policy * fix(memory): allow admitted OpenViking operations to acquire clients during shutdown drain * fix(memory): bound OpenViking provider cleanup on shutdown and harden diagnostics * fix(memory): avoid waiting on cleanup from _end_operation tail * fix(memory): run recorder and provider cleanup in single shutdown worker * fix(memory): harden multi-user api_key_env validation and cleanup worker start failure
This commit is contained in:
parent
b8e03f71de
commit
178edb4721
@ -5,7 +5,10 @@ Each subfolder under `agents/memory/backends/` is a pluggable memory backend. Sw
|
||||
- `deermem/` - the default backend (deer-flow's own: structured facts + JSON storage).
|
||||
- `noop/` - an empty backend and the **template** to copy when adding a new one.
|
||||
- `openviking/` - optional remote backend using the official
|
||||
`langchain-openviking` package (single-user middleware mode).
|
||||
`langchain-openviking` package (`memory.mode: middleware` only; supports
|
||||
single-user `owner_user_id` + `api_key_env` and fail-closed multi-user /
|
||||
multi-tenant isolation via `user_credentials` or `credential_provider` with
|
||||
optional `tenant_id` and `client_pool`).
|
||||
- `honcho/` - optional remote Honcho backend over HTTP: user-model memory (representations built by Honcho's server-side deriver; no local LLM calls). Workspace-per-user isolation with per-user overrides.
|
||||
|
||||
This guide tells you **which files to touch** when you change, swap, or add a memory system. Paths are relative to `backend/` unless noted.
|
||||
|
||||
@ -1,7 +1,13 @@
|
||||
"""OpenViking memory backend using the official LangChain integration."""
|
||||
|
||||
from .credentials import OpenVikingCredential, OpenVikingCredentialProvider
|
||||
from .openviking_manager import OpenVikingMemoryManager
|
||||
|
||||
MANAGER_CLASS = OpenVikingMemoryManager
|
||||
|
||||
__all__ = ["OpenVikingMemoryManager"]
|
||||
__all__ = [
|
||||
"MANAGER_CLASS",
|
||||
"OpenVikingCredential",
|
||||
"OpenVikingCredentialProvider",
|
||||
"OpenVikingMemoryManager",
|
||||
]
|
||||
|
||||
@ -4,14 +4,27 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from math import isfinite
|
||||
from types import MappingProxyType
|
||||
from typing import Any, Literal
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from .credentials import (
|
||||
OpenVikingCredential,
|
||||
has_control_chars,
|
||||
validate_api_key,
|
||||
validate_provider_path,
|
||||
validate_user_key,
|
||||
)
|
||||
|
||||
_SAFE_PEER_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
|
||||
GENERATED_PEER_PREFIX = "df-agent-"
|
||||
_DEFAULT_POOL_MAX_CLIENTS = 64
|
||||
_MAX_POOL_CLIENTS = 4096
|
||||
_DEFAULT_POOL_IDLE_TTL_SECONDS = 900.0
|
||||
_ALLOWED_USER_CREDENTIAL_KEYS = frozenset({"api_key", "api_key_env", "tenant_id"})
|
||||
_REMOVED_CUSTOM_HTTP_FIELDS = frozenset(
|
||||
{
|
||||
"connect_timeout_seconds",
|
||||
@ -31,9 +44,15 @@ class OpenVikingConfig:
|
||||
|
||||
base_url: str
|
||||
storage_path: str
|
||||
owner_user_id: str
|
||||
owner_user_id: str | None
|
||||
api_key: str = field(repr=False)
|
||||
api_key_env: str
|
||||
api_key_env: str | None
|
||||
isolation_mode: Literal["single_user", "multi_user"]
|
||||
user_credentials: Mapping[str, OpenVikingCredential] = field(repr=False)
|
||||
credential_provider: str | None
|
||||
credential_provider_config: Mapping[str, Any] = field(repr=False)
|
||||
pool_max_clients: int
|
||||
pool_idle_ttl_seconds: float | None
|
||||
default_peer_id: str
|
||||
timeout_seconds: float
|
||||
search_top_k: int
|
||||
@ -51,60 +70,132 @@ class OpenVikingConfig:
|
||||
def from_backend_config(
|
||||
cls,
|
||||
backend_config: dict[str, Any] | None,
|
||||
*,
|
||||
has_injected_credential_provider: bool = False,
|
||||
) -> OpenVikingConfig:
|
||||
"""Parse and validate ``backend_config`` without imports or network I/O."""
|
||||
|
||||
cfg = dict(backend_config or {})
|
||||
if "auth_mode" in cfg or "account" in cfg:
|
||||
raise ValueError("OpenViking trusted mode is no longer supported by this backend; use a USER API key and configure owner_user_id")
|
||||
raise ValueError("OpenViking trusted mode is no longer supported by this backend; use a USER API key and configure owner_user_id, user_credentials, or credential_provider")
|
||||
removed_fields = sorted(_REMOVED_CUSTOM_HTTP_FIELDS.intersection(cfg))
|
||||
if removed_fields:
|
||||
raise ValueError("OpenViking custom HTTP client fields are no longer supported: " + ", ".join(removed_fields))
|
||||
|
||||
retrieval = _mapping(cfg.pop("retrieval", {}), "retrieval")
|
||||
failure_policy = _mapping(
|
||||
cfg.pop("failure_policy", {}),
|
||||
"failure_policy",
|
||||
)
|
||||
api_key_env = str(cfg.pop("api_key_env", "OPENVIKING_API_KEY")).strip()
|
||||
if not api_key_env:
|
||||
raise ValueError("OpenViking api_key_env must not be empty")
|
||||
failure_policy = _mapping(cfg.pop("failure_policy", {}), "failure_policy")
|
||||
client_pool = _mapping(cfg.pop("client_pool", {}), "client_pool")
|
||||
|
||||
result = cls(
|
||||
base_url=str(cfg.pop("base_url", "http://127.0.0.1:1933")).rstrip("/"),
|
||||
storage_path=str(cfg.pop("storage_path", "")),
|
||||
owner_user_id=str(cfg.pop("owner_user_id", "")).strip(),
|
||||
api_key=os.environ.get(api_key_env, "").strip(),
|
||||
api_key_env=api_key_env,
|
||||
default_peer_id=str(cfg.pop("default_peer_id", "deerflow")).strip(),
|
||||
timeout_seconds=_number(cfg, "timeout_seconds", 30.0, float),
|
||||
search_top_k=_number(retrieval, "top_k", 8, int),
|
||||
score_threshold=_optional_float(retrieval.pop("score_threshold", None), "score_threshold"),
|
||||
max_injection_chars=_number(retrieval, "max_injection_chars", 12_000, int),
|
||||
content_mode=str(retrieval.pop("content_mode", "overview")).lower(), # type: ignore[arg-type]
|
||||
injection_query=str(
|
||||
retrieval.pop(
|
||||
"injection_query",
|
||||
"user profile preferences important entities events ongoing goals constraints and prior decisions",
|
||||
)
|
||||
).strip(),
|
||||
startup_policy=str(cfg.pop("startup_policy", "fail_fast")).lower(), # type: ignore[arg-type]
|
||||
read_failure_policy=str(failure_policy.pop("read", "fail_open")).lower(), # type: ignore[arg-type]
|
||||
write_failure_policy=str(failure_policy.pop("write", "log_and_drop")).lower(), # type: ignore[arg-type]
|
||||
allow_insecure_http=_boolean(
|
||||
cfg.pop("allow_insecure_http", False),
|
||||
"allow_insecure_http",
|
||||
),
|
||||
max_seen_message_ids=_number(cfg, "max_seen_message_ids", 512, int),
|
||||
)
|
||||
credential_provider = _parse_credential_provider(cfg.pop("credential_provider", None))
|
||||
provider_config = _mapping(cfg.pop("credential_provider_config", {}), "credential_provider_config")
|
||||
|
||||
has_explicit_owner_user_id = "owner_user_id" in cfg
|
||||
has_explicit_api_key_env = "api_key_env" in cfg
|
||||
raw_owner_user_id = cfg.pop("owner_user_id", None)
|
||||
raw_api_key_env = cfg.pop("api_key_env", None)
|
||||
raw_user_credentials = cfg.pop("user_credentials", None)
|
||||
|
||||
is_multi_user = raw_user_credentials is not None or credential_provider is not None or has_injected_credential_provider
|
||||
|
||||
if provider_config and credential_provider is None:
|
||||
raise ValueError("OpenViking credential_provider_config requires credential_provider in backend_config")
|
||||
if client_pool and not is_multi_user:
|
||||
raise ValueError("OpenViking client_pool is only supported in multi-user mode with user_credentials or credential_provider")
|
||||
|
||||
user_credential_unknowns: list[str] = []
|
||||
if is_multi_user:
|
||||
if has_explicit_owner_user_id or has_explicit_api_key_env:
|
||||
raise ValueError("OpenViking owner_user_id and api_key_env cannot be used in multi-user mode with user_credentials or credential_provider")
|
||||
if raw_user_credentials is not None:
|
||||
user_credential_unknowns = _validate_user_credentials_structure(raw_user_credentials)
|
||||
isolation_mode: Literal["single_user", "multi_user"] = "multi_user"
|
||||
owner_user_id: str | None = None
|
||||
api_key_env: str | None = None
|
||||
api_key = ""
|
||||
else:
|
||||
isolation_mode = "single_user"
|
||||
if raw_owner_user_id is None:
|
||||
owner_user_id = ""
|
||||
elif not isinstance(raw_owner_user_id, str) or has_control_chars(raw_owner_user_id):
|
||||
raise ValueError("OpenViking owner_user_id must be a string without control characters")
|
||||
else:
|
||||
owner_user_id = raw_owner_user_id.strip()
|
||||
if raw_api_key_env is None:
|
||||
api_key_env = "OPENVIKING_API_KEY"
|
||||
elif not isinstance(raw_api_key_env, str) or has_control_chars(raw_api_key_env):
|
||||
raise ValueError("OpenViking api_key_env must be a string without control characters")
|
||||
else:
|
||||
api_key_env = raw_api_key_env.strip()
|
||||
if not api_key_env:
|
||||
raise ValueError("OpenViking api_key_env must not be empty")
|
||||
api_key = os.environ.get(api_key_env, "").strip()
|
||||
|
||||
pool_max_clients = _pool_int(client_pool, "max_clients", _DEFAULT_POOL_MAX_CLIENTS)
|
||||
pool_idle_ttl_seconds = _pool_idle_ttl(client_pool)
|
||||
|
||||
base_url = str(cfg.pop("base_url", "http://127.0.0.1:1933")).rstrip("/")
|
||||
storage_path = str(cfg.pop("storage_path", ""))
|
||||
default_peer_id = str(cfg.pop("default_peer_id", "deerflow")).strip()
|
||||
timeout_seconds = _number(cfg, "timeout_seconds", 30.0, float)
|
||||
search_top_k = _number(retrieval, "top_k", 8, int)
|
||||
score_threshold = _optional_float(retrieval.pop("score_threshold", None), "score_threshold")
|
||||
max_injection_chars = _number(retrieval, "max_injection_chars", 12_000, int)
|
||||
content_mode = str(retrieval.pop("content_mode", "overview")).lower()
|
||||
injection_query = str(
|
||||
retrieval.pop(
|
||||
"injection_query",
|
||||
"user profile preferences important entities events ongoing goals constraints and prior decisions",
|
||||
)
|
||||
).strip()
|
||||
startup_policy = str(cfg.pop("startup_policy", "fail_fast")).lower()
|
||||
read_failure_policy = str(failure_policy.pop("read", "fail_open")).lower()
|
||||
write_failure_policy = str(failure_policy.pop("write", "log_and_drop")).lower()
|
||||
allow_insecure_http = _boolean(cfg.pop("allow_insecure_http", False), "allow_insecure_http")
|
||||
max_seen_message_ids = _number(cfg, "max_seen_message_ids", 512, int)
|
||||
|
||||
unknown = sorted(
|
||||
[
|
||||
*cfg,
|
||||
*(f"retrieval.{key}" for key in retrieval),
|
||||
*(f"failure_policy.{key}" for key in failure_policy),
|
||||
*(f"client_pool.{key}" for key in client_pool),
|
||||
*user_credential_unknowns,
|
||||
]
|
||||
)
|
||||
if unknown:
|
||||
raise ValueError("Unknown OpenViking backend_config fields: " + ", ".join(unknown))
|
||||
|
||||
parsed_user_credentials: dict[str, OpenVikingCredential] = {}
|
||||
if is_multi_user and raw_user_credentials is not None:
|
||||
if not raw_user_credentials and credential_provider is None and not has_injected_credential_provider:
|
||||
raise ValueError("OpenViking user_credentials must not be empty when no credential_provider is configured")
|
||||
parsed_user_credentials = _resolve_user_credentials(raw_user_credentials)
|
||||
|
||||
result = cls(
|
||||
base_url=base_url,
|
||||
storage_path=storage_path,
|
||||
owner_user_id=owner_user_id,
|
||||
api_key=api_key,
|
||||
api_key_env=api_key_env,
|
||||
isolation_mode=isolation_mode,
|
||||
user_credentials=MappingProxyType(parsed_user_credentials),
|
||||
credential_provider=credential_provider,
|
||||
credential_provider_config=MappingProxyType(provider_config),
|
||||
pool_max_clients=pool_max_clients,
|
||||
pool_idle_ttl_seconds=pool_idle_ttl_seconds,
|
||||
default_peer_id=default_peer_id,
|
||||
timeout_seconds=timeout_seconds,
|
||||
search_top_k=search_top_k,
|
||||
score_threshold=score_threshold,
|
||||
max_injection_chars=max_injection_chars,
|
||||
content_mode=content_mode, # type: ignore[arg-type]
|
||||
injection_query=injection_query,
|
||||
startup_policy=startup_policy, # type: ignore[arg-type]
|
||||
read_failure_policy=read_failure_policy, # type: ignore[arg-type]
|
||||
write_failure_policy=write_failure_policy, # type: ignore[arg-type]
|
||||
allow_insecure_http=allow_insecure_http,
|
||||
max_seen_message_ids=max_seen_message_ids,
|
||||
)
|
||||
result._validate()
|
||||
return result
|
||||
|
||||
@ -112,12 +203,20 @@ class OpenVikingConfig:
|
||||
parsed = urlparse(self.base_url)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise ValueError("OpenViking base_url must be an absolute http(s) URL")
|
||||
if parsed.username is not None or parsed.password is not None:
|
||||
raise ValueError("OpenViking base_url must not embed credentials; configure api_key_env, user_credentials, or credential_provider instead")
|
||||
if parsed.scheme == "http" and not self.allow_insecure_http and parsed.hostname not in {"127.0.0.1", "localhost", "openviking"}:
|
||||
raise ValueError("OpenViking plain HTTP is allowed only for localhost/openviking; set allow_insecure_http=true only for a trusted internal network")
|
||||
if not self.owner_user_id:
|
||||
raise ValueError("OpenViking owner_user_id must not be empty")
|
||||
if not self.api_key:
|
||||
raise ValueError(f"OpenViking USER API key is missing; set {self.api_key_env}")
|
||||
if self.isolation_mode == "single_user":
|
||||
if not self.owner_user_id:
|
||||
raise ValueError("OpenViking owner_user_id must not be empty")
|
||||
if not self.api_key:
|
||||
raise ValueError(f"OpenViking USER API key is missing; set {self.api_key_env}")
|
||||
validate_api_key(self.api_key)
|
||||
if not 1 <= self.pool_max_clients <= _MAX_POOL_CLIENTS:
|
||||
raise ValueError(f"OpenViking client_pool.max_clients must be between 1 and {_MAX_POOL_CLIENTS}")
|
||||
if self.pool_idle_ttl_seconds is not None and (not isfinite(self.pool_idle_ttl_seconds) or self.pool_idle_ttl_seconds <= 0):
|
||||
raise ValueError("OpenViking client_pool.idle_ttl_seconds must be a finite value > 0 or null")
|
||||
if not is_safe_peer_id(self.default_peer_id):
|
||||
raise ValueError("OpenViking default_peer_id must start with a lowercase letter or digit and contain at most 64 lowercase letters, digits, '_' or '-'")
|
||||
if self.default_peer_id.startswith(GENERATED_PEER_PREFIX):
|
||||
@ -150,6 +249,72 @@ def is_safe_peer_id(value: str) -> bool:
|
||||
return _SAFE_PEER_RE.fullmatch(value) is not None
|
||||
|
||||
|
||||
def _parse_credential_provider(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("OpenViking credential_provider must be a non-empty string")
|
||||
if not value.strip():
|
||||
raise ValueError("OpenViking credential_provider must not be empty")
|
||||
validate_provider_path(value)
|
||||
return value
|
||||
|
||||
|
||||
def _validate_user_credentials_structure(raw_user_credentials: Any) -> list[str]:
|
||||
if not isinstance(raw_user_credentials, dict):
|
||||
raise ValueError("OpenViking user_credentials must be a mapping")
|
||||
unknown: list[str] = []
|
||||
for raw_uid, raw_spec in raw_user_credentials.items():
|
||||
uid = validate_user_key(raw_uid)
|
||||
if not isinstance(raw_spec, dict):
|
||||
raise ValueError(f"OpenViking user_credentials.{uid} must be a mapping")
|
||||
for key in raw_spec:
|
||||
if not isinstance(key, str):
|
||||
raise ValueError(f"OpenViking user_credentials.{uid} keys must be strings, got {type(key).__name__}")
|
||||
if key not in _ALLOWED_USER_CREDENTIAL_KEYS:
|
||||
unknown.append(f"user_credentials.{uid}.{key}")
|
||||
return unknown
|
||||
|
||||
|
||||
def _resolve_user_credentials(raw_user_credentials: dict[str, dict[str, Any]]) -> dict[str, OpenVikingCredential]:
|
||||
resolved: dict[str, OpenVikingCredential] = {}
|
||||
seen_fingerprints: dict[str, str] = {}
|
||||
for uid, spec in raw_user_credentials.items():
|
||||
has_inline = spec.get("api_key") is not None
|
||||
has_env = spec.get("api_key_env") is not None
|
||||
if has_inline == has_env:
|
||||
raise ValueError(f"OpenViking user_credentials.{uid} must specify exactly one of 'api_key' or 'api_key_env'")
|
||||
|
||||
raw_tenant = spec.get("tenant_id")
|
||||
env_name: str | None = None
|
||||
if has_env:
|
||||
raw_env = spec["api_key_env"]
|
||||
if not isinstance(raw_env, str) or not raw_env.strip() or has_control_chars(raw_env):
|
||||
raise ValueError(f"OpenViking user_credentials.{uid}.api_key_env must be a non-empty string without control characters")
|
||||
env_name = raw_env.strip()
|
||||
api_key_value = os.environ.get(env_name, "").strip()
|
||||
if not api_key_value:
|
||||
raise ValueError(f"OpenViking USER API key is missing for user {uid!r}; set {env_name}")
|
||||
else:
|
||||
api_key_value = spec["api_key"]
|
||||
|
||||
try:
|
||||
cred = OpenVikingCredential(
|
||||
api_key=api_key_value,
|
||||
tenant_id=raw_tenant,
|
||||
api_key_env=env_name,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"Invalid OpenViking user_credentials.{uid}: {exc}") from exc
|
||||
|
||||
existing_uid = seen_fingerprints.get(cred.key_fingerprint)
|
||||
if existing_uid is not None:
|
||||
raise ValueError(f"OpenViking user_credentials must not share the same API key across users ({existing_uid!r} and {uid!r})")
|
||||
seen_fingerprints[cred.key_fingerprint] = uid
|
||||
resolved[uid] = cred
|
||||
return resolved
|
||||
|
||||
|
||||
def _mapping(value: Any, name: str) -> dict[str, Any]:
|
||||
if value is None:
|
||||
return {}
|
||||
@ -171,6 +336,8 @@ def _number[T](cfg: dict[str, Any], key: str, default: T, cast: Callable[[Any],
|
||||
value = cfg.pop(key, default)
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return default
|
||||
if isinstance(value, bool):
|
||||
raise ValueError(f"OpenViking {key} must be a number, got {type(value).__name__}")
|
||||
try:
|
||||
return cast(value)
|
||||
except (TypeError, ValueError):
|
||||
@ -183,12 +350,42 @@ def _optional_float(value: Any, name: str) -> float | None:
|
||||
falling back to a default."""
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
raise ValueError(f"OpenViking {name} must be a number, got {type(value).__name__}")
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"OpenViking {name} must be a number, got {type(value).__name__}") from None
|
||||
|
||||
|
||||
def _pool_int(pool: dict[str, Any], key: str, default: int) -> int:
|
||||
value = pool.pop(key, default)
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return default
|
||||
if isinstance(value, (bool, float)):
|
||||
raise ValueError(f"OpenViking client_pool.{key} must be an integer, got {type(value).__name__}")
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"OpenViking client_pool.{key} must be an integer, got {type(value).__name__}") from None
|
||||
|
||||
|
||||
def _pool_idle_ttl(pool: dict[str, Any]) -> float | None:
|
||||
if "idle_ttl_seconds" not in pool:
|
||||
return _DEFAULT_POOL_IDLE_TTL_SECONDS
|
||||
value = pool.pop("idle_ttl_seconds")
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
raise ValueError(f"OpenViking client_pool.idle_ttl_seconds must be a number, got {type(value).__name__}")
|
||||
if isinstance(value, str) and not value.strip():
|
||||
raise ValueError("OpenViking client_pool.idle_ttl_seconds must be a number or null, got empty str")
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"OpenViking client_pool.idle_ttl_seconds must be a number, got {type(value).__name__}") from None
|
||||
|
||||
|
||||
def _boolean(value: Any, name: str) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
|
||||
@ -0,0 +1,200 @@
|
||||
"""Credential types, validation, and dynamic provider loading for OpenViking."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib
|
||||
import keyword
|
||||
import unicodedata
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
|
||||
_MAX_TENANT_ID_LENGTH = 128
|
||||
_ALLOWED_PROVIDER_RESULT_KEYS = frozenset({"api_key", "tenant_id"})
|
||||
|
||||
|
||||
def has_control_chars(value: str) -> bool:
|
||||
"""Return whether *value* contains NUL or any Unicode control character."""
|
||||
|
||||
return any(ord(ch) < 0x20 or ord(ch) == 0x7F or 0x80 <= ord(ch) <= 0x9F or unicodedata.category(ch) == "Cc" for ch in value)
|
||||
|
||||
|
||||
def validate_api_key(api_key: Any) -> str:
|
||||
"""Validate an OpenViking USER API key without ever echoing its value."""
|
||||
|
||||
if not isinstance(api_key, str):
|
||||
raise ValueError(f"OpenViking API key must be a non-empty string, got {type(api_key).__name__}")
|
||||
if not api_key:
|
||||
raise ValueError("OpenViking API key must not be empty")
|
||||
if any(ord(ch) < 0x21 or ord(ch) > 0x7E for ch in api_key):
|
||||
raise ValueError("OpenViking API key must contain printable ASCII characters only (0x21..0x7E)")
|
||||
return api_key
|
||||
|
||||
|
||||
def validate_tenant_id(tenant_id: Any) -> str | None:
|
||||
"""Validate an optional DeerFlow tenant identifier."""
|
||||
|
||||
if tenant_id is None:
|
||||
return None
|
||||
if not isinstance(tenant_id, str):
|
||||
raise ValueError(f"OpenViking tenant_id must be a string, got {type(tenant_id).__name__}")
|
||||
if not tenant_id:
|
||||
raise ValueError("OpenViking tenant_id must not be empty")
|
||||
if tenant_id != tenant_id.strip():
|
||||
raise ValueError("OpenViking tenant_id must not have leading or trailing whitespace")
|
||||
if len(tenant_id) > _MAX_TENANT_ID_LENGTH:
|
||||
raise ValueError(f"OpenViking tenant_id must be at most {_MAX_TENANT_ID_LENGTH} characters")
|
||||
if has_control_chars(tenant_id):
|
||||
raise ValueError("OpenViking tenant_id must not contain control characters")
|
||||
return tenant_id
|
||||
|
||||
|
||||
def validate_user_key(user_id: Any) -> str:
|
||||
"""Validate a static ``user_credentials`` map key."""
|
||||
|
||||
if not isinstance(user_id, str):
|
||||
raise ValueError(f"OpenViking user_credentials keys must be strings, got {type(user_id).__name__}")
|
||||
if not user_id or user_id != user_id.strip() or has_control_chars(user_id):
|
||||
raise ValueError(f"OpenViking user_credentials key {user_id!r} must be a non-empty stripped string without control characters")
|
||||
return user_id
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OpenVikingCredential:
|
||||
"""Validated OpenViking USER API credential for one DeerFlow identity."""
|
||||
|
||||
api_key: str = field(repr=False)
|
||||
tenant_id: str | None = None
|
||||
api_key_env: str | None = None
|
||||
key_fingerprint: str = field(init=False, repr=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
validated_key = validate_api_key(self.api_key)
|
||||
validated_tenant = validate_tenant_id(self.tenant_id)
|
||||
object.__setattr__(self, "api_key", validated_key)
|
||||
object.__setattr__(self, "tenant_id", validated_tenant)
|
||||
if self.api_key_env is not None:
|
||||
if not isinstance(self.api_key_env, str) or not self.api_key_env.strip() or has_control_chars(self.api_key_env):
|
||||
raise ValueError("OpenViking api_key_env must be a non-empty string without control characters when provided")
|
||||
object.__setattr__(self, "api_key_env", self.api_key_env.strip())
|
||||
digest = hashlib.sha256(validated_key.encode("utf-8")).hexdigest()
|
||||
object.__setattr__(self, "key_fingerprint", digest)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class OpenVikingCredentialProvider(Protocol):
|
||||
"""Dynamic per-user credential resolver for multi-user OpenViking deployments."""
|
||||
|
||||
def resolve(self, user_id: str) -> OpenVikingCredential | Mapping[str, Any] | str | None:
|
||||
"""Resolve an OpenViking USER credential for *user_id*, or ``None`` if unauthorized."""
|
||||
...
|
||||
|
||||
|
||||
def _is_valid_identifier(part: str) -> bool:
|
||||
return bool(part) and part.isidentifier() and not keyword.iskeyword(part)
|
||||
|
||||
|
||||
def _parse_provider_path(path: str) -> tuple[str, list[str]]:
|
||||
if not isinstance(path, str) or not path or path != path.strip():
|
||||
raise ValueError("OpenViking credential_provider must be a non-empty 'module:attr' or 'module.attr' path")
|
||||
if ":" in path:
|
||||
if path.count(":") != 1:
|
||||
raise ValueError("OpenViking credential_provider must contain at most one ':' separator")
|
||||
module_path, attr_path = path.split(":", 1)
|
||||
module_parts = module_path.split(".")
|
||||
attr_parts = attr_path.split(".")
|
||||
if not module_parts or not attr_parts or not all(_is_valid_identifier(p) for p in (*module_parts, *attr_parts)):
|
||||
raise ValueError(f"Invalid OpenViking credential_provider path {path!r}: expected valid Python identifiers")
|
||||
return module_path, attr_parts
|
||||
|
||||
parts = path.split(".")
|
||||
if len(parts) < 2 or not all(_is_valid_identifier(p) for p in parts):
|
||||
raise ValueError(f"Invalid OpenViking credential_provider path {path!r}: expected 'pkg.mod:Attr' or 'pkg.mod.Attr'")
|
||||
return ".".join(parts[:-1]), [parts[-1]]
|
||||
|
||||
|
||||
def validate_provider_path(path: str) -> None:
|
||||
"""Validate ``credential_provider`` dotted/colon path syntax without importing or doing I/O."""
|
||||
|
||||
_parse_provider_path(path)
|
||||
|
||||
|
||||
def _is_usable_provider(provider: Any) -> bool:
|
||||
return callable(getattr(provider, "resolve", None)) or callable(provider)
|
||||
|
||||
|
||||
def load_credential_provider(path: str, config: Mapping[str, Any]) -> Any:
|
||||
"""Import and instantiate/validate a configured OpenViking credential provider."""
|
||||
|
||||
module_path, attr_parts = _parse_provider_path(path)
|
||||
if not isinstance(config, Mapping):
|
||||
raise ValueError("OpenViking credential_provider_config must be a mapping")
|
||||
kwargs = dict(config)
|
||||
|
||||
module = importlib.import_module(module_path)
|
||||
target: Any = module
|
||||
for attr in attr_parts:
|
||||
target = getattr(target, attr)
|
||||
|
||||
if isinstance(target, type):
|
||||
try:
|
||||
provider = target(**kwargs)
|
||||
except Exception as exc:
|
||||
raise ValueError(f"OpenViking credential_provider {path!r} initialization failed ({type(exc).__name__})") from None
|
||||
if not _is_usable_provider(provider):
|
||||
raise ValueError(f"OpenViking credential_provider {path!r} instance must define a callable 'resolve(user_id)' method or be callable")
|
||||
return provider
|
||||
|
||||
if callable(target):
|
||||
if kwargs:
|
||||
try:
|
||||
provider = target(**kwargs)
|
||||
except Exception as exc:
|
||||
raise ValueError(f"OpenViking credential_provider {path!r} initialization failed ({type(exc).__name__})") from None
|
||||
if not _is_usable_provider(provider):
|
||||
raise ValueError(f"OpenViking credential_provider factory {path!r} must return a callable or an object with a callable 'resolve(user_id)' method")
|
||||
return provider
|
||||
return target
|
||||
|
||||
raise ValueError(f"OpenViking credential_provider {path!r} must resolve to a class or callable, got {type(target).__name__}")
|
||||
|
||||
|
||||
def normalize_resolved_credential(raw: Any, *, user_id: str) -> OpenVikingCredential | None:
|
||||
"""Normalize a provider return value into ``OpenVikingCredential`` without echoing secrets."""
|
||||
|
||||
if raw is None:
|
||||
return None
|
||||
if isinstance(raw, OpenVikingCredential):
|
||||
return raw
|
||||
if isinstance(raw, str):
|
||||
return OpenVikingCredential(api_key=raw)
|
||||
if isinstance(raw, Mapping):
|
||||
if not all(isinstance(k, str) for k in raw):
|
||||
raise ValueError(f"OpenViking credential provider returned non-string keys for user {user_id!r}")
|
||||
unknown = sorted(k for k in raw if k not in _ALLOWED_PROVIDER_RESULT_KEYS)
|
||||
if unknown:
|
||||
raise ValueError(f"OpenViking credential provider returned unsupported keys for user {user_id!r}: {', '.join(unknown)}")
|
||||
if "api_key" not in raw:
|
||||
raise ValueError(f"OpenViking credential provider response for user {user_id!r} is missing 'api_key'")
|
||||
api_key = raw["api_key"]
|
||||
if not isinstance(api_key, str) or not api_key:
|
||||
raise ValueError(f"OpenViking credential provider returned invalid 'api_key' for user {user_id!r}")
|
||||
tenant_id = raw.get("tenant_id")
|
||||
if tenant_id is not None and not isinstance(tenant_id, str):
|
||||
raise ValueError(f"OpenViking credential provider returned invalid 'tenant_id' for user {user_id!r}")
|
||||
return OpenVikingCredential(api_key=api_key, tenant_id=tenant_id)
|
||||
raise ValueError(f"OpenViking credential provider returned unsupported credential type {type(raw).__name__} for user {user_id!r}")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"OpenVikingCredential",
|
||||
"OpenVikingCredentialProvider",
|
||||
"has_control_chars",
|
||||
"load_credential_provider",
|
||||
"normalize_resolved_credential",
|
||||
"validate_api_key",
|
||||
"validate_provider_path",
|
||||
"validate_tenant_id",
|
||||
"validate_user_key",
|
||||
]
|
||||
@ -10,15 +10,25 @@ import os
|
||||
import threading
|
||||
import time
|
||||
import weakref
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Callable, Mapping
|
||||
from contextlib import AbstractContextManager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, ClassVar, Literal
|
||||
|
||||
import httpx
|
||||
from pydantic import PrivateAttr
|
||||
|
||||
from deerflow.agents.memory.manager import MemoryManager, MemoryManagerError, MemoryReadError
|
||||
|
||||
from .config import OpenVikingConfig
|
||||
from .credentials import (
|
||||
OpenVikingCredential,
|
||||
load_credential_provider,
|
||||
normalize_resolved_credential,
|
||||
validate_user_key,
|
||||
)
|
||||
from .session import (
|
||||
_advanced_cursor,
|
||||
_canonical_peer_id,
|
||||
@ -32,9 +42,25 @@ from .session import (
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_ClientPoolKey = tuple[str | None, str, str] # (tenant_id, user_id, key_fingerprint)
|
||||
|
||||
|
||||
@dataclass(slots=True, eq=False)
|
||||
class _ScopedClientEntry:
|
||||
"""Pooled OpenViking SDK handles bound to one resolved credential scope."""
|
||||
|
||||
key: _ClientPoolKey
|
||||
recorder: Any
|
||||
retriever: Any
|
||||
client: Any
|
||||
active_ops: int = 0
|
||||
last_used: float = 0.0
|
||||
retired: bool = False
|
||||
closed: bool = False
|
||||
|
||||
|
||||
class OpenVikingMemoryManager(MemoryManager):
|
||||
"""Single-user OpenViking backend using the official integration package.
|
||||
"""OpenViking memory backend supporting single-user and multi-user isolation.
|
||||
|
||||
DeerFlow continues to choose when capture and recall occur. The official
|
||||
adapter owns SDK transport, message conversion, batching, commit retries,
|
||||
@ -44,10 +70,18 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
supports_search: ClassVar[bool] = True
|
||||
|
||||
_config: OpenVikingConfig = PrivateAttr()
|
||||
_client: Any = PrivateAttr()
|
||||
_recorder: Any = PrivateAttr()
|
||||
_retriever: Any = PrivateAttr()
|
||||
_integration: dict[str, Any] = PrivateAttr()
|
||||
_credential_provider: Any = PrivateAttr(default=None)
|
||||
_single_user_credential: OpenVikingCredential | None = PrivateAttr(default=None)
|
||||
_pool: OrderedDict[_ClientPoolKey, _ScopedClientEntry] = PrivateAttr(default_factory=OrderedDict)
|
||||
_pool_lock: threading.Lock = PrivateAttr(default_factory=threading.Lock)
|
||||
_inflight_entries: set[_ScopedClientEntry] = PrivateAttr(default_factory=set)
|
||||
_clock: Callable[[], float] = PrivateAttr(default=time.monotonic)
|
||||
_client: Any = PrivateAttr(default=None)
|
||||
_recorder: Any = PrivateAttr(default=None)
|
||||
_retriever: Any = PrivateAttr(default=None)
|
||||
_use_actor_peer: Any = PrivateAttr()
|
||||
_use_home_alias_uris: bool = PrivateAttr(default=False)
|
||||
_partial_write_error: type[Exception] = PrivateAttr()
|
||||
_should_keep_hidden_message: Any = PrivateAttr(default=None)
|
||||
_session_locks: weakref.WeakValueDictionary[str, threading.RLock] = PrivateAttr(default_factory=weakref.WeakValueDictionary)
|
||||
@ -57,34 +91,69 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
_closed: bool = PrivateAttr(default=False)
|
||||
_close_requested: bool = PrivateAttr(default=False)
|
||||
_resources_closed: bool = PrivateAttr(default=False)
|
||||
_cleanup_started: bool = PrivateAttr(default=False)
|
||||
_cleanup_done: threading.Event = PrivateAttr(default_factory=threading.Event)
|
||||
_cleanup_failed: bool = PrivateAttr(default=False)
|
||||
_flush_timed_out: bool = PrivateAttr(default=False)
|
||||
_resource_lock: threading.Lock = PrivateAttr(default_factory=threading.Lock)
|
||||
|
||||
def model_post_init(self, __context: Any) -> None:
|
||||
self._config = OpenVikingConfig.from_backend_config(self.backend_config)
|
||||
integration = _load_official_integration()
|
||||
commit_policy = integration["OpenVikingCommitPolicy"](mode="always")
|
||||
self._recorder = integration["OpenVikingSessionRecorder"](
|
||||
url=self._config.base_url,
|
||||
api_key=self._config.api_key,
|
||||
timeout=self._config.timeout_seconds,
|
||||
# An explicit mapping disables the SDK's ovcli.conf header fallback.
|
||||
extra_headers={},
|
||||
commit_policy=commit_policy,
|
||||
if self.mode != "middleware":
|
||||
raise ValueError("The OpenViking automatic-memory backend supports memory.mode='middleware' only; use OpenViking MCP for explicit model tools")
|
||||
|
||||
injected_provider = __context.get("credential_provider") if isinstance(__context, Mapping) else None
|
||||
if injected_provider is not None and (isinstance(injected_provider, type) or not (callable(getattr(injected_provider, "resolve", None)) or callable(injected_provider))):
|
||||
raise ValueError("OpenViking injected credential_provider must expose a callable 'resolve(user_id)' method or be callable")
|
||||
|
||||
self._config = OpenVikingConfig.from_backend_config(
|
||||
self.backend_config,
|
||||
has_injected_credential_provider=injected_provider is not None,
|
||||
)
|
||||
# The recorder owns one recovery-aware SDK client. Retrieval borrows the
|
||||
# same handle, so this backend has one connection pool and one owner.
|
||||
self._client = self._recorder.client
|
||||
self._retriever = integration["OpenVikingRetriever"](
|
||||
client=self._client,
|
||||
search_mode="find",
|
||||
limit=self._config.search_top_k,
|
||||
score_threshold=self._config.score_threshold,
|
||||
context_types=("memory",),
|
||||
content_mode=self._config.content_mode,
|
||||
max_content_chars=self._config.max_injection_chars,
|
||||
)
|
||||
self._use_actor_peer = integration["use_actor_peer"]
|
||||
self._partial_write_error = integration["OpenVikingPartialWriteError"]
|
||||
if injected_provider is not None and self._config.credential_provider is not None:
|
||||
raise ValueError("OpenViking cannot configure both backend_config.credential_provider and an injected credential_provider")
|
||||
|
||||
loaded_provider = False
|
||||
if injected_provider is not None:
|
||||
self._credential_provider = injected_provider
|
||||
elif self._config.credential_provider is not None:
|
||||
self._credential_provider = load_credential_provider(
|
||||
self._config.credential_provider,
|
||||
self._config.credential_provider_config,
|
||||
)
|
||||
loaded_provider = True
|
||||
|
||||
try:
|
||||
self._integration = _load_official_integration()
|
||||
self._use_actor_peer = self._integration["use_actor_peer"]
|
||||
self._partial_write_error = self._integration["OpenVikingPartialWriteError"]
|
||||
|
||||
if self._config.isolation_mode == "single_user":
|
||||
assert self._config.owner_user_id is not None
|
||||
credential = OpenVikingCredential(
|
||||
api_key=self._config.api_key,
|
||||
tenant_id=None,
|
||||
api_key_env=self._config.api_key_env,
|
||||
)
|
||||
self._single_user_credential = credential
|
||||
key: _ClientPoolKey = (None, self._config.owner_user_id, credential.key_fingerprint)
|
||||
try:
|
||||
entry = self._build_scoped_entry(
|
||||
key=key,
|
||||
api_key=credential.api_key,
|
||||
now=self._clock(),
|
||||
)
|
||||
except (MemoryManagerError, ValueError):
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise MemoryManagerError(f"Failed to initialize OpenViking client ({type(exc).__name__})") from None
|
||||
self._pool[key] = entry
|
||||
self._recorder = entry.recorder
|
||||
self._client = entry.client
|
||||
self._retriever = entry.retriever
|
||||
except BaseException:
|
||||
if loaded_provider:
|
||||
self._close_credential_provider()
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def from_config(
|
||||
@ -96,7 +165,11 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
) -> OpenVikingMemoryManager:
|
||||
if mode != "middleware":
|
||||
raise ValueError("The OpenViking automatic-memory backend supports memory.mode='middleware' only; use OpenViking MCP for explicit model tools")
|
||||
instance = cls(backend_config=backend_config or {}, mode=mode)
|
||||
injected_provider = host_hooks.get("credential_provider")
|
||||
instance = cls.model_validate(
|
||||
{"backend_config": backend_config or {}, "mode": mode},
|
||||
context={"credential_provider": injected_provider},
|
||||
)
|
||||
hidden_filter = host_hooks.get("should_keep_hidden_message")
|
||||
instance._should_keep_hidden_message = hidden_filter if callable(hidden_filter) else None
|
||||
return instance
|
||||
@ -125,6 +198,18 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
) -> bool:
|
||||
return OpenVikingConfig.from_backend_config(backend_config).read_failure_policy == "raise"
|
||||
|
||||
@property
|
||||
def read_failures_are_fatal(self) -> bool:
|
||||
"""Whether read failures or timeouts abort for this manager instance.
|
||||
|
||||
``DynamicContextMiddleware`` consults the classmethod
|
||||
:meth:`read_failures_are_fatal_for_config` over ``backend_config`` (which
|
||||
requires ``user_credentials`` or ``credential_provider``), whereas this
|
||||
instance property also covers direct programmatic callers injecting
|
||||
``host_hooks["credential_provider"]``.
|
||||
"""
|
||||
return self._config.read_failure_policy == "raise"
|
||||
|
||||
def add_nowait(
|
||||
self,
|
||||
thread_id: str,
|
||||
@ -168,22 +253,33 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
thread_id: str | None = None,
|
||||
query: str | None = None,
|
||||
) -> str:
|
||||
del query
|
||||
if not self._begin_operation():
|
||||
return ""
|
||||
entry: _ScopedClientEntry | None = None
|
||||
try:
|
||||
peer_id = self._resolve_read_scope(user_id, agent_name)
|
||||
retriever = copy.copy(self._retriever)
|
||||
retriever.target_uri = _memory_target_uris(peer_id)
|
||||
resolved_user, credential, peer_id = self._resolve_read_scope(user_id, agent_name)
|
||||
try:
|
||||
entry = self._acquire_client(resolved_user, credential)
|
||||
except MemoryManagerError as exc:
|
||||
if self._config.read_failure_policy == "raise":
|
||||
raise MemoryReadError(str(exc)) from exc
|
||||
raise
|
||||
retriever = copy.copy(entry.retriever)
|
||||
if thread_id:
|
||||
retriever.search_mode = "search"
|
||||
retriever.session_id = _session_id(
|
||||
self._config.owner_user_id,
|
||||
resolved_user,
|
||||
peer_id,
|
||||
thread_id,
|
||||
tenant_id=credential.tenant_id,
|
||||
)
|
||||
try:
|
||||
with self._actor_peer_scope(peer_id):
|
||||
documents = retriever.invoke(self._config.injection_query)
|
||||
documents = self._invoke_retriever(
|
||||
retriever,
|
||||
self._config.injection_query,
|
||||
peer_id=peer_id,
|
||||
)
|
||||
except Exception as exc:
|
||||
if self._config.read_failure_policy == "raise":
|
||||
raise MemoryReadError("OpenViking context retrieval failed") from exc
|
||||
@ -197,6 +293,8 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
max_chars=self._config.max_injection_chars,
|
||||
)
|
||||
finally:
|
||||
if entry is not None:
|
||||
self._release_client(entry)
|
||||
self._end_operation()
|
||||
|
||||
async def aget_context(
|
||||
@ -226,10 +324,16 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
) -> list[dict[str, Any]]:
|
||||
if not query.strip() or not self._begin_operation():
|
||||
return []
|
||||
entry: _ScopedClientEntry | None = None
|
||||
try:
|
||||
peer_id = self._resolve_read_scope(user_id, agent_name)
|
||||
retriever = copy.copy(self._retriever)
|
||||
retriever.target_uri = _memory_target_uris(peer_id)
|
||||
resolved_user, credential, peer_id = self._resolve_read_scope(user_id, agent_name)
|
||||
try:
|
||||
entry = self._acquire_client(resolved_user, credential)
|
||||
except MemoryManagerError as exc:
|
||||
if self._config.read_failure_policy == "raise":
|
||||
raise MemoryReadError(str(exc)) from exc
|
||||
raise
|
||||
retriever = copy.copy(entry.retriever)
|
||||
retriever.search_mode = "find"
|
||||
retriever.session_id = None
|
||||
retriever.limit = max(1, min(int(top_k), 100))
|
||||
@ -240,8 +344,11 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
"conds": [category],
|
||||
}
|
||||
try:
|
||||
with self._actor_peer_scope(peer_id):
|
||||
documents = retriever.invoke(query.strip())
|
||||
documents = self._invoke_retriever(
|
||||
retriever,
|
||||
query.strip(),
|
||||
peer_id=peer_id,
|
||||
)
|
||||
except Exception as exc:
|
||||
if self._config.read_failure_policy == "raise":
|
||||
raise MemoryReadError("OpenViking memory search failed") from exc
|
||||
@ -252,6 +359,8 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
return []
|
||||
return [_document_to_fact(document) for document in documents]
|
||||
finally:
|
||||
if entry is not None:
|
||||
self._release_client(entry)
|
||||
self._end_operation()
|
||||
|
||||
async def asearch(
|
||||
@ -277,11 +386,16 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
return False
|
||||
try:
|
||||
try:
|
||||
health = getattr(self._client, "health", None)
|
||||
healthy = bool(health()) if callable(health) else True
|
||||
except Exception:
|
||||
if self._config.isolation_mode == "single_user":
|
||||
health = getattr(self._client, "health", None)
|
||||
healthy = bool(health()) if callable(health) else True
|
||||
else:
|
||||
healthy = self._probe_health_unauthenticated()
|
||||
except Exception as exc:
|
||||
if self._config.startup_policy == "fail_fast":
|
||||
raise
|
||||
if isinstance(exc, MemoryManagerError):
|
||||
raise
|
||||
raise MemoryManagerError("OpenViking startup validation failed") from exc
|
||||
logger.warning(
|
||||
"OpenViking startup validation failed; memory will run in degraded mode",
|
||||
exc_info=True,
|
||||
@ -295,6 +409,18 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
finally:
|
||||
self._end_operation()
|
||||
|
||||
def _probe_health_unauthenticated(self) -> bool:
|
||||
url = f"{self._config.base_url}/health"
|
||||
with httpx.Client(timeout=self._config.timeout_seconds) as client:
|
||||
response = client.get(url)
|
||||
if response.status_code != 200:
|
||||
return False
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
return False
|
||||
return isinstance(payload, dict) and payload.get("status") == "ok"
|
||||
|
||||
def shutdown_flush(self, timeout: float) -> bool:
|
||||
"""Stop new work, drain accepted calls, and close owned resources."""
|
||||
|
||||
@ -305,10 +431,18 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
while self._active_operations:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
self._flush_timed_out = True
|
||||
return False
|
||||
self._lifecycle.wait(remaining)
|
||||
self._close_resources()
|
||||
return True
|
||||
done = self._start_resource_cleanup()
|
||||
if done.is_set():
|
||||
return not self._cleanup_failed
|
||||
finished = done.wait(timeout=max(0.0, deadline - time.monotonic()))
|
||||
if not finished:
|
||||
with self._lifecycle:
|
||||
self._flush_timed_out = True
|
||||
return False
|
||||
return not self._cleanup_failed
|
||||
|
||||
def close(self) -> None:
|
||||
"""Request idempotent closure after any active operation finishes."""
|
||||
@ -317,8 +451,12 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
self._closed = True
|
||||
self._close_requested = True
|
||||
can_close = self._active_operations == 0
|
||||
if can_close:
|
||||
self._close_resources()
|
||||
already_timed_out = self._flush_timed_out
|
||||
if not can_close:
|
||||
return
|
||||
done = self._start_resource_cleanup()
|
||||
if not done.is_set() and not already_timed_out:
|
||||
done.wait(timeout=self._config.timeout_seconds)
|
||||
|
||||
def _write_conversation(
|
||||
self,
|
||||
@ -331,26 +469,30 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
if not self._begin_operation():
|
||||
logger.warning("OpenViking write ignored after backend shutdown")
|
||||
return
|
||||
entry: _ScopedClientEntry | None = None
|
||||
try:
|
||||
if not thread_id:
|
||||
raise ValueError("OpenViking memory write requires thread_id")
|
||||
try:
|
||||
peer_id = self._resolve_scope(user_id, agent_name)
|
||||
resolved_user, credential, peer_id = self._resolve_scope(user_id, agent_name)
|
||||
entry = self._acquire_client(resolved_user, credential)
|
||||
except MemoryManagerError as exc:
|
||||
# The owner check has already refused the write before any
|
||||
# remote call; the write policy decides whether that refusal
|
||||
# Scope/credential checks have already refused the write before
|
||||
# any remote call; the write policy decides whether that refusal
|
||||
# also fails a turn whose answer was already generated.
|
||||
if self._config.write_failure_policy == "raise":
|
||||
raise
|
||||
logger.error("%s Dropping the memory write (thread=%s).", exc, thread_id)
|
||||
return
|
||||
session_id = _session_id(
|
||||
self._config.owner_user_id,
|
||||
resolved_user,
|
||||
peer_id,
|
||||
thread_id,
|
||||
tenant_id=credential.tenant_id,
|
||||
)
|
||||
with self._session_lock(session_id):
|
||||
self._capture_locked(
|
||||
entry.recorder,
|
||||
session_id,
|
||||
peer_id,
|
||||
_captureable_messages(
|
||||
@ -359,10 +501,13 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
),
|
||||
)
|
||||
finally:
|
||||
if entry is not None:
|
||||
self._release_client(entry)
|
||||
self._end_operation()
|
||||
|
||||
def _capture_locked(
|
||||
self,
|
||||
recorder: Any,
|
||||
session_id: str,
|
||||
peer_id: str,
|
||||
messages: list[Any],
|
||||
@ -373,7 +518,7 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
if state.get("commit_pending"):
|
||||
try:
|
||||
with self._actor_peer_scope(peer_id):
|
||||
self._recorder.flush(session_id)
|
||||
recorder.flush(session_id)
|
||||
except Exception as exc:
|
||||
self._handle_write_error(
|
||||
exc,
|
||||
@ -382,7 +527,8 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
)
|
||||
return
|
||||
state = {**state, "commit_pending": False}
|
||||
self._save_cursor(session_id, state)
|
||||
if not self._save_cursor_with_policy(session_id, state):
|
||||
return
|
||||
|
||||
start = _matching_prefix_count(state, signatures)
|
||||
append_only = start is not None
|
||||
@ -396,7 +542,7 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
pending_signatures = [signature for _, signature in pending_pairs]
|
||||
|
||||
if not pending:
|
||||
self._save_cursor(
|
||||
self._save_cursor_with_policy(
|
||||
session_id,
|
||||
_advanced_cursor(
|
||||
state,
|
||||
@ -410,7 +556,7 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
|
||||
try:
|
||||
with self._actor_peer_scope(peer_id):
|
||||
self._recorder.record(
|
||||
recorder.record(
|
||||
session_id,
|
||||
pending,
|
||||
peer_id=peer_id,
|
||||
@ -427,16 +573,23 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
commit_pending = bool(getattr(exc, "commit_pending", False))
|
||||
if confirmed or commit_pending:
|
||||
confirmed_prefix = signatures[: int(start or 0) + consumed] if append_only else None
|
||||
self._save_cursor(
|
||||
session_id,
|
||||
_advanced_cursor(
|
||||
state,
|
||||
confirmed_prefix,
|
||||
confirmed,
|
||||
max_seen=self._config.max_seen_message_ids,
|
||||
commit_pending=commit_pending,
|
||||
),
|
||||
)
|
||||
try:
|
||||
self._save_cursor(
|
||||
session_id,
|
||||
_advanced_cursor(
|
||||
state,
|
||||
confirmed_prefix,
|
||||
confirmed,
|
||||
max_seen=self._config.max_seen_message_ids,
|
||||
commit_pending=commit_pending,
|
||||
),
|
||||
)
|
||||
except OSError as cursor_exc:
|
||||
logger.warning(
|
||||
"Failed to persist partial OpenViking capture cursor (session=%s, error=%s)",
|
||||
session_id,
|
||||
type(cursor_exc).__name__,
|
||||
)
|
||||
self._handle_write_error(
|
||||
exc,
|
||||
"OpenViking partially recorded a conversation; confirmed progress was preserved",
|
||||
@ -451,7 +604,7 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
)
|
||||
return
|
||||
|
||||
self._save_cursor(
|
||||
self._save_cursor_with_policy(
|
||||
session_id,
|
||||
_advanced_cursor(
|
||||
state,
|
||||
@ -466,17 +619,58 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
self,
|
||||
user_id: str | None,
|
||||
agent_name: str | None,
|
||||
) -> str:
|
||||
resolved_user = str(user_id or "default")
|
||||
if resolved_user != self._config.owner_user_id:
|
||||
raise MemoryManagerError(f"OpenViking USER API key is bound to DeerFlow owner_user_id {self._config.owner_user_id!r}, but this request belongs to {resolved_user!r}. Refusing to share one credential across users.")
|
||||
return _canonical_peer_id(agent_name, self._config.default_peer_id)
|
||||
) -> tuple[str, OpenVikingCredential, str]:
|
||||
if self._config.isolation_mode == "single_user":
|
||||
resolved_user = str(user_id or "default")
|
||||
if resolved_user != self._config.owner_user_id:
|
||||
raise MemoryManagerError(f"OpenViking USER API key is bound to DeerFlow owner_user_id {self._config.owner_user_id!r}, but this request belongs to {resolved_user!r}. Refusing to share one credential across users.")
|
||||
assert self._single_user_credential is not None
|
||||
try:
|
||||
peer_id = _canonical_peer_id(agent_name, self._config.default_peer_id)
|
||||
except ValueError as exc:
|
||||
raise MemoryManagerError(str(exc)) from exc
|
||||
return resolved_user, self._single_user_credential, peer_id
|
||||
|
||||
if user_id is None:
|
||||
raise MemoryManagerError("OpenViking multi-user mode requires a non-empty DeerFlow user_id; refusing anonymous fallback.")
|
||||
resolved_user = str(user_id)
|
||||
if not resolved_user or not resolved_user.strip():
|
||||
raise MemoryManagerError("OpenViking multi-user mode requires a non-empty DeerFlow user_id; refusing blank fallback.")
|
||||
try:
|
||||
resolved_user = validate_user_key(resolved_user)
|
||||
except ValueError as exc:
|
||||
raise MemoryManagerError(f"OpenViking multi-user mode requires a stripped DeerFlow user_id without control characters, got {resolved_user!r}") from exc
|
||||
|
||||
credential = self._config.user_credentials.get(resolved_user)
|
||||
if credential is None and self._credential_provider is not None:
|
||||
try:
|
||||
resolve_fn = getattr(self._credential_provider, "resolve", None)
|
||||
if callable(resolve_fn):
|
||||
raw = resolve_fn(resolved_user)
|
||||
else:
|
||||
raw = self._credential_provider(resolved_user)
|
||||
except Exception as exc:
|
||||
raise MemoryManagerError(f"OpenViking credential provider failed for DeerFlow user {resolved_user!r} ({type(exc).__name__})") from None
|
||||
try:
|
||||
credential = normalize_resolved_credential(raw, user_id=resolved_user)
|
||||
except ValueError as exc:
|
||||
raise MemoryManagerError(str(exc)) from exc
|
||||
|
||||
if credential is None:
|
||||
self._retire_user_entries(resolved_user)
|
||||
raise MemoryManagerError(f"No OpenViking USER API key is configured for DeerFlow user {resolved_user!r}. Refusing to share or fall back to another credential.")
|
||||
|
||||
try:
|
||||
peer_id = _canonical_peer_id(agent_name, self._config.default_peer_id)
|
||||
except ValueError as exc:
|
||||
raise MemoryManagerError(str(exc)) from exc
|
||||
return resolved_user, credential, peer_id
|
||||
|
||||
def _resolve_read_scope(
|
||||
self,
|
||||
user_id: str | None,
|
||||
agent_name: str | None,
|
||||
) -> str:
|
||||
) -> tuple[str, OpenVikingCredential, str]:
|
||||
try:
|
||||
return self._resolve_scope(user_id, agent_name)
|
||||
except MemoryManagerError as exc:
|
||||
@ -484,6 +678,267 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
raise MemoryReadError(str(exc)) from exc
|
||||
raise
|
||||
|
||||
def _build_scoped_entry(
|
||||
self,
|
||||
*,
|
||||
key: _ClientPoolKey,
|
||||
api_key: str,
|
||||
now: float,
|
||||
) -> _ScopedClientEntry:
|
||||
if not api_key:
|
||||
raise MemoryManagerError("Refusing to construct OpenViking client with an empty API key")
|
||||
commit_policy = self._integration["OpenVikingCommitPolicy"](mode="always")
|
||||
recorder = self._integration["OpenVikingSessionRecorder"](
|
||||
url=self._config.base_url,
|
||||
api_key=api_key,
|
||||
timeout=self._config.timeout_seconds,
|
||||
# An explicit mapping disables the SDK's ovcli.conf header fallback.
|
||||
extra_headers={},
|
||||
commit_policy=commit_policy,
|
||||
)
|
||||
try:
|
||||
# The recorder owns one recovery-aware SDK client. Retrieval borrows the
|
||||
# same handle, so each scope has one connection pool and one owner.
|
||||
client = recorder.client
|
||||
retriever = self._integration["OpenVikingRetriever"](
|
||||
client=client,
|
||||
search_mode="find",
|
||||
limit=self._config.search_top_k,
|
||||
score_threshold=self._config.score_threshold,
|
||||
context_types=("memory",),
|
||||
content_mode=self._config.content_mode,
|
||||
max_content_chars=self._config.max_injection_chars,
|
||||
)
|
||||
except BaseException:
|
||||
try:
|
||||
recorder.close()
|
||||
except Exception as close_exc:
|
||||
logger.debug("Failed to close OpenViking recorder after setup error (%s)", type(close_exc).__name__)
|
||||
raise
|
||||
return _ScopedClientEntry(
|
||||
key=key,
|
||||
recorder=recorder,
|
||||
retriever=retriever,
|
||||
client=client,
|
||||
last_used=now,
|
||||
)
|
||||
|
||||
def _acquire_client(
|
||||
self,
|
||||
user_id: str,
|
||||
credential: OpenVikingCredential,
|
||||
) -> _ScopedClientEntry:
|
||||
key: _ClientPoolKey = (credential.tenant_id, user_id, credential.key_fingerprint)
|
||||
if self._config.isolation_mode == "single_user":
|
||||
with self._pool_lock:
|
||||
if self._resources_closed:
|
||||
raise MemoryManagerError("OpenViking memory backend is closed")
|
||||
entry = self._pool.get(key)
|
||||
if entry is None or entry.retired or entry.closed:
|
||||
raise MemoryManagerError("OpenViking client handle is unavailable")
|
||||
entry.active_ops += 1
|
||||
entry.last_used = self._clock()
|
||||
self._pool.move_to_end(key)
|
||||
self._inflight_entries.add(entry)
|
||||
return entry
|
||||
|
||||
to_close: list[_ScopedClientEntry] = []
|
||||
error: MemoryManagerError | None = None
|
||||
acquired: _ScopedClientEntry | None = None
|
||||
now = self._clock()
|
||||
|
||||
with self._pool_lock:
|
||||
if self._resources_closed:
|
||||
raise MemoryManagerError("OpenViking memory backend is closed")
|
||||
to_close.extend(self._evict_idle_ttl_locked(now))
|
||||
error = self._check_fingerprint_conflict_locked(user_id=user_id, credential=credential)
|
||||
if error is None:
|
||||
existing = self._pool.get(key)
|
||||
if existing is not None and not existing.retired and not existing.closed:
|
||||
existing.active_ops += 1
|
||||
existing.last_used = now
|
||||
self._pool.move_to_end(key)
|
||||
self._inflight_entries.add(existing)
|
||||
acquired = existing
|
||||
|
||||
self._close_entries(to_close)
|
||||
if error is not None:
|
||||
raise error
|
||||
if acquired is not None:
|
||||
return acquired
|
||||
|
||||
# Build the SDK handles outside _pool_lock so concurrent users never stall on init/I/O.
|
||||
try:
|
||||
new_entry = self._build_scoped_entry(
|
||||
key=key,
|
||||
api_key=credential.api_key,
|
||||
now=now,
|
||||
)
|
||||
except MemoryManagerError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise MemoryManagerError(f"Failed to initialize OpenViking client for DeerFlow user {user_id!r} ({type(exc).__name__})") from None
|
||||
|
||||
to_close = []
|
||||
discard_new = False
|
||||
publish_error: MemoryManagerError | None = None
|
||||
winner: _ScopedClientEntry | None = None
|
||||
now = self._clock()
|
||||
|
||||
with self._pool_lock:
|
||||
if self._resources_closed:
|
||||
discard_new = True
|
||||
publish_error = MemoryManagerError("OpenViking memory backend is closed")
|
||||
else:
|
||||
to_close.extend(self._evict_idle_ttl_locked(now))
|
||||
publish_error = self._check_fingerprint_conflict_locked(user_id=user_id, credential=credential)
|
||||
if publish_error is not None:
|
||||
discard_new = True
|
||||
else:
|
||||
existing = self._pool.get(key)
|
||||
if existing is not None and not existing.retired and not existing.closed:
|
||||
existing.active_ops += 1
|
||||
existing.last_used = now
|
||||
self._pool.move_to_end(key)
|
||||
self._inflight_entries.add(existing)
|
||||
winner = existing
|
||||
discard_new = True
|
||||
else:
|
||||
to_close.extend(self._retire_scope_rotations_locked(key))
|
||||
to_close.extend(self._evict_lru_locked())
|
||||
new_entry.active_ops = 1
|
||||
new_entry.last_used = now
|
||||
self._pool[key] = new_entry
|
||||
self._inflight_entries.add(new_entry)
|
||||
winner = new_entry
|
||||
|
||||
if discard_new:
|
||||
to_close.append(new_entry)
|
||||
self._close_entries(to_close)
|
||||
if publish_error is not None:
|
||||
raise publish_error
|
||||
assert winner is not None
|
||||
return winner
|
||||
|
||||
def _release_client(self, entry: _ScopedClientEntry) -> None:
|
||||
should_close = False
|
||||
with self._pool_lock:
|
||||
if entry.active_ops > 0:
|
||||
entry.active_ops -= 1
|
||||
if self._config.isolation_mode == "multi_user":
|
||||
entry.last_used = self._clock()
|
||||
if entry.active_ops == 0:
|
||||
self._inflight_entries.discard(entry)
|
||||
if entry.retired and not entry.closed:
|
||||
entry.closed = True
|
||||
should_close = True
|
||||
if should_close:
|
||||
self._close_entries([entry])
|
||||
|
||||
def _evict_idle_ttl_locked(self, now: float) -> list[_ScopedClientEntry]:
|
||||
ttl = self._config.pool_idle_ttl_seconds
|
||||
if ttl is None:
|
||||
return []
|
||||
evicted: list[_ScopedClientEntry] = []
|
||||
for entry_key in list(self._pool):
|
||||
entry = self._pool[entry_key]
|
||||
if entry.active_ops == 0 and (now - entry.last_used) >= ttl:
|
||||
del self._pool[entry_key]
|
||||
entry.retired = True
|
||||
if not entry.closed:
|
||||
entry.closed = True
|
||||
evicted.append(entry)
|
||||
return evicted
|
||||
|
||||
def _check_fingerprint_conflict_locked(
|
||||
self,
|
||||
*,
|
||||
user_id: str,
|
||||
credential: OpenVikingCredential,
|
||||
) -> MemoryManagerError | None:
|
||||
target_scope = (credential.tenant_id, user_id)
|
||||
# In hybrid mode, also reject reuse of uncached or LRU/TTL-evicted static credentials.
|
||||
for static_user, static_cred in self._config.user_credentials.items():
|
||||
static_scope = (static_cred.tenant_id, static_user)
|
||||
if static_cred.key_fingerprint == credential.key_fingerprint and static_scope != target_scope:
|
||||
return MemoryManagerError(f"OpenViking USER API key cannot be shared across distinct DeerFlow scopes ({static_scope!r} and {target_scope!r})")
|
||||
for entry in (*self._pool.values(), *self._inflight_entries):
|
||||
if entry.key[2] == credential.key_fingerprint and (entry.key[0], entry.key[1]) != target_scope:
|
||||
other_scope = (entry.key[0], entry.key[1])
|
||||
return MemoryManagerError(f"OpenViking USER API key cannot be shared across distinct DeerFlow scopes ({other_scope!r} and {target_scope!r})")
|
||||
return None
|
||||
|
||||
def _retire_scope_rotations_locked(
|
||||
self,
|
||||
new_key: _ClientPoolKey,
|
||||
) -> list[_ScopedClientEntry]:
|
||||
user_id = new_key[1]
|
||||
retired: list[_ScopedClientEntry] = []
|
||||
for entry_key in list(self._pool):
|
||||
if entry_key[1] == user_id and entry_key != new_key:
|
||||
entry = self._pool.pop(entry_key)
|
||||
entry.retired = True
|
||||
if entry.active_ops == 0 and not entry.closed:
|
||||
entry.closed = True
|
||||
retired.append(entry)
|
||||
for entry in self._inflight_entries:
|
||||
if entry.key[1] == user_id and entry.key != new_key:
|
||||
entry.retired = True
|
||||
return retired
|
||||
|
||||
def _evict_lru_locked(self) -> list[_ScopedClientEntry]:
|
||||
evicted: list[_ScopedClientEntry] = []
|
||||
while len(self._pool) >= self._config.pool_max_clients:
|
||||
victim_key = next(
|
||||
(k for k, entry in self._pool.items() if entry.active_ops == 0),
|
||||
None,
|
||||
)
|
||||
if victim_key is None:
|
||||
victim_key, victim = self._pool.popitem(last=False)
|
||||
else:
|
||||
victim = self._pool.pop(victim_key)
|
||||
victim.retired = True
|
||||
if victim.active_ops == 0 and not victim.closed:
|
||||
victim.closed = True
|
||||
evicted.append(victim)
|
||||
return evicted
|
||||
|
||||
def _retire_user_entries(self, user_id: str) -> None:
|
||||
to_close: list[_ScopedClientEntry] = []
|
||||
with self._pool_lock:
|
||||
for entry_key in [k for k in self._pool if k[1] == user_id]:
|
||||
entry = self._pool.pop(entry_key)
|
||||
entry.retired = True
|
||||
if entry.active_ops == 0 and not entry.closed:
|
||||
entry.closed = True
|
||||
to_close.append(entry)
|
||||
for entry in self._inflight_entries:
|
||||
if entry.key[1] == user_id:
|
||||
entry.retired = True
|
||||
self._close_entries(to_close)
|
||||
|
||||
@staticmethod
|
||||
def _close_entries(entries: list[_ScopedClientEntry]) -> None:
|
||||
for entry in entries:
|
||||
try:
|
||||
entry.recorder.close()
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Failed to close OpenViking recorder for scope (%r, %r) (%s)",
|
||||
entry.key[0],
|
||||
entry.key[1],
|
||||
type(exc).__name__,
|
||||
)
|
||||
|
||||
def _close_credential_provider(self) -> None:
|
||||
provider = self._credential_provider
|
||||
close_fn = getattr(provider, "close", None)
|
||||
if callable(close_fn):
|
||||
try:
|
||||
close_fn()
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to close OpenViking credential provider (%s)", type(exc).__name__)
|
||||
|
||||
def _actor_peer_scope(
|
||||
self,
|
||||
peer_id: str,
|
||||
@ -512,17 +967,59 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
self._lifecycle.notify_all()
|
||||
should_close = self._close_requested
|
||||
if should_close:
|
||||
try:
|
||||
self._close_resources()
|
||||
except Exception:
|
||||
logger.exception("Failed to close OpenViking memory resources")
|
||||
# Start single-flight cleanup without blocking the finishing operation's
|
||||
# executor worker; shutdown_flush()/close() own any cleanup wait budget.
|
||||
self._start_resource_cleanup()
|
||||
|
||||
def _close_resources(self) -> None:
|
||||
def _start_resource_cleanup(self) -> threading.Event:
|
||||
to_close: list[_ScopedClientEntry] = []
|
||||
should_spawn = False
|
||||
with self._resource_lock:
|
||||
if self._resources_closed:
|
||||
return
|
||||
self._recorder.close()
|
||||
self._resources_closed = True
|
||||
if not self._cleanup_started:
|
||||
self._cleanup_started = True
|
||||
with self._pool_lock:
|
||||
self._resources_closed = True
|
||||
drained = list(self._pool.values())
|
||||
self._pool.clear()
|
||||
for entry in drained:
|
||||
entry.retired = True
|
||||
if entry.active_ops == 0 and not entry.closed:
|
||||
entry.closed = True
|
||||
to_close.append(entry)
|
||||
for entry in self._inflight_entries:
|
||||
entry.retired = True
|
||||
if entry.active_ops == 0 and not entry.closed:
|
||||
entry.closed = True
|
||||
to_close.append(entry)
|
||||
close_fn = getattr(self._credential_provider, "close", None)
|
||||
if not to_close and not callable(close_fn):
|
||||
self._cleanup_done.set()
|
||||
else:
|
||||
should_spawn = True
|
||||
|
||||
if should_spawn:
|
||||
|
||||
def _run_cleanup() -> None:
|
||||
try:
|
||||
self._close_entries(to_close)
|
||||
self._close_credential_provider()
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to close OpenViking memory resources (%s)", type(exc).__name__)
|
||||
finally:
|
||||
self._cleanup_done.set()
|
||||
|
||||
try:
|
||||
threading.Thread(
|
||||
target=_run_cleanup,
|
||||
name="openviking-resource-cleanup",
|
||||
daemon=True,
|
||||
).start()
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to start OpenViking cleanup worker (%s)", type(exc).__name__)
|
||||
self._cleanup_failed = True
|
||||
self._cleanup_done.set()
|
||||
|
||||
return self._cleanup_done
|
||||
|
||||
def _state_path(self, session_id: str) -> Path:
|
||||
root = Path(self._config.storage_path or ".") / "openviking" / "sessions"
|
||||
@ -560,6 +1057,36 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
def _save_cursor_with_policy(self, session_id: str, state: dict[str, Any]) -> bool:
|
||||
try:
|
||||
self._save_cursor(session_id, state)
|
||||
return True
|
||||
except OSError as exc:
|
||||
self._handle_write_error(
|
||||
exc,
|
||||
"OpenViking capture cursor persistence failed",
|
||||
session_id,
|
||||
)
|
||||
return False
|
||||
|
||||
def _invoke_retriever(self, retriever: Any, query: str, *, peer_id: str) -> list[Any]:
|
||||
use_home = self._use_home_alias_uris
|
||||
retriever.target_uri = _memory_target_uris(peer_id, use_home_alias=use_home)
|
||||
try:
|
||||
with self._actor_peer_scope(peer_id):
|
||||
return retriever.invoke(query)
|
||||
except Exception as exc:
|
||||
if use_home or not _should_retry_with_home_alias(exc):
|
||||
raise
|
||||
# OpenViking >=0.5.5 rejects uid-less ``viking://user/<reserved>`` shorthands;
|
||||
# retry once with ``viking://~/...`` and remember it for future calls.
|
||||
self._use_home_alias_uris = True
|
||||
logger.info("OpenViking server requires 'viking://~/' user-space URIs; switching target_uri format")
|
||||
retry_retriever = copy.copy(retriever)
|
||||
retry_retriever.target_uri = _memory_target_uris(peer_id, use_home_alias=True)
|
||||
with self._actor_peer_scope(peer_id):
|
||||
return retry_retriever.invoke(query)
|
||||
|
||||
def _handle_write_error(
|
||||
self,
|
||||
exc: Exception,
|
||||
@ -572,6 +1099,14 @@ class OpenVikingMemoryManager(MemoryManager):
|
||||
logger.error(detail, exc_info=True)
|
||||
|
||||
|
||||
def _should_retry_with_home_alias(exc: Exception) -> bool:
|
||||
"""Return True when an OpenViking >=0.5.5 server rejected legacy uid-less URIs."""
|
||||
|
||||
if "viking://~/" not in str(exc):
|
||||
return False
|
||||
return getattr(exc, "code", None) == "INVALID_URI" or type(exc).__name__ == "InvalidURIError"
|
||||
|
||||
|
||||
def _load_official_integration() -> dict[str, Any]:
|
||||
try:
|
||||
from langchain_openviking import (
|
||||
|
||||
@ -10,6 +10,7 @@ from typing import Any
|
||||
from .config import GENERATED_PEER_PREFIX, is_safe_peer_id
|
||||
|
||||
_SESSION_NAMESPACE = "deerflow-openviking-adapter-v1"
|
||||
_TENANT_SESSION_NAMESPACE = "deerflow-openviking-adapter-v2"
|
||||
_DEFAULT_AGENT_SCOPE = "__default__"
|
||||
_CURSOR_SCHEMA_VERSION = 1
|
||||
|
||||
@ -40,19 +41,26 @@ def _session_id(
|
||||
owner_user_id: str,
|
||||
peer_id: str,
|
||||
thread_id: str,
|
||||
*,
|
||||
tenant_id: str | None = None,
|
||||
) -> str:
|
||||
"""Derive one stable OpenViking session for one DeerFlow thread."""
|
||||
|
||||
digest = hashlib.sha256(f"{_SESSION_NAMESPACE}\0{owner_user_id}\0{peer_id}\0{thread_id}".encode()).hexdigest()
|
||||
if tenant_id is None:
|
||||
raw = f"{_SESSION_NAMESPACE}\0{owner_user_id}\0{peer_id}\0{thread_id}"
|
||||
else:
|
||||
raw = f"{_TENANT_SESSION_NAMESPACE}\0{tenant_id}\0{owner_user_id}\0{peer_id}\0{thread_id}"
|
||||
digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||
return f"df_{digest[:48]}"
|
||||
|
||||
|
||||
def _memory_target_uris(peer_id: str) -> list[str]:
|
||||
def _memory_target_uris(peer_id: str, *, use_home_alias: bool = False) -> list[str]:
|
||||
"""Return the self and current-peer memory roots for a request."""
|
||||
|
||||
prefix = "viking://~" if use_home_alias else "viking://user"
|
||||
return [
|
||||
"viking://user/memories",
|
||||
f"viking://user/peers/{peer_id}/memories",
|
||||
f"{prefix}/memories",
|
||||
f"{prefix}/peers/{peer_id}/memories",
|
||||
]
|
||||
|
||||
|
||||
|
||||
@ -2,6 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@ -145,3 +148,149 @@ async def test_async_openviking_operations_do_not_block_event_loop(
|
||||
"score": 0.9,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_multi_user_async_openviking_operations_and_eviction_do_not_block_event_loop(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
import deerflow.agents.memory.backends.openviking.openviking_manager as module
|
||||
|
||||
probe_dir = tmp_path / "probes"
|
||||
probe_dir.mkdir()
|
||||
creds_path = tmp_path / "credentials.json"
|
||||
creds_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"alice": {"api_key": "alice-key", "tenant_id": "acme"},
|
||||
"bob": {"api_key": "bob-key", "tenant_id": "globex"},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
events: list[tuple[str, str, int]] = []
|
||||
close_files: list[Path] = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def _record_event(kind: str, label: str) -> int:
|
||||
idx_holder: int
|
||||
with lock:
|
||||
events.append((kind, label, threading.get_ident()))
|
||||
idx_holder = len(events)
|
||||
return idx_holder
|
||||
|
||||
class _FileCredentialProvider:
|
||||
def resolve(self, user_id: str) -> dict[str, Any] | None:
|
||||
_record_event("resolve", user_id)
|
||||
data = json.loads(creds_path.read_text(encoding="utf-8"))
|
||||
return data.get(user_id)
|
||||
|
||||
class _MultiUserClient(_Client):
|
||||
def __init__(self, api_key: str) -> None:
|
||||
self.api_key = api_key
|
||||
|
||||
class _MultiUserBlockingRecorder:
|
||||
def __init__(self, *, commit_policy: Any, api_key: str, **kwargs: Any):
|
||||
del kwargs
|
||||
self.commit_policy = commit_policy
|
||||
self.api_key = api_key
|
||||
self.client = _MultiUserClient(api_key)
|
||||
idx = _record_event("init", api_key)
|
||||
(probe_dir / f"init-{api_key}-{idx}.txt").write_text("init", encoding="utf-8")
|
||||
|
||||
def record(
|
||||
self,
|
||||
session_id: str,
|
||||
messages: list[Any],
|
||||
peer_id: str | None = None,
|
||||
) -> None:
|
||||
del session_id, messages, peer_id
|
||||
idx = _record_event("record", self.api_key)
|
||||
(probe_dir / f"record-{self.api_key}-{idx}.txt").write_text("record", encoding="utf-8")
|
||||
|
||||
def flush(self, session_id: str) -> None:
|
||||
del session_id
|
||||
|
||||
def close(self) -> None:
|
||||
idx = _record_event("close", self.api_key)
|
||||
path = probe_dir / f"close-{self.api_key}-{idx}.txt"
|
||||
path.write_text("close", encoding="utf-8")
|
||||
close_files.append(path)
|
||||
|
||||
class _MultiUserBlockingRetriever(_BlockingRetriever):
|
||||
def __init__(self, *, client: Any, **kwargs: Any):
|
||||
super().__init__(client=client, **kwargs)
|
||||
self._api_key = getattr(client, "api_key", "")
|
||||
|
||||
def __copy__(self) -> _MultiUserBlockingRetriever:
|
||||
copied = type(self)(client=None)
|
||||
copied.__dict__.update(self.__dict__)
|
||||
return copied
|
||||
|
||||
def invoke(self, query: str) -> list[Document]:
|
||||
del query
|
||||
idx = _record_event("retrieve", self._api_key)
|
||||
(probe_dir / f"retrieve-{self._api_key}-{idx}.txt").write_text("retrieve", encoding="utf-8")
|
||||
return [
|
||||
Document(
|
||||
page_content="Prefers concise answers.",
|
||||
metadata={
|
||||
"openviking_uri": "viking://user/memories/preferences/test.md",
|
||||
"openviking_category": "preferences",
|
||||
"openviking_score": 0.9,
|
||||
},
|
||||
)
|
||||
]
|
||||
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"_load_official_integration",
|
||||
lambda: {
|
||||
"OpenVikingCommitPolicy": _CommitPolicy,
|
||||
"OpenVikingPartialWriteError": RuntimeError,
|
||||
"OpenVikingRetriever": _MultiUserBlockingRetriever,
|
||||
"OpenVikingSessionRecorder": _MultiUserBlockingRecorder,
|
||||
"use_actor_peer": lambda peer_id: nullcontext(),
|
||||
},
|
||||
)
|
||||
|
||||
manager = OpenVikingMemoryManager.from_config(
|
||||
{
|
||||
"base_url": "http://openviking:1933",
|
||||
"storage_path": str(tmp_path),
|
||||
"startup_policy": "warn",
|
||||
"failure_policy": {"read": "raise", "write": "raise"},
|
||||
"client_pool": {"max_clients": 1},
|
||||
},
|
||||
credential_provider=_FileCredentialProvider(),
|
||||
)
|
||||
|
||||
event_loop_thread = threading.get_ident()
|
||||
messages: list[Any] = [HumanMessage("hello", id="h1"), AIMessage("hi", id="a1")]
|
||||
try:
|
||||
await manager.aadd("thread-1", messages, user_id="alice")
|
||||
context = await manager.aget_context("bob", thread_id="thread-1")
|
||||
results = await manager.asearch("answer style", user_id="alice")
|
||||
|
||||
assert context == "- [preferences] Prefers concise answers."
|
||||
assert results == [
|
||||
{
|
||||
"id": "viking://user/memories/preferences/test.md",
|
||||
"content": "Prefers concise answers.",
|
||||
"category": "preferences",
|
||||
"confidence": 0.9,
|
||||
"source": "viking://user/memories/preferences/test.md",
|
||||
"score": 0.9,
|
||||
}
|
||||
]
|
||||
eviction_closes = [(label, tid) for kind, label, tid in events if kind == "close"]
|
||||
assert [label for label, _ in eviction_closes] == ["alice-key", "bob-key"]
|
||||
assert len(close_files) == 2
|
||||
assert all(path.exists() for path in close_files)
|
||||
assert {kind for kind, _, _ in events} == {"resolve", "init", "record", "retrieve", "close"}
|
||||
assert all(tid != event_loop_thread for _, _, tid in events)
|
||||
assert list((tmp_path / "openviking" / "sessions").glob("*.json"))
|
||||
finally:
|
||||
await asyncio.to_thread(manager.close)
|
||||
|
||||
@ -170,6 +170,71 @@ class TestMemoryBackendConfigCheck:
|
||||
assert "USER API key is missing" in result.detail
|
||||
assert result.fix == "Add OPENVIKING_API_KEY=<your-key> to your .env file"
|
||||
|
||||
def test_multi_user_valid_config_passes(self, doctor, monkeypatch):
|
||||
monkeypatch.setenv("ALICE_OV_KEY", "alice-secret")
|
||||
monkeypatch.setenv("BOB_OV_KEY", "bob-secret")
|
||||
static_cfg = self._config(
|
||||
"openviking",
|
||||
{
|
||||
"base_url": "http://127.0.0.1:1933",
|
||||
"user_credentials": {
|
||||
"alice": {"api_key_env": "ALICE_OV_KEY", "tenant_id": "acme"},
|
||||
"bob": {"api_key_env": "BOB_OV_KEY", "tenant_id": "globex"},
|
||||
},
|
||||
"client_pool": {"max_clients": 16, "idle_ttl_seconds": None},
|
||||
},
|
||||
)
|
||||
assert doctor._check_memory_backend_config(static_cfg).status == "ok"
|
||||
|
||||
provider_cfg = self._config(
|
||||
"openviking",
|
||||
{
|
||||
"base_url": "http://127.0.0.1:1933",
|
||||
"credential_provider": "nonexistent_doctor_mod.auth:VaultProvider",
|
||||
"credential_provider_config": {"endpoint": "https://vault.internal"},
|
||||
},
|
||||
)
|
||||
assert doctor._check_memory_backend_config(provider_cfg).status == "ok"
|
||||
|
||||
def test_multi_user_missing_api_key_advises_dotenv(self, doctor, monkeypatch):
|
||||
monkeypatch.setenv("ALICE_OV_KEY", "alice-secret")
|
||||
monkeypatch.delenv("BOB_OV_KEY", raising=False)
|
||||
config = self._config(
|
||||
"openviking",
|
||||
{
|
||||
"base_url": "http://127.0.0.1:1933",
|
||||
"user_credentials": {
|
||||
"alice": {"api_key_env": "ALICE_OV_KEY"},
|
||||
"bob": {"api_key_env": "BOB_OV_KEY"},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
result = doctor._check_memory_backend_config(config)
|
||||
|
||||
assert result.status == "fail"
|
||||
assert "USER API key is missing" in result.detail
|
||||
assert "bob" in result.detail
|
||||
assert result.fix == "Add BOB_OV_KEY=<your-key> to your .env file"
|
||||
|
||||
def test_conflicting_owner_user_id_and_user_credentials_fails(self, doctor, monkeypatch):
|
||||
monkeypatch.setenv("ALICE_OV_KEY", "alice-secret")
|
||||
config = self._config(
|
||||
"openviking",
|
||||
{
|
||||
"base_url": "http://127.0.0.1:1933",
|
||||
"owner_user_id": "alice",
|
||||
"user_credentials": {
|
||||
"alice": {"api_key_env": "ALICE_OV_KEY"},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
result = doctor._check_memory_backend_config(config)
|
||||
|
||||
assert result.status == "fail"
|
||||
assert "owner_user_id" in result.detail
|
||||
|
||||
|
||||
def test_memory_backend_config_failure_is_reported_end_to_end(doctor_checkout: Path):
|
||||
(doctor_checkout / "config.yaml").write_text(
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -2582,10 +2582,9 @@ memory:
|
||||
# Backend-private config (a dict), passed verbatim to the backend __init__.
|
||||
# Each backend self-interprets it (DeerMem parses it into DeerMemConfig).
|
||||
#
|
||||
# OpenViking example (replace this DeerMem backend_config block when
|
||||
# manager_class is openviking). This first official-adapter integration uses
|
||||
# one credential-bound OpenViking USER key for one DeerFlow user and supports
|
||||
# middleware mode only. Use owner_user_id: default when DeerFlow auth is off.
|
||||
# OpenViking single-user example (replace this DeerMem backend_config block
|
||||
# when manager_class is openviking; supports middleware mode only). Use
|
||||
# owner_user_id: default when DeerFlow auth is off.
|
||||
#
|
||||
# backend_config:
|
||||
# base_url: http://openviking:1933
|
||||
@ -2607,6 +2606,26 @@ memory:
|
||||
# user profile preferences important entities events ongoing goals
|
||||
# constraints and prior decisions
|
||||
#
|
||||
# OpenViking multi-user / multi-tenant isolation example (api_key mode,
|
||||
# middleware mode only; mutually exclusive with owner_user_id/api_key_env):
|
||||
#
|
||||
# backend_config:
|
||||
# base_url: http://openviking:1933
|
||||
# user_credentials:
|
||||
# alice:
|
||||
# api_key_env: OPENVIKING_API_KEY_ALICE
|
||||
# tenant_id: acme # optional; derives tenant-isolated v2 session IDs
|
||||
# bob:
|
||||
# api_key_env: OPENVIKING_API_KEY_BOB
|
||||
# tenant_id: globex
|
||||
# # Or resolve credentials dynamically (optionally paired with user_credentials
|
||||
# # or injected programmatically via host_hooks["credential_provider"]):
|
||||
# # credential_provider: my_company.openviking_auth:VaultCredentialProvider
|
||||
# # credential_provider_config: {}
|
||||
# client_pool: # multi-user mode only
|
||||
# max_clients: 64 # LRU cap (1..4096)
|
||||
# idle_ttl_seconds: 900.0 # null disables idle TTL eviction
|
||||
#
|
||||
# For a host-installed OpenViking used by Docker DeerFlow, set base_url to
|
||||
# http://host.docker.internal:1933 and allow_insecure_http: true. The bundled
|
||||
# optional Compose overlay uses the internal http://openviking:1933 address.
|
||||
|
||||
@ -7,8 +7,8 @@ package instead of implementing OpenViking's HTTP protocol inside DeerFlow.
|
||||
|
||||
## Current scope
|
||||
|
||||
The first official-adapter integration deliberately preserves DeerFlow's
|
||||
existing automatic-memory behavior:
|
||||
The OpenViking integration preserves DeerFlow's automatic-memory behavior across
|
||||
both single-user and multi-user / multi-tenant deployments:
|
||||
|
||||
- memory is recalled through DeerFlow's existing fixed memory query;
|
||||
- completed turns are captured by the existing memory middleware;
|
||||
@ -16,8 +16,10 @@ existing automatic-memory behavior:
|
||||
- every accepted capture is committed to the thread's stable OpenViking Session;
|
||||
- the official adapter handles message conversion, tool calls and results,
|
||||
100-message batching, partial-write progress, commit retry, and SDK transport;
|
||||
- one recorder-owned SDK client is shared with retrieval and closed through
|
||||
DeerFlow's existing memory shutdown contract.
|
||||
- in single-user mode, one recorder-owned SDK client is shared with retrieval
|
||||
and closed on shutdown; in multi-user mode, a bounded LRU/TTL `client_pool`
|
||||
manages isolated per-scope SDK clients and drains/closes them cleanly on
|
||||
eviction, key rotation, revocation, and shutdown.
|
||||
|
||||
This backend supports `memory.mode: middleware`. It does not implement DeerMem
|
||||
fact CRUD, import/export, or the Settings memory-document view. OpenViking MCP
|
||||
@ -25,44 +27,62 @@ tools are a separate integration surface and are not enabled by this backend.
|
||||
|
||||
## Authentication boundary
|
||||
|
||||
This version is for one DeerFlow user backed by one ordinary OpenViking **USER
|
||||
API key**. OpenViking derives the account and user from that credential.
|
||||
DeerFlow does not configure trusted account/user headers and must not receive a
|
||||
root key for normal memory traffic.
|
||||
The supported server configuration is OpenViking `api_key` mode, where each
|
||||
ordinary OpenViking **USER API key** determines the OpenViking account and user
|
||||
server-side. DeerFlow supports two isolation modes on top of `api_key` mode:
|
||||
|
||||
The supported server configuration is OpenViking `api_key` mode, where the USER
|
||||
key determines the account and user. DeerFlow supplies its URL and API key
|
||||
explicitly, overrides any ambient actor peer during memory operations, and does
|
||||
not inherit arbitrary HTTP headers from `ovcli.conf`.
|
||||
- **Single-user mode** (`owner_user_id` + `api_key_env`): binds one DeerFlow
|
||||
user identity to one OpenViking USER API key. Use `owner_user_id: default`
|
||||
when DeerFlow authentication is disabled, or that user's DeerFlow ID in an
|
||||
authenticated single-user deployment. A request for another DeerFlow user is
|
||||
rejected before OpenViking is contacted, preventing one USER key from silently
|
||||
sharing memory across users. The failure policies below decide what that
|
||||
rejection does to the turn: with `write: log_and_drop` the other user's write
|
||||
is logged as refused, without message content, and dropped, and the run still
|
||||
completes.
|
||||
- **Multi-user / multi-tenant isolation mode** (`user_credentials` and/or
|
||||
`credential_provider` / `host_hooks["credential_provider"]`, plus optional
|
||||
`tenant_id` and `client_pool`): resolves a distinct OpenViking USER API key
|
||||
(and optional `tenant_id`) per DeerFlow user and isolates each scope's
|
||||
client handle, headers, and session IDs. Multi-user configuration is mutually
|
||||
exclusive with `owner_user_id` and `api_key_env`.
|
||||
|
||||
### Why `auth_mode: trusted` / `account` remains unsupported
|
||||
|
||||
In OpenViking `api_key` mode, OpenViking derives `account` and `user`
|
||||
server-side from the USER API key (`X-API-Key`). Accepting `auth_mode: trusted`
|
||||
or `account` headers in DeerFlow would trust caller-asserted identity headers
|
||||
instead of key-derived identity and is therefore rejected at configuration time
|
||||
(pointing operators to `owner_user_id`, `user_credentials`, or
|
||||
`credential_provider`). DeerFlow also must not receive a root key for normal
|
||||
memory traffic, overrides any ambient actor peer during memory operations, and
|
||||
passes an explicit empty `extra_headers={}` mapping so the SDK never inherits
|
||||
arbitrary HTTP headers from `ovcli.conf`.
|
||||
|
||||
Before enabling this backend, remove legacy `OPENVIKING_ACCOUNT` and
|
||||
`OPENVIKING_USER` values from DeerFlow's repository-root `.env` and service
|
||||
environment, and remove `account` and `user` defaults from
|
||||
`~/.openviking/ovcli.conf`. Those settings belong to trusted-mode
|
||||
configurations and are outside this adapter's supported setup.
|
||||
|
||||
`owner_user_id` binds the configured key to one DeerFlow identity. Use
|
||||
`default` when DeerFlow authentication is disabled. In an authenticated
|
||||
single-user deployment, use that user's DeerFlow ID. A request for another
|
||||
DeerFlow user is rejected before OpenViking is contacted, preventing one USER
|
||||
key from silently sharing memory across users. The failure policies below
|
||||
decide what that rejection does to the turn: with `write: log_and_drop` the
|
||||
other user's write is logged as refused, without message content, and dropped,
|
||||
and the run still completes.
|
||||
|
||||
Multi-user credential provisioning and storage are intentionally outside this
|
||||
first adapter PR.
|
||||
`~/.openviking/ovcli.conf`. Those settings belong to trusted-mode configurations
|
||||
and are outside this adapter's supported setup. In multi-user mode, do not rely
|
||||
on a shared ambient `OPENVIKING_API_KEY`; per-user keys are never resolved from
|
||||
an ambient fallback.
|
||||
|
||||
Existing trusted-mode configurations are not migrated automatically. Configure
|
||||
the OpenViking server in `api_key` mode, replace `auth_mode`, `account`, and the
|
||||
root key with `owner_user_id` and a USER key, and remove the legacy ambient
|
||||
identity settings listed above. Because the credential-bound user and Session
|
||||
mapping differ from the old trusted-user mapping, previously captured
|
||||
root key with either single-user (`owner_user_id` + `api_key_env`) or multi-user
|
||||
(`user_credentials` / `credential_provider`) USER keys, and remove the legacy
|
||||
ambient identity settings listed above. Because credential-bound user and Session
|
||||
mappings differ from the old trusted-user mapping, previously captured
|
||||
trusted-mode data remains in its old OpenViking namespace rather than being
|
||||
silently reassigned.
|
||||
|
||||
## Configure DeerFlow
|
||||
|
||||
The dependency on `langchain-openviking==0.1.0` is declared by DeerFlow's
|
||||
harness package and is installed by the normal `uv sync` flow.
|
||||
|
||||
### Single-user mode
|
||||
|
||||
Create or select an OpenViking user, then copy its USER API key into DeerFlow's
|
||||
repository-root `.env`:
|
||||
|
||||
@ -101,8 +121,144 @@ For a host-installed OpenViking used by Docker DeerFlow, set `base_url` to
|
||||
`http://host.docker.internal:1933` and `allow_insecure_http: true`. The optional
|
||||
Compose overlay uses the internal `http://openviking:1933` address.
|
||||
|
||||
The dependency on `langchain-openviking==0.1.0` is declared by DeerFlow's
|
||||
harness package and is installed by the normal `uv sync` flow.
|
||||
### Multi-user and multi-tenant isolation mode
|
||||
|
||||
Use `user_credentials` for a static per-user mapping, `credential_provider`
|
||||
for dynamic resolution, or both together (static `user_credentials` is checked
|
||||
first, and `credential_provider` resolves users not listed statically). Do **not**
|
||||
set `owner_user_id` or `api_key_env` at the `backend_config` top level when
|
||||
using multi-user mode.
|
||||
|
||||
#### Static per-user mapping (`user_credentials`)
|
||||
|
||||
Put each user's OpenViking USER API key in DeerFlow's `.env` or service
|
||||
environment:
|
||||
|
||||
```dotenv
|
||||
OPENVIKING_API_KEY_ALICE=replace-with-alice-user-api-key
|
||||
OPENVIKING_API_KEY_BOB=replace-with-bob-user-api-key
|
||||
```
|
||||
|
||||
Configure `user_credentials` and `client_pool` in `config.yaml`:
|
||||
|
||||
```yaml
|
||||
memory:
|
||||
enabled: true
|
||||
injection_enabled: true
|
||||
shutdown_flush_timeout_seconds: 30
|
||||
manager_class: openviking
|
||||
mode: middleware
|
||||
backend_config:
|
||||
base_url: http://127.0.0.1:1933
|
||||
user_credentials:
|
||||
alice:
|
||||
api_key_env: OPENVIKING_API_KEY_ALICE
|
||||
tenant_id: acme
|
||||
bob:
|
||||
api_key_env: OPENVIKING_API_KEY_BOB
|
||||
tenant_id: globex
|
||||
client_pool:
|
||||
max_clients: 64
|
||||
idle_ttl_seconds: 900.0
|
||||
startup_policy: fail_fast
|
||||
failure_policy:
|
||||
read: fail_open
|
||||
write: log_and_drop
|
||||
retrieval:
|
||||
top_k: 8
|
||||
score_threshold: 0.25
|
||||
max_injection_chars: 12000
|
||||
content_mode: overview
|
||||
injection_query: >-
|
||||
user profile preferences important entities events ongoing goals
|
||||
constraints and prior decisions
|
||||
```
|
||||
|
||||
`user_credentials` rules:
|
||||
|
||||
- Each mapping key is the exact DeerFlow `user_id` (non-empty stripped string
|
||||
with no control characters or `\0`).
|
||||
- Each user entry accepts only `api_key_env`, `api_key`, and optional
|
||||
`tenant_id`. Exactly **one** of `api_key_env` or `api_key` is required per
|
||||
entry; `api_key_env` is recommended so secret keys stay out of `config.yaml`.
|
||||
- `tenant_id` is optional. When set, it must be a non-empty stripped string of
|
||||
at most 128 characters with no control characters or `\0`.
|
||||
- When `credential_provider` (or `host_hooks["credential_provider"]`) is not
|
||||
configured, `user_credentials` must be non-empty.
|
||||
- Every statically configured user must have a distinct API key.
|
||||
|
||||
#### Dynamic credential resolution (`credential_provider` and `host_hooks`)
|
||||
|
||||
For dynamic, KMS/vault-backed, or rotating user credentials, specify a dotted
|
||||
Python import path in `credential_provider` (`pkg.module:Attr` or
|
||||
`pkg.module.Attr`) and optional constructor/factory keyword arguments in
|
||||
`credential_provider_config`:
|
||||
|
||||
```yaml
|
||||
memory:
|
||||
enabled: true
|
||||
injection_enabled: true
|
||||
manager_class: openviking
|
||||
mode: middleware
|
||||
backend_config:
|
||||
base_url: http://127.0.0.1:1933
|
||||
credential_provider: my_company.openviking_auth:VaultCredentialProvider
|
||||
credential_provider_config:
|
||||
vault_url: https://vault.internal
|
||||
namespace: deerflow
|
||||
client_pool:
|
||||
max_clients: 128
|
||||
idle_ttl_seconds: 900.0
|
||||
```
|
||||
|
||||
Provider resolution contract (`OpenVikingCredentialProvider`):
|
||||
|
||||
- `OpenVikingConfig.from_backend_config()` validates `credential_provider`
|
||||
path syntax without importing the module or performing I/O, keeping `make doctor`
|
||||
and policy checks side-effect-free.
|
||||
- At manager initialization, DeerFlow imports the target attribute:
|
||||
- If the target is a class, DeerFlow instantiates
|
||||
`Attr(**credential_provider_config)` and expects a callable `.resolve`
|
||||
method or callable instance.
|
||||
- If the target is a callable factory/function and `credential_provider_config`
|
||||
is non-empty, DeerFlow calls `Attr(**credential_provider_config)` and uses
|
||||
the returned resolver (`.resolve` method or callable). If
|
||||
`credential_provider_config` is empty, `Attr` itself is used directly.
|
||||
- Embedded hosts and custom extensions can also inject a provider instance or
|
||||
callable programmatically via `host_hooks["credential_provider"]` when calling
|
||||
`OpenVikingMemoryManager.from_config(..., credential_provider=...)`, without
|
||||
declaring an import path in `config.yaml`. Because Gateway and
|
||||
`DynamicContextMiddleware` config bootstrap consult
|
||||
`OpenVikingMemoryManager.read_failures_are_fatal_for_config(backend_config)`
|
||||
(which requires `user_credentials` or `credential_provider` in
|
||||
`backend_config`), `host_hooks["credential_provider"]` is intended for direct
|
||||
programmatic callers outside config-driven Gateway/`DynamicContextMiddleware`
|
||||
wiring.
|
||||
- `credential_provider_config` applies only when DeerFlow instantiates a
|
||||
config-declared `credential_provider` and must be omitted or empty when
|
||||
`credential_provider` is not set in `backend_config` (including when passing an
|
||||
already-instantiated hook via `host_hooks["credential_provider"]`).
|
||||
- At request time, the provider's `resolve(user_id)` returns one of:
|
||||
- `OpenVikingCredential(api_key=..., tenant_id=...)`
|
||||
- a mapping containing only `api_key` and optional `tenant_id`
|
||||
- a plain `str` (treated as `api_key` with `tenant_id=None`)
|
||||
- `None` (treated as unmapped or revoked; fails closed)
|
||||
- If the provider defines a callable `.close()` method, DeerFlow invokes it
|
||||
during graceful shutdown (`shutdown_flush()` / `close()`).
|
||||
|
||||
#### Client pool (`client_pool`)
|
||||
|
||||
Multi-user mode caches scoped `(tenant_id, user_id, key_fingerprint)` SDK
|
||||
recorder/retriever handles in a bounded pool:
|
||||
|
||||
- `max_clients` (integer `1..4096`, default `64`): maximum active client
|
||||
handles retained in the LRU pool. When full, the least-recently-used idle
|
||||
handle is evicted and closed; if an evicted handle still has active in-flight
|
||||
operations, `close()` is deferred until those operations finish.
|
||||
- `idle_ttl_seconds` (positive finite float or `null`, default `900.0`): idle
|
||||
eviction threshold in seconds. Omitting `idle_ttl_seconds` keeps the
|
||||
`900.0`-second default; setting `idle_ttl_seconds: null` explicitly disables
|
||||
TTL-based eviction.
|
||||
|
||||
## Start the services
|
||||
|
||||
@ -140,9 +296,16 @@ docker compose \
|
||||
up -d --build
|
||||
```
|
||||
|
||||
Configure OpenViking in API-key mode and obtain a USER key through its identity
|
||||
management flow. Only that USER key belongs in DeerFlow's
|
||||
`OPENVIKING_API_KEY` variable.
|
||||
Configure OpenViking in `api_key` mode and obtain ordinary USER keys through
|
||||
its identity management flow. Put only USER keys in DeerFlow's `OPENVIKING_API_KEY`
|
||||
(single-user), per-user environment variables referenced by `user_credentials`,
|
||||
or your `credential_provider` store.
|
||||
|
||||
In single-user mode, `warm()` verifies OpenViking health through the configured
|
||||
client's `health()` check. In multi-user mode, because no single user key owns
|
||||
the backend, `warm()` probes `GET {base_url}/health` without any user API key
|
||||
or ambient `ovcli.conf` headers, checks for HTTP 200 and JSON `status == "ok"`,
|
||||
and honors `startup_policy` (`fail_fast` vs `warn`).
|
||||
|
||||
## Identity and session mapping
|
||||
|
||||
@ -150,12 +313,75 @@ One DeerFlow thread maps deterministically to one OpenViking Session. A commit
|
||||
creates an archive inside that Session; it does not create a new Session, so a
|
||||
thread keeps the same identity when the user returns later.
|
||||
|
||||
Session ID derivation depends on whether `tenant_id` is set:
|
||||
|
||||
- **Unscoped (`tenant_id` is unset / `None`)**: preserves the v1 derivation
|
||||
(`deerflow-openviking-adapter-v1`, hashing namespace, `user_id`, `peer_id`,
|
||||
and `thread_id`), so existing single-user deployments and unscoped multi-user
|
||||
entries keep their stable v1 `df_<hash>` session IDs.
|
||||
- **Tenant-scoped (`tenant_id` is set)**: uses the v2 derivation
|
||||
(`deerflow-openviking-adapter-v2`, hashing namespace, `tenant_id`, `user_id`,
|
||||
`peer_id`, and `thread_id`). Even when two tenants use the same DeerFlow
|
||||
`user_id`, `agent_name`, and `thread_id`, their OpenViking `session_id`
|
||||
values and local capture cursors are completely disjoint from each other and
|
||||
from unscoped v1 sessions.
|
||||
|
||||
The default DeerFlow agent uses `default_peer_id` (`deerflow` by default).
|
||||
Named agents use lowercase OpenViking peer IDs. Names that are not valid peer
|
||||
IDs, conflict with the default, or enter the reserved `df-agent-` namespace are
|
||||
mapped to collision-resistant IDs. USER-key identity remains the security
|
||||
boundary; peers separate memory scopes within that user.
|
||||
|
||||
## Security and isolation invariants
|
||||
|
||||
- **Fail-closed user resolution**: in multi-user mode, `None`, empty, or
|
||||
whitespace-only `user_id` values, leading/trailing whitespace or control
|
||||
characters (`\0`) on runtime `user_id` values, unmapped users, revoked users
|
||||
(`None` from `credential_provider`), invalid/blank keys, and provider errors
|
||||
are all rejected before any OpenViking HTTP call is made or local cursor file
|
||||
is written: read paths raise `MemoryManagerError` (or `MemoryReadError` when
|
||||
`failure_policy.read: raise`), and write paths follow `failure_policy.write`
|
||||
(`log_and_drop` logs the refusal without message content or secrets and drops
|
||||
the write; `raise` propagates `MemoryManagerError`).
|
||||
- **No fallback to shared or ambient credentials**: DeerFlow never falls back
|
||||
to another user's key, a default key, ambient `OPENVIKING_API_KEY`, or
|
||||
`ovcli.conf` headers.
|
||||
- **Cross-user duplicate key rejection**: DeerFlow tracks each key by its
|
||||
SHA-256 `key_fingerprint` and refuses to share the same API key across
|
||||
different users—both statically during `user_credentials` config validation
|
||||
and dynamically in the runtime `client_pool`. Static `user_credentials`
|
||||
fingerprints are always checked globally (including in hybrid deployments even
|
||||
when a static user has not yet been called or was evicted); for purely dynamic
|
||||
providers, runtime duplicate-key detection covers currently cached and
|
||||
in-flight pool entries rather than evicted historical scopes.
|
||||
- **Key validation without secret echoes**: API keys must contain printable
|
||||
ASCII (`0x21..0x7E`) only (rejecting whitespace, newlines, `\0`, control
|
||||
characters, and non-ASCII to prevent header injection). Config/validation
|
||||
errors and `repr(OpenVikingConfig)` never echo raw API keys.
|
||||
- **Key rotation and revocation**: pool entries are keyed by
|
||||
`(tenant_id, user_id, key_fingerprint)`. When a provider rotates a user's key
|
||||
or reassigns their `tenant_id`, DeerFlow opens a fresh scoped handle and
|
||||
retires all previous cached and in-flight handles for that `user_id` so they
|
||||
close once active operations complete. When a provider revokes a user by
|
||||
returning `None`, DeerFlow immediately retires all cached and in-flight
|
||||
handles for that user and refuses the request.
|
||||
- **Refcount-safe, lock-free handle lifecycle**: in-flight operations hold a
|
||||
reference count on the acquired entry so evicted, rotated, or revoked handles
|
||||
are never closed out from under an active request, and pool locks are never
|
||||
held while calling `credential_provider.resolve()`, constructing SDK clients,
|
||||
or calling `close()`.
|
||||
- **Gateway `/api/memory/config` masking**: `GET /api/memory/config` masks
|
||||
`user_credentials` wholesale as `"***"` (hiding nested `api_key`,
|
||||
`api_key_env`, and `tenant_id` entries) and masks secret-named keys inside
|
||||
`credential_provider_config` (keys matching `api_key`, `secret`, `token`,
|
||||
`password`, `credentials`, `authorization`, `bearer`, or `cookie`), while
|
||||
keeping top-level non-secret settings (`base_url`, single-user `api_key_env`,
|
||||
`client_pool`, and non-secret provider options) visible. Providers that need
|
||||
DSNs or URLs with embedded credentials should read them from environment
|
||||
variables or secret stores inside the provider rather than passing them via
|
||||
non-secret keys in `credential_provider_config`. Note that `GET /api/memory/status`
|
||||
returns HTTP `501` for OpenViking (same as `GET /api/memory`).
|
||||
|
||||
## Retry and failure behavior
|
||||
|
||||
- `read: fail_open` logs retrieval failures and continues the turn without
|
||||
@ -169,18 +395,21 @@ boundary; peers separate memory scopes within that user.
|
||||
- `write: log_and_drop` logs capture failures without failing an already
|
||||
generated answer. `write: raise` propagates them.
|
||||
- DeerFlow stores only hashes and counters in a bounded local capture cursor
|
||||
under `{storage_path}/openviking/sessions/`. It never stores message text
|
||||
there.
|
||||
under `{storage_path}/openviking/sessions/{session_id}.json`. It never stores
|
||||
message text there.
|
||||
- The cursor prevents full LangGraph transcript snapshots from being submitted
|
||||
again. It also records confirmed progress from partial batches and retries a
|
||||
failed commit before appending more messages.
|
||||
- An unreadable cursor fails closed because replaying an unknown prefix could
|
||||
duplicate private conversation history.
|
||||
- Graceful shutdown stops new memory work, waits up to
|
||||
`shutdown_flush_timeout_seconds` for accepted operations, and closes the
|
||||
recorder-owned SDK client. It does not introduce a new DeerFlow lifecycle or
|
||||
background worker.
|
||||
- Capture cursors remain local per Gateway instance. Shared DB-backed capture
|
||||
cursors for multi-replica Gateways writing concurrently to the same thread
|
||||
remain a Phase 2 follow-up.
|
||||
- Graceful shutdown stops new memory work, drains accepted operations, and
|
||||
bounds closing pooled recorder-owned SDK clients and
|
||||
`credential_provider.close()` (if defined) within the same
|
||||
`shutdown_flush_timeout_seconds` budget via a single-flight teardown, without
|
||||
introducing a new DeerFlow lifecycle or persistent background worker.
|
||||
|
||||
For deployments where a lost memory update is unacceptable, a durable outbox
|
||||
is still required. This initial integration does not claim at-least-once
|
||||
delivery.
|
||||
is still required. This integration does not claim at-least-once delivery.
|
||||
|
||||
@ -83,9 +83,12 @@ is off by default and does not affect targeted fact updates.
|
||||
DeerFlow also includes an optional `openviking` memory backend. It uses the
|
||||
official `langchain-openviking` package to capture completed turns into stable
|
||||
OpenViking Sessions and recall memory for prompt injection while leaving
|
||||
DeerMem as the default. The initial integration supports one DeerFlow user with
|
||||
one credential-bound OpenViking USER API key in `memory.mode: middleware` and
|
||||
does not inherit arbitrary HTTP headers from `ovcli.conf`.
|
||||
DeerMem as the default. It runs in `memory.mode: middleware` with either
|
||||
single-user binding (`owner_user_id` + `api_key_env`) or fail-closed
|
||||
multi-user / multi-tenant isolation (`user_credentials` or
|
||||
`credential_provider` with optional `tenant_id` and a bounded `client_pool`) in
|
||||
OpenViking `api_key` mode, and does not inherit arbitrary HTTP headers from
|
||||
`ovcli.conf`.
|
||||
See [OpenViking memory backend](../../docs/OPENVIKING.md) for its configuration,
|
||||
behavior, and current boundaries.
|
||||
|
||||
|
||||
@ -313,10 +313,12 @@ memory:
|
||||
```
|
||||
|
||||
The optional `openviking` backend connects to an independent OpenViking server
|
||||
through `langchain-openviking` and currently supports one DeerFlow user in
|
||||
`mode: middleware`. Its private configuration uses `base_url`,
|
||||
`owner_user_id`, `api_key_env`, `failure_policy`, and `retrieval` with an
|
||||
ordinary OpenViking USER API key instead of the DeerMem fields shown above. See
|
||||
through `langchain-openviking` in `mode: middleware` instead of using the
|
||||
DeerMem fields shown above. It supports single-user deployments
|
||||
(`owner_user_id` + `api_key_env`) as well as fail-closed multi-user and
|
||||
multi-tenant isolation using per-user OpenViking USER API keys via
|
||||
`user_credentials` or `credential_provider` (with optional `tenant_id` and
|
||||
`client_pool`), alongside `base_url`, `failure_policy`, and `retrieval`. See
|
||||
`docs/OPENVIKING.md` in the repository for the complete configuration and
|
||||
Docker startup sequence.
|
||||
|
||||
|
||||
@ -100,6 +100,8 @@ deermem is the default backend and implements the full contract:
|
||||
|
||||
OpenViking is a remote memory backend with a crisp responsibility split: **DeerFlow owns capture timing, the recall query, and the transcript cursor; the `langchain-openviking` package owns transport, message conversion, batching, and Session commits.**
|
||||
|
||||
Single-user example:
|
||||
|
||||
```yaml
|
||||
memory:
|
||||
enabled: true
|
||||
@ -119,11 +121,34 @@ memory:
|
||||
max_injection_chars: 12000
|
||||
```
|
||||
|
||||
Multi-user / multi-tenant example:
|
||||
|
||||
```yaml
|
||||
memory:
|
||||
enabled: true
|
||||
injection_enabled: true
|
||||
manager_class: openviking
|
||||
mode: middleware
|
||||
backend_config:
|
||||
base_url: http://openviking:1933
|
||||
user_credentials:
|
||||
alice:
|
||||
api_key_env: OPENVIKING_API_KEY_ALICE
|
||||
tenant_id: acme
|
||||
bob:
|
||||
api_key_env: OPENVIKING_API_KEY_BOB
|
||||
tenant_id: globex
|
||||
# Or use credential_provider (+ credential_provider_config) / host_hooks["credential_provider"]
|
||||
client_pool:
|
||||
max_clients: 64
|
||||
idle_ttl_seconds: 900.0
|
||||
```
|
||||
|
||||
Integration notes:
|
||||
|
||||
- **One API key is bound to one DeerFlow owner**; accessing another owner is rejected. Keep the USER key in the server environment (`api_key_env`), never in `config.yaml`.
|
||||
- **One DeerFlow thread maps to one stable OpenViking Session**; bounded hash-only cursors live under `{storage_path}/openviking/sessions/`.
|
||||
- This version supports one user with one key in middleware mode; multi-user key provisioning is out of scope. See `docs/OPENVIKING.md` for the full boundary and startup guide.
|
||||
- **Single-user vs. multi-user isolation in `api_key` mode**: single-user mode binds one OpenViking USER API key (`api_key_env`) to `owner_user_id`. Multi-user mode uses `user_credentials` (`api_key_env` or `api_key`, plus optional `tenant_id`) and/or a dynamic `credential_provider` (`credential_provider` + `credential_provider_config`, or programmatic `host_hooks["credential_provider"]`) with a bounded LRU/TTL `client_pool`. Mutually exclusive with `owner_user_id` / `api_key_env`; unmapped, blank, or revoked users fail closed without falling back to another key or ambient `OPENVIKING_API_KEY`.
|
||||
- **One DeerFlow thread maps to one stable OpenViking Session** (unscoped requests keep v1 session hashes while `tenant_id` derives disjoint v2 hashes); bounded hash-only local cursors live under `{storage_path}/openviking/sessions/`.
|
||||
- **Middleware mode only**: `auth_mode: trusted` / `account` headers remain unsupported because OpenViking derives account and user server-side from each USER API key. See `docs/OPENVIKING.md` for the full security boundary, key rotation/revocation, and startup guide.
|
||||
|
||||
## Implementing your own memory backend
|
||||
|
||||
@ -264,9 +289,12 @@ memory:
|
||||
|
||||
Set `manager_class: openviking` to send completed turns to an independent
|
||||
OpenViking server and recall its memory through the official
|
||||
`langchain-openviking` adapter. This first version supports one DeerFlow user
|
||||
with one OpenViking USER API key in middleware mode; DeerMem remains the
|
||||
default.
|
||||
`langchain-openviking` adapter. It supports `memory.mode: middleware` in both
|
||||
single-user mode (`owner_user_id` + `api_key_env`) and fail-closed multi-user
|
||||
/ multi-tenant isolation (`user_credentials` or `credential_provider` with
|
||||
optional `tenant_id` and `client_pool`); DeerMem remains the default.
|
||||
|
||||
Single-user configuration:
|
||||
|
||||
```yaml
|
||||
memory:
|
||||
@ -287,11 +315,38 @@ memory:
|
||||
max_injection_chars: 12000
|
||||
```
|
||||
|
||||
Use `owner_user_id: default` when DeerFlow authentication is disabled. Put the
|
||||
USER key in the server environment, not directly in `config.yaml`. Trusted-mode
|
||||
account headers, root-key memory access, and multi-user key provisioning are not
|
||||
part of this version. See `docs/OPENVIKING.md` for the full boundary and startup
|
||||
guide.
|
||||
Multi-user / multi-tenant configuration (mutually exclusive with
|
||||
`owner_user_id` and `api_key_env`):
|
||||
|
||||
```yaml
|
||||
memory:
|
||||
enabled: true
|
||||
injection_enabled: true
|
||||
manager_class: openviking
|
||||
mode: middleware
|
||||
backend_config:
|
||||
base_url: http://openviking:1933
|
||||
user_credentials:
|
||||
alice:
|
||||
api_key_env: OPENVIKING_API_KEY_ALICE
|
||||
tenant_id: acme
|
||||
bob:
|
||||
api_key_env: OPENVIKING_API_KEY_BOB
|
||||
tenant_id: globex
|
||||
# Or resolve keys dynamically with credential_provider (+ credential_provider_config)
|
||||
# or programmatic host_hooks["credential_provider"]
|
||||
client_pool:
|
||||
max_clients: 64
|
||||
idle_ttl_seconds: 900.0
|
||||
```
|
||||
|
||||
Use `owner_user_id: default` when DeerFlow authentication is disabled in
|
||||
single-user deployments. Put USER keys in the server environment (or resolve
|
||||
them through `credential_provider`), not directly in `config.yaml`.
|
||||
Trusted-mode `auth_mode` / `account` headers and root-key memory access remain
|
||||
unsupported because OpenViking derives `account` and `user` server-side from
|
||||
each USER API key. See `docs/OPENVIKING.md` for the full security boundary,
|
||||
session-ID scoping, key rotation/revocation, and startup guide.
|
||||
|
||||
## Global vs per-agent memory
|
||||
|
||||
|
||||
@ -99,6 +99,8 @@ deermem 是默认后端,完整实现了契约的全部能力:
|
||||
|
||||
OpenViking 是远程记忆后端,职责边界划分得很清楚:**DeerFlow 负责捕获时机、召回查询和会话游标;`langchain-openviking` 包负责传输、消息转换、批处理与 Session 提交**。
|
||||
|
||||
单用户示例:
|
||||
|
||||
```yaml
|
||||
memory:
|
||||
enabled: true
|
||||
@ -118,11 +120,34 @@ memory:
|
||||
max_injection_chars: 12000
|
||||
```
|
||||
|
||||
多用户 / 多租户隔离示例:
|
||||
|
||||
```yaml
|
||||
memory:
|
||||
enabled: true
|
||||
injection_enabled: true
|
||||
manager_class: openviking
|
||||
mode: middleware
|
||||
backend_config:
|
||||
base_url: http://openviking:1933
|
||||
user_credentials:
|
||||
alice:
|
||||
api_key_env: OPENVIKING_API_KEY_ALICE
|
||||
tenant_id: acme
|
||||
bob:
|
||||
api_key_env: OPENVIKING_API_KEY_BOB
|
||||
tenant_id: globex
|
||||
# 或使用 credential_provider(+ credential_provider_config)/ host_hooks["credential_provider"]
|
||||
client_pool:
|
||||
max_clients: 64
|
||||
idle_ttl_seconds: 900.0
|
||||
```
|
||||
|
||||
接入要点:
|
||||
|
||||
- **一个 API Key 绑定一个 DeerFlow 拥有者**,访问其他用户会被拒绝;USER Key 放在服务端环境变量(`api_key_env`),不要写进 `config.yaml`。
|
||||
- **一个 DeerFlow 线程映射到一个稳定的 OpenViking Session**,会话游标以哈希形式存于 `{storage_path}/openviking/sessions/` 下。
|
||||
- 当前版本支持单用户单 Key、middleware 模式;多用户 Key 分发不在本版本范围内。完整边界与启动指南见 `docs/OPENVIKING.md`。
|
||||
- **支持 `api_key` 模式下的单用户绑定与多用户 / 多租户隔离**:单用户模式通过 `owner_user_id` + `api_key_env` 将一个 USER API Key 绑定到一个 DeerFlow 拥有者;多用户模式通过 `user_credentials`(每用户 `api_key_env` 或 `api_key`,以及可选 `tenant_id`)或动态 `credential_provider`(`credential_provider` + `credential_provider_config`,或宿主注入 `host_hooks["credential_provider"]`)与有界 LRU/TTL `client_pool` 实现按作用域隔离。多用户配置与 `owner_user_id` / `api_key_env` 互斥,未映射、空白或已吊销的用户一律 fail-closed 拒绝,绝不回退到其他用户的 Key 或环境变量 `OPENVIKING_API_KEY`。
|
||||
- **一个 DeerFlow 线程映射到一个稳定的 OpenViking Session**(未配置 `tenant_id` 时保留 v1 会话哈希,配置 `tenant_id` 时生成互相隔离的 v2 哈希),仅含哈希的本地游标存于 `{storage_path}/openviking/sessions/` 下。
|
||||
- **仅支持 `memory.mode: middleware`**:不支持 `auth_mode: trusted` / `account` 头(OpenViking 服务端由每个 USER API Key 推导 `account` 与 `user`)。完整安全边界、密钥轮换/吊销与启动指南见 `docs/OPENVIKING.md`。
|
||||
|
||||
## 实现自己的记忆后端
|
||||
|
||||
|
||||
@ -485,13 +485,13 @@ def _resolves_to_builtin_openviking(manager_class: str) -> bool:
|
||||
def _memory_backend_config_fix(detail: str) -> str | None:
|
||||
"""Remediation matched to the validator's failure modes; None lets the
|
||||
verbatim error speak for itself."""
|
||||
if "USER API key is missing; set" in detail:
|
||||
var = detail.rsplit("set ", 1)[-1].strip().rstrip(".")
|
||||
if "USER API key is missing" in detail and "; set " in detail:
|
||||
var = detail.rsplit("; set ", 1)[-1].strip().rstrip(".")
|
||||
return f"Add {var}=<your-key> to your .env file"
|
||||
if "Unknown OpenViking backend_config fields" in detail:
|
||||
return "Remove the fields named in the error from memory.backend_config, or switch manager_class back"
|
||||
if "trusted mode is no longer supported" in detail:
|
||||
return "Use a USER API key (api_key_env) and configure owner_user_id instead of auth_mode/account"
|
||||
return "Use a USER API key and configure owner_user_id, user_credentials, or credential_provider instead of auth_mode/account"
|
||||
if "custom HTTP client fields are no longer supported" in detail:
|
||||
return "Remove the custom HTTP client fields from memory.backend_config"
|
||||
return None
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user