Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(connector): delegate add_resource imports to external Connector (#3084)
zihengli540139091fcb
diff --git a/openviking/connector/__init__.py b/openviking/connector/__init__.pynew file mode 100644index 000000000..236633478--- /dev/null+++ b/openviking/connector/__init__.py@@ -0,0 +1,2 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0diff --git a/openviking/connector/client.py b/openviking/connector/client.pynew file mode 100644index 000000000..304955fcc--- /dev/null+++ b/openviking/connector/client.py@@ -0,0 +1,111 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Client for the external Connector service (knowledge-base doc/add pipeline)."""++from __future__ import annotations++from typing import Any, Dict, List, Optional++import httpx++from openviking_cli.exceptions import InternalError+from openviking_cli.utils import get_logger++logger = get_logger(__name__)+++def _unwrap_connector_response(payload: Any) -> Dict[str, Any]:+ """Validate the Connector business envelope and return its data object.++ The inner APIs return HTTP 200 for both success and business errors, so+ ``raise_for_status`` alone is insufficient. Flat dictionaries remain+ accepted for compatibility with Connector deployments that do not wrap+ responses in ``code/data``.+ """+ if not isinstance(payload, dict):+ raise InternalError("Connector returned a non-object JSON response")++ if "code" not in payload and "data" not in payload:+ return payload++ code = payload.get("code")+ if code not in (0, "0"):+ message = payload.get("message") or "unknown Connector error"+ raise InternalError(f"Connector request failed (code={code}): {message}")++ data = payload.get("data")+ if not isinstance(data, dict):+ raise InternalError("Connector success response contains no data object")+ return data+++class ConnectorClient:+ """Wraps the Connector service's doc/add and task/info APIs."""++ def __init__(self, doc_add_url: str, task_info_url: str, account_id: str = "") -> None:+ self._doc_add_url = doc_add_url+ self._task_info_url = task_info_url+ self._headers = {"V-Account-Id": account_id} if account_id else {}++ def _request_headers(self, api_key: str) -> Dict[str, str]:+ """Build the headers required by the inner Connector endpoints."""+ headers = dict(self._headers)+ token = api_key if api_key.lower().startswith("bearer ") else f"Bearer {api_key}"+ headers["Authorization"] = token+ return headers++ async def submit_doc_add(+ self,+ add_type: str,+ api_key: str,+ *,+ tos_path: Optional[str] = None,+ path_prefix: Optional[List[str]] = None,+ include_child: bool = True,+ extra_params: Optional[Dict[str, Any]] = None,+ ) -> Dict[str, Any]:+ """Submit a document import job via the configured doc/add endpoint.++ Returns the Connector response dict (contains task key / id on success).+ """+ payload: Dict[str, Any] = {+ "add_type": add_type,+ "backend": "ov",+ "include_child": include_child,+ }+ if tos_path is not None:+ payload["tos_path"] = tos_path+ if path_prefix is not None:+ payload["path_prefix"] = path_prefix+ if extra_params:+ # Authentication belongs exclusively in the Authorization header.+ payload.update({key: value for key, value in extra_params.items() if key != "api_key"})++ async with httpx.AsyncClient(timeout=30.0) as client:+ rsp = await client.post(+ self._doc_add_url,+ json=payload,+ headers=self._request_headers(api_key),+ )+ rsp.raise_for_status()+ return _unwrap_connector_response(rsp.json())++ async def get_task_info(self, task_key: str, api_key: str) -> Dict[str, Any]:+ """Query task status via the configured task/info endpoint.++ Connector task statuses: pending / running / succeeded / failed / cancelled.+ """+ async with httpx.AsyncClient(timeout=10.0) as client:+ rsp = await client.post(+ self._task_info_url,+ json={"TaskKey": task_key},+ headers=self._request_headers(api_key),+ )+ rsp.raise_for_status()+ data = _unwrap_connector_response(rsp.json())+ task = data.get("Task") or data.get("task")+ if task is None:+ return data+ if not isinstance(task, dict):+ raise InternalError("Connector task response contains an invalid Task object")+ return taskdiff --git a/openviking/server/auth/__init__.py b/openviking/server/auth/__init__.pyindex 5f245b901..593b6594c 100644--- a/openviking/server/auth/__init__.py+++ b/openviking/server/auth/__init__.py@@ -136,6 +136,8 @@ async def get_request_context(identity: ResolvedIdentity = Depends(resolve_identity),x_openviking_actor_peer: Optional[str] = Header(None, alias="X-OpenViking-Actor-Peer"),x_openviking_agent: Optional[str] = Header(None, alias="X-OpenViking-Agent"),+ x_api_key_ctx: Optional[str] = Header(None, alias="X-API-Key"),+ authorization_ctx: Optional[str] = Header(None, alias="Authorization"),) -> RequestContext:"""Convert ResolvedIdentity to RequestContext."""path = request.url.path@@ -146,6 +148,8 @@ async def get_request_context(x_openviking_agent,)+ raw_api_key = _extract_api_key(x_api_key_ctx, authorization_ctx)+ctx = RequestContext(user=UserIdentifier(identity.account_id or "default",@@ -155,6 +159,7 @@ async def get_request_context(actor_peer_id=actor_peer_id,legacy_agent_id=legacy_agent_id,from_oauth=identity.from_oauth,+ api_key=raw_api_key,)# Update the unified root observability context after authentication succeeds.update_root_span_identity(diff --git a/openviking/server/identity.py b/openviking/server/identity.pyindex 87bb053ee..2673fa538 100644--- a/openviking/server/identity.py+++ b/openviking/server/identity.py@@ -105,6 +105,9 @@ class RequestContext:# prevent a stolen access token from laundering itself into a long-lived# refresh-token chain.from_oauth: bool = False+ # Raw API key from the request — used by Connector to call back into OV+ # on behalf of the original user+ api_key: Optional[str] = field(default=None, repr=False)@propertydef account_id(self) -> str:diff --git a/openviking/server/local_input_guard.py b/openviking/server/local_input_guard.pyindex 9fdaccf20..30e67176e 100644--- a/openviking/server/local_input_guard.py+++ b/openviking/server/local_input_guard.py@@ -12,7 +12,9 @@ from openviking.utils.network_guard import ensure_public_remote_targetfrom openviking_cli.exceptions import PermissionDeniedError_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[\\/]")-_REMOTE_SOURCE_PREFIXES = ("http://", "https://", "git@", "ssh://", "git://")+_NETWORK_SOURCE_PREFIXES = ("http://", "https://", "git@", "ssh://", "git://")+_PRIVATE_SOURCE_PREFIXES = ("tos://",)+_REMOTE_SOURCE_PREFIXES = _NETWORK_SOURCE_PREFIXES + _PRIVATE_SOURCE_PREFIXES# Shape of temp_file_ids minted by TempUploadStore. Used by MCP add_resource to# detect when an agent has passed a tfid as the `path` argument by mistake and@@ -20,9 +22,24 @@ _REMOTE_SOURCE_PREFIXES = ("http://", "https://", "git@", "ssh://", "git://")TEMP_FILE_ID_RE = re.compile(r"^(upload_|shared_)[a-zA-Z0-9]+(\.[^/\\]+)?$")+def _is_configured_connector_source(source: str) -> bool:+ """Return whether Connector is enabled for the source URL scheme."""+ try:+ from openviking_cli.utils.config.open_viking_config import get_openviking_config++ config = get_openviking_config().connector+ except Exception:+ return False++ if not config.enable:+ return False+ allowed_schemes = tuple(f"{add_type}://" for add_type in config.allowed_add_types)+ return source.startswith(allowed_schemes)++def is_remote_resource_source(source: str) -> bool:"""Return True if *source* is a remotely fetchable resource location."""- return source.startswith(_REMOTE_SOURCE_PREFIXES)+ return source.startswith(_REMOTE_SOURCE_PREFIXES) or _is_configured_connector_source(source)def looks_like_local_path(value: str) -> bool:@@ -44,7 +61,8 @@ def require_remote_resource_source(source: str) -> str:"HTTP server only accepts remote resource URLs or temp-uploaded files; ""direct host filesystem paths are not allowed.")- ensure_public_remote_target(source)+ if source.startswith(_NETWORK_SOURCE_PREFIXES):+ ensure_public_remote_target(source)return sourcediff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex c1faff13b..2cc946861 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -44,7 +44,7 @@ from openviking.retrieve.type_quota_recall import (DEFAULT_QUOTAS,search_type_quota_recall,)-from openviking.server.auth import resolve_actor_peer_headers, resolve_identity+from openviking.server.auth import _extract_api_key, resolve_actor_peer_headers, resolve_identityfrom openviking.server.dependencies import get_server_config, get_servicefrom openviking.server.identity import RequestContextfrom openviking.server.local_input_guard import (@@ -150,11 +150,13 @@ class _IdentityASGIMiddleware:return await self.app(scope, receive, send)request = Request(scope)+ x_api_key = request.headers.get("x-api-key")+ authorization = request.headers.get("authorization")try:identity = await resolve_identity(request,- x_api_key=request.headers.get("x-api-key"),- authorization=request.headers.get("authorization"),+ x_api_key=x_api_key,+ authorization=authorization,x_openviking_account=request.headers.get("x-openviking-account"),x_openviking_user=request.headers.get("x-openviking-user"),)@@ -195,6 +197,7 @@ class _IdentityASGIMiddleware:actor_peer_id=actor_peer_id,legacy_agent_id=legacy_agent_id,from_oauth=identity.from_oauth,+ api_key=_extract_api_key(x_api_key, authorization),)url_info = {"x_forwarded_proto": request.headers.get("x-forwarded-proto"),@@ -531,6 +534,7 @@ async def add_resource(description: str = "",watch_interval: float = 0,to: str = "",+ parent: str = "",args: Optional[dict[str, Any]] = None,) -> str:"""Add a resource to OpenViking. Asynchronous — processing happens in the background.@@ -552,6 +556,8 @@ async def add_resource(Only applies to remote-URL invocations.to: Target URI under viking://resources/ (e.g. "viking://resources/volcengine/OpenViking").Leave empty to derive a URI from the source.+ parent: Parent URI under viking://resources/ for remote imports. Mutually exclusive+ with ``to``.args: Parser-specific options, e.g. {"feishu_access_token": "..."} for Feishu imports,or {"site": true} for whole-site ingestion."""@@ -616,6 +622,7 @@ async def add_resource(path=path,ctx=ctx,to=to or None,+ parent=parent or None,reason=description,wait=False,watch_interval=watch_interval,@@ -625,15 +632,19 @@ async def add_resource(except Exception as exc:return f"Error adding resource: {exc}"root_uri = result.get("root_uri", "")+ task_id = result.get("task_id", "")if watch_interval > 0:watch_suffix = f" (watch enabled, refresh every {watch_interval:g} minute(s))"else:watch_suffix = ""- message = (- f"Resource added: {root_uri}{watch_suffix}"- if root_uri- else f"Resource added (processing in background){watch_suffix}."- )+ if root_uri:+ message = f"Resource added: {root_uri}{watch_suffix}"+ elif task_id:+ message = (+ f"Resource accepted (task_id: {task_id}; processing in background){watch_suffix}."+ )+ else:+ message = f"Resource added (processing in background){watch_suffix}."# Detect-and-suggest: if this single page belongs to a site that exposes a# sitemap/RSS feed, hint at whole-site ingestion. Never auto-crawls; the# add above is already done, so a slow/failed probe has no functional impact.diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex b738b60c8..a42ccbf41 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -16,6 +16,9 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Dict, List, Optional+import httpx++from openviking.connector.client import ConnectorClientfrom openviking.core.content_targets import ContentTargetSpecfrom openviking.core.uri_validation import validate_optional_content_target_urifrom openviking.resource.feishu_watch_auth import (@@ -54,6 +57,7 @@ from openviking.utils.skill_processor import SkillProcessingPreparation, SkillPrfrom openviking_cli.exceptions import (ConflictError,DeadlineExceededError,+ InternalError,InvalidArgumentError,NotInitializedError,)@@ -658,6 +662,28 @@ class ResourceService:if default_parent:parent = default_parentkwargs["create_parent"] = True++ if self._should_use_connector(+ path,+ ctx=ctx,+ to=to,+ parent=parent,+ wait=wait,+ reason=reason,+ instruction=instruction,+ build_index=build_index,+ summarize=summarize,+ watch_interval=watch_interval,+ connector_args=args or {},+ kwargs=kwargs,+ ):+ return await self._add_resource_via_connector(+ path=path,+ ctx=ctx,+ parent=parent,+ **kwargs,+ )+if not wait and is_git_repo_url(path):return await self.enqueue_git_add_resource(path=path,@@ -1125,6 +1151,366 @@ class ResourceService:request_wait_tracker.cleanup(telemetry_id)unregister_wait_telemetry(telemetry_id)+ # ── Connector routing ──++ # Schemes only the external Connector can import; the standard pipeline+ # has no accessor for them, so degrading to it would only fail later with+ # a misleading parse error.+ _CONNECTOR_ONLY_SCHEMES = ("tos://",)++ def _should_use_connector(+ self,+ path: str,+ *,+ ctx: Optional[RequestContext] = None,+ to: Optional[str] = None,+ parent: Optional[str] = None,+ wait: bool = False,+ reason: str = "",+ instruction: str = "",+ build_index: bool = True,+ summarize: bool = False,+ watch_interval: float = 0,+ connector_args: Optional[Dict[str, Any]] = None,+ kwargs: Optional[Dict[str, Any]] = None,+ ) -> bool:+ """Decide whether a top-level resource path belongs to Connector.++ Returns True to delegate to the Connector, False to route to the+ standard pipeline. A source type only the Connector can import+ (tos://) raises InvalidArgumentError when the Connector is disabled,+ does not allow the type, or cannot honor the request parameters —+ degrading such a request would only fail later with a misleading+ parse error. Source types the standard pipeline can also handle+ degrade to it instead when parameters are unsupported.+ """+ from openviking_cli.utils.config.open_viking_config import get_openviking_config++ if not isinstance(path, str):+ return False+ connector_only = path.startswith(self._CONNECTOR_ONLY_SCHEMES)++ config = get_openviking_config().connector+ # Match full URL schemes, not bare prefixes: "tos" must not capture+ # paths like "tostring://..." or a local file named "tos_notes.md".+ allowed_schemes = tuple(f"{add_type}://" for add_type in config.allowed_add_types)+ if not config.enable or not path.startswith(allowed_schemes):+ if connector_only:+ raise InvalidArgumentError(+ f"'{path}' can only be imported through the Connector integration, "+ "which is disabled or does not allow this source type."+ )+ return False++ if ctx is not None and (to or parent):+ target = ContentTargetSpec.from_fields(+ ctx=ctx,+ kind="resource",+ to=to,+ parent=parent,+ create_parent=bool((kwargs or {}).get("create_parent", False)),+ )+ to = target.to+ parent = target.parent++ unsupported = self._unsupported_connector_params(+ wait=wait,+ reason=reason,+ instruction=instruction,+ build_index=build_index,+ summarize=summarize,+ watch_interval=watch_interval,+ connector_args=connector_args or {},+ kwargs=kwargs or {},+ to=to,+ parent=parent,+ )+ if not unsupported:+ return True+ detail = "; ".join(unsupported)+ if connector_only:+ raise InvalidArgumentError(f"Connector import does not support: {detail}")+ logger.info(+ f"[ResourceService] Connector does not support {detail} for path {path}; "+ "falling back to the standard import pipeline"+ )+ return False++ @staticmethod+ def _unsupported_connector_params(+ *,+ wait: bool,+ reason: str,+ instruction: str,+ build_index: bool,+ summarize: bool,+ watch_interval: float,+ connector_args: Dict[str, Any],+ kwargs: Dict[str, Any],+ to: Optional[str] = None,+ parent: Optional[str] = None,+ ) -> List[str]:+ """add_resource params the Connector delegation cannot honor.++ Returns an empty list when the request is fully supported.+ """+ unsupported: List[str] = []+ if to:+ unsupported.append(+ "exact 'to' targets (Connector imports require a parent destination)"+ )+ if (+ parent+ and parent != "viking://resources"+ and not parent.startswith("viking://resources/")+ ):+ unsupported.append("parent outside the public resources root (viking://resources/...)")+ if watch_interval > 0:+ unsupported.append("watch_interval>0 (Connector imports cannot be watched yet)")+ if wait:+ unsupported.append(+ "wait=true (Connector imports run asynchronously; poll the returned task_id)"+ )+ if reason:+ unsupported.append("reason (Connector imports cannot preserve resource-reason semantics)")+ if instruction:+ unsupported.append("instruction")+ if not build_index:+ unsupported.append("build_index=false")+ if summarize:+ unsupported.append("summarize=true")+ if kwargs.get("strict"):+ unsupported.append("strict=true (Connector imports fail per file, not all-or-nothing)")+ for field in ("ignore_dirs", "include", "exclude"):+ if kwargs.get(field):+ unsupported.append(f"{field} (scope TOS imports with the tos:// path prefix)")+ if kwargs.get("preserve_structure") is False:+ unsupported.append(+ "preserve_structure=false (Connector always mirrors the source directory tree)"+ )+ if not kwargs.get("directly_upload_media", True):+ unsupported.append("directly_upload_media=false")+ if kwargs.get("source_name"):+ unsupported.append("source_name")+ if connector_args:+ unsupported.append(+ "args (Connector imports derive path_prefix from parent; "+ "args keys are not forwarded)"+ )+ return unsupported++ @staticmethod+ def _connector_path_prefix(target_uri: Optional[str]) -> Optional[List[str]]:+ """Map the resolved parent target onto the Connector's path_prefix.++ The TOS plugin composes final URIs as+ viking://resources/<path_prefix>/<source path>/<doc name>, so only+ parent targets under the public resources root can be honored.+ """+ if not target_uri:+ return None+ root = "viking://resources"+ if target_uri == root:+ return None+ if not target_uri.startswith(root + "/"):+ raise InvalidArgumentError(+ "Connector imports can only target the public resources root "+ f"(viking://resources/...), got '{target_uri}'."+ )+ segments = [seg for seg in target_uri[len(root) + 1 :].split("/") if seg]+ return segments or None++ async def _add_resource_via_connector(+ self,+ path: str,+ ctx: RequestContext,+ parent: Optional[str],+ **kwargs: Any,+ ) -> Dict[str, Any]:+ """Route add_resource to the external Connector service."""+ from openviking.service.task_tracker import get_task_tracker+ from openviking_cli.utils.config.open_viking_config import get_openviking_config++ config = get_openviking_config().connector+ if not ctx.api_key:+ raise InvalidArgumentError("Connector import requires an API key in the request.")++ target = ContentTargetSpec.from_fields(+ ctx=ctx,+ kind="resource",+ parent=parent,+ create_parent=bool(kwargs.get("create_parent", False)),+ )+ task_resource_id = target.parent or None+ path_prefix = self._connector_path_prefix(task_resource_id)++ client = ConnectorClient(+ doc_add_url=config.connector,+ task_info_url=config.tracker,+ account_id=ctx.account_id,+ )++ add_type, separator, source_path = path.partition("://")+ source_path = source_path.strip()+ if not separator or not add_type or not source_path:+ raise InvalidArgumentError(+ "Connector import requires path='<add_type>://<source path>'."+ )++ task_tracker = get_task_tracker()+ task = await task_tracker.create(+ "connector_import",+ resource_id=task_resource_id,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )+ try:+ result = await client.submit_doc_add(+ add_type=add_type,+ api_key=ctx.api_key,+ tos_path=source_path,+ path_prefix=path_prefix,+ include_child=True,+ extra_params=None,+ )++ connector_task_key = result.get("task_key") or result.get("TaskKey") or ""+ if not connector_task_key:+ raise InternalError(+ f"Connector accepted the import but returned no task key: {result}"+ )+ except asyncio.CancelledError:+ await task_tracker.fail(+ task.task_id,+ "connector task submission cancelled",+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )+ raise+ except Exception as exc:+ await task_tracker.fail(+ task.task_id,+ str(exc),+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )+ raise++ background = asyncio.create_task(+ self._monitor_connector_task(+ client=client,+ connector_task_key=connector_task_key,+ ov_task_id=task.task_id,+ poll_interval_ms=config.poll_interval_ms,+ timeout_seconds=config.timeout_seconds,+ ctx=ctx,+ )+ )+ self._background_tasks.add(background)+ background.add_done_callback(self._background_tasks.discard)++ response = {+ "status": "accepted",+ "task_id": task.task_id,+ "connector_task_key": connector_task_key,+ }+ if task_resource_id:+ response["resource_id"] = task_resource_id+ return response++ async def _monitor_connector_task(+ self,+ client: ConnectorClient,+ connector_task_key: str,+ ov_task_id: str,+ poll_interval_ms: int,+ timeout_seconds: int,+ ctx: RequestContext,+ ) -> None:+ """Poll the Connector task until terminal state, then update OV TaskRecord."""+ from openviking.service.task_tracker import get_task_tracker++ task_tracker = get_task_tracker()+ await task_tracker.start(+ ov_task_id,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )++ poll_interval = poll_interval_ms / 1000.0+ deadline = time.perf_counter() + timeout_seconds+ terminal_statuses = {"succeeded", "failed", "cancelled"}++ try:+ while time.perf_counter() < deadline:+ await asyncio.sleep(poll_interval)+ try:+ info = await client.get_task_info(connector_task_key, ctx.api_key)+ except httpx.HTTPStatusError as exc:+ status_code = exc.response.status_code+ if status_code not in {408, 429} and status_code < 500:+ raise+ logger.warning(+ "[ResourceService] Transient Connector task polling HTTP error "+ f"for {connector_task_key}: {status_code}; retrying"+ )+ continue+ except httpx.RequestError as exc:+ logger.warning(+ "[ResourceService] Transient Connector task polling error "+ f"for {connector_task_key}: {exc}; retrying"+ )+ continue+ status = (info.get("Status") or info.get("status") or "").lower()++ await task_tracker.update_stage(+ ov_task_id,+ f"connector:{status}",+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )++ if status in terminal_statuses:+ if status == "succeeded":+ await task_tracker.complete(+ ov_task_id,+ {"connector_status": status, "connector_task_key": connector_task_key},+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )+ else:+ error_msg = info.get("ErrorMessage") or info.get("error_message") or status+ await task_tracker.fail(+ ov_task_id,+ f"connector task {status}: {error_msg}",+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )+ return++ await task_tracker.fail(+ ov_task_id,+ f"connector task timed out after {timeout_seconds}s",+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )+ except asyncio.CancelledError:+ await task_tracker.fail(+ ov_task_id,+ "background connector task monitoring cancelled",+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )+ raise+ except Exception as exc:+ logger.error(f"[ResourceService] Connector task monitor error: {exc}")+ await task_tracker.fail(+ ov_task_id,+ str(exc),+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ )+async def _handle_watch_task_creation(self,path: str,diff --git a/openviking_cli/utils/config/open_viking_config.py b/openviking_cli/utils/config/open_viking_config.pyindex 45886023c..d7c3fff34 100644--- a/openviking_cli/utils/config/open_viking_config.py+++ b/openviking_cli/utils/config/open_viking_config.py@@ -54,6 +54,38 @@ def _get_config_warning_logger():return logging.getLogger(__name__)+class ConnectorConfig(BaseModel):+ """Configuration for external Connector service."""++ enable: bool = False+ connector: str = ""+ tracker: str = ""+ timeout_seconds: int = 3600+ poll_interval_ms: int = 5000+ allowed_add_types: List[str] = Field(+ default_factory=lambda: ["tos"]+ )++ model_config = {"extra": "forbid"}++ @model_validator(mode="after")+ def _validate(self) -> "ConnectorConfig":+ if self.enable:+ for name, url in (("connector", self.connector), ("tracker", self.tracker)):+ if not url.strip():+ raise ValueError(f"connector.{name} is required when connector.enable=true")+ if "://" not in url:+ raise ValueError(+ f"connector.{name} must be a full endpoint URL including scheme "+ "(e.g., http://...)"+ )+ if self.timeout_seconds <= 0:+ raise ValueError("connector.timeout_seconds must be > 0")+ if self.poll_interval_ms <= 0:+ raise ValueError("connector.poll_interval_ms must be > 0")+ return self++class ParserApiConfig(BaseModel):"""Configuration for the Understanding files/responses API."""@@ -202,6 +234,11 @@ class OpenVikingConfig(BaseModel):description="Third-party parser API configuration (files/responses)",)+ connector: ConnectorConfig = Field(+ default_factory=ConnectorConfig,+ description="External Connector service configuration for data import",+ )+auto_generate_l0: bool = Field(default=True, description="Automatically generate L0 (abstract) if not provided")diff --git a/tests/connector/test_client.py b/tests/connector/test_client.pynew file mode 100644index 000000000..26bcff9d6--- /dev/null+++ b/tests/connector/test_client.py@@ -0,0 +1,94 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Focused tests for the external Connector HTTP contract."""++from types import SimpleNamespace++import pytest++from openviking.connector import client as client_module+from openviking.connector.client import ConnectorClient, _unwrap_connector_response+from openviking_cli.exceptions import InternalError+++class _FakeAsyncClient:+ response_payload = {}+ calls = []++ def __init__(self, *, timeout):+ self.timeout = timeout++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return None++ async def post(self, url, *, json, headers):+ self.calls.append({"url": url, "json": json, "headers": headers, "timeout": self.timeout})+ return SimpleNamespace(+ raise_for_status=lambda: None,+ json=lambda: self.response_payload,+ )++[email protected](autouse=True)+def _fake_httpx(monkeypatch):+ _FakeAsyncClient.calls = []+ _FakeAsyncClient.response_payload = {}+ monkeypatch.setattr(client_module.httpx, "AsyncClient", _FakeAsyncClient)+++async def test_submit_doc_add_sends_controlled_payload_and_auth_headers():+ _FakeAsyncClient.response_payload = {"code": 0, "data": {"task_key": "connector-1"}}+ client = ConnectorClient("https://connector/doc/add", "https://tracker/task/info", "acct")++ result = await client.submit_doc_add(+ add_type="tos",+ api_key="secret",+ tos_path="bucket/prefix",+ path_prefix=["docs"],+ include_child=False,+ extra_params={"parser": "pdf", "api_key": "must-not-leak"},+ )++ assert result == {"task_key": "connector-1"}+ assert _FakeAsyncClient.calls == [+ {+ "url": "https://connector/doc/add",+ "json": {+ "add_type": "tos",+ "backend": "ov",+ "include_child": False,+ "tos_path": "bucket/prefix",+ "path_prefix": ["docs"],+ "parser": "pdf",+ },+ "headers": {+ "V-Account-Id": "acct",+ "Authorization": "Bearer secret",+ },+ "timeout": 30.0,+ }+ ]+++async def test_get_task_info_unwraps_task_object():+ _FakeAsyncClient.response_payload = {+ "code": 0,+ "data": {"Task": {"TaskKey": "connector-1", "Status": "running"}},+ }+ client = ConnectorClient("https://connector/doc/add", "https://tracker/task/info")++ result = await client.get_task_info("connector-1", "Bearer secret")++ assert result == {"TaskKey": "connector-1", "Status": "running"}+ assert _FakeAsyncClient.calls[0]["json"] == {"TaskKey": "connector-1"}+ assert _FakeAsyncClient.calls[0]["headers"] == {"Authorization": "Bearer secret"}+++def test_connector_business_error_is_not_treated_as_success():+ with pytest.raises(InternalError, match=r"code=1003.*permission denied"):+ _unwrap_connector_response({"code": 1003, "message": "permission denied", "data": {}})diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 017baed28..a9af214c1 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -272,6 +272,43 @@ async def test_mcp_middleware_sets_actor_peer_context():assert response.status_code == 200+ ("headers", "expected_api_key"),+ [+ ({"X-API-Key": "api-key-secret"}, "api-key-secret"),+ ({"Authorization": "Bearer bearer-secret"}, "bearer-secret"),+ ({}, None),+ ],+)+async def test_mcp_middleware_propagates_request_api_key(headers, expected_api_key):+ async def downstream(scope, receive, send):+ assert _get_ctx().api_key == expected_api_key+ response = httpx.Response(200, json={"ok": True})+ await send(+ {+ "type": "http.response.start",+ "status": response.status_code,+ "headers": [(b"content-type", b"application/json")],+ }+ )+ await send({"type": "http.response.body", "body": response.content})++ app = FastAPI()+ app.state.config = SimpleNamespace(get_effective_auth_mode=lambda: AuthMode.DEV)+ app.state.auth_plugin = DevAuthPlugin()+ app.routes.append(Route("/mcp", endpoint=_IdentityASGIMiddleware(downstream), methods=["POST"]))++ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://ov.test") as client:+ response = await client.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "ping"},+ headers=headers,+ )++ assert response.status_code == 200++async def test_mcp_middleware_rejects_invalid_actor_peer_header():async def downstream(scope, receive, send):raise AssertionError("invalid actor peer header should not reach downstream app")@@ -514,6 +551,40 @@ async def test_add_resource_remote_url_is_ingested(service, monkeypatch):assert captured["enforce_public_remote_targets"] is True+async def test_add_resource_remote_async_result_exposes_task_id(service, monkeypatch):+ async def fake_add_resource(*, path, ctx, **kwargs):+ return {+ "status": "accepted",+ "task_id": "ov-task-123",+ "connector_task_key": "connector-task-456",+ }++ monkeypatch.setattr(service.resources, "add_resource", fake_add_resource)++ result = await add_resource(path="tos://bucket/docs")++ assert "task_id: ov-task-123" in result+ assert "processing in background" in result+++async def test_add_resource_remote_parent_is_forwarded(service, monkeypatch):+ captured = {}++ async def fake_add_resource(*, path, ctx, **kwargs):+ captured.update(kwargs)+ return {"task_id": "ov-task-123"}++ monkeypatch.setattr(service.resources, "add_resource", fake_add_resource)++ await add_resource(+ path="tos://bucket/docs",+ parent="viking://resources/imports",+ )++ assert captured["parent"] == "viking://resources/imports"+ assert captured["to"] is None++async def test_add_resource_temp_file_id_branch_resolves_and_ingests(service, upload_temp_dir, monkeypatch):diff --git a/tests/service/test_resource_service_connector.py b/tests/service/test_resource_service_connector.pynew file mode 100644index 000000000..007b7ae38--- /dev/null+++ b/tests/service/test_resource_service_connector.py@@ -0,0 +1,469 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Core routing and task-state tests for Connector imports."""++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock++import httpx+import pytest++from openviking.server.identity import RequestContext, Role+from openviking.service import resource_service as resource_service_module+from openviking.service.resource_service import ResourceService+from openviking_cli.exceptions import InvalidArgumentError+from openviking_cli.session.user_id import UserIdentifier+++class _BackgroundTask:+ def add_done_callback(self, _callback):+ pass+++def connector_config(monkeypatch):+ import openviking_cli.utils.config.open_viking_config as config_module++ config = SimpleNamespace(+ enable=True,+ connector="https://connector.example/doc/add",+ tracker="https://connector.example/task/info",+ timeout_seconds=60,+ poll_interval_ms=10,+ allowed_add_types=["tos"],+ )+ monkeypatch.setattr(+ config_module,+ "get_openviking_config",+ lambda: SimpleNamespace(connector=config),+ )+ return config+++def ctx():+ return RequestContext(+ user=UserIdentifier("acct", "alice"),+ role=Role.USER,+ api_key="secret",+ )+++def service():+ return ResourceService(+ vikingdb=object(),+ viking_fs=object(),+ resource_processor=object(),+ skill_processor=object(),+ )+++def _task_tracker():+ return SimpleNamespace(+ create=AsyncMock(return_value=SimpleNamespace(task_id="task-1")),+ start=AsyncMock(),+ update_stage=AsyncMock(),+ complete=AsyncMock(),+ fail=AsyncMock(),+ )+++def _install_connector_dependencies(monkeypatch, tracker, connector_client):+ monkeypatch.setattr(+ "openviking.service.task_tracker.get_task_tracker",+ lambda: tracker,+ )+ monkeypatch.setattr(+ resource_service_module,+ "ConnectorClient",+ lambda **_kwargs: connector_client,+ )++ def discard_monitor(coro):+ coro.close()+ return _BackgroundTask()++ monkeypatch.setattr(resource_service_module.asyncio, "create_task", discard_monitor)+++async def test_add_resource_routes_tos_to_connector(+ monkeypatch,+ connector_config,+ ctx,+ service,+):+ tracker = _task_tracker()+ connector_client = SimpleNamespace(+ submit_doc_add=AsyncMock(return_value={"task_key": "connector-1"})+ )+ _install_connector_dependencies(monkeypatch, tracker, connector_client)++ result = await service.add_resource(+ path="tos://bucket/a/b/c",+ ctx=ctx,+ parent="viking://resources/x/y",+ )++ assert result == {+ "status": "accepted",+ "task_id": "task-1",+ "connector_task_key": "connector-1",+ "resource_id": "viking://resources/x/y",+ }+ connector_client.submit_doc_add.assert_awaited_once_with(+ add_type="tos",+ api_key="secret",+ tos_path="bucket/a/b/c",+ path_prefix=["x", "y"],+ include_child=True,+ extra_params=None,+ )+ tracker.create.assert_awaited_once_with(+ "connector_import",+ resource_id="viking://resources/x/y",+ account_id="acct",+ user_id="alice",+ )+++async def test_add_resource_uses_source_scheme_as_connector_add_type(+ monkeypatch,+ connector_config,+ ctx,+ service,+):+ connector_config.allowed_add_types = ["s3", "tos"]+ tracker = _task_tracker()+ connector_client = SimpleNamespace(+ submit_doc_add=AsyncMock(return_value={"task_key": "connector-1"})+ )+ _install_connector_dependencies(monkeypatch, tracker, connector_client)++ await service.add_resource(+ path="s3://bucket/prefix",+ ctx=ctx,+ parent="viking://resources/imports",+ )++ connector_client.submit_doc_add.assert_awaited_once_with(+ add_type="s3",+ api_key="secret",+ tos_path="bucket/prefix",+ path_prefix=["imports"],+ include_child=True,+ extra_params=None,+ )+++async def test_connector_import_persists_task_before_remote_submission(+ monkeypatch,+ connector_config,+ ctx,+ service,+):+ tracker = _task_tracker()++ async def fail_submission(**_kwargs):+ tracker.create.assert_awaited_once()+ raise RuntimeError("submission failed")++ connector_client = SimpleNamespace(+ submit_doc_add=AsyncMock(side_effect=fail_submission)+ )+ _install_connector_dependencies(monkeypatch, tracker, connector_client)++ with pytest.raises(RuntimeError, match="submission failed"):+ await service.add_resource(+ path="tos://bucket/prefix",+ ctx=ctx,+ parent="viking://resources/imports",+ )++ tracker.fail.assert_awaited_once_with(+ "task-1",+ "submission failed",+ account_id="acct",+ user_id="alice",+ )+++async def test_connector_import_rejects_exact_to_target(+ connector_config,+ ctx,+ service,+):+ with pytest.raises(InvalidArgumentError, match="exact 'to' targets"):+ await service.add_resource(+ path="tos://bucket/a/b/c",+ ctx=ctx,+ to="viking://resources/x/y",+ )+++def test_connector_only_route_rejects_disabled_or_unsupported_requests(+ connector_config,+ service,+):+ assert service._should_use_connector("https://example.com/doc") is False++ with pytest.raises(InvalidArgumentError, match="wait=true"):+ service._should_use_connector("tos://bucket/prefix", wait=True)++ with pytest.raises(InvalidArgumentError, match="reason"):+ service._should_use_connector("tos://bucket/prefix", reason="needed for Q3 planning")++ connector_config.enable = False+ with pytest.raises(InvalidArgumentError, match="Connector integration"):+ service._should_use_connector("tos://bucket/prefix")+++ ("path", "target"),+ [+ (+ "https://example.com/manual.pdf",+ {"to": "viking://resources/manual.pdf"},+ ),+ (+ "http://example.com/manual.pdf",+ {"parent": "viking://user/alice/resources/manuals"},+ ),+ (+ "git://example.com/repository.git",+ {"parent": "viking://user/alice/peers/bob/resources/manuals"},+ ),+ ],+)+def test_shared_connector_sources_fall_back_for_unsupported_targets(+ connector_config,+ service,+ path,+ target,+):+ connector_config.allowed_add_types = ["https", "http", "git"]++ assert service._should_use_connector(path, **target) is False+++ "parent",+ ["viking://resources/manuals", "resources/manuals"],+)+def test_connector_route_accepts_public_parent(connector_config, ctx, service, parent):+ connector_config.allowed_add_types = ["https"]++ assert (+ service._should_use_connector(+ "https://example.com/manual.pdf",+ ctx=ctx,+ parent=parent,+ )+ is True+ )+++async def test_add_resource_falls_back_for_shared_source_with_exact_to(+ monkeypatch,+ connector_config,+ ctx,+ service,+):+ connector_config.allowed_add_types = ["https"]+ monkeypatch.setattr(resource_service_module, "is_git_repo_url", lambda _path: True)+ service._add_resource_via_connector = AsyncMock()+ service.enqueue_git_add_resource = AsyncMock(return_value={"root_uri": "standard-pipeline"})++ result = await service.add_resource(+ path="https://example.com/manual.pdf",+ ctx=ctx,+ to="viking://resources/manual.pdf",+ )++ assert result == {"root_uri": "standard-pipeline"}+ service._add_resource_via_connector.assert_not_awaited()+ service.enqueue_git_add_resource.assert_awaited_once()+++async def test_connector_import_without_target_keeps_resource_id_unset(+ monkeypatch,+ connector_config,+ ctx,+ service,+):+ tracker = _task_tracker()+ connector_client = SimpleNamespace(+ submit_doc_add=AsyncMock(return_value={"TaskKey": "connector-1"})+ )+ _install_connector_dependencies(monkeypatch, tracker, connector_client)++ result = await service._add_resource_via_connector(+ path="tos://bucket/prefix",+ ctx=ctx,+ parent=None,+ )++ assert "resource_id" not in result+ assert tracker.create.await_args.kwargs["resource_id"] is None+++async def test_connector_import_rejects_target_outside_public_resources_root(+ connector_config,+ ctx,+ service,+):+ with pytest.raises(InvalidArgumentError, match="public resources root"):+ await service.add_resource(+ path="tos://bucket/prefix",+ ctx=ctx,+ parent="viking://user/alice/resources/spec",+ )+++async def test_connector_import_rejects_nonempty_args(+ connector_config,+ ctx,+ service,+):+ with pytest.raises(InvalidArgumentError, match="args"):+ await service.add_resource(+ path="tos://bucket/prefix",+ ctx=ctx,+ parent="viking://resources/spec",+ args={"parser": "pdf"},+ )+++ ("task_info", "expected_stage", "expected_error"),+ [+ ({"Status": "succeeded"}, "connector:succeeded", None),+ (+ {"status": "failed", "error_message": "source unavailable"},+ "connector:failed",+ "connector task failed: source unavailable",+ ),+ ],+)+async def test_monitor_connector_task_maps_terminal_status(+ monkeypatch,+ connector_config,+ ctx,+ task_info,+ expected_stage,+ expected_error,+):+ tracker = _task_tracker()+ monkeypatch.setattr(+ "openviking.service.task_tracker.get_task_tracker",+ lambda: tracker,+ )++ async def no_sleep(_seconds):+ pass++ monkeypatch.setattr(resource_service_module.asyncio, "sleep", no_sleep)+ client = SimpleNamespace(get_task_info=AsyncMock(return_value=task_info))++ await ResourceService()._monitor_connector_task(+ client=client,+ connector_task_key="connector-1",+ ov_task_id="task-1",+ poll_interval_ms=1,+ timeout_seconds=1,+ ctx=ctx,+ )++ assert tracker.update_stage.await_args.args[1] == expected_stage+ if expected_error is None:+ tracker.complete.assert_awaited_once()+ tracker.fail.assert_not_awaited()+ else:+ assert tracker.fail.await_args.args[1] == expected_error+ tracker.complete.assert_not_awaited()+++async def test_monitor_connector_task_retries_transient_polling_error(+ monkeypatch,+ connector_config,+ ctx,+):+ tracker = _task_tracker()+ monkeypatch.setattr(+ "openviking.service.task_tracker.get_task_tracker",+ lambda: tracker,+ )++ async def no_sleep(_seconds):+ pass++ monkeypatch.setattr(resource_service_module.asyncio, "sleep", no_sleep)+ client = SimpleNamespace(+ get_task_info=AsyncMock(+ side_effect=[+ httpx.ReadTimeout("temporary timeout"),+ {"Status": "succeeded"},+ ]+ )+ )++ await ResourceService()._monitor_connector_task(+ client=client,+ connector_task_key="connector-1",+ ov_task_id="task-1",+ poll_interval_ms=1,+ timeout_seconds=1,+ ctx=ctx,+ )++ assert client.get_task_info.await_count == 2+ tracker.complete.assert_awaited_once()+ tracker.fail.assert_not_awaited()+++async def test_monitor_connector_task_marks_cancelled_monitor_as_failed(+ monkeypatch,+ connector_config,+ ctx,+):+ tracker = _task_tracker()+ monkeypatch.setattr(+ "openviking.service.task_tracker.get_task_tracker",+ lambda: tracker,+ )++ async def cancelled_sleep(_seconds):+ raise asyncio.CancelledError++ monkeypatch.setattr(resource_service_module.asyncio, "sleep", cancelled_sleep)+ client = SimpleNamespace(get_task_info=AsyncMock())++ with pytest.raises(asyncio.CancelledError):+ await ResourceService()._monitor_connector_task(+ client=client,+ connector_task_key="connector-1",+ ov_task_id="task-1",+ poll_interval_ms=1,+ timeout_seconds=1,+ ctx=ctx,+ )++ tracker.fail.assert_awaited_once_with(+ "task-1",+ "background connector task monitoring cancelled",+ account_id="acct",+ user_id="alice",+ )+ tracker.complete.assert_not_awaited()diff --git a/tests/unit/test_connector_config.py b/tests/unit/test_connector_config.pynew file mode 100644index 000000000..f16d21a96--- /dev/null+++ b/tests/unit/test_connector_config.py@@ -0,0 +1,59 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Focused tests for Connector configuration."""++import pytest++from openviking_cli.utils.config.open_viking_config import ConnectorConfig, OpenVikingConfig+++def test_connector_config_is_opt_in_and_tos_only_by_default():+ config = ConnectorConfig()++ assert config.enable is False+ assert config.allowed_add_types == ["tos"]+++def test_openviking_config_parses_connector_section():+ config = OpenVikingConfig.from_dict(+ {+ "connector": {+ "enable": True,+ "connector": "https://connector.example/doc/add",+ "tracker": "https://connector.example/task/info",+ "timeout_seconds": 120,+ "poll_interval_ms": 250,+ "allowed_add_types": ["tos"],+ }+ }+ )++ assert config.connector.model_dump() == {+ "enable": True,+ "connector": "https://connector.example/doc/add",+ "tracker": "https://connector.example/task/info",+ "timeout_seconds": 120,+ "poll_interval_ms": 250,+ "allowed_add_types": ["tos"],+ }+++ ("kwargs", "match"),+ [+ ({"enable": True}, "connector.connector is required"),+ (+ {+ "enable": True,+ "connector": "connector.example/doc/add",+ "tracker": "https://connector.example/task/info",+ },+ "must be a full endpoint URL",+ ),+ ({"timeout_seconds": 0}, "timeout_seconds must be > 0"),+ ({"poll_interval_ms": 0}, "poll_interval_ms must be > 0"),+ ],+)+def test_connector_config_rejects_invalid_runtime_settings(kwargs, match):+ with pytest.raises(ValueError, match=match):+ ConnectorConfig(**kwargs)