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
fix(langchain): resolve local resource paths before ingestion (#2522)
Hao Zhe33a70c9f4bdf
diff --git a/openviking/integrations/langchain/tools.py b/openviking/integrations/langchain/tools.pyindex 743087194..9e858f0fc 100644--- a/openviking/integrations/langchain/tools.py+++ b/openviking/integrations/langchain/tools.py@@ -6,7 +6,10 @@ from __future__ import annotationsimport loggingimport re+from pathlib import Pathfrom typing import Annotated, Any, Iterable, Literal+from urllib.parse import urlparse+from urllib.request import url2pathnamefrom pydantic import BeforeValidator, Field@@ -417,17 +420,35 @@ def create_openviking_tools(is not for ordinary chat facts or ad hoc memory notes."""- result = call_openviking(- get_client(),- "add_resource",- path=path,- to=to,- parent=parent,- reason=reason,- instruction=instruction,- wait=wait,- timeout=timeout,- )+ resolved_path = _resolve_resource_source(path)+ if isinstance(resolved_path, dict):+ return compact_json(resolved_path)++ try:+ result = call_openviking(+ get_client(),+ "add_resource",+ path=str(resolved_path),+ to=to,+ parent=parent,+ reason=reason,+ instruction=instruction,+ wait=wait,+ timeout=timeout,+ )+ except Exception as exc:+ if _is_probably_local_path(path) and "direct host filesystem paths" in str(exc):+ return compact_json(+ {+ "error": "local_paths_not_supported_for_http_server",+ "path": path,+ "message": (+ "The OpenViking HTTP client could not upload this local path. "+ "Provide an existing local file/directory or a remote URL/repository."+ ),+ }+ )+ raisereturn stringify(result, max_chars=8_000)def viking_add_skill(@@ -546,6 +567,60 @@ def _is_directory_read_error(exc: Exception) -> bool:)+def _is_probably_local_path(value: str) -> bool:+ text = str(value or "").strip()+ if not text or "\n" in text or "\r" in text:+ return False+ if _is_remote_resource_source(text):+ return False+ if text.startswith(("/", "./", "../", "~/", ".\\", "..\\", "~\\")):+ return True+ if re.match(r"^[A-Za-z]:[\\/]", text) or "\\" in text:+ return True+ if "/" in text:+ first_segment = text.split("/", 1)[0]+ return "." not in first_segment+ return False+++def _is_remote_resource_source(value: str) -> bool:+ text = str(value or "").strip()+ return text.startswith(("http://", "https://", "git@", "ssh://", "git://"))+++def _resolve_resource_source(value: str) -> str | dict[str, str]:+ text = str(value or "").strip()+ if not text:+ return {"error": "missing_path", "message": "path is required"}++ parsed = urlparse(text)+ if parsed.scheme == "file":+ if parsed.netloc not in ("", "localhost"):+ return {+ "error": "unsupported_file_uri",+ "path": text,+ "message": f"Unsupported non-local file URI: {text}",+ }+ path = Path(url2pathname(parsed.path)).expanduser()+ elif parsed.scheme and not re.match(r"^[A-Za-z]$", parsed.scheme):+ return text+ else:+ path = Path(text).expanduser()++ if path.exists():+ return str(path)+ if _is_probably_local_path(text):+ return {+ "error": "local_path_not_found",+ "path": text,+ "message": (+ f"Local resource path does not exist: {text}. "+ "Existing local files/directories can be uploaded as resources."+ ),+ }+ return text++def _format_openviking_health(status: Any) -> dict[str, Any]:state = _infer_health_state(status)return {diff --git a/tests/unit/test_langchain_integration.py b/tests/unit/test_langchain_integration.pyindex 6b186f163..337a17cba 100644--- a/tests/unit/test_langchain_integration.py+++ b/tests/unit/test_langchain_integration.py@@ -35,7 +35,7 @@ from openviking.integrations.langchain.history import (openviking_message_to_langchain,)from openviking.integrations.langchain.middleware import _message_signature-from openviking.integrations.langchain.tools import _archive_grep_pattern+from openviking.integrations.langchain.tools import _archive_grep_pattern, _resolve_resource_sourcefrom openviking_cli.exceptions import InvalidArgumentError@@ -179,6 +179,74 @@ def test_create_openviking_tools_passes_peer_id_without_exposing_tool_arg():)+def test_add_resource_resolves_existing_local_file_for_client_upload(tmp_path):+ class RecordingClient:+ def __init__(self):+ self.paths = []++ def add_resource(self, path, **_kwargs):+ self.paths.append(path)+ return {"uri": "viking://resources/report.md"}++ client = RecordingClient()+ resource_file = tmp_path / "report.md"+ resource_file.write_text("deployment notes", encoding="utf-8")+ tools = {+ tool.name: tool+ for tool in create_openviking_tools(+ client=client,+ tool_names=["viking_add_resource"],+ )+ }++ result = tools["viking_add_resource"].invoke({"path": str(resource_file)})++ assert client.paths == [str(resource_file)]+ assert "viking://resources/report.md" in result+++def test_resolve_resource_source_handles_local_and_remote_sources(tmp_path):+ local_file = tmp_path / "resource with spaces.md"+ local_file.write_text("notes", encoding="utf-8")++ assert (+ _resolve_resource_source("https://example.com/repo.git") == "https://example.com/repo.git"+ )+ assert _resolve_resource_source("[email protected]:org/repo.git") == "[email protected]:org/repo.git"+ assert (+ _resolve_resource_source("ssh://[email protected]/org/repo.git")+ == "ssh://[email protected]/org/repo.git"+ )+ assert _resolve_resource_source("github.com/org/repo") == "github.com/org/repo"+ assert _resolve_resource_source(f"file://{local_file}") == str(local_file)+ assert (+ _resolve_resource_source("file://remote-host/tmp/report.md")["error"]+ == "unsupported_file_uri"+ )++ missing = _resolve_resource_source(str(tmp_path / "missing.md"))+ assert missing["error"] == "local_path_not_found"+ assert _resolve_resource_source("docs/missing.md")["error"] == "local_path_not_found"+++def test_add_resource_keeps_explicit_local_clients_supported(tmp_path):+ client = InMemoryOpenVikingClient()+ resource_file = tmp_path / "report.md"+ resource_file.write_text("report", encoding="utf-8")+ tools = {+ tool.name: tool+ for tool in create_openviking_tools(+ client=client,+ tool_names=["viking_add_resource"],+ )+ }++ result = tools["viking_add_resource"].invoke({"path": str(resource_file)})++ assert "viking://resources/report.md" in result+ assert "viking://resources/report.md" in client.records++def test_create_openviking_tools_profiles_control_destructive_tools():client = InMemoryOpenVikingClient()