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): bind watch tasks to imported root URI (#2378)
Qin Haojieb55df525bc9b
diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.mdindex f1a364ede..561a6cefc 100644--- a/docs/en/api/02-resources.md+++ b/docs/en/api/02-resources.md@@ -88,7 +88,7 @@ Resource incremental updates are implemented via the **Watch Task** mechanism:#### Watch Task Creation- Set `watch_interval > 0` (in minutes) when calling `add_resource` to create a watch task-- Must specify the `to` parameter to define the target URI+- You may specify `to` to define the target URI; if omitted, the task binds to the `root_uri` returned by this import- `WatchManager` handles task persistence- Supports multi-tenant permission control (ROOT/ADMIN/USER permission levels)@@ -149,7 +149,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 |-| watch_interval | float | No | 0 | Scheduled update interval (minutes). >0 creates task; <=0 cancels task |+| watch_interval | float | No | 0 | Scheduled update interval (minutes). >0 creates task; <=0 cancels task; explicit `to` wins, otherwise binds to the imported `root_uri` || telemetry | TelemetryRequest | No | False | Whether to return telemetry data |**Additional Notes**:@@ -157,7 +157,7 @@ This endpoint is the core entry point for resource management, supporting adding- `path` and `temp_file_id` cannot be specified together- Raw HTTP calls for local files require first uploading via [temp_upload](#temp_upload) to obtain `temp_file_id`- When `to` is specified and the target already exists, triggers incremental update-- `watch_interval` only takes effect when `to` is provided+- When `watch_interval > 0`, the watch task binds to `to` if provided; otherwise it binds to the `root_uri` returned by this import. If no stable `root_uri` is available, the request fails and asks for an explicit `to`.- For local directory inputs, scanning respects `.gitignore` files (root and nested) with standard Git semantics; `ignore_dirs`, `include`, and `exclude` further refine what is ingested.- To create or update plain text directly, use [content/write](03-filesystem.md#write) instead of `add_resource`. Semantic processing and embeddings are refreshed automatically after resource ingestion and content writes.@@ -252,6 +252,9 @@ ov add-resource ./documents/guide.md --wait# Enable scheduled updates (check every 60 minutes)ov add-resource https://github.com/example/repo.git --to viking://resources/guide.md --watch-interval 60+# Enable scheduled updates and bind to the URI created by this import+ov add-resource https://github.com/example/repo.git --watch-interval 60+# Cancel scheduled updatesov add-resource https://github.com/example/repo.git --to viking://resources/guide.md --watch-interval 0@@ -423,7 +426,7 @@ list_watches() # one line per task; Ucancel_watch(to_uri="viking://resources/guide.md") # idempotent removal by URI```-Pause / resume / trigger / update are intentionally not exposed via MCP — those power-user operations live on the CLI/REST surface to keep the agent system prompt compact. Creating a watch or changing its cadence from the agent side still goes through [`add_resource`](#add_resource) with `watch_interval` and `to`.+Pause / resume / trigger / update are intentionally not exposed via MCP — those power-user operations live on the CLI/REST surface to keep the agent system prompt compact. Creating a watch or changing its cadence from the agent side still goes through [`add_resource`](#add_resource) with `watch_interval`; pass `to` explicitly or let the system bind to the `root_uri` returned by this import.---diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.mdindex e857e22bd..488ae573b 100644--- a/docs/zh/api/02-resources.md+++ b/docs/zh/api/02-resources.md@@ -83,7 +83,7 @@ URL/文件 Parser TreeBuilder AGFS Summarizer/Vector#### 监控任务创建- 调用 `add_resource` 时设置 `watch_interval > 0` (单位:分钟)创建监控任务-- 需指定 `to` 参数确定目标 URI+- 可指定 `to` 参数确定目标 URI;未指定时,系统会使用本次导入返回的 `root_uri` 作为监控目标- `WatchManager` 负责任务持久化存储- 支持多租户权限控制(ROOT/ADMIN/USER 权限分级)@@ -144,13 +144,13 @@ URL/文件 Parser TreeBuilder AGFS Summarizer/Vector| exclude | string | 否 | None | 排除的文件模式(glob) || directly_upload_media | bool | 否 | True | 是否直接上传媒体文件 || preserve_structure | bool | 否 | None | 是否保留目录结构 |-| watch_interval | float | 否 | 0 | 定时更新间隔(分钟)。>0 创建任务;≤0 取消任务,依赖 `to` 目标指定 |+| watch_interval | float | 否 | 0 | 定时更新间隔(分钟)。>0 创建任务;≤0 取消任务;显式 `to` 优先,否则绑定本次导入的 `root_uri` || telemetry | TelemetryRequest | 否 | False | 是否返回遥测数据 |**补充说明**:- `to` 和 `parent` 不能同时使用;如果使用 `parent` 且希望父目录不存在时自动创建,请传 `create_parent=true`。指定 `to` 且目标已存在时,触发增量更新。- `path` 和 `temp_file_id` 不能同时指定,上传本地文件需要先通过 [temp_upload](#temp_upload) 上传获取 `temp_file_id`,在 SDK 和 CLI 中已经封装好。-- `watch_interval` 仅在指定 `to` 时生效+- `watch_interval > 0` 时,如果指定了 `to`,监控任务绑定该目标;如果未指定 `to`,监控任务绑定本次导入返回的 `root_uri`。如果无法得到稳定 `root_uri`,请求会报错并要求显式传 `to`。- 本地目录输入会遵循 `.gitignore`(根目录和子目录,标准 Git 语义);`ignore_dirs`、`include`、`exclude` 会在此基础上进一步过滤。- 如果要直接创建或更新纯文本内容,请使用 [content/write](03-filesystem.md#write),不要使用 `add_resource`。资源导入和内容写入后都会自动刷新语义与 embedding。@@ -245,6 +245,9 @@ ov add-resource ./documents/guide.md --wait# 开启定时更新(每60分钟检测一次)ov add-resource https://github.com/example/repo.git --to viking://resources/my_repo --watch-interval 60+# 开启定时更新并自动绑定本次导入生成的 URI+ov add-resource https://github.com/example/repo.git --watch-interval 60+# 取消定时更新ov add-resource https://github.com/example/repo.git --to viking://resources/my_repo --watch-interval 0@@ -416,7 +419,7 @@ list_watches() # 每个任务一行cancel_watch(to_uri="viking://resources/guide.md") # 按 URI 幂等删除```-暂停 / 恢复 / 触发 / 更新故意不通过 MCP 暴露——这些 power-user 操作放在 CLI/REST 一侧,以保持 Agent 系统提示词的紧凑。Agent 侧若需创建监控任务或调整周期,仍走 [`add_resource`](#add_resource) 配合 `watch_interval` 和 `to`。+暂停 / 恢复 / 触发 / 更新故意不通过 MCP 暴露——这些 power-user 操作放在 CLI/REST 一侧,以保持 Agent 系统提示词的紧凑。Agent 侧若需创建监控任务或调整周期,仍走 [`add_resource`](#add_resource) 配合 `watch_interval`;可显式传 `to`,也可让系统绑定本次导入返回的 `root_uri`。---diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 1d76b2ff3..a42e487fb 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -432,16 +432,6 @@ def _resolve_public_base_url() -> tuple[str, str]:return "http://127.0.0.1:1933", "listen"-_WATCH_REQUIRES_TO_HINT = (- "watch_interval > 0 requires `to` to be specified (the stable target URI to refresh into). "- "Pick a deterministic URI under viking://resources/. For example:\n"- " - https://github.com/<org>/<repo> -> to='viking://resources/<org>/<repo>'\n"- " - https://example.com/docs/api -> to='viking://resources/example.com/docs/api'\n"- "Tip: call add_resource without watch_interval first, observe the returned URI, "- "then call again with watch_interval=<minutes> and to=<that URI>."-)--@mcp.tool()async def add_resource(path: str = "",@@ -455,8 +445,9 @@ async def add_resource(Three ways to invoke:1. Remote URL: pass ``path`` set to an http(s)://, git@, ssh://, or git:// URL.- Returns a success message immediately. Supports ``watch_interval`` + ``to`` for- auto-refresh subscriptions.+ Returns a success message immediately. Supports ``watch_interval`` for+ auto-refresh subscriptions; pass ``to`` to choose the exact target URI, or+ omit it to bind the watch to the URI created by this add.2. Local file: pass ``path`` set to a local filesystem path (e.g. ``/tmp/foo.pdf``).The response is NOT a success message — it's a multi-step upload instruction.@@ -475,12 +466,12 @@ async def add_resource(watch_interval: Auto-refresh cadence in minutes. 0 (default) = no watch.>0 = periodically re-fetch the resource at that cadence (full re-ingesteach time). Prefer >=1440 (24h) unless the source genuinely changes- faster — every refresh re-embeds the entire resource. Requires ``to``.+ faster — every refresh re-embeds the entire resource. When ``to`` is+ omitted, the watch binds to the URI created by this add.Only applies to remote-URL invocations.to: Target URI under viking://resources/ (e.g.- "viking://resources/volcengine/OpenViking"). Required when- watch_interval > 0. Leave empty for one-shot adds — the system will- auto-derive a URI from the source.+ "viking://resources/volcengine/OpenViking"). Leave empty to let the+ system derive a URI from the source."""from openviking.server.local_input_guard import require_remote_resource_source@@ -539,8 +530,6 @@ async def add_resource(# Branch 3: remote URL — same flow as beforeif is_remote_resource_source(path):- if watch_interval > 0 and not to:- return f"Error: {_WATCH_REQUIRES_TO_HINT}"try:path = require_remote_resource_source(path)result = await service.resources.add_resource(diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex 90256ded7..63041a1c6 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -166,9 +166,7 @@ class ResourceService:if telemetry_id:request_wait_tracker.register_request(telemetry_id)watch_manager = self._get_watch_manager()- watch_enabled = bool(- watch_manager and to and not skip_watch_management and watch_interval > 0- )+ watch_enabled = bool(watch_manager and not skip_watch_management and watch_interval > 0)telemetry.set("resource.flags.wait", wait)telemetry.set("resource.flags.build_index", build_index)@@ -192,10 +190,6 @@ class ResourceService:field_name="parent",allowed_scopes={"resources"},)- if watch_manager and not skip_watch_management and watch_interval > 0 and not to:- raise InvalidArgumentError(- "watch_interval > 0 requires 'to' to be specified (target URI to watch)"- )if enforce_public_remote_targets and is_remote_resource_source(path):path = require_remote_resource_source(path)kwargs.setdefault("request_validator", ensure_public_remote_target)@@ -257,15 +251,29 @@ class ResourceService:root_uri=result.get("root_uri"),)telemetry.set("queue.wait.duration_ms", queue_wait_duration_ms)- if watch_manager and to and not skip_watch_management:+ if watch_manager and not skip_watch_management:with telemetry.measure("resource.watch"):if watch_interval > 0:+ watch_to = to+ parent_uri = parent+ if not watch_to:+ watch_to = validate_optional_viking_uri(+ result.get("root_uri"),+ field_name="root_uri",+ allowed_scopes={"resources"},+ )+ parent_uri = None+ if not watch_to:+ raise InvalidArgumentError(+ "watch_interval > 0 requires a stable target URI. "+ "Pass 'to' explicitly, or add a resource type that returns root_uri."+ )try:processor_kwargs = self._sanitize_watch_processor_kwargs(kwargs)await self._handle_watch_task_creation(path=path,- to_uri=to,- parent_uri=parent,+ to_uri=watch_to,+ parent_uri=parent_uri,reason=reason,instruction=instruction,watch_interval=watch_interval,@@ -278,9 +286,9 @@ class ResourceService:raiseexcept Exception as e:logger.warning(- f"[ResourceService] Failed to create watch task for {to}: {e}"+ f"[ResourceService] Failed to create watch task for {watch_to}: {e}")- else:+ elif to:try:await self._handle_watch_task_cancellation(to_uri=to, ctx=ctx)except Exception as e:diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.pyindex ede56065a..f9d566289 100644--- a/openviking_cli/client/http.py+++ b/openviking_cli/client/http.py@@ -388,6 +388,7 @@ class AsyncHTTPClient(BaseClient):exclude: Optional[str] = None,directly_upload_media: bool = True,preserve_structure: Optional[bool] = None,+ watch_interval: float = 0,telemetry: TelemetryRequest = False,) -> Dict[str, Any]:"""Add resource to OpenViking."""@@ -407,6 +408,7 @@ class AsyncHTTPClient(BaseClient):"include": include,"exclude": exclude,"directly_upload_media": directly_upload_media,+ "watch_interval": watch_interval,"telemetry": telemetry,}if preserve_structure is not None:diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.pyindex f482df8bb..1f330509b 100644--- a/openviking_cli/client/sync_http.py+++ b/openviking_cli/client/sync_http.py@@ -225,6 +225,7 @@ class SyncHTTPClient:include: Optional[str] = None,exclude: Optional[str] = None,directly_upload_media: bool = True,+ watch_interval: float = 0,telemetry: TelemetryRequest = False,) -> Dict[str, Any]:"""Add resource to OpenViking."""@@ -232,18 +233,19 @@ class SyncHTTPClient:raise ValueError("Cannot specify both 'to' and 'parent' at the same time.")return run_async(self._async_client.add_resource(- path,- to,- parent,- reason,- instruction,- wait,- timeout,- strict,- ignore_dirs,- include,- exclude,- directly_upload_media,+ path=path,+ to=to,+ parent=parent,+ reason=reason,+ instruction=instruction,+ wait=wait,+ timeout=timeout,+ strict=strict,+ ignore_dirs=ignore_dirs,+ include=include,+ exclude=exclude,+ directly_upload_media=directly_upload_media,+ watch_interval=watch_interval,telemetry=telemetry,))diff --git a/tests/client/test_http_client_local_upload.py b/tests/client/test_http_client_local_upload.pyindex f0c5b5e17..5bed45efa 100644--- a/tests/client/test_http_client_local_upload.py+++ b/tests/client/test_http_client_local_upload.py@@ -90,11 +90,12 @@ async def test_add_resource_uploads_local_file_even_when_url_is_localhost(tmp_pa"result": {"root_uri": "viking://resources/demo"}}- await client.add_resource(str(resource_file), reason="test")+ await client.add_resource(str(resource_file), reason="test", watch_interval=60)call = fake_http.calls[-1]assert call["path"] == "/api/v1/resources"assert call["json"]["temp_file_id"] == "upload_resource.md"+ assert call["json"]["watch_interval"] == 60assert "path" not in call["json"]diff --git a/tests/server/test_api_resources.py b/tests/server/test_api_resources.pyindex a65417e03..c94378a41 100644--- a/tests/server/test_api_resources.py+++ b/tests/server/test_api_resources.py@@ -415,8 +415,9 @@ async def test_wait_processed_after_add(assert resp.json()["status"] == "ok"-async def test_add_resource_with_watch_interval_requires_to(+async def test_add_resource_with_watch_interval_auto_binds_root_uri(client: httpx.AsyncClient,+ service,sample_markdown_file,upload_temp_dir,):@@ -428,10 +429,20 @@ async def test_add_resource_with_watch_interval_requires_to("watch_interval": 5.0,},)- assert resp.status_code == 400+ assert resp.status_code == 200body = resp.json()- assert body["status"] == "error"- assert "watch_interval > 0 requires 'to' to be specified" in body["error"]["message"]+ assert body["status"] == "ok"+ root_uri = body["result"]["root_uri"]+ task = await service.watch_scheduler.watch_manager.get_task_by_uri(+ to_uri=root_uri,+ account_id="default",+ user_id="test_user",+ role="ROOT",+ agent_id="default",+ )+ assert task is not None+ assert task.to_uri == root_uri+ assert task.watch_interval == 5.0async def test_add_resource_with_default_watch_interval(diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 6cf131d45..31451157b 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -442,22 +442,32 @@ async def test_add_resource_temp_file_id_branch_resolves_and_ingests(upload_token_store.clear()-async def test_add_resource_watch_requires_to(service):- """watch_interval > 0 without `to` returns hint about deterministic URI."""+async def test_add_resource_watch_without_to_is_forwarded(service, monkeypatch):+ """watch_interval > 0 may omit `to`; the service binds to the created root_uri."""+ captured = {}++ async def fake_add_resource(*, path, ctx, **kwargs):+ captured["path"] = path+ captured.update(kwargs)+ return {"root_uri": "viking://resources/foo"}++ monkeypatch.setattr(service.resources, "add_resource", fake_add_resource)+result = await add_resource(path="https://example.com/foo",watch_interval=1440,)- assert "error" in result.lower()- assert "watch_interval > 0 requires `to`" in result+ assert "Resource added" in result+ assert captured["path"] == "https://example.com/foo"+ assert captured["to"] is None+ assert captured["watch_interval"] == 1440async def test_add_resource_rejects_negative_watch_interval(service):"""watch_interval < 0 is rejected at the MCP boundary, even when `to` is given.- Without this guard, a negative value would bypass the `> 0 requires to`- check (passing the `> 0` comparison as false) and be forwarded into- the service layer with undefined semantics.+ Without this guard, a negative value would bypass watch creation and be+ forwarded into the service layer with cancellation-like semantics."""result = await add_resource(path="https://example.com/foo",diff --git a/tests/service/test_resource_service_watch.py b/tests/service/test_resource_service_watch.pyindex 43e96ae66..98ba4b35e 100644--- a/tests/service/test_resource_service_watch.py+++ b/tests/service/test_resource_service_watch.py@@ -11,7 +11,7 @@ import pytest_asynciofrom openviking.resource.watch_manager import WatchManagerfrom openviking.server.identity import RequestContext, Rolefrom openviking.service.resource_service import ResourceService-from openviking_cli.exceptions import ConflictError, InvalidArgumentError+from openviking_cli.exceptions import ConflictErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -29,7 +29,7 @@ class MockResourceProcessor:"""Mock ResourceProcessor for testing."""async def process_resource(self, **kwargs):- return {"root_uri": kwargs.get("to", "viking://resources/test")}+ return {"root_uri": kwargs.get("to") or "viking://resources/test"}class MockSkillProcessor:@@ -116,16 +116,24 @@ class TestWatchTaskCreation:assert task.is_active is True@pytest.mark.asyncio- async def test_watch_interval_requires_to_when_watch_enabled(+ async def test_watch_interval_auto_binds_root_uri_when_to_omitted(self, resource_service: ResourceService, request_context: RequestContext):- with pytest.raises(InvalidArgumentError, match="requires 'to'"):- await resource_service.add_resource(- path="/test/path",- ctx=request_context,- to=None,- watch_interval=30.0,- )+ result = await resource_service.add_resource(+ path="/test/path",+ ctx=request_context,+ to=None,+ watch_interval=30.0,+ )++ assert result["root_uri"] == "viking://resources/test"++ task = await get_task_by_uri(resource_service, "viking://resources/test", request_context)+ assert task is not None+ assert task.path == "/test/path"+ assert task.to_uri == "viking://resources/test"+ assert task.parent_uri is None+ assert task.watch_interval == 30.0@pytest.mark.asyncioasync def test_watch_task_aligns_processor_params(