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(resources): support TOS auth args for HTTP imports (#4248)
Jiahui Zhou604275f272a1
diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.mdindex 3260725a5..e52e432b9 100644--- a/docs/en/api/02-resources.md+++ b/docs/en/api/02-resources.md@@ -177,7 +177,7 @@ This endpoint is the core entry point for resource management, supporting adding| exclude | string | No | None | File patterns to exclude (glob) || directly_upload_media | bool | No | True | Whether to directly upload media files || preserve_structure | bool | No | None | Whether to preserve directory structure |-| args | object | No | `{}` | Parser-specific import options forwarded to the source parser/accessor. Native HTTPS Git imports and watches accept HTTP Basic credentials over TLS as `args.auth_config={"username":"oauth2","token":"..."}`; `username` defaults to `oauth2`. Git `branch` or `commit` remains at the top level of `args`. `args.parse_mode` accepts `default` (existing splitting behavior) or `no_split` (parse and convert each source document to one Markdown body). E.g. `args.site=true/false` forces/opts out of whole-site (sitemap/RSS) ingestion, `args.max_pages` etc. override the `webfeed` config; the recursive web crawler accepts `args.depth`, `args.max_pages`, `args.include_paths`, `args.exclude_paths`, `args.allow_external_links`, `args.skip_download_links`; Feishu user-token imports pass `args.feishu_access_token`. Core `add_resource` fields such as `path`, `to`, `watch_interval`, `include`, and `exclude` are not allowed inside `args` |+| args | object | No | `{}` | Parser-specific import options forwarded to the source parser/accessor. Native HTTPS Git imports and watches accept HTTP Basic credentials over TLS as `args.auth_config={"username":"oauth2","token":"..."}`; `username` defaults to `oauth2`. Git `branch` or `commit` remains at the top level of `args`. To import a private TOS object through its HTTP(S) URL, pass exactly one non-empty string: `args.tos_signature` (sent as `X-Tos-Signature`) or `args.tos_access` (sent as `X-Tos-Access`). TOS credentials are used only for the current HEAD/GET fetch, which is staged as a snapshot; they are not persisted to resource metadata or queue jobs. `args.parse_mode` accepts `default` (existing splitting behavior) or `no_split` (parse and convert each source document to one Markdown body). E.g. `args.site=true/false` forces/opts out of whole-site (sitemap/RSS) ingestion, `args.max_pages` etc. override the `webfeed` config; the recursive web crawler accepts `args.depth`, `args.max_pages`, `args.include_paths`, `args.exclude_paths`, `args.allow_external_links`, `args.skip_download_links`; Feishu user-token imports pass `args.feishu_access_token`. Core `add_resource` fields such as `path`, `to`, `watch_interval`, `include`, and `exclude` are not allowed inside `args` || watch_interval | float | No | 0 | Scheduled update interval (minutes). >0 creates a task for a re-readable URL/sitemap/RSS source; uploaded `temp_file_id` content is a static snapshot and must be re-added when it changes. <=0 cancels a task; explicit `to` wins, otherwise binds to the imported `root_uri` || processing_mode | string | No | `semantic_and_vectors` | Post-ingest processing mode. `semantic_and_vectors` is the normal flow: generate semantic artifacts (`.abstract.md`, `.overview.md`) and vectors. `vectors_only` skips semantic understanding/VLM summarization and only vectorizes current resource files || telemetry | TelemetryRequest | No | False | Whether to return telemetry data |diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.mdindex ba00c5fec..98f4c28dd 100644--- a/docs/zh/api/02-resources.md+++ b/docs/zh/api/02-resources.md@@ -170,7 +170,7 @@ URL/文件 Parser TreeBuilder AGFS Summarizer/Vector| exclude | string | 否 | None | 排除的文件模式(glob) || directly_upload_media | bool | 否 | True | 是否直接上传媒体文件 || preserve_structure | bool | 否 | None | 是否保留目录结构 |-| args | object | 否 | `{}` | 传给特定 parser/accessor 的导入参数。原生 HTTPS Git 导入和 Watch 可通过 `args.auth_config={"username":"oauth2","token":"..."}` 在 TLS 上传递 HTTP Basic 凭据;`username` 默认为 `oauth2`。Git 的 `branch` 或 `commit` 仍放在 `args` 顶层。`args.parse_mode` 支持 `default`(保持现有拆分行为)和 `no_split`(正常解析并将每个源文档正文保存为一个 Markdown 文件)。例如 `args.site=true/false` 强制/禁用整站(sitemap/RSS)导入,`args.max_pages` 等可覆盖 `webfeed` 配置;递归网页爬虫支持 `args.depth`、`args.max_pages`、`args.include_paths`、`args.exclude_paths`、`args.allow_external_links`、`args.skip_download_links`;飞书用户 token 导入传 `args.feishu_access_token`。`path`、`to`、`watch_interval`、`include`、`exclude` 等 `add_resource` 核心字段不能放入 `args` |+| args | object | 否 | `{}` | 传给特定 parser/accessor 的导入参数。原生 HTTPS Git 导入和 Watch 可通过 `args.auth_config={"username":"oauth2","token":"..."}` 在 TLS 上传递 HTTP Basic 凭据;`username` 默认为 `oauth2`。Git 的 `branch` 或 `commit` 仍放在 `args` 顶层。通过 HTTP(S) URL 导入私有 TOS 对象时,二选一传入非空字符串:`args.tos_signature`(映射为 `X-Tos-Signature`)或 `args.tos_access`(映射为 `X-Tos-Access`)。TOS 凭证只用于当前 HEAD/GET 抓取;资源会先保存为快照,凭证不会写入资源元数据或队列任务。`args.parse_mode` 支持 `default`(保持现有拆分行为)和 `no_split`(正常解析并将每个源文档正文保存为一个 Markdown 文件)。例如 `args.site=true/false` 强制/禁用整站(sitemap/RSS)导入,`args.max_pages` 等可覆盖 `webfeed` 配置;递归网页爬虫支持 `args.depth`、`args.max_pages`、`args.include_paths`、`args.exclude_paths`、`args.allow_external_links`、`args.skip_download_links`;飞书用户 token 导入传 `args.feishu_access_token`。`path`、`to`、`watch_interval`、`include`、`exclude` 等 `add_resource` 核心字段不能放入 `args` || watch_interval | float | 否 | 0 | 定时更新间隔(分钟)。>0 为 URL/sitemap/RSS 等可重新读取的来源创建任务;通过 `temp_file_id` 上传的内容是一次性快照,变化后需重新添加。≤0 取消任务;显式 `to` 优先,否则绑定本次导入的 `root_uri` || processing_mode | string | 否 | `semantic_and_vectors` | 入库后的处理模式。`semantic_and_vectors` 是默认流程:生成语义产物(`.abstract.md`、`.overview.md`)并生成向量。`vectors_only` 跳过语义理解/VLM 总结,只对当前资源文件生成向量 || tags | string[] | 否 | None | 导入时写入向量检索记录的显式检索标签,格式必须是 `k=v`,例如 `["team=search", "env=test"]`。搜索接口可用同名 `tags` 参数过滤召回 |diff --git a/openviking/parse/accessors/http_accessor.py b/openviking/parse/accessors/http_accessor.pyindex 315872a72..395640566 100644--- a/openviking/parse/accessors/http_accessor.py+++ b/openviking/parse/accessors/http_accessor.py@@ -158,6 +158,7 @@ class URLTypeDetector:url: str,timeout: Optional[float] = None,request_validator=None,+ headers: Optional[Mapping[str, str]] = None,) -> Tuple[URLType, Dict[str, Any]]:"""Detect URL content type using IANA standards.@@ -206,7 +207,7 @@ class URLTypeDetector:client_kwargs["trust_env"] = Falseasync with httpx.AsyncClient(**client_kwargs) as client:- response = await client.head(url)+ response = await client.head(url, headers=headers)meta["status_code"] = response.status_codeif not (200 <= response.status_code < 300):@@ -443,12 +444,16 @@ class HTTPAccessor(DataAccessor):"""source_str = str(source)request_validator = kwargs.get("request_validator")+ tos_signature = kwargs.get("tos_signature")+ tos_access = kwargs.get("tos_access")# Download the URL- temp_path, url_type, meta = await self._download_url(- source_str,- request_validator=request_validator,- )+ download_kwargs = {"request_validator": request_validator}+ if tos_signature is not None:+ download_kwargs["tos_signature"] = tos_signature+ if tos_access is not None:+ download_kwargs["tos_access"] = tos_access+ temp_path, url_type, meta = await self._download_url(source_str, **download_kwargs)# Both an extensionless text/html page (WEBPAGE) and an explicit# ``.html``/``.htm`` URL (DOWNLOAD_HTML) are webpages the user may want@@ -532,6 +537,8 @@ class HTTPAccessor(DataAccessor):self,url: str,request_validator=None,+ tos_signature: Optional[str] = None,+ tos_access: Optional[str] = None,) -> Tuple[str, URLType, Dict[str, Any]]:"""Download URL content to a temporary file.@@ -552,6 +559,7 @@ class HTTPAccessor(DataAccessor):url_type, detect_meta = await self._url_detector.detect(url,request_validator=request_validator,+ headers=self._request_headers(tos_signature, tos_access),)temp_path: Optional[str] = None@@ -568,7 +576,7 @@ class HTTPAccessor(DataAccessor):client_kwargs["trust_env"] = Falseasync with httpx.AsyncClient(**client_kwargs) as client:- headers = {"User-Agent": self.user_agent}+ headers = self._request_headers(tos_signature, tos_access)try:response = await client.get(url, headers=headers)response.raise_for_status()@@ -627,6 +635,20 @@ class HTTPAccessor(DataAccessor):passraise+ def _request_headers(+ self,+ tos_signature: Optional[str],+ tos_access: Optional[str],+ ) -> Dict[str, str]:+ headers = {"User-Agent": self.user_agent}+ if tos_signature is not None and tos_access is not None:+ raise ValueError("tos_signature and tos_access cannot both be provided")+ if tos_signature is not None:+ headers["X-Tos-Signature"] = tos_signature+ elif tos_access is not None:+ headers["X-Tos-Access"] = tos_access+ return headers+def _finalize_download_metadata(self,url: str,diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex a56b9c59b..ca2fc1901 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -130,6 +130,7 @@ _ADD_RESOURCE_ARGS_RESERVED_FIELDS = frozenset("tag_mode",})+_ADD_RESOURCE_TRANSIENT_ARGS = frozenset({"tos_signature", "tos_access"})_ADD_RESOURCE_TAG_MODES = frozenset({"replace", "append"})_INTERNAL_INGESTION_FIELDS = frozenset(@@ -725,7 +726,7 @@ class ResourceService:queued_args = {key: valuefor key, value in processor_kwargs.items()- if key not in _ADD_RESOURCE_ARGS_RESERVED_FIELDS+ if key not in _ADD_RESOURCE_ARGS_RESERVED_FIELDS | _ADD_RESOURCE_TRANSIENT_ARGS}queued_args = self._sanitize_watch_processor_kwargs(queued_args)task_auth: Dict[str, Any] = {}@@ -785,7 +786,8 @@ class ResourceService:prepared = await self._resource_processor.prepare_durable_source(path,ctx,- snapshot_required=local_source,+ snapshot_required=local_source+ or bool(processor_kwargs.get("tos_signature") or processor_kwargs.get("tos_access")),parse_mode=mode,allow_local_path_resolution=allow_local_path_resolution,**processor_kwargs,@@ -1293,6 +1295,20 @@ class ResourceService:"field and in args.")kwargs.update(normalized_args.processor_kwargs)+ tos_signature = kwargs.get("tos_signature")+ tos_access = kwargs.get("tos_access")+ if tos_signature is not None or tos_access is not None:+ if not path.startswith(("http://", "https://")):+ raise InvalidArgumentError(+ "tos_signature and tos_access are only supported for HTTP(S) resource URLs."+ )+ if tos_signature is not None and tos_access is not None:+ raise InvalidArgumentError("tos_signature and tos_access cannot both be provided.")+ for field, value in (("tos_signature", tos_signature), ("tos_access", tos_access)):+ if value is not None:+ if not isinstance(value, str) or not value.strip():+ raise InvalidArgumentError(f"args.{field} must be a non-empty string.")+ kwargs[field] = value.strip()git_repo_source = is_git_repo_url(path)if git_repo_source:reject_git_http_userinfo(path)diff --git a/openviking/utils/media_processor.py b/openviking/utils/media_processor.pyindex 589a3ba19..a70bdd48e 100644--- a/openviking/utils/media_processor.py+++ b/openviking/utils/media_processor.py@@ -240,6 +240,8 @@ class UnifiedResourceProcessor:and self._has_prepared_understanding_response(kwargs)):parse_kwargs = dict(kwargs)+ parse_kwargs.pop("tos_signature", None)+ parse_kwargs.pop("tos_access", None)parse_kwargs["instruction"] = instructionparse_kwargs["vlm_processor"] = self._get_vlm_processor()parse_kwargs["storage"] = self.storage@@ -262,6 +264,8 @@ class UnifiedResourceProcessor:and self.should_use_understanding_directly(source, **kwargs)):parse_kwargs = dict(kwargs)+ parse_kwargs.pop("tos_signature", None)+ parse_kwargs.pop("tos_access", None)parse_kwargs["instruction"] = instructionparse_kwargs["vlm_processor"] = self._get_vlm_processor()parse_kwargs["storage"] = self.storage@@ -291,6 +295,8 @@ class UnifiedResourceProcessor:# Source credentials are consumed by the accessor. Never forward# them into parser kwargs, parse results, or later queue payloads.parse_kwargs.pop("auth_config", None)+ parse_kwargs.pop("tos_signature", None)+ parse_kwargs.pop("tos_access", None)parse_kwargs["instruction"] = instructionparse_kwargs["_source_meta"] = local_resource.metaparse_kwargs["resolved_extension"] = kwargs.get(diff --git a/tests/service/test_resource_service_parse_mode.py b/tests/service/test_resource_service_parse_mode.pyindex f91ab68b6..b9e1f08a7 100644--- a/tests/service/test_resource_service_parse_mode.py+++ b/tests/service/test_resource_service_parse_mode.py@@ -260,6 +260,60 @@ async def test_rejects_invalid_parse_mode(service: ResourceService, ctx: Request)+async def test_tos_auth_args_require_http_resource_url(+ service: ResourceService,+ ctx: RequestContext,+):+ with pytest.raises(InvalidArgumentError, match=r"tos_signature and tos_access are only supported"):+ await service.add_resource(+ path="/test/path",+ ctx=ctx,+ to="viking://resources/test",+ args={"tos_signature": "signed-value"},+ )+++async def test_tos_auth_args_are_mutually_exclusive(+ service: ResourceService,+ ctx: RequestContext,+):+ with pytest.raises(InvalidArgumentError, match="cannot both be provided"):+ await service.add_resource(+ path="https://tos.example.com/object",+ ctx=ctx,+ to="viking://resources/test",+ args={+ "tos_signature": "signed-value",+ "tos_access": "access-key",+ },+ )+++async def test_tos_auth_args_are_snapshotted_and_omitted_from_queue(+ service: ResourceService,+ ctx: RequestContext,+):+ prepare_durable_source = AsyncMock(return_value=None)+ service._resource_processor.prepare_durable_source = prepare_durable_source++ await service.add_resource(+ path="https://tos.example.com/object",+ ctx=ctx,+ to="viking://resources/test",+ args={"tos_signature": "signed-value"},+ allow_local_path_resolution=False,+ )++ assert prepare_durable_source.await_args.kwargs["snapshot_required"] is True+ assert prepare_durable_source.await_args.kwargs["tos_signature"] == "signed-value"+ message = service._enqueue_add_resource_job.await_args.args[0]+ assert "tos_signature" not in message.args+ assert "tos_access" not in message.args++@pytest.mark.asyncioasync def test_no_split_allows_directory_flattening(service: ResourceService,diff --git a/tests/unit/test_accessors_http.py b/tests/unit/test_accessors_http.pyindex aa5098f63..62908bfc6 100644--- a/tests/unit/test_accessors_http.py+++ b/tests/unit/test_accessors_http.py@@ -3,7 +3,9 @@"""Unit tests for HTTPAccessor."""from types import SimpleNamespace-from unittest.mock import patch+from unittest.mock import AsyncMock, patch++import httpximport pytest@@ -84,6 +86,122 @@ class TestHTTPAccessor:"""Test filename extraction from URLs."""assert HTTPAccessor._extract_filename_from_url(url) == expected+ @pytest.mark.parametrize(+ ("tos_args", "header_name", "header_value"),+ [+ ({"tos_signature": "signed-value"}, "X-Tos-Signature", "signed-value"),+ ({"tos_access": "access-key"}, "X-Tos-Access", "access-key"),+ ],+ )+ async def test_tos_auth_is_sent_for_head_and_get(+ self, accessor: HTTPAccessor, monkeypatch: pytest.MonkeyPatch, tos_args, header_name, header_value+ ) -> None:+ seen: list[tuple[str, str | None]] = []++ async def handler(request: httpx.Request) -> httpx.Response:+ seen.append((request.method, request.headers.get(header_name)))+ return httpx.Response(+ 200,+ headers={"Content-Type": "text/plain"},+ content=b"TOS resource",+ request=request,+ )++ class Client:+ def __init__(self, **_kwargs):+ self._client = httpx.AsyncClient(transport=httpx.MockTransport(handler))++ async def __aenter__(self):+ return self._client++ async def __aexit__(self, *args):+ await self._client.aclose()++ monkeypatch.setattr(+ "openviking.parse.accessors.http_accessor.lazy_import",+ lambda _name: SimpleNamespace(AsyncClient=Client),+ )++ resource = await accessor.access(+ "https://tos.example.com/object",+ **tos_args,+ )++ try:+ assert seen == [("HEAD", header_value), ("GET", header_value)]+ finally:+ resource.cleanup()++ async def test_tos_auth_args_do_not_reach_parser(+ self, tmp_path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from openviking.parse.accessors.base import LocalResource, SourceType+ from openviking.utils.media_processor import UnifiedResourceProcessor++ source = tmp_path / "resource.txt"+ source.write_text("content", encoding="utf-8")+ local = LocalResource(+ path=source,+ source_type=SourceType.HTTP,+ original_source="https://tos.example.com/object",+ is_temporary=False,+ )+ received: dict[str, object] = {}++ class Registry:+ async def access(self, *_args, **_kwargs):+ return local++ class Router:+ def should_use_understanding_directly(self, *_args, **_kwargs):+ return False++ async def parse(self, _source, **kwargs):+ received.update(kwargs)+ return SimpleNamespace()++ processor = UnifiedResourceProcessor()+ processor._accessor_registry = Registry()+ processor._parser_router = Router()+ monkeypatch.setattr(processor, "_get_vlm_processor", lambda: None)++ await processor.process(+ "https://tos.example.com/object",+ tos_signature="signed-value",+ tos_access="access-key",+ )++ assert "tos_signature" not in received+ assert "tos_access" not in received++ async def test_tos_auth_args_do_not_reach_direct_understanding_parser(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from openviking.utils.media_processor import UnifiedResourceProcessor++ received: dict[str, object] = {}++ class Router:+ def should_use_understanding_directly(self, *_args, **_kwargs):+ return True++ async def parse(self, _source, **kwargs):+ received.update(kwargs)+ return SimpleNamespace()++ processor = UnifiedResourceProcessor()+ processor._parser_router = Router()+ monkeypatch.setattr(processor, "_get_vlm_processor", lambda: None)++ await processor.process(+ "https://tos.example.com/object",+ tos_signature="signed-value",+ tos_access="access-key",+ )++ assert "tos_signature" not in received+ assert "tos_access" not in received+@pytest.mark.parametrize("entry_url_type", [URLType.WEBPAGE, URLType.DOWNLOAD_HTML])async def test_webpage_uses_web_importer_directory(self, accessor, tmp_path, monkeypatch, entry_url_type