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
refactor(langchain): extract standalone integration package (#3685)
Hao Zheb2e1972610c9
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.ymlindex 7e9259d58..319c3c1db 100644--- a/.github/workflows/pr.yml+++ b/.github/workflows/pr.yml@@ -68,6 +68,7 @@ jobs:outputs:deps_changed: ${{ steps.check.outputs.deps_changed }}cuvs_changed: ${{ steps.check.outputs.cuvs_changed }}+ langchain_changed: ${{ steps.check.outputs.langchain_changed }}steps:- uses: actions/checkout@v6with:@@ -107,6 +108,18 @@ jobs:echo "cuvs_changed=false" >> $GITHUB_OUTPUTfi+ LANGCHAIN_PATTERN="integrations/langchain/|openviking/integrations/langchain/|tests/(unit/test_langchain|integration/langchain_langgraph/)|examples/langchain-langgraph/|pyproject\.toml|uv\.lock|\.github/workflows/(pr|python-langchain-release)\.yml"+ LANGCHAIN_CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }} HEAD | grep -E "$LANGCHAIN_PATTERN" || true)++ if [ -n "$LANGCHAIN_CHANGED_FILES" ]; then+ echo "LangChain integration changes detected:"+ echo "$LANGCHAIN_CHANGED_FILES"+ echo "langchain_changed=true" >> $GITHUB_OUTPUT+ else+ echo "No LangChain integration changes detected."+ echo "langchain_changed=false" >> $GITHUB_OUTPUT+ fi+build:needs: check-depsif: ${{ needs.check-deps.outputs.deps_changed == 'true' }}@@ -119,3 +132,80 @@ jobs:with:os_json: '["ubuntu-24.04"]'python_json: '["3.11"]'++ langchain-tests:+ needs: check-deps+ if: ${{ needs.check-deps.outputs.langchain_changed == 'true' }}+ runs-on: ubuntu-24.04+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.10", "3.12"]+ steps:+ - uses: actions/checkout@v6+ with:+ fetch-depth: 0++ - uses: actions/setup-python@v6+ with:+ python-version: ${{ matrix.python-version }}++ - uses: astral-sh/setup-uv@v7+ with:+ enable-cache: true++ - name: Install standalone integration+ run: |+ uv pip install --system -e sdk/python+ uv pip install --system -e "integrations/langchain[langgraph,test,dev]"++ - name: Check package formatting and lint+ run: |+ ruff format --check \+ integrations/langchain/src \+ integrations/langchain/tests \+ openviking/integrations/langchain \+ tests/integration/langchain_langgraph \+ tests/unit/test_langchain*.py+ ruff check \+ integrations/langchain/src \+ integrations/langchain/tests \+ openviking/integrations/langchain \+ tests/integration/langchain_langgraph \+ tests/unit/test_langchain*.py++ - name: Type-check package+ run: >-+ mypy+ --config-file integrations/langchain/pyproject.toml+ integrations/langchain/src/langchain_openviking++ - name: Run LangChain and LangGraph tests+ run: |+ python -m pytest -q --noconftest -o addopts='' \+ tests/unit/test_langchain*.py \+ tests/integration/langchain_langgraph++ - name: Build and inspect distributions+ run: |+ python -m build integrations/langchain+ python -m twine check integrations/langchain/dist/*++ - name: Verify the installed wheel+ if: matrix.python-version == '3.12'+ run: |+ WHEEL_PATH="${GITHUB_WORKSPACE}/$(find integrations/langchain/dist -name '*.whl' -print -quit)"+ uv venv .langchain-wheel-venv --python "${{ matrix.python-version }}"+ uv pip install \+ --python .langchain-wheel-venv/bin/python \+ sdk/python \+ "${WHEEL_PATH}"+ cd /tmp+ "${GITHUB_WORKSPACE}/.langchain-wheel-venv/bin/python" \+ "${GITHUB_WORKSPACE}/integrations/langchain/tests/installed_base_smoke.py"+ uv pip install \+ --python "${GITHUB_WORKSPACE}/.langchain-wheel-venv/bin/python" \+ "${WHEEL_PATH}[langgraph]"+ "${GITHUB_WORKSPACE}/.langchain-wheel-venv/bin/python" \+ "${GITHUB_WORKSPACE}/integrations/langchain/tests/installed_smoke.py"+ uv pip check --python "${GITHUB_WORKSPACE}/.langchain-wheel-venv/bin/python"diff --git a/.github/workflows/python-langchain-release.yml b/.github/workflows/python-langchain-release.ymlnew file mode 100644index 000000000..23719ffe4--- /dev/null+++ b/.github/workflows/python-langchain-release.yml@@ -0,0 +1,131 @@+name: LangChain Integration Release++on:+ release:+ types: [published]+ workflow_dispatch:+ inputs:+ target:+ description: "Publish target"+ required: true+ type: choice+ default: "testpypi"+ options:+ - testpypi+ - pypi+ - both++permissions:+ contents: read++jobs:+ build-package:+ name: Build langchain-openviking+ if: github.event_name == 'workflow_dispatch' || startsWith(github.event.release.tag_name, 'langchain-openviking@')+ runs-on: ubuntu-24.04+ outputs:+ package_version: ${{ steps.version.outputs.package_version }}+ publish_target: ${{ steps.target.outputs.publish_target }}+ steps:+ - name: Checkout repository+ uses: actions/checkout@v6+ with:+ fetch-depth: 0++ - name: Fetch all tags+ run: git fetch --force --tags++ - name: Set publish target+ id: target+ run: |+ if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then+ echo "publish_target=${{ inputs.target }}" >> "$GITHUB_OUTPUT"+ else+ echo "publish_target=pypi" >> "$GITHUB_OUTPUT"+ fi++ - name: Set up Python+ uses: actions/setup-python@v6+ with:+ python-version: "3.12"++ - name: Install build dependencies+ working-directory: integrations/langchain+ run: python -m pip install build setuptools setuptools-scm twine wheel++ - name: Resolve package version+ id: version+ working-directory: integrations/langchain+ run: |+ PACKAGE_VERSION=$(python -m setuptools_scm)+ echo "package_version=$PACKAGE_VERSION" >> "$GITHUB_OUTPUT"+ echo "Resolved package version: $PACKAGE_VERSION"++ - name: Validate release tag+ if: github.event_name == 'release'+ env:+ TAG_NAME: ${{ github.event.release.tag_name }}+ PACKAGE_VERSION: ${{ steps.version.outputs.package_version }}+ run: |+ EXPECTED_TAG="langchain-openviking@${PACKAGE_VERSION}"+ if [ "$TAG_NAME" != "$EXPECTED_TAG" ]; then+ echo "Tag $TAG_NAME does not match resolved package version $PACKAGE_VERSION"+ exit 1+ fi++ - name: Build distributions+ working-directory: integrations/langchain+ run: python -m build++ - name: Validate distributions+ working-directory: integrations/langchain+ run: python -m twine check dist/*++ - name: Upload distributions+ uses: actions/upload-artifact@v7+ with:+ name: langchain-openviking-distributions+ path: integrations/langchain/dist/*++ publish-testpypi:+ name: Publish to TestPyPI+ needs: [build-package]+ if: needs.build-package.outputs.publish_target == 'testpypi' || needs.build-package.outputs.publish_target == 'both'+ runs-on: ubuntu-24.04+ environment:+ name: testpypi+ url: https://test.pypi.org/p/langchain-openviking+ permissions:+ id-token: write+ steps:+ - uses: actions/download-artifact@v8+ with:+ name: langchain-openviking-distributions+ path: dist/++ - uses: pypa/gh-action-pypi-publish@release/v1+ with:+ repository-url: https://test.pypi.org/legacy/+ skip-existing: true+ verbose: true++ publish-pypi:+ name: Publish to PyPI+ needs: [build-package]+ if: needs.build-package.outputs.publish_target == 'pypi' || needs.build-package.outputs.publish_target == 'both'+ runs-on: ubuntu-24.04+ environment:+ name: pypi+ url: https://pypi.org/p/langchain-openviking+ permissions:+ id-token: write+ steps:+ - uses: actions/download-artifact@v8+ with:+ name: langchain-openviking-distributions+ path: dist/++ - uses: pypa/gh-action-pypi-publish@release/v1+ with:+ skip-existing: true+ verbose: truediff --git a/docs/en/agent-integrations/07-langchain-langgraph.md b/docs/en/agent-integrations/07-langchain-langgraph.mdindex 9f0e1d051..7d071cc42 100644--- a/docs/en/agent-integrations/07-langchain-langgraph.md+++ b/docs/en/agent-integrations/07-langchain-langgraph.md@@ -1,18 +1,25 @@# LangChain and LangGraph-Wire OpenViking into your LangChain or LangGraph agent as the context backend. The SDK provides a retriever, chat history, context wrapper, agent tools, LangGraph store, and middleware for HTTP-backed or embedded OpenViking deployments.+Wire OpenViking into your LangChain or LangGraph agent as the context backend. The+standalone integration package provides a retriever, chat history, context wrapper,+agent tools, LangGraph store, and middleware for HTTP-backed or embedded OpenViking+deployments.## Install```bash-pip install "openviking[langchain]" # retriever + chat history-pip install "openviking[langgraph]" # full LangGraph support (includes langchain)+pip install langchain-openviking # LangChain adapters+pip install "langchain-openviking[langgraph]" # LangGraph middleware support```+Existing applications may continue to use `openviking[langchain]` or+`openviking[langgraph]`; the full package forwards the legacy import path to+`langchain-openviking`.+## Connection```python-from openviking.integrations.langchain import create_openviking_tools+from langchain_openviking import create_openviking_toolstools = create_openviking_tools(url="http://localhost:1933",@@ -21,7 +28,7 @@ tools = create_openviking_tools()```-When both `url` and `path` are omitted, adapters use the HTTP connection settings from the OpenViking CLI config. Pass `path` to use an embedded workspace through OpenViking's synchronous client. Embedding and VLM providers are configured in OpenViking, not in your app.+When both `url` and `path` are omitted, adapters use the HTTP connection settings from the OpenViking CLI config. Pass `path` to use an embedded workspace through OpenViking's synchronous client; embedded mode also requires the full `openviking` package. Embedding and VLM providers are configured in OpenViking, not in your app.### Async applications@@ -49,8 +56,8 @@ Long-lived applications can initialize one caller-owned async client and reuseit across adapters running on the same event loop:```python-from openviking.client import AsyncHTTPClient-from openviking.integrations.langchain import OpenVikingRetriever+from openviking_sdk import AsyncHTTPClient+from langchain_openviking import OpenVikingRetrieverclient = AsyncHTTPClient(url="http://localhost:1933", api_key="...")await client.initialize()@@ -164,7 +171,7 @@ chain.invoke(LangGraph run while reusing its credential-bound HTTP clients:```python-from openviking.integrations.langchain import OpenVikingContextMiddleware+from langchain_openviking import OpenVikingContextMiddlewaredef resolve_actor_peer(_state, runtime):@@ -216,7 +223,7 @@ feature in an existing environment.### Retriever```python-from openviking.integrations.langchain import OpenVikingRetriever+from langchain_openviking import OpenVikingRetrieverretriever = OpenVikingRetriever(url="http://localhost:1933", api_key="...")docs = retriever.invoke("What did the user decide about deployment?")@@ -227,7 +234,7 @@ docs = retriever.invoke("What did the user decide about deployment?")```pythonfrom langchain_core.messages import AIMessagefrom langchain_core.runnables import RunnableLambda-from openviking.integrations.langchain import with_openviking_context+from langchain_openviking import with_openviking_contextwith with_openviking_context(RunnableLambda(lambda msgs: AIMessage(content="...")),@@ -240,7 +247,7 @@ with with_openviking_context(### Agent tools```python-from openviking.integrations.langchain import create_openviking_tools+from langchain_openviking import create_openviking_toolstools = create_openviking_tools(url="http://localhost:1933", profile="agent")# Includes: viking_find, viking_search, viking_browse, viking_read,@@ -250,7 +257,7 @@ tools = create_openviking_tools(url="http://localhost:1933", profile="agent")### LangGraph store```python-from openviking.integrations.langchain import OpenVikingStore+from langchain_openviking import OpenVikingStorestore = OpenVikingStore(url="http://localhost:1933", api_key="...")store.put(("users", "ada"), "preferences", {"color": "azure"})@@ -260,7 +267,7 @@ items = store.search(("users",), query="azure", limit=3)### LangGraph middleware```python-from openviking.integrations.langchain import OpenVikingContextMiddleware+from langchain_openviking import OpenVikingContextMiddlewaremiddleware = OpenVikingContextMiddleware(url="http://localhost:1933",@@ -275,7 +282,7 @@ Use the recorder when your application already owns the conversation lifecycleand only needs reusable OpenViking persistence:```python-from openviking.integrations.langchain import (+from langchain_openviking import (OpenVikingPartialWriteError,OpenVikingSessionRecorder,)@@ -312,11 +319,11 @@ finish an async lifecycle with `recorder.close()`.The repository includes runnable examples that work without model credentials using an in-memory test client:```bash-uv run --extra langgraph python examples/langchain-langgraph/langchain/rag/quick_app.py-uv run --extra langgraph python examples/langchain-langgraph/langchain/context-backend/quick_app.py-uv run --extra langgraph python examples/langchain-langgraph/langchain/message-history/quick_app.py-uv run --extra langgraph python examples/langchain-langgraph/langgraph/agent/quick_app.py-uv run --extra langgraph python examples/langchain-langgraph/langgraph/middleware/quick_app.py+uv run --project integrations/langchain --extra langgraph python examples/langchain-langgraph/langchain/rag/quick_app.py+uv run --project integrations/langchain --extra langgraph python examples/langchain-langgraph/langchain/context-backend/quick_app.py+uv run --project integrations/langchain --extra langgraph python examples/langchain-langgraph/langchain/message-history/quick_app.py+uv run --project integrations/langchain --extra langgraph python examples/langchain-langgraph/langgraph/agent/quick_app.py+uv run --project integrations/langchain --extra langgraph python examples/langchain-langgraph/langgraph/middleware/quick_app.py```For a real OpenViking server and OpenAI-compatible model flow, see the [live LangGraph app](https://github.com/volcengine/OpenViking/blob/main/examples/langchain-langgraph/langgraph/agent/live_app.py).diff --git a/docs/zh/agent-integrations/07-langchain-langgraph.md b/docs/zh/agent-integrations/07-langchain-langgraph.mdindex 182551ad0..7e68ede25 100644--- a/docs/zh/agent-integrations/07-langchain-langgraph.md+++ b/docs/zh/agent-integrations/07-langchain-langgraph.md@@ -1,18 +1,23 @@# LangChain 和 LangGraph-把 OpenViking 接入你的 LangChain 或 LangGraph Agent 作为上下文后端。SDK 提供 retriever、chat history、context wrapper、agent tools、LangGraph store 和 middleware,可连接 HTTP 服务或嵌入式 OpenViking。+把 OpenViking 接入你的 LangChain 或 LangGraph Agent 作为上下文后端。独立集成包提供+retriever、chat history、context wrapper、agent tools、LangGraph store 和 middleware,+可连接 HTTP 服务或嵌入式 OpenViking。## 安装```bash-pip install "openviking[langchain]" # retriever + chat history-pip install "openviking[langgraph]" # 完整 LangGraph 支持(包含 langchain)+pip install langchain-openviking # LangChain 适配器+pip install "langchain-openviking[langgraph]" # LangGraph middleware```+现有应用仍可使用 `openviking[langchain]` 或 `openviking[langgraph]`。完整包会把旧导入路径+转发到 `langchain-openviking`。+## 连接```python-from openviking.integrations.langchain import create_openviking_tools+from langchain_openviking import create_openviking_toolstools = create_openviking_tools(url="http://localhost:1933",@@ -21,7 +26,9 @@ tools = create_openviking_tools()```-同时省略 `url` 和 `path` 时,适配器会使用 OpenViking CLI 配置中的 HTTP 连接信息。传入 `path` 时,通过 OpenViking 同步 client 使用嵌入式 workspace。Embedding 和 VLM 在 OpenViking 侧配置,不在你的应用中。+同时省略 `url` 和 `path` 时,适配器会使用 OpenViking CLI 配置中的 HTTP 连接信息。传入+`path` 时,通过 OpenViking 同步 client 使用嵌入式 workspace,该模式还需要安装完整的+`openviking` 包。Embedding 和 VLM 在 OpenViking 侧配置,不在你的应用中。### 异步应用@@ -49,8 +56,8 @@ result = await chain.ainvoke(内的多个适配器之间复用:```python-from openviking.client import AsyncHTTPClient-from openviking.integrations.langchain import OpenVikingRetriever+from openviking_sdk import AsyncHTTPClient+from langchain_openviking import OpenVikingRetrieverclient = AsyncHTTPClient(url="http://localhost:1933", api_key="...")await client.initialize()@@ -154,7 +161,7 @@ chain.invoke(LangGraph 运行中解析当前 actor peer:```python-from openviking.integrations.langchain import OpenVikingContextMiddleware+from langchain_openviking import OpenVikingContextMiddlewaredef resolve_actor_peer(_state, runtime):@@ -201,7 +208,7 @@ middleware,不支持 embedded `path=` client。注入的自定义 client 必### Retriever```python-from openviking.integrations.langchain import OpenVikingRetriever+from langchain_openviking import OpenVikingRetrieverretriever = OpenVikingRetriever(url="http://localhost:1933", api_key="...")docs = retriever.invoke("用户之前对部署方案做了什么决定?")@@ -212,7 +219,7 @@ docs = retriever.invoke("用户之前对部署方案做了什么决定?")```pythonfrom langchain_core.messages import AIMessagefrom langchain_core.runnables import RunnableLambda-from openviking.integrations.langchain import with_openviking_context+from langchain_openviking import with_openviking_contextwith with_openviking_context(RunnableLambda(lambda msgs: AIMessage(content="...")),@@ -225,7 +232,7 @@ with with_openviking_context(### Agent tools```python-from openviking.integrations.langchain import create_openviking_tools+from langchain_openviking import create_openviking_toolstools = create_openviking_tools(url="http://localhost:1933", profile="agent")# 包括:viking_find, viking_search, viking_browse, viking_read,@@ -235,7 +242,7 @@ tools = create_openviking_tools(url="http://localhost:1933", profile="agent")### LangGraph store```python-from openviking.integrations.langchain import OpenVikingStore+from langchain_openviking import OpenVikingStorestore = OpenVikingStore(url="http://localhost:1933", api_key="...")store.put(("users", "ada"), "preferences", {"color": "azure"})@@ -245,7 +252,7 @@ items = store.search(("users",), query="azure", limit=3)### LangGraph middleware```python-from openviking.integrations.langchain import OpenVikingContextMiddleware+from langchain_openviking import OpenVikingContextMiddlewaremiddleware = OpenVikingContextMiddleware(url="http://localhost:1933",@@ -259,7 +266,7 @@ middleware = OpenVikingContextMiddleware(当应用已经自行管理会话生命周期,只需要复用 OpenViking 持久化能力时,可使用 recorder:```python-from openviking.integrations.langchain import (+from langchain_openviking import (OpenVikingPartialWriteError,OpenVikingSessionRecorder,)@@ -293,11 +300,11 @@ commit 策略。如果后续批次或写入后的 commit 失败,`OpenVikingPar仓库内提供了可直接运行的最小示例,使用内存测试客户端,无需模型凭证:```bash-uv run --extra langgraph python examples/langchain-langgraph/langchain/rag/quick_app.py-uv run --extra langgraph python examples/langchain-langgraph/langchain/context-backend/quick_app.py-uv run --extra langgraph python examples/langchain-langgraph/langchain/message-history/quick_app.py-uv run --extra langgraph python examples/langchain-langgraph/langgraph/agent/quick_app.py-uv run --extra langgraph python examples/langchain-langgraph/langgraph/middleware/quick_app.py+uv run --project integrations/langchain --extra langgraph python examples/langchain-langgraph/langchain/rag/quick_app.py+uv run --project integrations/langchain --extra langgraph python examples/langchain-langgraph/langchain/context-backend/quick_app.py+uv run --project integrations/langchain --extra langgraph python examples/langchain-langgraph/langchain/message-history/quick_app.py+uv run --project integrations/langchain --extra langgraph python examples/langchain-langgraph/langgraph/agent/quick_app.py+uv run --project integrations/langchain --extra langgraph python examples/langchain-langgraph/langgraph/middleware/quick_app.py```连接真实 OpenViking 服务和 OpenAI 兼容模型的示例见 [live LangGraph app](https://github.com/volcengine/OpenViking/blob/main/examples/langchain-langgraph/langgraph/agent/live_app.py)。diff --git a/examples/langchain-langgraph/langchain/context-backend/quick_app.py b/examples/langchain-langgraph/langchain/context-backend/quick_app.pyindex 1c82ed93b..fdc5e96f2 100644--- a/examples/langchain-langgraph/langchain/context-backend/quick_app.py+++ b/examples/langchain-langgraph/langchain/context-backend/quick_app.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom langchain_core.messages import AIMessage, HumanMessagefrom langchain_core.runnables import RunnableLambda-from openviking.integrations.langchain import (+from langchain_openviking import (InMemoryOpenVikingClient,OpenVikingCommitPolicy,with_openviking_context,diff --git a/examples/langchain-langgraph/langchain/message-history/quick_app.py b/examples/langchain-langgraph/langchain/message-history/quick_app.pyindex e516553ed..a0be3ca9a 100644--- a/examples/langchain-langgraph/langchain/message-history/quick_app.py+++ b/examples/langchain-langgraph/langchain/message-history/quick_app.py@@ -6,11 +6,11 @@ from langchain_core.messages import AIMessage, BaseMessage, HumanMessagefrom langchain_core.runnables import RunnableLambdafrom langchain_core.runnables.history import RunnableWithMessageHistory-from openviking.integrations.langchain import (+from langchain_openviking import (InMemoryOpenVikingClient,OpenVikingChatMessageHistory,)-from openviking.integrations.langchain.client import extract_message_text+from langchain_openviking.client import extract_message_textdef build_app(client: InMemoryOpenVikingClient | None = None):diff --git a/examples/langchain-langgraph/langchain/rag/quick_app.py b/examples/langchain-langgraph/langchain/rag/quick_app.pyindex beaf40af3..068b725f3 100644--- a/examples/langchain-langgraph/langchain/rag/quick_app.py+++ b/examples/langchain-langgraph/langchain/rag/quick_app.py@@ -7,7 +7,7 @@ from langchain_core.output_parsers import StrOutputParserfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.runnables import RunnableLambda, RunnablePassthrough-from openviking.integrations.langchain import InMemoryOpenVikingClient, OpenVikingRetriever+from langchain_openviking import InMemoryOpenVikingClient, OpenVikingRetrieverdef build_app(client: InMemoryOpenVikingClient | None = None):diff --git a/examples/langchain-langgraph/langgraph/agent/live_app.py b/examples/langchain-langgraph/langgraph/agent/live_app.pyindex e6728d482..b9b17ad99 100644--- a/examples/langchain-langgraph/langgraph/agent/live_app.py+++ b/examples/langchain-langgraph/langgraph/agent/live_app.py@@ -21,8 +21,8 @@ from langgraph.graph.message import add_messagesfrom openai import OpenAIfrom typing_extensions import Annotated, TypedDict-from openviking.integrations.langchain import OpenVikingContextMiddleware-from openviking.integrations.langchain.client import extract_message_text+from langchain_openviking import OpenVikingContextMiddleware+from langchain_openviking.client import extract_message_textclass LiveState(TypedDict, total=False):@@ -30,7 +30,7 @@ class LiveState(TypedDict, total=False):def build_context_client():- from openviking.client import SyncHTTPClient+ from openviking_sdk import SyncHTTPClientclient = SyncHTTPClient(url=os.environ.get("OPENVIKING_URL") or None,diff --git a/examples/langchain-langgraph/langgraph/agent/quick_app.py b/examples/langchain-langgraph/langgraph/agent/quick_app.pyindex 3384c34ae..7a5fcebd0 100644--- a/examples/langchain-langgraph/langgraph/agent/quick_app.py+++ b/examples/langchain-langgraph/langgraph/agent/quick_app.py@@ -6,7 +6,7 @@ from langgraph.graph import END, START, StateGraphfrom langgraph.graph.message import add_messagesfrom typing_extensions import Annotated, TypedDict-from openviking.integrations.langchain import (+from langchain_openviking import (InMemoryOpenVikingClient,OpenVikingStore,create_openviking_tools,diff --git a/examples/langchain-langgraph/langgraph/middleware/quick_app.py b/examples/langchain-langgraph/langgraph/middleware/quick_app.pyindex d12b3f134..37c5d8777 100644--- a/examples/langchain-langgraph/langgraph/middleware/quick_app.py+++ b/examples/langchain-langgraph/langgraph/middleware/quick_app.py@@ -7,11 +7,11 @@ from langgraph.graph import END, START, StateGraphfrom langgraph.graph.message import add_messagesfrom typing_extensions import Annotated, TypedDict-from openviking.integrations.langchain import (+from langchain_openviking import (InMemoryOpenVikingClient,OpenVikingContextMiddleware,)-from openviking.integrations.langchain.client import extract_message_text+from langchain_openviking.client import extract_message_textclass AgentState(TypedDict, total=False):diff --git a/integrations/langchain/README.md b/integrations/langchain/README.mdnew file mode 100644index 000000000..a87e4e68f--- /dev/null+++ b/integrations/langchain/README.md@@ -0,0 +1,60 @@+# langchain-openviking++`langchain-openviking` is the official OpenViking integration package for+LangChain and LangGraph applications. It keeps framework-specific adapters+separate from the OpenViking server and communicates with remote OpenViking+instances through the lightweight `openviking-sdk` package.++## Installation++For LangChain retrievers, tools, message history, and context wrappers:++```bash+pip install langchain-openviking+```++For the LangGraph store and middleware:++```bash+pip install "langchain-openviking[langgraph]"+```++## Quick start++```python+from langchain_openviking import OpenVikingRetriever+from openviking_sdk import SyncHTTPClient++client = SyncHTTPClient(+ url="http://127.0.0.1:1933",+ api_key="your-user-api-key",+)+client.initialize()+retriever = OpenVikingRetriever(+ client=client,+ target_uri="viking://user/memories",+)++try:+ documents = retriever.invoke("What deployment preferences should I remember?")+finally:+ client.close()+```++The package also provides `OpenVikingSessionRecorder`,+`OpenVikingContextMiddleware`, `OpenVikingStore`,+`OpenVikingChatMessageHistory`, and `create_openviking_tools`.++## Client ownership++- A client supplied through `client=` or `async_client=` remains caller-owned.+- Clients created from `url=` are managed by the adapter and can be closed with+ `close()` or `aclose()` as documented by each adapter.+- Embedded `path=` mode requires the full `openviking` package. It is kept for+ compatibility, while the standalone package's default boundary is HTTP.++The previous `openviking.integrations.langchain` import path remains available+from the full `openviking` distribution as a compatibility shim.++See the [OpenViking documentation](https://openviking.ai) and the repository's+`examples/langchain-langgraph` directory for complete examples.diff --git a/integrations/langchain/README_CN.md b/integrations/langchain/README_CN.mdnew file mode 100644index 000000000..bc9897c1e--- /dev/null+++ b/integrations/langchain/README_CN.md@@ -0,0 +1,47 @@+# langchain-openviking++`langchain-openviking` 是 OpenViking 官方维护的 LangChain 和 LangGraph+集成包。框架适配逻辑不再依赖 OpenViking 服务端实现,远程访问统一通过轻量的+`openviking-sdk` 完成。++## 安装++LangChain Retriever、Tools、Message History 和 Context Wrapper:++```bash+pip install langchain-openviking+```++LangGraph Store 和 Middleware:++```bash+pip install "langchain-openviking[langgraph]"+```++## 快速开始++```python+from langchain_openviking import OpenVikingRetriever+from openviking_sdk import SyncHTTPClient++client = SyncHTTPClient(+ url="http://127.0.0.1:1933",+ api_key="your-user-api-key",+)+client.initialize()+retriever = OpenVikingRetriever(+ client=client,+ target_uri="viking://user/memories",+)++try:+ documents = retriever.invoke("需要记住哪些部署偏好?")+finally:+ client.close()+```++外部传入的 client 仍由调用方管理。通过 `url=` 创建的 client 由适配器管理。+`path=` 嵌入模式需要另外安装完整的 `openviking` 包。++完整 `openviking` 包会继续保留原有的+`openviking.integrations.langchain` 导入路径,并转发到本包,方便现有应用平滑迁移。diff --git a/integrations/langchain/pyproject.toml b/integrations/langchain/pyproject.tomlnew file mode 100644index 000000000..c32842cca--- /dev/null+++ b/integrations/langchain/pyproject.toml@@ -0,0 +1,98 @@+[build-system]+requires = ["setuptools>=61.0", "setuptools-scm>=8.0", "wheel"]+build-backend = "setuptools.build_meta"++[project]+name = "langchain-openviking"+dynamic = ["version"]+description = "OpenViking integrations for LangChain and LangGraph"+readme = "README.md"+requires-python = ">=3.10"+authors = [+ {name = "ByteDance", email = "[email protected]"},+]+license = "AGPL-3.0"+classifiers = [+ "Development Status :: 3 - Alpha",+ "Intended Audience :: Developers",+ "Topic :: Scientific/Engineering :: Artificial Intelligence",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: 3.13",+ "Programming Language :: Python :: 3.14",+]+dependencies = [+ "langchain-core>=1.0.0,<2.0.0",+ "openviking-sdk>=0.1.1",+ "pydantic>=2.0.0",+]++[project.optional-dependencies]+langgraph = [+ "langchain>=1.0.0,<2.0.0",+ "langgraph>=1.0.0,<2.0.0",+]+test = [+ "pytest>=7.0.0",+ "pytest-asyncio>=0.21.0",+]+dev = [+ "build>=1.2.0",+ "mypy>=1.0.0",+ "ruff>=0.1.0",+ "twine>=5.0.0",+]++[project.urls]+Homepage = "https://github.com/volcengine/openviking"+Documentation = "https://openviking.ai"+Repository = "https://github.com/volcengine/openviking"+Issues = "https://github.com/volcengine/openviking/issues"++[tool.setuptools]+package-dir = {"" = "src"}++[tool.setuptools.packages.find]+where = ["src"]+include = ["langchain_openviking*"]++[tool.setuptools.package-data]+langchain_openviking = ["py.typed"]++[tool.setuptools_scm]+root = "../.."+local_scheme = "no-local-version"+tag_regex = "^langchain-openviking@(?P<version>[0-9]+(?:\\.[0-9]+)*)$"+git_describe_command = "git describe --dirty --tags --long --match langchain-openviking@*"++[tool.mypy]+python_version = "3.10"+warn_return_any = false+warn_unused_configs = true+check_untyped_defs = true+no_implicit_optional = false+warn_redundant_casts = true+warn_unused_ignores = true+ignore_missing_imports = true++[tool.pytest.ini_options]+asyncio_mode = "auto"++[tool.ruff]+line-length = 100+target-version = "py310"++[tool.ruff.lint]+select = ["E", "W", "F", "I", "C", "B"]+ignore = ["E501", "B008", "C901", "B006", "B904", "E741", "E722", "B027"]++[tool.ruff.lint.per-file-ignores]+"__init__.py" = ["F401"]++[tool.ruff.format]+quote-style = "double"+indent-style = "space"+skip-magic-trailing-comma = false+line-ending = "auto"diff --git a/integrations/langchain/src/langchain_openviking/__init__.py b/integrations/langchain/src/langchain_openviking/__init__.pynew file mode 100644index 000000000..24cc73ae8--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/__init__.py@@ -0,0 +1,106 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""LangChain and LangGraph integrations for OpenViking.++The base distribution depends on ``langchain-core``. LangGraph middleware is+loaded only when the ``langgraph`` extra (or compatible dependencies) is+installed.+"""++from __future__ import annotations++from importlib.util import find_spec+from typing import Any++from langchain_openviking.actor_peer import (+ has_request_actor_peer_support,+)++__all__ = [+ "InMemoryOpenVikingClient",+ "OpenVikingChatMessageHistory",+ "OpenVikingCancellationProgress",+ "OpenVikingCommitPolicy",+ "OpenVikingContextRunnable",+ "OpenVikingPartialWriteError",+ "OpenVikingRecordResult",+ "OpenVikingRetriever",+ "OpenVikingSessionContextAssembler",+ "OpenVikingSessionRecorder",+ "OpenVikingStore",+ "create_openviking_tools",+ "get_openviking_cancellation_progress",+ "has_request_actor_peer_support",+ "with_openviking_context",+]++if find_spec("langchain") is not None:+ __all__.append("OpenVikingContextMiddleware")+++def __getattr__(name: str) -> Any:+ if name == "OpenVikingRetriever":+ from langchain_openviking.retrievers import OpenVikingRetriever++ return OpenVikingRetriever+ if name == "create_openviking_tools":+ from langchain_openviking.tools import create_openviking_tools++ return create_openviking_tools+ if name == "OpenVikingStore":+ from langchain_openviking.store import OpenVikingStore++ return OpenVikingStore+ if name == "OpenVikingChatMessageHistory":+ from langchain_openviking.history import OpenVikingChatMessageHistory++ return OpenVikingChatMessageHistory+ if name == "OpenVikingSessionContextAssembler":+ from langchain_openviking.context import OpenVikingSessionContextAssembler++ return OpenVikingSessionContextAssembler+ if name == "OpenVikingContextRunnable":+ from langchain_openviking.context import OpenVikingContextRunnable++ return OpenVikingContextRunnable+ if name == "OpenVikingSessionRecorder":+ from langchain_openviking.recording import OpenVikingSessionRecorder++ return OpenVikingSessionRecorder+ if name == "OpenVikingPartialWriteError":+ from langchain_openviking.recording import OpenVikingPartialWriteError++ return OpenVikingPartialWriteError+ if name == "OpenVikingRecordResult":+ from langchain_openviking.recording import OpenVikingRecordResult++ return OpenVikingRecordResult+ if name == "OpenVikingCancellationProgress":+ from langchain_openviking.recording import (+ OpenVikingCancellationProgress,+ )++ return OpenVikingCancellationProgress+ if name == "get_openviking_cancellation_progress":+ from langchain_openviking.recording import (+ get_openviking_cancellation_progress,+ )++ return get_openviking_cancellation_progress+ if name == "OpenVikingCommitPolicy":+ from langchain_openviking.client import OpenVikingCommitPolicy++ return OpenVikingCommitPolicy+ if name == "with_openviking_context":+ from langchain_openviking.context import with_openviking_context++ return with_openviking_context+ if name == "OpenVikingContextMiddleware":+ from langchain_openviking.middleware import OpenVikingContextMiddleware++ return OpenVikingContextMiddleware+ if name == "InMemoryOpenVikingClient":+ from langchain_openviking.testing import InMemoryOpenVikingClient++ return InMemoryOpenVikingClient+ raise AttributeError(name)diff --git a/integrations/langchain/src/langchain_openviking/_async_client_cache.py b/integrations/langchain/src/langchain_openviking/_async_client_cache.pynew file mode 100644index 000000000..1bab5615a--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/_async_client_cache.py@@ -0,0 +1,124 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Private event-loop scoped cache for integration-owned async clients."""++from __future__ import annotations++import asyncio+import inspect+import threading+import weakref+from collections.abc import Callable+from typing import Any, Protocol+++class _Closeable(Protocol):+ def close(self) -> Any: ...+++class _AsyncCloseable(Protocol):+ def aclose(self) -> Any: ...+++def _close_client(client: _Closeable) -> Any:+ return client.close()+++def _aclose_client(client: _AsyncCloseable) -> Any:+ return client.aclose()+++class LoopScopedAsyncClientCache:+ """Cache integration-owned async clients per running event loop.++ HTTP clients may bind internal asyncio primitives to the loop that first+ uses them. Keeping this small cache private lets the adapter own that+ lifecycle without importing OpenViking server utilities.+ """++ def __init__(self) -> None:+ self._clients_by_loop: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, Any] = (+ weakref.WeakKeyDictionary()+ )+ self._fallback_client: Any = None+ self._lock = threading.Lock()++ def __copy__(self) -> LoopScopedAsyncClientCache:+ """Return an empty cache instead of sharing live async clients."""++ return type(self)()++ def __deepcopy__(self, memo: dict[int, Any]) -> LoopScopedAsyncClientCache:+ """Return an empty cache instead of copying loop-bound clients."""++ copied = type(self)()+ memo[id(self)] = copied+ return copied++ def get(self, factory: Callable[[], Any]) -> Any:+ """Return the client for the current loop, creating it if necessary."""++ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ with self._lock:+ if self._fallback_client is None:+ self._fallback_client = factory()+ return self._fallback_client++ with self._lock:+ client = self._clients_by_loop.get(loop)+ if client is None:+ client = factory()+ self._clients_by_loop[loop] = client+ return client++ def has_clients(self) -> bool:+ """Return whether the cache currently retains any clients."""++ with self._lock:+ return bool(self._clients_by_loop) or self._fallback_client is not None++ def pop_all(self) -> list[Any]:+ """Remove and return every retained client."""++ with self._lock:+ clients = list(self._clients_by_loop.values())+ self._clients_by_loop.clear()+ if self._fallback_client is not None:+ clients.append(self._fallback_client)+ self._fallback_client = None+ return clients++ @staticmethod+ async def _close_clients(clients: list[Any], close_client: Callable[[Any], Any]) -> None:+ seen: set[int] = set()+ for client in clients:+ client_id = id(client)+ if client_id in seen:+ continue+ seen.add(client_id)+ result = close_client(client)+ if inspect.isawaitable(result):+ await result++ def close_all(self, close_client: Callable[[Any], Any]) -> None:+ """Close and clear all cached clients on a best-effort basis."""++ clients = self.pop_all()+ if not clients:+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ loop = None+ if loop and loop.is_running():+ loop.create_task(self._close_clients(clients, close_client))+ else:+ asyncio.run(self._close_clients(clients, close_client))++ def close_all_with_close(self) -> None:+ self.close_all(_close_client)++ def close_all_with_aclose(self) -> None:+ self.close_all(_aclose_client)diff --git a/integrations/langchain/src/langchain_openviking/_testing_utils.py b/integrations/langchain/src/langchain_openviking/_testing_utils.pynew file mode 100644index 000000000..08aa18fd9--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/_testing_utils.py@@ -0,0 +1,62 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Private deterministic helpers for the in-memory integration test client."""++from __future__ import annotations++import math+import re++_IDENTIFIER_PATTERN = re.compile(r"^[a-zA-Z0-9_.@-]+$")+++def normalize_peer_id(peer_id: str | None) -> str | None:+ """Normalize a peer identifier using OpenViking's public wire constraints."""++ if peer_id is None:+ return None+ if not isinstance(peer_id, str):+ raise ValueError("Invalid peer_id: peer_id must be a string.")+ normalized = peer_id.strip()+ if not normalized:+ return None+ if normalized in {".", ".."}:+ raise ValueError("Invalid peer_id: peer_id must not be '.' or '..'")+ if not _IDENTIFIER_PATTERN.fullmatch(normalized):+ raise ValueError("Invalid peer_id: peer_id must be alpha_numeric string.")+ if normalized.count("@") > 1:+ raise ValueError("Invalid peer_id: peer_id must have at most one @.")+ return normalized+++def _is_cjk_code_point(code_point: int) -> bool:+ return (+ 0x3400 <= code_point <= 0x4DBF+ or 0x4E00 <= code_point <= 0x9FFF+ or 0xF900 <= code_point <= 0xFAFF+ or 0x20000 <= code_point <= 0x2EBEF+ or 0x3040 <= code_point <= 0x30FF+ or 0x31F0 <= code_point <= 0x31FF+ or 0xAC00 <= code_point <= 0xD7AF+ or 0x1100 <= code_point <= 0x11FF+ or 0x3130 <= code_point <= 0x318F+ or 0xFF00 <= code_point <= 0xFFEF+ or 0x3000 <= code_point <= 0x303F+ )+++def estimate_text_tokens(text: str | None) -> int:+ """Estimate tokens conservatively without depending on server internals."""++ if not text:+ return 0+ weight = 0.0+ for char in text:+ code_point = ord(char)+ if _is_cjk_code_point(code_point):+ weight += 1.5+ elif code_point > 0xFFFF:+ weight += 2.0+ else:+ weight += 0.25+ return math.ceil(weight)diff --git a/integrations/langchain/src/langchain_openviking/_uri.py b/integrations/langchain/src/langchain_openviking/_uri.pynew file mode 100644index 000000000..01f2822ce--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/_uri.py@@ -0,0 +1,61 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Narrow Viking URI parsing used by the LangGraph store adapter."""++from __future__ import annotations++from dataclasses import dataclass++_CONTENT_SEGMENTS = frozenset({"memories", "resources", "skills"})+_PEER_CONTENT_SEGMENTS = frozenset({"memories", "resources"})+++@dataclass(frozen=True)+class UriClassification:+ """Structural URI information needed to validate store record paths."""++ parts: tuple[str, ...]+ scope: str+ content_index: int | None+++def _uri_parts(uri: str) -> tuple[str, ...]:+ value = str(uri or "").split("?", 1)[0].strip()+ if not value:+ return ()+ if value == "/":+ value = "viking://"+ elif not value.startswith("viking://"):+ value = f"viking://{value.lstrip('/')}"+ if value.rstrip("/") == "viking:":+ return ()+ return tuple(part for part in value[len("viking://") :].split("/") if part)+++def _content_segment_index(parts: tuple[str, ...]) -> int | None:+ if len(parts) >= 2 and parts[:2] == ("agent", "skills"):+ return 1+ if len(parts) >= 3 and parts[0] == "agent" and parts[2] in _CONTENT_SEGMENTS:+ return 2+ if len(parts) < 2 or parts[0] != "user":+ return None+ if parts[1] in _CONTENT_SEGMENTS:+ return 1+ if len(parts) >= 4 and parts[1] == "peers" and parts[3] in _PEER_CONTENT_SEGMENTS:+ return 3+ if len(parts) >= 5 and parts[2] == "peers" and parts[4] in _PEER_CONTENT_SEGMENTS:+ return 4+ if len(parts) >= 3 and parts[2] in _CONTENT_SEGMENTS:+ return 2+ return None+++def classify_uri(uri: str) -> UriClassification:+ """Classify the user/agent namespace shape of a Viking URI."""++ parts = _uri_parts(uri)+ return UriClassification(+ parts=parts,+ scope=parts[0] if parts else "",+ content_index=_content_segment_index(parts),+ )diff --git a/integrations/langchain/src/langchain_openviking/actor_peer.py b/integrations/langchain/src/langchain_openviking/actor_peer.pynew file mode 100644index 000000000..c69c629bf--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/actor_peer.py@@ -0,0 +1,48 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Compatibility bridge for request-scoped actor peers in openviking-sdk."""++from __future__ import annotations++from contextlib import AbstractContextManager+from importlib import import_module+from typing import Callable, cast++_openviking_sdk = import_module("openviking_sdk")+_actor_peer_getter = getattr(_openviking_sdk, "get_actor_peer_id", None)+_actor_peer_scope = getattr(_openviking_sdk, "use_actor_peer", None)+++def has_request_actor_peer_support() -> bool:+ """Return whether the installed SDK supports request-scoped actor peers."""++ return _actor_peer_getter is not None and _actor_peer_scope is not None+++def require_request_actor_peer_support() -> None:+ """Raise an actionable error when request-scoped actor peers are unavailable."""++ if not has_request_actor_peer_support():+ raise ImportError(+ "Runtime actor peers require an openviking-sdk release with "+ "request-scoped actor-peer support. Upgrade openviking-sdk and retry."+ )+++def get_actor_peer_id() -> str | None:+ """Return the active SDK actor peer, tolerating older SDKs when unused."""++ if _actor_peer_getter is None:+ return None+ return cast(Callable[[], str | None], _actor_peer_getter)()+++def use_actor_peer(actor_peer_id: str | None) -> AbstractContextManager[None]:+ """Apply an SDK actor-peer scope after confirming SDK support."""++ require_request_actor_peer_support()+ scope_factory = cast(+ Callable[[str | None], AbstractContextManager[None]],+ _actor_peer_scope,+ )+ return scope_factory(actor_peer_id)diff --git a/integrations/langchain/src/langchain_openviking/client.py b/integrations/langchain/src/langchain_openviking/client.pynew file mode 100644index 000000000..3c58f9fcc--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/client.py@@ -0,0 +1,872 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Shared helpers for LangChain/LangGraph integration adapters."""++from __future__ import annotations++import asyncio+import copy+import inspect+import json+import logging+import threading+from dataclasses import dataclass+from importlib import import_module+from typing import Any, Callable, Iterable, Literal++from langchain_openviking._async_client_cache import LoopScopedAsyncClientCache++logger = logging.getLogger(__name__)++_RETRYABLE_READ_METHODS = {+ "abstract",+ "archive_expand",+ "archive_search",+ "find",+ "get_session",+ "get_session_archive",+ "get_session_context",+ "get_status",+ "glob",+ "health",+ "is_healthy",+ "ls",+ "overview",+ "read",+ "relations",+ "search",+ "session_exists",+ "stat",+}++_RECOVERABLE_OPENVIKING_CODES = {"DEADLINE_EXCEEDED", "UNAVAILABLE"}+_RECOVERABLE_RUNTIME_MESSAGE_FRAGMENTS = (+ "event loop is closed",+ "attached to a different loop",+ "bound to a different event loop",+)+_ASYNC_INITIALIZATION_LOCKS_ATTR = "_openviking_integration_initialize_locks"+++class OptionalDependencyError(ImportError):+ """Raised when an optional framework dependency is not installed."""+++def missing_dependency(extra: str, package: str | None = None) -> OptionalDependencyError:+ package = package or extra+ install_target = "langchain-openviking"+ if extra == "langgraph":+ install_target += "[langgraph]"+ return OptionalDependencyError(+ f"{package} is required for this OpenViking integration. "+ f'Install it with `pip install "{install_target}"`.'+ )+++@dataclass(slots=True)+class OpenVikingConnection:+ """Connection settings for lazily creating an OpenViking client."""++ client: Any = None+ url: str | None = None+ api_key: str | None = None+ account: str | None = None+ user: str | None = None+ user_id: str | None = None+ actor_peer_id: str | None = None+ path: str | None = None+ timeout: float = 60.0+ extra_headers: dict[str, str] | None = None+ auto_initialize: bool = True+ async_client: Any = None++ def __deepcopy__(self, memo: dict[int, Any]) -> OpenVikingConnection:+ """Copy configuration while preserving caller-owned client identities."""++ copied = type(self)(+ client=self.client,+ async_client=self.async_client,+ url=self.url,+ api_key=self.api_key,+ account=self.account,+ user=self.user,+ user_id=self.user_id,+ actor_peer_id=self.actor_peer_id,+ path=self.path,+ timeout=self.timeout,+ extra_headers=copy.deepcopy(self.extra_headers, memo),+ auto_initialize=self.auto_initialize,+ )+ memo[id(self)] = copied+ return copied+++@dataclass(slots=True)+class OpenVikingCommitPolicy:+ """Commit behavior for OpenViking-backed agent sessions."""++ mode: Literal["never", "always", "pending_tokens"] = "never"+ pending_token_threshold: int = 8_000+++class OpenVikingClientHandle:+ """Lazy OpenViking client wrapper with one-shot recovery for safe reads."""++ def __init__(self, connection: OpenVikingConnection):+ self._connection = connection+ self._client: Any = None+ self._client_lock = threading.Lock()++ @property+ def supports_request_actor_peer(self) -> bool:+ """Return whether this handle supports request-scoped actor peers."""++ return _uses_http_client(self._connection)++ @property+ def _initialized(self) -> bool:+ client = self._client+ return bool(client is not None and getattr(client, "_initialized", False))++ def close(self) -> None:+ self.reset()++ def reset(self) -> None:+ with self._client_lock:+ client = self._client+ self._client = None+ self._close_client(client)++ def _reset_if_current(self, client: Any) -> None:+ with self._client_lock:+ if self._client is not client:+ return+ self._client = None+ self._close_client(client)++ @staticmethod+ def _close_client(client: Any) -> None:+ if client is None:+ return+ close = getattr(client, "close", None)+ if not callable(close):+ return+ try:+ close()+ except Exception:+ logger.debug("OpenViking client close during recovery failed", exc_info=True)++ def get(self) -> Any:+ with self._client_lock:+ if self._client is None:+ self._client = _create_client_from_connection(self._connection)+ return self._client++ def _openviking_call(self, method_name: str, /, **kwargs: Any) -> Any:+ return self._call_with_recovery(method_name, **kwargs)++ def _call_with_recovery(self, method_name: str, /, *args: Any, **kwargs: Any) -> Any:+ client = self.get()+ try:+ return _call_client_method(client, method_name, *args, **kwargs)+ except Exception as exc:+ if not _is_recoverable_client_error(exc):+ raise+ self._reset_if_current(client)+ if not _should_retry_method(method_name):+ raise+ retry_client = self.get()+ try:+ return _call_client_method(retry_client, method_name, *args, **kwargs)+ except Exception as retry_exc:+ if _is_recoverable_client_error(retry_exc):+ self._reset_if_current(retry_client)+ raise++ def __copy__(self) -> OpenVikingClientHandle:+ return self++ def __deepcopy__(self, memo: dict[int, Any]) -> OpenVikingClientHandle:+ copied = type(self)(copy.deepcopy(self._connection, memo))+ memo[id(self)] = copied+ return copied++ def __getattr__(self, name: str) -> Any:+ attr = getattr(self.get(), name)+ if not callable(attr):+ return attr++ def recovered_method(*args: Any, **kwargs: Any) -> Any:+ return self._call_with_recovery(name, *args, **kwargs)++ return recovered_method+++class OpenVikingAsyncClientHandle:+ """Lazy, loop-local async client wrapper with one-shot recovery for safe reads.++ Method calls through the handle are recovery-safe. Direct client attribute+ access is best-effort and may be unavailable while recovery replaces the+ underlying client.+ """++ def __init__(self, connection: OpenVikingConnection):+ self._connection = connection+ self._client: Any = None+ self._client_lock = asyncio.Lock()+ try:+ self._loop: asyncio.AbstractEventLoop | None = asyncio.get_running_loop()+ except RuntimeError:+ self._loop = None++ @property+ def supports_request_actor_peer(self) -> bool:+ """Return whether this handle supports request-scoped actor peers."""++ return _uses_http_client(self._connection)++ @property+ def _initialized(self) -> bool:+ client = self._client+ return bool(client is not None and _async_client_is_initialized(client))++ async def initialize(self) -> None:+ """Initialize the underlying client once."""++ await self.get()++ async def close(self) -> None:+ owner_loop = self._loop+ current_loop = asyncio.get_running_loop()+ if owner_loop is None or owner_loop is current_loop:+ await self.reset()+ return+ if owner_loop.is_running():+ reset = self.reset()+ try:+ future = asyncio.run_coroutine_threadsafe(reset, owner_loop)+ except RuntimeError:+ reset.close()+ else:+ await asyncio.wrap_future(future)+ return+ await self._reset_without_lock()++ async def reset(self) -> None:+ async with self._client_lock:+ client = self._client+ self._client = None+ await self._close_client(client)++ async def _reset_if_current(self, client: Any) -> None:+ """Reset only when ``client`` is still the active snapshot."""++ async with self._client_lock:+ if self._client is not client:+ return+ self._client = None+ await self._close_client(client)++ async def _reset_without_lock(self) -> None:+ """Detach a client after its originating loop has stopped."""++ client = self._client+ self._client = None+ await self._close_client(client)++ async def _close_client(self, client: Any) -> None:+ if client is None:+ return+ try:+ await aclose_openviking_client(client)+ except Exception:+ logger.debug("OpenViking async client close during recovery failed", exc_info=True)++ async def get(self) -> Any:+ """Return the current client snapshot, initializing it when necessary.++ Read raw properties immediately and do not retain this client: a later+ recovery may replace and close it.+ """++ current_loop = asyncio.get_running_loop()+ if self._loop is None:+ self._loop = current_loop+ elif self._loop is not current_loop:+ raise RuntimeError(+ "OpenVikingAsyncClientHandle is loop-local and cannot be reused "+ "from another event loop"+ )+ if self._client is None:+ async with self._client_lock:+ if self._client is None:+ self._client = await _create_async_client_from_connection(self._connection)+ return self._client++ async def _openviking_acall(self, method_name: str, /, **kwargs: Any) -> Any:+ return await self._call_with_recovery(method_name, **kwargs)++ async def _call_with_recovery(+ self,+ method_name: str,+ /,+ *args: Any,+ **kwargs: Any,+ ) -> Any:+ client = await self.get()+ try:+ return await _acall_client_method(+ client,+ method_name,+ *args,+ **kwargs,+ )+ except Exception as exc:+ if not _is_recoverable_client_error(exc):+ raise+ await self._reset_if_current(client)+ if not _should_retry_method(method_name):+ raise+ retry_client = await self.get()+ try:+ return await _acall_client_method(+ retry_client,+ method_name,+ *args,+ **kwargs,+ )+ except Exception as retry_exc:+ if _is_recoverable_client_error(retry_exc):+ await self._reset_if_current(retry_client)+ raise++ def __copy__(self) -> OpenVikingAsyncClientHandle:+ return self++ def __deepcopy__(self, memo: dict[int, Any]) -> OpenVikingAsyncClientHandle:+ copied = type(self)(copy.deepcopy(self._connection, memo))+ memo[id(self)] = copied+ return copied++ def __getattr__(self, name: str) -> Any:+ if name.startswith("__") and name.endswith("__"):+ raise AttributeError(name)+ client = self._client+ if client is not None:+ attr = getattr(client, name)+ if not callable(attr):+ return attr++ async def recovered_method(*args: Any, **kwargs: Any) -> Any:+ return await self._call_with_recovery(name, *args, **kwargs)++ return recovered_method+++def ensure_client(connection: OpenVikingConnection) -> Any:+ """Return an initialized OpenViking client from explicit or connection settings."""++ client = connection.client+ if client is None:+ if connection.url or connection.path is None:+ handle = OpenVikingClientHandle(connection)+ if connection.auto_initialize:+ handle.get()+ return handle+ return _create_client_from_connection(connection)+ if connection.auto_initialize and hasattr(client, "initialize"):+ if not getattr(client, "_initialized", False):+ client.initialize()+ return client+++async def ensure_async_client(+ connection: OpenVikingConnection,+ *,+ client_cache: LoopScopedAsyncClientCache | None = None,+ embedded_client_factory: Callable[[], Any] | None = None,+) -> Any:+ """Return a client suitable for non-blocking OpenViking calls.++ An explicitly supplied async client is preferred. Existing synchronous+ clients remain supported and are dispatched through a worker thread by+ :func:`acall_openviking`. Internally created HTTP handles can be scoped to+ the running loop with ``client_cache``. Embedded ``path=`` connections+ intentionally use the synchronous client so their stateful async internals+ remain on OpenViking's shared background loop.+ """++ client = connection.async_client+ if client is None and connection.client is not None:+ client = connection.client+ if client is None:+ if _uses_http_client(connection):+ if client_cache is None:+ handle = OpenVikingAsyncClientHandle(connection)+ else:+ handle = client_cache.get(lambda: OpenVikingAsyncClientHandle(connection))+ if connection.auto_initialize:+ await handle.get()+ return handle+ if embedded_client_factory is not None:+ if client_cache is not None:+ # The thread hop is load-bearing: without a running event loop,+ # the embedded singleton occupies the cache's shared fallback slot.+ return await asyncio.to_thread(+ client_cache.get,+ embedded_client_factory,+ )+ return await asyncio.to_thread(embedded_client_factory)+ return await asyncio.to_thread(_create_client_from_connection, connection)+ if connection.auto_initialize and hasattr(client, "initialize"):+ await _ainitialize_client(client)+ return client+++def is_not_found_error(exc: BaseException) -> bool:+ """True for OpenViking NOT_FOUND across cli/sdk exception classes."""++ if isinstance(exc, FileNotFoundError):+ return True+ return str(getattr(exc, "code", "") or "").upper() == "NOT_FOUND"+++def apply_commit_policy(+ client: Any,+ session_id: str,+ policy: OpenVikingCommitPolicy | None,+ *,+ persisted_pending_tokens: Any = None,+) -> dict[str, Any] | None:+ """Apply the configured session commit policy after message persistence.++ ``persisted_pending_tokens`` is the post-write value returned by+ ``add_message`` or ``batch_add_messages``. When an older client does not+ return it, the pending-token policy falls back to the legacy session lookup.+ Committing remains a separate operation from message persistence.+ """++ if policy is None or policy.mode == "never":+ return None+ if policy.mode == "always":+ return call_openviking(+ client,+ "commit_session",+ session_id=session_id,+ )+ if policy.mode != "pending_tokens":+ raise ValueError(f"Unsupported OpenViking commit policy: {policy.mode}")++ pending_tokens: int | None = None+ if persisted_pending_tokens is not None:+ try:+ pending_tokens = int(persisted_pending_tokens or 0)+ except (TypeError, ValueError):+ logger.debug(+ "Ignoring invalid persisted pending-token value and falling back "+ "to session lookup: %r",+ persisted_pending_tokens,+ )++ if pending_tokens is None:+ try:+ session = call_openviking(+ client, "get_session", session_id=session_id, auto_create=False+ )+ except Exception:+ logger.debug(+ "Skipping OpenViking pending-token commit because session lookup failed",+ exc_info=True,+ )+ return None+ pending_tokens = int(item_value(session, "pending_tokens", 0) or 0)+ if pending_tokens < policy.pending_token_threshold:+ return None+ return call_openviking(+ client,+ "commit_session",+ session_id=session_id,+ )+++async def aapply_commit_policy(+ client: Any,+ session_id: str,+ policy: OpenVikingCommitPolicy | None,+ *,+ persisted_pending_tokens: Any = None,+) -> dict[str, Any] | None:+ """Apply the configured session commit policy without blocking the event loop."""++ if policy is None or policy.mode == "never":+ return None+ if policy.mode == "always":+ return await acall_openviking(+ client,+ "commit_session",+ session_id=session_id,+ )+ if policy.mode != "pending_tokens":+ raise ValueError(f"Unsupported OpenViking commit policy: {policy.mode}")++ pending_tokens: int | None = None+ if persisted_pending_tokens is not None:+ try:+ pending_tokens = int(persisted_pending_tokens or 0)+ except (TypeError, ValueError):+ logger.debug(+ "Ignoring invalid persisted pending-token value and falling back "+ "to session lookup: %r",+ persisted_pending_tokens,+ )++ if pending_tokens is None:+ try:+ session = await acall_openviking(+ client,+ "get_session",+ session_id=session_id,+ auto_create=False,+ )+ except Exception:+ logger.debug(+ "Skipping OpenViking pending-token commit because session lookup failed",+ exc_info=True,+ )+ return None+ pending_tokens = int(item_value(session, "pending_tokens", 0) or 0)+ if pending_tokens < policy.pending_token_threshold:+ return None+ return await acall_openviking(+ client,+ "commit_session",+ session_id=session_id,+ )+++def call_openviking(client: Any, method_name: str, /, **kwargs: Any) -> Any:+ """Call a client method, filtering kwargs unsupported by local/HTTP variants."""++ openviking_call = getattr(client, "_openviking_call", None)+ if callable(openviking_call):+ return openviking_call(method_name, **kwargs)+ return _call_client_method(client, method_name, **kwargs)+++async def acall_openviking(client: Any, method_name: str, /, **kwargs: Any) -> Any:+ """Call an async or sync client method without blocking the event loop."""++ openviking_call = getattr(client, "_openviking_acall", None)+ if callable(openviking_call):+ return await openviking_call(method_name, **kwargs)+ return await _acall_client_method(client, method_name, **kwargs)+++def _create_client_from_connection(connection: OpenVikingConnection) -> Any:+ client: Any+ if connection.url or connection.path is None:+ from openviking_sdk import SyncHTTPClient++ client = SyncHTTPClient(+ url=connection.url,+ api_key=connection.api_key,+ account=connection.account,+ user=connection.user,+ user_id=connection.user_id,+ actor_peer_id=connection.actor_peer_id,+ timeout=connection.timeout,+ extra_headers=connection.extra_headers,+ )+ else:+ try:+ openviking = import_module("openviking")+ sync_openviking = openviking.SyncOpenViking+ except ImportError as exc:+ raise OptionalDependencyError(+ "Embedded path= connections require the full openviking package. "+ 'Install it with `pip install "openviking"`, or configure an '+ "OpenViking server URL for lightweight HTTP usage."+ ) from exc++ client = sync_openviking(path=connection.path, actor_peer_id=connection.actor_peer_id)++ if connection.auto_initialize and hasattr(client, "initialize"):+ if not getattr(client, "_initialized", False):+ client.initialize()+ return client+++async def _create_async_client_from_connection(connection: OpenVikingConnection) -> Any:+ if not _uses_http_client(connection):+ raise ValueError("Native async clients are created automatically only for HTTP connections")++ from openviking_sdk import AsyncHTTPClient++ client: Any = AsyncHTTPClient(+ url=connection.url,+ api_key=connection.api_key,+ account=connection.account,+ user=connection.user,+ user_id=connection.user_id,+ actor_peer_id=connection.actor_peer_id,+ timeout=connection.timeout,+ extra_headers=connection.extra_headers,+ )++ try:+ if connection.auto_initialize and hasattr(client, "initialize"):+ await _ainitialize_client(client)+ except BaseException:+ try:+ await aclose_openviking_client(client)+ except Exception:+ logger.debug(+ "OpenViking async client close after initialization failure failed",+ exc_info=True,+ )+ raise+ return client+++async def aclose_openviking_client(client: Any) -> None:+ """Close an async or sync OpenViking client without blocking the event loop."""++ close = getattr(client, "close", None)+ if not callable(close):+ return+ if inspect.iscoroutinefunction(close):+ await close()+ return+ result = await asyncio.to_thread(close)+ if inspect.isawaitable(result):+ await result+++async def aclose_openviking_clients(*clients: Any) -> None:+ """Close every distinct client and re-raise the first cleanup failure."""++ seen: set[int] = set()+ first_error: BaseException | None = None+ for client in clients:+ if client is None or id(client) in seen:+ continue+ seen.add(id(client))+ try:+ await aclose_openviking_client(client)+ except BaseException as exc:+ if first_error is None:+ first_error = exc+ if first_error is not None:+ raise first_error+++def _call_client_method(+ client: Any,+ method_name: str,+ /,+ *args: Any,+ **kwargs: Any,+) -> Any:+ method = getattr(client, method_name)+ return method(*args, **_filter_client_kwargs(method, kwargs))+++async def _acall_client_method(+ client: Any,+ method_name: str,+ /,+ *args: Any,+ **kwargs: Any,+) -> Any:+ method = getattr(client, method_name)+ filtered_kwargs = _filter_client_kwargs(method, kwargs)+ if inspect.iscoroutinefunction(method):+ return await method(*args, **filtered_kwargs)+ result = await asyncio.to_thread(method, *args, **filtered_kwargs)+ if inspect.isawaitable(result):+ return await result+ return result+++async def _ainitialize_client(client: Any) -> None:+ if _async_client_is_initialized(client):+ return+ lock = _async_client_initialization_lock(client)+ async with lock:+ if _async_client_is_initialized(client):+ return+ await _acall_client_method(client, "initialize")+ try:+ client._openviking_integration_initialized = True+ except Exception:+ pass+++def _async_client_initialization_lock(client: Any) -> asyncio.Lock:+ try:+ locks = inspect.getattr_static(client, _ASYNC_INITIALIZATION_LOCKS_ATTR)+ except AttributeError:+ locks = LoopScopedAsyncClientCache()+ try:+ setattr(client, _ASYNC_INITIALIZATION_LOCKS_ATTR, locks)+ except Exception:+ return asyncio.Lock()+ if not isinstance(locks, LoopScopedAsyncClientCache):+ locks = LoopScopedAsyncClientCache()+ try:+ setattr(client, _ASYNC_INITIALIZATION_LOCKS_ATTR, locks)+ except Exception:+ return asyncio.Lock()+ return locks.get(asyncio.Lock)+++def _uses_http_client(connection: OpenVikingConnection) -> bool:+ """Return whether connection settings select the HTTP transport."""++ return bool(connection.url) or connection.path is None+++def _async_client_is_initialized(client: Any) -> bool:+ for name in ("_initialized", "_http"):+ try:+ inspect.getattr_static(client, name)+ except AttributeError:+ continue+ value = getattr(client, name, None)+ if name == "_http":+ return value is not None+ return bool(value)+ try:+ inspect.getattr_static(client, "_openviking_integration_initialized")+ except AttributeError:+ return False+ return bool(getattr(client, "_openviking_integration_initialized", False))+++def _filter_client_kwargs(method: Any, kwargs: dict[str, Any]) -> dict[str, Any]:+ """Drop ``None`` and arguments unsupported by a concrete client variant."""++ try:+ signature = inspect.signature(method)+ except (TypeError, ValueError):+ return {key: value for key, value in kwargs.items() if value is not None}++ accepts_kwargs = any(+ parameter.kind == inspect.Parameter.VAR_KEYWORD+ for parameter in signature.parameters.values()+ )+ if accepts_kwargs:+ return {key: value for key, value in kwargs.items() if value is not None}+ return {+ key: value+ for key, value in kwargs.items()+ if value is not None and key in signature.parameters+ }+++def _should_retry_method(method_name: str) -> bool:+ return method_name in _RETRYABLE_READ_METHODS+++def _is_recoverable_client_error(exc: BaseException) -> bool:+ code = getattr(exc, "code", None)+ if isinstance(code, str) and code.upper() in _RECOVERABLE_OPENVIKING_CODES:+ return True+ if isinstance(exc, (ConnectionError, TimeoutError, OSError)):+ return True+ if isinstance(exc, RuntimeError):+ message = str(exc).lower()+ return any(fragment in message for fragment in _RECOVERABLE_RUNTIME_MESSAGE_FRAGMENTS)+ try:+ import httpx+ except Exception: # pragma: no cover - httpx is available in HTTP installs+ return False+ return isinstance(exc, (httpx.TimeoutException, httpx.TransportError))+++def result_groups(result: Any) -> list[tuple[str, list[Any]]]:+ """Normalize OpenViking retrieval results into named context groups."""++ if result is None:+ return []+ if isinstance(result, dict):+ return [+ ("memory", list(result.get("memories") or [])),+ ("resource", list(result.get("resources") or [])),+ ("skill", list(result.get("skills") or [])),+ ]+ return [+ ("memory", list(getattr(result, "memories", []) or [])),+ ("resource", list(getattr(result, "resources", []) or [])),+ ("skill", list(getattr(result, "skills", []) or [])),+ ]+++def item_value(item: Any, key: str, default: Any = None) -> Any:+ if isinstance(item, dict):+ return item.get(key, default)+ return getattr(item, key, default)+++def iter_result_items(+ result: Any,+ context_types: Iterable[str] = ("memory", "resource", "skill"),+) -> Iterable[tuple[str, Any]]:+ allowed = set(context_types)+ for context_type, items in result_groups(result):+ if context_type not in allowed:+ continue+ for item in items:+ yield context_type, item+++def compact_json(value: Any) -> str:+ return json.dumps(value, ensure_ascii=False, default=str, separators=(",", ":"))+++def stringify(value: Any, *, max_chars: int = 12_000) -> str:+ if value is None:+ text = ""+ elif isinstance(value, str):+ text = value+ else:+ text = json.dumps(value, ensure_ascii=False, default=str, indent=2)+ if max_chars > 0 and len(text) > max_chars:+ return text[:max_chars] + "\n...[truncated]"+ return text+++def extract_message_text(content: Any) -> str:+ """Extract text from LangChain/OpenAI-style message content."""++ if isinstance(content, str):+ return content+ if isinstance(content, list):+ chunks: list[str] = []+ for block in content:+ if isinstance(block, str):+ chunks.append(block)+ elif isinstance(block, dict):+ if block.get("type") == "text" and isinstance(block.get("text"), str):+ chunks.append(block["text"])+ elif isinstance(block.get("content"), str):+ chunks.append(block["content"])+ return "\n".join(chunk for chunk in chunks if chunk)+ if content is None:+ return ""+ return str(content)+++def get_latest_user_text(messages: Iterable[Any]) -> str:+ for message in reversed(list(messages)):+ role = getattr(message, "type", None) or getattr(message, "role", None)+ if isinstance(message, dict):+ role = message.get("type") or message.get("role")+ content = message.get("content")+ else:+ content = getattr(message, "content", "")+ if role in {"human", "user"}:+ text = extract_message_text(content).strip()+ if text:+ return text+ return ""diff --git a/integrations/langchain/src/langchain_openviking/context.py b/integrations/langchain/src/langchain_openviking/context.pynew file mode 100644index 000000000..b06e94958--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/context.py@@ -0,0 +1,944 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""High-level OpenViking context lifecycle helpers for LangChain."""++from __future__ import annotations++import asyncio+import logging+import threading+from collections.abc import AsyncIterator, Callable, Sequence+from contextlib import asynccontextmanager, contextmanager+from copy import deepcopy+from dataclasses import dataclass, field+from typing import Any, Iterator++from pydantic import PrivateAttr++try:+ from langchain_core.messages import BaseMessage, SystemMessage+ from langchain_core.runnables import ConfigurableFieldSpec, RunnableLambda+ from langchain_core.runnables.history import RunnableWithMessageHistory+except ImportError as exc: # pragma: no cover - exercised by optional import path+ from langchain_openviking.client import missing_dependency++ raise missing_dependency("langchain", "langchain-core") from exc++from langchain_openviking._async_client_cache import LoopScopedAsyncClientCache+from langchain_openviking.client import (+ OpenVikingCommitPolicy,+ OpenVikingConnection,+ acall_openviking,+ aclose_openviking_clients,+ call_openviking,+ ensure_async_client,+ ensure_client,+ extract_message_text,+ get_latest_user_text,+ is_not_found_error,+)+from langchain_openviking.history import (+ OpenVikingChatMessageHistory,+ context_parts_from_documents,+)+from langchain_openviking.messages import OPENVIKING_CONTEXT_MARKER+from langchain_openviking.recording import OpenVikingSessionRecorder+from langchain_openviking.retrievers import OpenVikingRetriever++logger = logging.getLogger(__name__)+++@dataclass(slots=True)+class OpenVikingAssembledContext:+ """Context block plus structured references assembled before an agent turn."""++ block: str = ""+ context_parts: list[dict[str, Any]] = field(default_factory=list)+ session_context: dict[str, Any] = field(default_factory=dict)+ recall_documents: list[Any] = field(default_factory=list)+++@dataclass(slots=True)+class _AsyncSessionWriteLockEntry:+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)+ users: int = 0+++class _AsyncSessionWriteLockPool:+ """Serialize completed writes without retaining inactive session IDs."""++ def __init__(self) -> None:+ self._entries: dict[str, _AsyncSessionWriteLockEntry] = {}++ @asynccontextmanager+ async def acquire(self, session_id: str) -> AsyncIterator[None]:+ entry = self._entries.get(session_id)+ if entry is None:+ entry = _AsyncSessionWriteLockEntry()+ self._entries[session_id] = entry+ entry.users += 1+ acquired = False+ try:+ await entry.lock.acquire()+ acquired = True+ yield+ finally:+ if acquired:+ entry.lock.release()+ entry.users -= 1+ if entry.users == 0 and self._entries.get(session_id) is entry:+ self._entries.pop(session_id, None)+++@dataclass(slots=True)+class _SyncSessionWriteLockEntry:+ lock: threading.Lock = field(default_factory=threading.Lock)+ users: int = 0+++class _SyncSessionWriteLockPool:+ """Serialize synchronous writes without retaining inactive session IDs."""++ def __init__(self) -> None:+ self._entries: dict[str, _SyncSessionWriteLockEntry] = {}+ self._entries_lock = threading.Lock()++ @contextmanager+ def acquire(self, session_id: str) -> Iterator[None]:+ with self._entries_lock:+ entry = self._entries.get(session_id)+ if entry is None:+ entry = _SyncSessionWriteLockEntry()+ self._entries[session_id] = entry+ entry.users += 1+ try:+ with entry.lock:+ yield+ finally:+ with self._entries_lock:+ entry.users -= 1+ if entry.users == 0 and self._entries.get(session_id) is entry:+ self._entries.pop(session_id, None)+++class _InvocationOpenVikingChatMessageHistory(OpenVikingChatMessageHistory):+ """Hold the entry history snapshot for one runnable invocation."""++ def __init__(+ self,+ *args: Any,+ recorder: OpenVikingSessionRecorder,+ sync_write_lock_pool: _SyncSessionWriteLockPool,+ async_write_lock_pools: LoopScopedAsyncClientCache,+ **kwargs: Any,+ ):+ super().__init__(*args, _recorder=recorder, **kwargs)+ self._entry_snapshot: list[BaseMessage] | None = None+ self._sync_write_lock_pool = sync_write_lock_pool+ self._async_write_lock_pools = async_write_lock_pools++ @property+ def messages(self) -> list[BaseMessage]: # type: ignore[override]+ if self._entry_snapshot is None:+ self._entry_snapshot = list(super().messages)+ return list(self._entry_snapshot)++ async def aget_messages(self) -> list[BaseMessage]:+ if self._entry_snapshot is None:+ self._entry_snapshot = list(await super().aget_messages())+ return list(self._entry_snapshot)++ def add_messages(self, messages: Sequence[BaseMessage]) -> None:+ try:+ with self._sync_write_lock_pool.acquire(self.session_id):+ super().add_messages(messages)+ finally:+ self._entry_snapshot = None++ async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:+ try:+ lock_pool = self._async_write_lock_pools.get(_AsyncSessionWriteLockPool)+ async with lock_pool.acquire(self.session_id):+ await super().aadd_messages(messages)+ finally:+ self._entry_snapshot = None+++class OpenVikingSessionContextAssembler:+ """Assemble session working memory, archive context, and recall results."""++ def __init__(+ self,+ *,+ client: Any = None,+ async_client: Any = None,+ retriever: OpenVikingRetriever | None = None,+ url: str | None = None,+ api_key: str | None = None,+ account: str | None = None,+ user: str | None = None,+ user_id: str | None = None,+ actor_peer_id: str | None = None,+ path: str | None = None,+ timeout: float = 60.0,+ extra_headers: dict[str, str] | None = None,+ auto_initialize: bool = True,+ target_uri: str | list[str] = "",+ limit: int = 5,+ score_threshold: float | None = None,+ token_budget: int = 128_000,+ include_session_context: bool = True,+ include_active_messages: bool = True,+ include_recall: bool = True,+ recall_header: str = "Relevant OpenViking context:",+ ):+ self._connection = OpenVikingConnection(+ client=client,+ async_client=async_client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ timeout=timeout,+ extra_headers=extra_headers,+ auto_initialize=auto_initialize,+ )+ self.retriever = retriever or OpenVikingRetriever(+ client=client,+ async_client=async_client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ timeout=timeout,+ extra_headers=extra_headers,+ auto_initialize=auto_initialize,+ target_uri=target_uri,+ limit=limit,+ score_threshold=score_threshold,+ search_mode="search",+ )+ self.token_budget = token_budget+ self.include_session_context = include_session_context+ self.include_active_messages = include_active_messages+ self.include_recall = include_recall+ self.recall_header = recall_header+ self._owns_client = client is None+ self._owns_retriever = retriever is None+ self._client_cache: Any = None+ self._client_cache_lock = threading.Lock()+ self._async_clients = LoopScopedAsyncClientCache()+ self._closed = False++ def __deepcopy__(+ self,+ memo: dict[int, Any] | None = None,+ ) -> OpenVikingSessionContextAssembler:+ """Copy configuration with fresh caches and preserved injected ownership."""++ memo = {} if memo is None else memo+ for client in (self._connection.client, self._connection.async_client):+ if client is not None:+ memo[id(client)] = client+ if not self._owns_retriever:+ memo[id(self.retriever)] = self.retriever++ copied = type(self).__new__(type(self))+ memo[id(self)] = copied+ copied.__dict__ = {+ name: (+ None+ if name == "_client_cache"+ else threading.Lock()+ if name == "_client_cache_lock"+ else LoopScopedAsyncClientCache()+ if name == "_async_clients"+ else deepcopy(value, memo)+ )+ for name, value in self.__dict__.items()+ }+ return copied++ def assemble(+ self,+ *,+ session_id: str,+ query: str = "",+ ) -> OpenVikingAssembledContext:+ client = self._get_client()+ session_context = self._get_session_context(client, session_id)+ recall_documents = self._get_recall_documents(+ session_id,+ query,+ )+ return self._assembled_context(session_context, recall_documents)++ async def aassemble(+ self,+ *,+ session_id: str,+ query: str = "",+ ) -> OpenVikingAssembledContext:+ """Asynchronously assemble session and recall context."""++ client = await self._get_async_client()+ session_context = await self._aget_session_context(client, session_id)+ recall_documents = await self._aget_recall_documents(+ session_id,+ query,+ )+ return self._assembled_context(session_context, recall_documents)++ def _assembled_context(+ self,+ session_context: dict[str, Any],+ recall_documents: list[Any],+ ) -> OpenVikingAssembledContext:+ block = self._format_context_block(session_context, recall_documents)+ return OpenVikingAssembledContext(+ block=block,+ context_parts=context_parts_from_documents(recall_documents),+ session_context=session_context,+ recall_documents=recall_documents,+ )++ def _get_client(self) -> Any:+ self._raise_if_closed()+ if self._client_cache is None:+ with self._client_cache_lock:+ self._raise_if_closed()+ if self._client_cache is None:+ self._client_cache = ensure_client(self._connection)+ client = self._client_cache+ self._raise_if_closed()+ return client++ async def get_async_client(self) -> Any:+ """Return the async client interface used by this assembler.++ Injected clients are returned unchanged and remain caller-owned.+ HTTP-backed connections return an internally managed, loop-local handle+ whose method calls support recovery. Direct attributes on that handle+ are best-effort during recovery; use ``await handle.get()`` only to read+ raw properties immediately because recovery may replace that snapshot.+ Embedded ``path=`` connections return an adapter-owned synchronous+ client whose calls are dispatched through a worker thread.+ """++ self._raise_if_closed()+ client = await ensure_async_client(+ self._connection,+ client_cache=self._async_clients,+ embedded_client_factory=self._get_client,+ )+ self._raise_if_closed()+ return client++ async def _get_async_client(self) -> Any:+ return await self.get_async_client()++ async def aclose(self) -> None:+ """Release clients and the default retriever owned by this assembler."""++ if self._closed:+ return+ self._closed = True+ with self._client_cache_lock:+ sync_client = self._client_cache+ self._client_cache = None+ async_clients = await asyncio.to_thread(self._async_clients.pop_all)++ first_error: BaseException | None = None+ try:+ await aclose_openviking_clients(+ sync_client if self._owns_client else None,+ *async_clients,+ )+ except BaseException as exc:+ first_error = exc+ if self._owns_retriever:+ try:+ await self.retriever.aclose()+ except BaseException as exc:+ if first_error is None:+ first_error = exc+ if first_error is not None:+ raise first_error++ def _raise_if_closed(self) -> None:+ if self._closed:+ raise RuntimeError("OpenVikingSessionContextAssembler is closed")++ def _ensure_session(self, client: Any, session_id: str) -> None:+ try:+ call_openviking(client, "create_session", session_id=session_id)+ except Exception:+ logger.debug("OpenViking session ensure failed", exc_info=True)+ pass++ async def _aensure_session(self, client: Any, session_id: str) -> None:+ try:+ await acall_openviking(client, "create_session", session_id=session_id)+ except Exception:+ logger.debug("OpenViking session ensure failed", exc_info=True)++ def _get_session_context(self, client: Any, session_id: str) -> dict[str, Any]:+ if not self.include_session_context:+ # Without a context read there is no NOT_FOUND signal to create from.+ # Preserve the previous guarantee that recall receives a valid session.+ self._ensure_session(client, session_id)+ return {}+ try:+ return call_openviking(+ client,+ "get_session_context",+ session_id=session_id,+ token_budget=self.token_budget,+ )+ except Exception as exc:+ if is_not_found_error(exc):+ # First use: materialize the empty session, but do not issue a second+ # context read because the newly created session has no context yet.+ self._ensure_session(client, session_id)+ return {}+ logger.debug("OpenViking session context assembly failed", exc_info=True)+ return {}++ async def _aget_session_context(+ self,+ client: Any,+ session_id: str,+ ) -> dict[str, Any]:+ if not self.include_session_context:+ # Without a context read there is no NOT_FOUND signal to create from.+ # Preserve the previous guarantee that recall receives a valid session.+ await self._aensure_session(client, session_id)+ return {}+ try:+ return await acall_openviking(+ client,+ "get_session_context",+ session_id=session_id,+ token_budget=self.token_budget,+ )+ except Exception as exc:+ if is_not_found_error(exc):+ # First use: materialize the empty session, but do not issue a second+ # context read because the newly created session has no context yet.+ await self._aensure_session(client, session_id)+ return {}+ logger.debug("OpenViking session context assembly failed", exc_info=True)+ return {}++ def _get_recall_documents(+ self,+ session_id: str,+ query: str,+ ) -> list[Any]:+ if not self.include_recall or not query:+ return []+ try:+ return list(+ _retriever_for_session(+ self.retriever,+ session_id,+ ).invoke(query)+ )+ except Exception:+ logger.debug("OpenViking recall retrieval failed", exc_info=True)+ return []++ async def _aget_recall_documents(+ self,+ session_id: str,+ query: str,+ ) -> list[Any]:+ if not self.include_recall or not query:+ return []+ try:+ return list(+ await _retriever_for_session(+ self.retriever,+ session_id,+ ).ainvoke(query)+ )+ except Exception:+ logger.debug("OpenViking recall retrieval failed", exc_info=True)+ return []++ def _format_context_block(+ self,+ session_context: dict[str, Any],+ recall_documents: Sequence[Any],+ ) -> str:+ sections: list[str] = []+ latest_archive = str(session_context.get("latest_archive_overview") or "").strip()+ if latest_archive:+ sections.append("Session archive overview:\n" + latest_archive)++ abstracts = []+ for archive in session_context.get("pre_archive_abstracts") or []:+ archive_id = archive.get("archive_id") or "archive"+ abstract = str(archive.get("abstract") or "").strip()+ if abstract:+ abstracts.append(f"[{archive_id}] {abstract}")+ if abstracts:+ sections.append("Older archive abstracts:\n" + "\n".join(abstracts))++ if self.include_active_messages:+ active_messages = [+ _format_session_message(message)+ for message in session_context.get("messages") or []+ ]+ active_messages = [message for message in active_messages if message]+ if active_messages:+ sections.append("Active session messages:\n" + "\n".join(active_messages))++ if recall_documents:+ recall_lines = []+ for index, doc in enumerate(recall_documents, start=1):+ metadata = getattr(doc, "metadata", {}) or {}+ uri = metadata.get("openviking_uri") or metadata.get("source") or ""+ recall_lines.append(f"[{index}] {uri}\n{doc.page_content}".strip())+ sections.append(self.recall_header + "\n\n" + "\n\n".join(recall_lines))++ if not sections:+ return ""+ return f"{OPENVIKING_CONTEXT_MARKER}\n" + "\n\n".join(sections) + "\n</openviking_context>"+++class _OpenVikingContextResources:+ """Share one lifecycle owner across derived runnable copies."""++ def __init__(+ self,+ assembler: OpenVikingSessionContextAssembler,+ recorder: OpenVikingSessionRecorder,+ ) -> None:+ self._assembler = assembler+ self._recorder = recorder+ self._closed = False+ self._close_lock = threading.Lock()++ def __copy__(self) -> _OpenVikingContextResources:+ return self++ def __deepcopy__(self, memo: dict[int, Any]) -> _OpenVikingContextResources:+ memo[id(self)] = self+ return self++ def close(self) -> None:+ with self._close_lock:+ if self._closed:+ return+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ asyncio.run(self.aclose())+ return+ raise RuntimeError(+ "OpenVikingContextRunnable.close() cannot run inside an active event loop; "+ "use `await runnable.aclose()`"+ )++ async def aclose(self) -> None:+ with self._close_lock:+ if self._closed:+ return+ self._closed = True++ first_error: BaseException | None = None+ for component in (self._assembler, self._recorder):+ try:+ await component.aclose()+ except BaseException as exc:+ if first_error is None:+ first_error = exc+ if first_error is not None:+ raise first_error++ def raise_if_closed(self) -> None:+ with self._close_lock:+ if self._closed:+ raise RuntimeError("OpenVikingContextRunnable is closed")+++class OpenVikingContextRunnable(RunnableWithMessageHistory):+ """LangChain history wrapper with deterministic OpenViking cleanup."""++ _resources: _OpenVikingContextResources = PrivateAttr()++ def __init__(+ self,+ *args: Any,+ _resources: _OpenVikingContextResources,+ **kwargs: Any,+ ) -> None:+ super().__init__(*args, **kwargs)+ self._resources = _resources++ def close(self) -> None:+ """Release internally created resources outside a running event loop."""++ self._resources.close()++ async def aclose(self) -> None:+ """Release internally created context and recording resources."""++ await self._resources.aclose()++ def __enter__(self) -> OpenVikingContextRunnable:+ """Enter a synchronous managed lifecycle."""++ self._resources.raise_if_closed()+ return self++ def __exit__(+ self,+ _exc_type: type[BaseException] | None,+ _exc: BaseException | None,+ _traceback: Any,+ ) -> None:+ self.close()++ async def __aenter__(self) -> OpenVikingContextRunnable:+ """Enter an asynchronous managed lifecycle."""++ self._resources.raise_if_closed()+ return self++ async def __aexit__(+ self,+ _exc_type: type[BaseException] | None,+ _exc: BaseException | None,+ _traceback: Any,+ ) -> None:+ await self.aclose()+++def with_openviking_context(+ runnable: Any,+ *,+ client: Any = None,+ async_client: Any = None,+ url: str | None = None,+ api_key: str | None = None,+ account: str | None = None,+ user: str | None = None,+ user_id: str | None = None,+ path: str | None = None,+ timeout: float = 60.0,+ extra_headers: dict[str, str] | None = None,+ auto_initialize: bool = True,+ session_id: str | None = None,+ peer_id: str | None = None,+ actor_peer_id: str | None = None,+ target_uri: str | list[str] = "",+ limit: int = 5,+ score_threshold: float | None = None,+ token_budget: int = 128_000,+ input_messages_key: str | None = None,+ output_messages_key: str | None = None,+ history_messages_key: str | None = None,+ commit_policy: OpenVikingCommitPolicy | None = None,+ session_id_config_key: str = "session_id",+ peer_id_config_key: str = "peer_id",+ inject_context: bool = True,+) -> OpenVikingContextRunnable:+ """Wrap a runnable with invocation-scoped history and managed resources.++ Use the returned runnable as a context manager, or call ``close()`` /+ ``await aclose()`` when it is no longer needed.+ """++ assembler = OpenVikingSessionContextAssembler(+ client=client,+ async_client=async_client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ timeout=timeout,+ extra_headers=extra_headers,+ auto_initialize=auto_initialize,+ target_uri=target_uri,+ limit=limit,+ score_threshold=score_threshold,+ token_budget=token_budget,+ include_active_messages=False,+ include_recall=inject_context,+ )+ recorder = OpenVikingSessionRecorder(+ client=client,+ async_client=async_client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ timeout=timeout,+ extra_headers=extra_headers,+ auto_initialize=auto_initialize,+ commit_policy=commit_policy,+ )+ resources = _OpenVikingContextResources(assembler, recorder)+ sync_write_lock_pool = _SyncSessionWriteLockPool()+ async_write_lock_pools = LoopScopedAsyncClientCache()++ def make_history(active_session_id: str) -> OpenVikingChatMessageHistory:+ resources.raise_if_closed()+ return _InvocationOpenVikingChatMessageHistory(+ session_id=active_session_id,+ recorder=recorder,+ sync_write_lock_pool=sync_write_lock_pool,+ async_write_lock_pools=async_write_lock_pools,+ peer_id=peer_id,+ token_budget=token_budget,+ )++ if session_id is None:++ def dynamic_session_history_factory(+ resolved_session_id: str,+ ) -> OpenVikingChatMessageHistory:+ return make_history(+ _validate_session_id(resolved_session_id, key=session_id_config_key)+ )++ session_history_factory: Callable[..., OpenVikingChatMessageHistory] = (+ dynamic_session_history_factory+ )+ history_factory_config = [+ ConfigurableFieldSpec(+ id=session_id_config_key,+ annotation=str,+ name="Session ID",+ description=("Required OpenViking session ID for dynamic chat history and recall."),+ default="",+ is_shared=True,+ )+ ]+ else:++ def fixed_session_history_factory() -> OpenVikingChatMessageHistory:+ return make_history(session_id)++ session_history_factory = fixed_session_history_factory+ history_factory_config = None++ def prepare_injection(+ input_value: Any,+ config: dict[str, Any] | None,+ ) -> tuple[str, _InvocationOpenVikingChatMessageHistory, str] | None:+ resolved_session_id = session_id or _session_id_from_config(+ config,+ key=session_id_config_key,+ )+ resolved_peer_id = _peer_id_from_config(+ config,+ key=peer_id_config_key,+ default=peer_id,+ )+ history = _invocation_history_from_config(config)+ history._prepare_invocation(peer_id=resolved_peer_id)+ if not inject_context:+ return None+ query = _latest_user_text_from_input(input_value, input_messages_key)+ return resolved_session_id, history, query++ def apply_injection(+ input_value: Any,+ history: _InvocationOpenVikingChatMessageHistory,+ assembled: OpenVikingAssembledContext,+ ) -> Any:+ if not assembled.block:+ return input_value+ if assembled.context_parts:+ history._prepare_invocation(+ peer_id=history.peer_id,+ context_parts=assembled.context_parts,+ )+ return _inject_system_context(input_value, assembled.block, input_messages_key)++ def inject(input_value: Any, config: dict[str, Any] | None = None) -> Any:+ prepared = prepare_injection(input_value, config)+ if prepared is None:+ return input_value+ resolved_session_id, history, query = prepared+ assembled = assembler.assemble(+ session_id=resolved_session_id,+ query=query,+ )+ return apply_injection(input_value, history, assembled)++ async def ainject(input_value: Any, config: dict[str, Any] | None = None) -> Any:+ prepared = prepare_injection(input_value, config)+ if prepared is None:+ return input_value+ resolved_session_id, history, query = prepared+ assembled = await assembler.aassemble(+ session_id=resolved_session_id,+ query=query,+ )+ return apply_injection(input_value, history, assembled)++ def clear_pending_on_error(_run: Any, config: dict[str, Any] | None = None) -> None:+ try:+ history = _invocation_history_from_config(config)+ except Exception:+ logger.debug(+ "OpenViking pending context cleanup could not resolve invocation history",+ exc_info=True,+ )+ return+ history._discard_invocation_context()++ bound = (RunnableLambda(inject, afunc=ainject) | runnable).with_listeners(+ on_error=clear_pending_on_error+ )+ wrapped = OpenVikingContextRunnable(+ bound,+ session_history_factory,+ input_messages_key=input_messages_key,+ output_messages_key=output_messages_key,+ history_messages_key=history_messages_key,+ history_factory_config=history_factory_config,+ _resources=resources,+ )+ return wrapped+++def _session_id_from_config(config: dict[str, Any] | None, *, key: str) -> str:+ configurable = (config or {}).get("configurable") or {}+ return _validate_session_id(configurable.get(key), key=key)+++def _peer_id_from_config(+ config: dict[str, Any] | None,+ *,+ key: str,+ default: str | None,+) -> str | None:+ configurable = (config or {}).get("configurable") or {}+ value = configurable.get(key, default)+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++def _validate_session_id(value: Any, *, key: str) -> str:+ session_id = str(value or "").strip()+ if not session_id:+ raise ValueError(+ "OpenViking dynamic sessions require "+ f"config={{'configurable': {{'{key}': '<session-id>'}}}}. "+ "Pass session_id='...' to with_openviking_context for no-config usage."+ )+ return session_id+++def _invocation_history_from_config(+ config: dict[str, Any] | None,+) -> _InvocationOpenVikingChatMessageHistory:+ configurable = (config or {}).get("configurable") or {}+ history = configurable.get("message_history")+ if not isinstance(history, _InvocationOpenVikingChatMessageHistory):+ raise RuntimeError("OpenViking runnable invocation history is unavailable")+ return history+++def _retriever_for_session(+ retriever: Any,+ session_id: str,+) -> Any:+ if hasattr(retriever, "model_copy"):+ update = {+ "session_id": session_id,+ "search_mode": "search",+ }+ return retriever.model_copy(update=update)+ return retriever+++def _latest_user_text_from_input(input_value: Any, input_messages_key: str | None) -> str:+ messages = _input_messages(input_value, input_messages_key)+ if messages:+ return get_latest_user_text(messages)+ if isinstance(input_value, str):+ return input_value+ if isinstance(input_value, dict):+ for value in input_value.values():+ if isinstance(value, str) and value.strip():+ return value.strip()+ return ""+++def _input_messages(input_value: Any, input_messages_key: str | None) -> list[Any]:+ if isinstance(input_value, list):+ return list(input_value)+ if isinstance(input_value, dict):+ key = input_messages_key or "messages"+ value = input_value.get(key)+ if isinstance(value, list):+ return list(value)+ return []+++def _inject_system_context(+ input_value: Any,+ context_block: str,+ input_messages_key: str | None,+) -> Any:+ if isinstance(input_value, list):+ return _merge_system_message(input_value, context_block)+ if isinstance(input_value, dict):+ key = input_messages_key or "messages"+ if isinstance(input_value.get(key), list):+ updated = dict(input_value)+ updated[key] = _merge_system_message(input_value[key], context_block)+ return updated+ updated = dict(input_value)+ updated["openviking_context"] = context_block+ return updated+ return input_value+++def _merge_system_message(messages: Sequence[Any], context_block: str) -> list[Any]:+ updated = list(messages)+ for index, message in enumerate(updated):+ if isinstance(message, SystemMessage):+ content = extract_message_text(message.content)+ updated[index] = SystemMessage(content=f"{content}\n\n{context_block}".strip())+ return updated+ return [SystemMessage(content=context_block), *updated]+++def _format_session_message(message: dict[str, Any]) -> str:+ role = str(message.get("role") or "assistant")+ parts = message.get("parts") or []+ chunks: list[str] = []+ for part in parts:+ part_type = part.get("type")+ if part_type == "text" and part.get("text"):+ chunks.append(str(part["text"]))+ elif part_type == "context" and part.get("abstract"):+ chunks.append(f"[context] {part['abstract']}")+ elif part_type == "tool":+ tool_name = part.get("tool_name") or "tool"+ status = part.get("tool_status") or "completed"+ output = part.get("tool_output") or ""+ chunks.append(f"[tool:{tool_name} ({status})] {output}".strip())+ text = "\n".join(chunk for chunk in chunks if chunk).strip()+ return f"[{role}] {text}" if text else ""diff --git a/integrations/langchain/src/langchain_openviking/history.py b/integrations/langchain/src/langchain_openviking/history.pynew file mode 100644index 000000000..8af1fb8f7--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/history.py@@ -0,0 +1,292 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""LangChain chat history backed by OpenViking sessions."""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Sequence+from typing import Any, Callable++try:+ from langchain_core.chat_history import BaseChatMessageHistory+ from langchain_core.messages import BaseMessage+except ImportError as exc: # pragma: no cover - exercised by optional import path+ from langchain_openviking.client import missing_dependency++ raise missing_dependency("langchain", "langchain-core") from exc++from langchain_openviking.client import (+ OpenVikingCommitPolicy,+ acall_openviking,+ call_openviking,+ is_not_found_error,+)+from langchain_openviking.messages import (+ langchain_message_to_openviking as langchain_message_to_openviking,+)+from langchain_openviking.messages import (+ openviking_message_to_langchain as openviking_message_to_langchain,+)+from langchain_openviking.messages import (+ restore_openviking_messages,+)+from langchain_openviking.recording import (+ OpenVikingPartialWriteError,+ OpenVikingSessionRecorder,+ get_openviking_cancellation_progress,+)++logger = logging.getLogger(__name__)+++class OpenVikingChatMessageHistory(BaseChatMessageHistory):+ """LangChain chat history implementation stored in an OpenViking session."""++ def __init__(+ self,+ session_id: str,+ *,+ client: Any = None,+ async_client: Any = None,+ url: str | None = None,+ api_key: str | None = None,+ account: str | None = None,+ user: str | None = None,+ user_id: str | None = None,+ actor_peer_id: str | None = None,+ path: str | None = None,+ timeout: float = 60.0,+ extra_headers: dict[str, str] | None = None,+ auto_initialize: bool = True,+ token_budget: int = 128_000,+ persist_system_messages: bool = False,+ commit_policy: OpenVikingCommitPolicy | None = None,+ context_parts_provider: Callable[[str], list[dict[str, Any]]] | None = None,+ context_parts_acknowledger: Callable[[str], None] | None = None,+ peer_id: str | None = None,+ peer_id_provider: Callable[[str], str | None] | None = None,+ _recorder: OpenVikingSessionRecorder | None = None,+ ):+ self.session_id = session_id+ self.peer_id = peer_id+ self.peer_id_provider = peer_id_provider+ self.token_budget = token_budget+ # Retained for constructor compatibility. System messages are runtime+ # policy, not conversation memory, so they are never persisted.+ self.persist_system_messages = False+ self.context_parts_provider = context_parts_provider+ self.context_parts_acknowledger = context_parts_acknowledger+ self._pending_context_parts: list[dict[str, Any]] = []+ self._owns_recorder = _recorder is None+ self._recorder = _recorder or OpenVikingSessionRecorder(+ client=client,+ async_client=async_client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ timeout=timeout,+ extra_headers=extra_headers,+ auto_initialize=auto_initialize,+ commit_policy=commit_policy,+ )++ @property+ def commit_policy(self) -> OpenVikingCommitPolicy | None:+ """Return the recorder commit policy used by this history."""++ return self._recorder.commit_policy++ @commit_policy.setter+ def commit_policy(self, value: OpenVikingCommitPolicy | None) -> None:+ self._recorder.commit_policy = value++ @property+ def messages(self) -> list[BaseMessage]: # type: ignore[override]+ client = self._get_client()+ try:+ context = call_openviking(+ client,+ "get_session_context",+ session_id=self.session_id,+ token_budget=self.token_budget,+ )+ except Exception as exc:+ logger.debug("OpenViking chat history context fetch failed", exc_info=True)+ if is_not_found_error(exc):+ self._ensure_session(client)+ return []++ return restore_openviking_messages(context.get("messages") or [])++ async def aget_messages(self) -> list[BaseMessage]:+ """Asynchronously return active messages from the OpenViking session."""++ client = await self._get_async_client()+ try:+ context = await acall_openviking(+ client,+ "get_session_context",+ session_id=self.session_id,+ token_budget=self.token_budget,+ )+ except Exception as exc:+ logger.debug("OpenViking chat history context fetch failed", exc_info=True)+ if is_not_found_error(exc):+ await self._aensure_session(client)+ return []++ return restore_openviking_messages(context.get("messages") or [])++ def add_messages(self, messages: Sequence[BaseMessage]) -> None:+ if not self._pending_context_parts and self.context_parts_provider:+ self._pending_context_parts = list(self.context_parts_provider(self.session_id))+ try:+ result = self._recorder.record(+ self.session_id,+ messages,+ peer_id=self._effective_peer_id(),+ context_parts=self._pending_context_parts,+ )+ except OpenVikingPartialWriteError as exc:+ if exc.context_attached:+ self._acknowledge_context_parts()+ raise+ if result.context_attached:+ self._acknowledge_context_parts()++ async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:+ """Asynchronously persist messages through the shared session recorder."""++ if not self._pending_context_parts and self.context_parts_provider:+ self._pending_context_parts = list(self.context_parts_provider(self.session_id))+ try:+ result = await self._recorder.arecord(+ self.session_id,+ messages,+ peer_id=self._effective_peer_id(),+ context_parts=self._pending_context_parts,+ )+ except OpenVikingPartialWriteError as exc:+ if exc.context_attached:+ self._acknowledge_context_parts()+ raise+ except asyncio.CancelledError as exc:+ progress = get_openviking_cancellation_progress(exc)+ if progress is not None and progress.context_attached:+ self._acknowledge_context_parts()+ raise+ if result.context_attached:+ self._acknowledge_context_parts()++ def clear(self) -> None:+ client = self._get_client()+ call_openviking(client, "delete_session", session_id=self.session_id)+ self._ensure_session(client)+ self._acknowledge_context_parts()++ async def aclear(self) -> None:+ """Asynchronously reset this OpenViking session."""++ client = await self._get_async_client()+ await acall_openviking(client, "delete_session", session_id=self.session_id)+ await self._aensure_session(client)+ self._acknowledge_context_parts()++ def close(self) -> None:+ """Release resources owned by this history adapter."""++ self._acknowledge_context_parts()+ if self._owns_recorder:+ self._recorder.close()++ async def aclose(self) -> None:+ """Asynchronously release resources owned by this history adapter."""++ self._acknowledge_context_parts()+ if self._owns_recorder:+ await self._recorder.aclose()++ def _get_client(self) -> Any:+ return self._recorder.client++ async def _get_async_client(self) -> Any:+ return await self._recorder.get_async_client()++ def _ensure_session(self, client: Any) -> None:+ try:+ call_openviking(client, "create_session", session_id=self.session_id)+ except Exception:+ logger.debug("OpenViking chat history session ensure failed", exc_info=True)+ pass++ async def _aensure_session(self, client: Any) -> None:+ try:+ await acall_openviking(client, "create_session", session_id=self.session_id)+ except Exception:+ logger.debug("OpenViking chat history session ensure failed", exc_info=True)++ def _effective_peer_id(self) -> str | None:+ if self.peer_id_provider is None:+ value = self.peer_id+ else:+ value = self.peer_id_provider(self.session_id)+ if value is None:+ return None+ text = str(value).strip()+ return text or None++ def _prepare_invocation(+ self,+ *,+ peer_id: str | None,+ context_parts: Sequence[dict[str, Any]] = (),+ ) -> None:+ """Set invocation-local attribution and recalled context."""++ self.peer_id = peer_id+ self._pending_context_parts = list(context_parts)++ def _discard_invocation_context(self) -> None:+ """Discard recalled context owned by an interrupted invocation."""++ self._pending_context_parts = []++ def _acknowledge_context_parts(self) -> None:+ had_pending_context = bool(self._pending_context_parts)+ self._pending_context_parts = []+ if not had_pending_context or self.context_parts_acknowledger is None:+ return+ try:+ self.context_parts_acknowledger(self.session_id)+ except Exception:+ logger.warning(+ "OpenViking context-parts acknowledgement failed",+ exc_info=True,+ )+++def context_parts_from_documents(documents: Sequence[Any]) -> list[dict[str, Any]]:+ """Build OpenViking ContextPart dictionaries from LangChain Documents."""++ parts: list[dict[str, Any]] = []+ for doc in documents:+ metadata = getattr(doc, "metadata", {}) or {}+ uri = metadata.get("openviking_uri") or metadata.get("source") or ""+ if not uri:+ continue+ parts.append(+ {+ "type": "context",+ "uri": uri,+ "context_type": metadata.get("openviking_context_type") or "resource",+ "abstract": metadata.get("openviking_abstract")+ or getattr(doc, "page_content", "")[:500],+ }+ )+ return partsdiff --git a/integrations/langchain/src/langchain_openviking/messages.py b/integrations/langchain/src/langchain_openviking/messages.pynew file mode 100644index 000000000..f1923968a--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/messages.py@@ -0,0 +1,206 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""LangChain message conversion and recording filters."""++from __future__ import annotations++from collections.abc import Sequence+from copy import deepcopy+from typing import Any++try:+ from langchain_core.messages import (+ AIMessage,+ BaseMessage,+ HumanMessage,+ SystemMessage,+ ToolMessage,+ )+except ImportError as exc: # pragma: no cover - exercised by optional import path+ from langchain_openviking.client import missing_dependency++ raise missing_dependency("langchain", "langchain-core") from exc++from langchain_openviking.client import extract_message_text++OPENVIKING_CONTEXT_MARKER = "<openviking_context>"+LANGCHAIN_SUMMARIZATION_SOURCE = "summarization"+++def is_recordable_langchain_message(message: BaseMessage) -> bool:+ """Return whether a framework message belongs in OpenViking session history."""++ if isinstance(message, SystemMessage):+ return False+ additional_kwargs = getattr(message, "additional_kwargs", {}) or {}+ if additional_kwargs.get("lc_source") == LANGCHAIN_SUMMARIZATION_SOURCE:+ return False+ if isinstance(message, AIMessage):+ return bool(+ extract_message_text(message.content)+ or message.tool_calls+ or additional_kwargs.get("tool_calls")+ )+ return bool(langchain_message_to_openviking(message))+++def is_context_carrier_langchain_message(message: BaseMessage) -> bool:+ """Return whether an otherwise-empty assistant can carry recalled context."""++ if not isinstance(message, AIMessage):+ return False+ additional_kwargs = getattr(message, "additional_kwargs", {}) or {}+ return additional_kwargs.get("lc_source") != LANGCHAIN_SUMMARIZATION_SOURCE+++def langchain_message_to_openviking(+ message: BaseMessage,+ *,+ persist_system_messages: bool = False,+) -> list[dict[str, Any]]:+ """Convert a LangChain message into one or more OpenViking message payloads."""++ del persist_system_messages # Retained for compatibility; system policy is never persisted.++ if isinstance(message, HumanMessage):+ human_parts = _text_parts(message.content)+ return [{"role": "user", "parts": human_parts or [{"type": "text", "text": ""}]}]++ if isinstance(message, AIMessage):+ parts: list[dict[str, Any]] = _text_parts(message.content)+ for tool_call in message.tool_calls or []:+ parts.append(+ {+ "type": "tool",+ "tool_id": str(tool_call.get("id") or ""),+ "tool_name": str(tool_call.get("name") or ""),+ "tool_input": _tool_args(tool_call.get("args")),+ "tool_status": "pending",+ }+ )+ return [{"role": "assistant", "parts": parts or [{"type": "text", "text": ""}]}]++ if isinstance(message, ToolMessage):+ return [+ {+ "role": "assistant",+ "parts": [+ {+ "type": "tool",+ "tool_id": str(message.tool_call_id or ""),+ "tool_name": str(message.name or ""),+ "tool_output": extract_message_text(message.content),+ "tool_status": _tool_status(message),+ }+ ],+ }+ ]++ if isinstance(message, SystemMessage):+ return []++ text = extract_message_text(getattr(message, "content", ""))+ if not text:+ return []+ role = "user" if getattr(message, "type", "") == "human" else "assistant"+ return [{"role": role, "parts": [{"type": "text", "text": text}]}]+++def openviking_message_to_langchain(message: dict[str, Any]) -> list[BaseMessage]:+ """Convert one OpenViking session message into LangChain messages."""++ role = str(message.get("role") or "")+ parts = list(message.get("parts") or [])+ text = _parts_text(parts)+ if role == "user":+ return [HumanMessage(content=text)]++ tool_calls = []+ tool_messages = []+ for part in parts:+ if part.get("type") != "tool":+ continue+ tool_id = str(part.get("tool_id") or "")+ tool_name = str(part.get("tool_name") or "")+ status = str(part.get("tool_status") or "")+ has_output = part.get("tool_output") is not None+ is_completed_result = has_output or status in {"completed", "error"}+ if is_completed_result:+ tool_messages.append(+ ToolMessage(+ content=str(part.get("tool_output") or ""),+ tool_call_id=tool_id or "openviking-tool",+ name=tool_name or None,+ status="error" if status == "error" else "success",+ )+ )+ else:+ tool_calls.append(+ {+ "id": tool_id,+ "name": tool_name,+ "args": _tool_args(part.get("tool_input")),+ }+ )++ messages: list[BaseMessage] = []+ if text or tool_calls or not tool_messages:+ messages.append(+ AIMessage(content=text, tool_calls=tool_calls or [])+ if tool_calls+ else AIMessage(content=text)+ )+ messages.extend(tool_messages)+ return messages+++def restore_openviking_messages(messages: Sequence[dict[str, Any]]) -> list[BaseMessage]:+ """Restore a valid LangChain message sequence from OpenViking session messages."""++ restored: list[BaseMessage] = []+ active_tool_call_ids: set[str] = set()+ for message in messages:+ for langchain_message in openviking_message_to_langchain(message):+ if isinstance(langchain_message, AIMessage):+ restored.append(langchain_message)+ for tool_call in langchain_message.tool_calls or []:+ tool_call_id = str(tool_call.get("id") or "")+ if tool_call_id:+ active_tool_call_ids.add(tool_call_id)+ elif isinstance(langchain_message, ToolMessage):+ tool_call_id = str(langchain_message.tool_call_id or "")+ if tool_call_id and tool_call_id in active_tool_call_ids:+ restored.append(langchain_message)+ active_tool_call_ids.discard(tool_call_id)+ else:+ restored.append(langchain_message)+ return restored+++def _text_parts(content: Any) -> list[dict[str, Any]]:+ text = extract_message_text(content)+ return [{"type": "text", "text": text}] if text else []+++def _parts_text(parts: Sequence[dict[str, Any]]) -> str:+ chunks: list[str] = []+ for part in parts:+ part_type = part.get("type")+ if part_type == "text" and part.get("text"):+ chunks.append(str(part["text"]))+ elif part_type == "context" and part.get("abstract"):+ uri = part.get("uri") or "context"+ chunks.append(f"[context:{uri}] {part['abstract']}")+ return "\n".join(chunks)+++def _tool_args(value: Any) -> dict[str, Any]:+ if value is None:+ return {}+ if isinstance(value, dict):+ return deepcopy(value)+ return {"value": deepcopy(value)}+++def _tool_status(message: ToolMessage) -> str:+ return "error" if getattr(message, "status", "") == "error" else "completed"diff --git a/integrations/langchain/src/langchain_openviking/middleware.py b/integrations/langchain/src/langchain_openviking/middleware.pynew file mode 100644index 000000000..52eacd3bf--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/middleware.py@@ -0,0 +1,598 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""LangGraph agent middleware for OpenViking recall and capture."""++from __future__ import annotations++import asyncio+import json+from contextlib import AbstractContextManager, nullcontext+from dataclasses import dataclass+from typing import Any, Callable++try:+ from langchain.agents.middleware import AgentMiddleware+ from langchain.agents.middleware.types import AgentState, ModelRequest+ from langchain_core.messages import (+ AIMessage,+ BaseMessage,+ HumanMessage,+ SystemMessage,+ ToolMessage,+ )+except ImportError as exc: # pragma: no cover - exercised by optional import path+ from langchain_openviking.client import missing_dependency++ raise missing_dependency("langgraph", "langchain/langgraph") from exc++from langchain_openviking.actor_peer import (+ get_actor_peer_id,+ require_request_actor_peer_support,+ use_actor_peer,+)+from langchain_openviking.client import (+ OpenVikingCommitPolicy,+ extract_message_text,+ get_latest_user_text,+)+from langchain_openviking.context import (+ OpenVikingAssembledContext,+ OpenVikingSessionContextAssembler,+)+from langchain_openviking.recording import (+ OpenVikingCancellationProgress,+ OpenVikingPartialWriteError,+ OpenVikingSessionRecorder,+ get_openviking_cancellation_progress,+)+from langchain_openviking.retrievers import OpenVikingRetriever++_SESSION_ID_ERROR = (+ "OpenVikingContextMiddleware requires a LangGraph session id. Pass "+ 'config={"configurable": {"thread_id": "..."}}, set state["session_id"], '+ "or provide session_id_resolver."+)+_CaptureKey = tuple[str, str] | tuple[str, str, str]+_ActorPeerResolver = Callable[+ [dict[str, Any], Any],+ str | None,+]+++@dataclass(slots=True)+class _CapturePlan:+ session_id: str+ peer_id: str | None+ actor_peer_id: str | None+ key: _CaptureKey+ messages: list[Any]+ signatures: tuple[str, ...]+ start: int+ context_parts: list[dict[str, Any]]+ unchanged: bool = False+++class OpenVikingContextMiddleware(AgentMiddleware):+ """Inject OpenViking recall into LangGraph agent model calls.++ The middleware mirrors the OpenClaw-style lifecycle at LangGraph's extension+ points: recall before model calls and optional session capture after agent+ execution.+ """++ def __init__(+ self,+ *,+ client: Any = None,+ async_client: Any = None,+ retriever: OpenVikingRetriever | None = None,+ url: str | None = None,+ api_key: str | None = None,+ account: str | None = None,+ user: str | None = None,+ user_id: str | None = None,+ actor_peer_id: str | None = None,+ path: str | None = None,+ target_uri: str | list[str] = "",+ limit: int = 5,+ peer_id: str | None = None,+ score_threshold: float | None = None,+ token_budget: int = 128_000,+ session_id_resolver: Callable[[dict[str, Any], Any], str] | None = None,+ peer_id_resolver: Callable[[dict[str, Any], Any], str | None] | None = None,+ actor_peer_resolver: _ActorPeerResolver | None = None,+ capture_on_after_agent: bool = True,+ commit_on_after_agent: bool = False,+ commit_policy: OpenVikingCommitPolicy | None = None,+ recall_header: str = "Relevant OpenViking context:",+ include_active_messages: bool = False,+ ):+ super().__init__()+ _validate_actor_peer_transport(+ actor_peer_resolver=actor_peer_resolver,+ client=client,+ async_client=async_client,+ retriever=retriever,+ path=path,+ )+ self.recorder = OpenVikingSessionRecorder(+ client=client,+ async_client=async_client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ commit_policy=None,+ )+ self._owns_retriever = retriever is None+ self.retriever = retriever or OpenVikingRetriever(+ client=client,+ async_client=async_client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ target_uri=target_uri,+ limit=limit,+ score_threshold=score_threshold,+ search_mode="search",+ )+ self.assembler = OpenVikingSessionContextAssembler(+ client=client,+ async_client=async_client,+ retriever=self.retriever,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ target_uri=target_uri,+ limit=limit,+ score_threshold=score_threshold,+ token_budget=token_budget,+ include_session_context=True,+ include_active_messages=include_active_messages,+ include_recall=True,+ recall_header=recall_header,+ )+ self.session_id_resolver = session_id_resolver+ self.peer_id = peer_id+ self.peer_id_resolver = peer_id_resolver+ self.actor_peer_resolver = actor_peer_resolver+ self.capture_on_after_agent = capture_on_after_agent+ self.commit_policy = commit_policy+ if commit_on_after_agent and self.commit_policy is None:+ self.commit_policy = OpenVikingCommitPolicy(mode="always")+ self.recall_header = recall_header+ self._captured_signatures: dict[_CaptureKey, tuple[str, ...]] = {}+ self._pending_context_parts: dict[_CaptureKey, list[dict[str, Any]]] = {}++ async def aclose(self) -> None:+ """Release all clients internally owned by this middleware."""++ first_error: BaseException | None = None+ components: list[Any] = [self.recorder, self.assembler]+ if self._owns_retriever:+ components.append(self.retriever)+ for component in components:+ try:+ await component.aclose()+ except BaseException as exc:+ if first_error is None:+ first_error = exc+ if first_error is not None:+ raise first_error++ def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], Any]) -> Any:+ plan = self._model_context_plan(request)+ if plan is None:+ return handler(request)+ session_id, pending_key, query, actor_peer_id = plan+ with self._actor_peer_scope(actor_peer_id):+ assembled = self.assembler.assemble(+ session_id=session_id,+ query=query,+ )+ updated_request = self._request_with_context(request, pending_key, assembled)+ if updated_request is None:+ return handler(request)+ try:+ return handler(updated_request)+ except Exception:+ self._pending_context_parts.pop(pending_key, None)+ raise++ async def awrap_model_call(+ self,+ request: ModelRequest,+ handler: Callable[[ModelRequest], Any],+ ) -> Any:+ """Asynchronously inject OpenViking context before a model call."""++ plan = self._model_context_plan(request)+ if plan is None:+ return await handler(request)+ session_id, pending_key, query, actor_peer_id = plan+ with self._actor_peer_scope(actor_peer_id):+ assembled = await self.assembler.aassemble(+ session_id=session_id,+ query=query,+ )+ updated_request = self._request_with_context(request, pending_key, assembled)+ if updated_request is None:+ return await handler(request)+ try:+ return await handler(updated_request)+ except BaseException:+ # CancelledError is a BaseException, so cancellation must also discard+ # context references prepared for the interrupted model call.+ self._pending_context_parts.pop(pending_key, None)+ raise++ def _model_context_plan(+ self,+ request: ModelRequest,+ ) -> tuple[str, _CaptureKey, str, str | None] | None:+ query = get_latest_user_text(request.messages)+ if not query:+ return None+ state = getattr(request, "state", {}) or {}+ runtime = getattr(request, "runtime", None)+ session_id = self._resolve_session_id(state, runtime)+ peer_id = self._resolve_peer_id(state, runtime)+ actor_peer_id = self._resolve_actor_peer_id(state, runtime)+ pending_key = _capture_key(session_id, peer_id, actor_peer_id)+ self._pending_context_parts.pop(pending_key, None)+ return session_id, pending_key, query, actor_peer_id++ def _request_with_context(+ self,+ request: ModelRequest,+ pending_key: _CaptureKey,+ assembled: OpenVikingAssembledContext,+ ) -> ModelRequest | None:+ context_block = assembled.block+ if not context_block:+ return None+ if assembled.context_parts:+ self._pending_context_parts[pending_key] = assembled.context_parts++ system_message = request.system_message+ if system_message is None:+ updated_system = SystemMessage(content=context_block)+ else:+ content = extract_message_text(system_message.content)+ updated_system = SystemMessage(content=f"{content}\n\n{context_block}".strip())+ return request.override(system_message=updated_system)++ def after_agent(self, state: AgentState[Any], runtime: Any) -> dict[str, Any] | None:+ plan = self._capture_plan(state, runtime)+ if plan is None:+ return None+ self.recorder.commit_policy = self.commit_policy+ if plan.unchanged:+ with self._actor_peer_scope(plan.actor_peer_id):+ self.recorder.record(plan.session_id, ())+ self._pending_context_parts.pop(plan.key, None)+ return None+ try:+ with self._actor_peer_scope(plan.actor_peer_id):+ result = self.recorder.record(+ plan.session_id,+ plan.messages[plan.start :],+ peer_id=plan.peer_id,+ context_parts=plan.context_parts,+ )+ except OpenVikingPartialWriteError as exc:+ self._handle_partial_capture(plan, exc)+ raise++ self._complete_capture(plan, context_attached=result.context_attached)+ return None++ async def aafter_agent(+ self,+ state: AgentState[Any],+ runtime: Any,+ ) -> dict[str, Any] | None:+ """Asynchronously capture messages after an agent run."""++ plan = self._capture_plan(state, runtime)+ if plan is None:+ return None+ self.recorder.commit_policy = self.commit_policy+ if plan.unchanged:+ with self._actor_peer_scope(plan.actor_peer_id):+ await self.recorder.arecord(plan.session_id, ())+ self._pending_context_parts.pop(plan.key, None)+ return None+ try:+ with self._actor_peer_scope(plan.actor_peer_id):+ result = await self.recorder.arecord(+ plan.session_id,+ plan.messages[plan.start :],+ peer_id=plan.peer_id,+ context_parts=plan.context_parts,+ )+ except OpenVikingPartialWriteError as exc:+ self._handle_partial_capture(plan, exc)+ raise+ except asyncio.CancelledError as exc:+ progress = get_openviking_cancellation_progress(exc)+ if progress is not None:+ self._handle_partial_capture(plan, progress)+ raise++ self._complete_capture(plan, context_attached=result.context_attached)+ return None++ def _capture_plan(+ self,+ state: AgentState[Any],+ runtime: Any,+ ) -> _CapturePlan | None:+ if not self.capture_on_after_agent:+ return None+ messages = list(state.get("messages") or [])+ if not messages:+ return None+ session_id = self._resolve_session_id(state, runtime)+ peer_id = self._resolve_peer_id(state, runtime)+ actor_peer_id = self._resolve_actor_peer_id(state, runtime)+ key = _capture_key(session_id, peer_id, actor_peer_id)+ previous_signatures = self._captured_signatures.get(key, ())+ signatures = tuple(_message_signature(message) for message in messages)+ unchanged = signatures == previous_signatures+ start = 0+ if (+ not unchanged+ and previous_signatures+ and len(signatures) > len(previous_signatures)+ and signatures[: len(previous_signatures)] == previous_signatures+ ):+ start = len(previous_signatures)+ return _CapturePlan(+ session_id=session_id,+ peer_id=peer_id,+ actor_peer_id=actor_peer_id,+ key=key,+ messages=messages,+ signatures=signatures,+ start=start,+ context_parts=list(self._pending_context_parts.get(key, [])),+ unchanged=unchanged,+ )++ def _handle_partial_capture(+ self,+ plan: _CapturePlan,+ error: OpenVikingPartialWriteError | OpenVikingCancellationProgress,+ ) -> None:+ if error.input_messages_consumed:+ consumed_end = plan.start + error.input_messages_consumed+ self._captured_signatures[plan.key] = plan.signatures[:consumed_end]+ if error.context_attached:+ self._pending_context_parts.pop(plan.key, None)++ def _complete_capture(+ self,+ plan: _CapturePlan,+ *,+ context_attached: bool,+ ) -> None:+ self._captured_signatures[plan.key] = plan.signatures+ if context_attached:+ self._pending_context_parts.pop(plan.key, None)++ def _resolve_session_id(self, state: Any, runtime: Any) -> str:+ if self.session_id_resolver:+ resolved = _normalize_session_id(self.session_id_resolver(state, runtime))+ if resolved:+ return resolved+ raise ValueError(_SESSION_ID_ERROR)+ candidates = [+ state.get("thread_id"),+ state.get("session_id"),+ _nested_get(getattr(runtime, "context", None), "thread_id"),+ _nested_get(getattr(runtime, "config", None), "configurable", "thread_id"),+ _nested_get(getattr(runtime, "config", None), "configurable", "session_id"),+ ]+ for candidate in candidates:+ resolved = _normalize_session_id(candidate)+ if resolved:+ return resolved+ raise ValueError(_SESSION_ID_ERROR)++ def _resolve_peer_id(self, state: Any, runtime: Any) -> str | None:+ if self.peer_id_resolver:+ return _normalize_peer_id(self.peer_id_resolver(state, runtime))+ candidates = [+ state.get("peer_id"),+ state.get("peerId"),+ _nested_get(getattr(runtime, "context", None), "peer_id"),+ _nested_get(getattr(runtime, "context", None), "peerId"),+ _nested_get(getattr(runtime, "config", None), "configurable", "peer_id"),+ _nested_get(getattr(runtime, "config", None), "configurable", "peerId"),+ self.peer_id,+ ]+ for candidate in candidates:+ resolved = _normalize_peer_id(candidate)+ if resolved:+ return resolved+ return None++ def _resolve_actor_peer_id(+ self,+ state: Any,+ runtime: Any,+ ) -> str | None:+ if self.actor_peer_resolver is None:+ return get_actor_peer_id()+ actor_peer_id = self.actor_peer_resolver(state, runtime)+ if actor_peer_id is None:+ return None+ if not isinstance(actor_peer_id, str):+ raise TypeError("OpenViking actor_peer_resolver must return a string or None")+ normalized = actor_peer_id.strip()+ if not normalized:+ raise ValueError("OpenViking actor_peer_resolver must not return an empty string")+ return normalized++ def _actor_peer_scope(+ self,+ actor_peer_id: str | None,+ ) -> AbstractContextManager[None]:+ if self.actor_peer_resolver is None:+ return nullcontext()+ return use_actor_peer(actor_peer_id)+++def _nested_get(value: Any, *keys: str) -> Any:+ current = value+ for key in keys:+ if current is None:+ return None+ if isinstance(current, dict):+ current = current.get(key)+ else:+ current = getattr(current, key, None)+ return current+++def _normalize_session_id(value: Any) -> str | None:+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++def _normalize_peer_id(value: Any) -> str | None:+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++def _capture_key(+ session_id: str,+ peer_id: str | None,+ actor_peer_id: str | None,+) -> _CaptureKey:+ if actor_peer_id is None:+ return (session_id, peer_id or "")+ return (actor_peer_id, session_id, peer_id or "")+++def _validate_actor_peer_transport(+ *,+ actor_peer_resolver: _ActorPeerResolver | None,+ client: Any,+ async_client: Any,+ retriever: OpenVikingRetriever | None,+ path: str | None,+) -> None:+ if actor_peer_resolver is None:+ return+ require_request_actor_peer_support()+ if path is not None or (retriever is not None and retriever.path is not None):+ raise ValueError("actor_peer_resolver requires an OpenViking HTTP connection")+ transports = [client, async_client]+ if retriever is not None:+ transports.extend([retriever.client, retriever.async_client])+ for transport in transports:+ if transport is not None and not getattr(+ transport,+ "supports_request_actor_peer",+ False,+ ):+ raise ValueError(+ "actor_peer_resolver requires OpenViking HTTP clients that support "+ "request-scoped actor peers"+ )+++def _message_role(message: Any) -> str:+ if isinstance(message, HumanMessage):+ return "user"+ if isinstance(message, AIMessage):+ return "assistant"+ if isinstance(message, BaseMessage):+ if message.type == "human":+ return "user"+ if message.type == "ai":+ return "assistant"+ return message.type+ if isinstance(message, dict):+ role = str(message.get("role") or message.get("type") or "")+ return {"human": "user", "ai": "assistant"}.get(role, role)+ return str(getattr(message, "role", "") or getattr(message, "type", ""))+++def _message_content(message: Any) -> str:+ if isinstance(message, dict):+ return extract_message_text(message.get("content"))+ return extract_message_text(getattr(message, "content", ""))+++def _message_stable_id(message: Any) -> str | None:+ if isinstance(message, dict):+ value = message.get("id")+ else:+ value = getattr(message, "id", None)+ return str(value) if value else None+++def _message_signature(message: Any) -> str:+ return _stable_json(+ {+ "id": _message_stable_id(message),+ "role": _message_role(message),+ "content": _message_content(message),+ "tool_calls": _message_tool_calls(message),+ "tool_result": _message_tool_result(message),+ }+ )+++def _message_tool_calls(message: Any) -> Any:+ if isinstance(message, AIMessage):+ calls = getattr(message, "tool_calls", None) or []+ if not calls:+ calls = (getattr(message, "additional_kwargs", {}) or {}).get("tool_calls") or []+ return calls+ if isinstance(message, dict):+ return message.get("tool_calls") or []+ return getattr(message, "tool_calls", None) or []+++def _message_tool_result(message: Any) -> dict[str, Any]:+ if isinstance(message, ToolMessage):+ return {+ "tool_call_id": getattr(message, "tool_call_id", None),+ "name": getattr(message, "name", None),+ "status": getattr(message, "status", None),+ }+ if isinstance(message, dict):+ return {+ "tool_call_id": message.get("tool_call_id") or message.get("tool_id"),+ "name": message.get("name") or message.get("tool_name"),+ "output": message.get("tool_output") or message.get("output"),+ "status": message.get("status") or message.get("tool_status"),+ }+ return {+ "tool_call_id": getattr(message, "tool_call_id", None),+ "name": getattr(message, "name", None),+ "status": getattr(message, "status", None),+ }+++def _stable_json(value: Any) -> str:+ return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)diff --git a/integrations/langchain/src/langchain_openviking/py.typed b/integrations/langchain/src/langchain_openviking/py.typednew file mode 100644index 000000000..8b1378917--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/py.typed@@ -0,0 +1 @@+diff --git a/integrations/langchain/src/langchain_openviking/recording.py b/integrations/langchain/src/langchain_openviking/recording.pynew file mode 100644index 000000000..21c92f0e3--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/recording.py@@ -0,0 +1,697 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Reusable OpenViking session recording for LangChain messages."""++from __future__ import annotations++import asyncio+import threading+from collections.abc import Iterable, Sequence+from copy import deepcopy+from dataclasses import dataclass+from typing import Any, Literal++try:+ from langchain_core.messages import BaseMessage+except ImportError as exc: # pragma: no cover - exercised by optional import path+ from langchain_openviking.client import missing_dependency++ raise missing_dependency("langchain", "langchain-core") from exc++from langchain_openviking._async_client_cache import LoopScopedAsyncClientCache+from langchain_openviking.client import (+ OpenVikingCommitPolicy,+ OpenVikingConnection,+ aapply_commit_policy,+ acall_openviking,+ aclose_openviking_clients,+ apply_commit_policy,+ call_openviking,+ ensure_async_client,+ ensure_client,+ item_value,+)+from langchain_openviking.messages import (+ is_context_carrier_langchain_message,+ is_recordable_langchain_message,+ langchain_message_to_openviking,+)++MAX_RECORDING_BATCH_SIZE = 100+++@dataclass(frozen=True, slots=True)+class OpenVikingRecordResult:+ """Confirmed progress from a recorder call."""++ messages_written: int = 0+ input_messages_consumed: int = 0+ context_attached: bool = False+++class OpenVikingPartialWriteError(RuntimeError):+ """Report confirmed progress when recording cannot finish."""++ def __init__(+ self,+ *,+ session_id: str,+ result: OpenVikingRecordResult,+ cause: Exception,+ stage: Literal["batch", "commit"] = "batch",+ ):+ if stage == "batch":+ detail = "before a later batch failed"+ else:+ detail = "before the commit policy failed"+ super().__init__(+ f"OpenViking recorded {result.messages_written} messages for session "+ f"{session_id!r} {detail}: {cause}"+ )+ self.session_id = session_id+ self.result = result+ self.stage = stage++ @property+ def messages_written(self) -> int:+ """Return the number of payloads confirmed written before failure."""++ return self.result.messages_written++ @property+ def input_messages_consumed(self) -> int:+ """Return the caller-message prefix that is safe to skip on retry."""++ return self.result.input_messages_consumed++ @property+ def context_attached(self) -> bool:+ """Return whether recalled context was confirmed persisted."""++ return self.result.context_attached++ @property+ def commit_pending(self) -> bool:+ """Return whether only the post-write commit remains incomplete."""++ return self.stage == "commit"+++@dataclass(frozen=True, slots=True)+class OpenVikingCancellationProgress:+ """Confirmed recording progress attached to an original cancellation."""++ session_id: str+ result: OpenVikingRecordResult+ stage: Literal["batch", "commit"] = "batch"++ @property+ def messages_written(self) -> int:+ """Return the number of payloads confirmed written before cancellation."""++ return self.result.messages_written++ @property+ def input_messages_consumed(self) -> int:+ """Return the caller-message prefix that is safe to skip on retry."""++ return self.result.input_messages_consumed++ @property+ def context_attached(self) -> bool:+ """Return whether recalled context was confirmed persisted."""++ return self.result.context_attached++ @property+ def commit_pending(self) -> bool:+ """Return whether only the post-write commit remains incomplete."""++ return self.stage == "commit"+++_CANCELLATION_PROGRESS_ATTRIBUTE = "_openviking_recording_progress"+++def get_openviking_cancellation_progress(+ error: BaseException,+) -> OpenVikingCancellationProgress | None:+ """Return recording progress from a cancellation or a timeout wrapping it."""++ current: BaseException | None = error+ seen: set[int] = set()+ while current is not None and id(current) not in seen:+ seen.add(id(current))+ progress = getattr(current, _CANCELLATION_PROGRESS_ATTRIBUTE, None)+ if isinstance(progress, OpenVikingCancellationProgress):+ return progress+ current = current.__cause__ or current.__context__+ return None+++def _attach_cancellation_progress(+ error: asyncio.CancelledError,+ *,+ session_id: str,+ result: OpenVikingRecordResult,+ stage: Literal["batch", "commit"] = "batch",+) -> None:+ """Annotate the original cancellation without changing its identity."""++ setattr(+ error,+ _CANCELLATION_PROGRESS_ATTRIBUTE,+ OpenVikingCancellationProgress(+ session_id=session_id,+ result=result,+ stage=stage,+ ),+ )+++@dataclass(slots=True)+class _PreparedMessage:+ input_end: int+ payloads: list[dict[str, Any]]+ context_attached: bool = False+++@dataclass(slots=True)+class _PreparedBatch:+ input_end: int+ payloads: list[dict[str, Any]]+ context_attached: bool = False+++class OpenVikingSessionRecorder:+ """Persist caller-selected LangChain messages to OpenViking sessions.++ The recorder intentionally does not decide which messages form a turn or+ deduplicate transcript snapshots. Callers own that policy and pass only the+ messages they want persisted.+ """++ def __init__(+ self,+ *,+ client: Any = None,+ async_client: Any = None,+ url: str | None = None,+ api_key: str | None = None,+ account: str | None = None,+ user: str | None = None,+ user_id: str | None = None,+ actor_peer_id: str | None = None,+ path: str | None = None,+ timeout: float = 60.0,+ extra_headers: dict[str, str] | None = None,+ auto_initialize: bool = True,+ commit_policy: OpenVikingCommitPolicy | None = None,+ batch_size: int = MAX_RECORDING_BATCH_SIZE,+ ):+ if batch_size <= 0 or batch_size > MAX_RECORDING_BATCH_SIZE:+ raise ValueError(f"batch_size must be between 1 and {MAX_RECORDING_BATCH_SIZE}")+ self._connection = OpenVikingConnection(+ client=client,+ async_client=async_client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ timeout=timeout,+ extra_headers=extra_headers,+ auto_initialize=auto_initialize,+ )+ self._owns_client = client is None+ self._client_cache: Any = None+ self._client_cache_lock = threading.Lock()+ self._async_clients = LoopScopedAsyncClientCache()+ self._pending_commit_sessions: set[str] = set()+ self._pending_commit_lock = threading.Lock()+ self._closed = False+ self.commit_policy = commit_policy+ self.batch_size = batch_size++ def __deepcopy__(+ self,+ memo: dict[int, Any] | None = None,+ ) -> OpenVikingSessionRecorder:+ """Copy configuration and logical state with fresh runtime resources."""++ memo = {} if memo is None else memo+ for client in (self._connection.client, self._connection.async_client):+ if client is not None:+ memo[id(client)] = client+ with self._pending_commit_lock:+ pending_commit_sessions = set(self._pending_commit_sessions)++ copied = type(self).__new__(type(self))+ memo[id(self)] = copied+ copied.__dict__ = {+ name: (+ None+ if name == "_client_cache"+ else threading.Lock()+ if name in {"_client_cache_lock", "_pending_commit_lock"}+ else LoopScopedAsyncClientCache()+ if name == "_async_clients"+ else pending_commit_sessions+ if name == "_pending_commit_sessions"+ else deepcopy(value, memo)+ )+ for name, value in self.__dict__.items()+ }+ return copied++ @property+ def client(self) -> Any:+ """Return the lazily initialized OpenViking client used by this recorder."""++ self._raise_if_closed()+ if self._client_cache is None:+ with self._client_cache_lock:+ self._raise_if_closed()+ if self._client_cache is None:+ self._client_cache = ensure_client(self._connection)+ client = self._client_cache+ self._raise_if_closed()+ return client++ def record(+ self,+ session_id: str,+ messages: Iterable[BaseMessage],+ peer_id: str | None = None,+ context_parts: Sequence[dict[str, Any]] = (),+ ) -> OpenVikingRecordResult:+ """Persist a caller-selected batch and apply the configured commit policy."""++ self._raise_if_closed()+ self._retry_pending_commit(session_id)+ input_messages = list(messages)+ prepared_messages = _prepare_messages(+ input_messages,+ peer_id=peer_id,+ context_parts=context_parts,+ )+ if not prepared_messages:+ return OpenVikingRecordResult(input_messages_consumed=len(input_messages))++ batches = _prepare_batches(prepared_messages, batch_size=self.batch_size)+ client = self.client+ messages_written = 0+ input_messages_consumed = 0+ context_attached = False+ persisted_pending_tokens: Any = None+ for batch in batches:+ try:+ write_result = call_openviking(+ client,+ "batch_add_messages",+ session_id=session_id,+ messages=batch.payloads,+ )+ except Exception as exc:+ if messages_written == 0:+ raise+ result = OpenVikingRecordResult(+ messages_written=messages_written,+ input_messages_consumed=input_messages_consumed,+ context_attached=context_attached,+ )+ raise OpenVikingPartialWriteError(+ session_id=session_id,+ result=result,+ cause=exc,+ ) from exc+ messages_written += len(batch.payloads)+ input_messages_consumed = batch.input_end+ context_attached = context_attached or batch.context_attached+ if isinstance(write_result, dict) and "pending_tokens" in write_result:+ persisted_pending_tokens = write_result.get("pending_tokens")+ else:+ hint = item_value(write_result, "pending_tokens")+ if hint is not None:+ persisted_pending_tokens = hint+ result = OpenVikingRecordResult(+ messages_written=messages_written,+ input_messages_consumed=len(input_messages),+ context_attached=context_attached,+ )+ try:+ apply_commit_policy(+ client,+ session_id,+ self.commit_policy,+ persisted_pending_tokens=persisted_pending_tokens,+ )+ except Exception as exc:+ self._mark_commit_pending(session_id)+ raise OpenVikingPartialWriteError(+ session_id=session_id,+ result=result,+ cause=exc,+ stage="commit",+ ) from exc+ return result++ async def arecord(+ self,+ session_id: str,+ messages: Iterable[BaseMessage],+ peer_id: str | None = None,+ context_parts: Sequence[dict[str, Any]] = (),+ ) -> OpenVikingRecordResult:+ """Asynchronously persist messages and apply the configured commit policy."""++ self._raise_if_closed()+ await self._aretry_pending_commit(session_id)+ input_messages = list(messages)+ prepared_messages = _prepare_messages(+ input_messages,+ peer_id=peer_id,+ context_parts=context_parts,+ )+ if not prepared_messages:+ return OpenVikingRecordResult(input_messages_consumed=len(input_messages))++ batches = _prepare_batches(prepared_messages, batch_size=self.batch_size)+ client = await self.get_async_client()+ messages_written = 0+ input_messages_consumed = 0+ context_attached = False+ persisted_pending_tokens: Any = None+ for batch in batches:+ try:+ write_result = await acall_openviking(+ client,+ "batch_add_messages",+ session_id=session_id,+ messages=batch.payloads,+ )+ except asyncio.CancelledError as exc:+ if messages_written == 0:+ raise+ result = OpenVikingRecordResult(+ messages_written=messages_written,+ input_messages_consumed=input_messages_consumed,+ context_attached=context_attached,+ )+ _attach_cancellation_progress(+ exc,+ session_id=session_id,+ result=result,+ )+ raise+ except Exception as exc:+ if messages_written == 0:+ raise+ result = OpenVikingRecordResult(+ messages_written=messages_written,+ input_messages_consumed=input_messages_consumed,+ context_attached=context_attached,+ )+ raise OpenVikingPartialWriteError(+ session_id=session_id,+ result=result,+ cause=exc,+ ) from exc+ messages_written += len(batch.payloads)+ input_messages_consumed = batch.input_end+ context_attached = context_attached or batch.context_attached+ if isinstance(write_result, dict) and "pending_tokens" in write_result:+ persisted_pending_tokens = write_result.get("pending_tokens")+ else:+ hint = item_value(write_result, "pending_tokens")+ if hint is not None:+ persisted_pending_tokens = hint+ result = OpenVikingRecordResult(+ messages_written=messages_written,+ input_messages_consumed=len(input_messages),+ context_attached=context_attached,+ )+ try:+ await aapply_commit_policy(+ client,+ session_id,+ self.commit_policy,+ persisted_pending_tokens=persisted_pending_tokens,+ )+ except asyncio.CancelledError as exc:+ self._mark_commit_pending(session_id)+ _attach_cancellation_progress(+ exc,+ session_id=session_id,+ result=result,+ stage="commit",+ )+ raise+ except Exception as exc:+ self._mark_commit_pending(session_id)+ raise OpenVikingPartialWriteError(+ session_id=session_id,+ result=result,+ cause=exc,+ stage="commit",+ ) from exc+ return result++ def flush(self, session_id: str) -> dict[str, Any] | None:+ """Commit a session only when it contains pending, uncommitted content."""++ result = self._flush_pending_content(session_id)+ self._discard_pending_commit(session_id)+ return result++ async def aflush(self, session_id: str) -> dict[str, Any] | None:+ """Asynchronously commit pending, uncommitted session content."""++ result = await self._aflush_pending_content(session_id)+ self._discard_pending_commit(session_id)+ return result++ def _flush_pending_content(self, session_id: str) -> dict[str, Any] | None:+ client = self.client+ try:+ session = call_openviking(+ client,+ "get_session",+ session_id=session_id,+ auto_create=False,+ )+ except Exception as exc:+ error_code = str(getattr(exc, "code", "")).upper()+ if isinstance(exc, FileNotFoundError) or error_code == "NOT_FOUND":+ return None+ raise+ if int(item_value(session, "pending_tokens", 0) or 0) <= 0:+ return None+ return call_openviking(client, "commit_session", session_id=session_id)++ async def _aflush_pending_content(self, session_id: str) -> dict[str, Any] | None:+ client = await self.get_async_client()+ try:+ session = await acall_openviking(+ client,+ "get_session",+ session_id=session_id,+ auto_create=False,+ )+ except Exception as exc:+ error_code = str(getattr(exc, "code", "")).upper()+ if isinstance(exc, FileNotFoundError) or error_code == "NOT_FOUND":+ return None+ raise+ if int(item_value(session, "pending_tokens", 0) or 0) <= 0:+ return None+ return await acall_openviking(client, "commit_session", session_id=session_id)++ def _retry_pending_commit(self, session_id: str) -> None:+ if not self._is_commit_pending(session_id):+ return+ self._flush_pending_content(session_id)+ self._discard_pending_commit(session_id)++ async def _aretry_pending_commit(self, session_id: str) -> None:+ if not self._is_commit_pending(session_id):+ return+ await self._aflush_pending_content(session_id)+ self._discard_pending_commit(session_id)++ def _is_commit_pending(self, session_id: str) -> bool:+ with self._pending_commit_lock:+ return session_id in self._pending_commit_sessions++ def _mark_commit_pending(self, session_id: str) -> None:+ with self._pending_commit_lock:+ self._pending_commit_sessions.add(session_id)++ def _discard_pending_commit(self, session_id: str) -> None:+ with self._pending_commit_lock:+ self._pending_commit_sessions.discard(session_id)++ def _clear_pending_commits(self) -> None:+ with self._pending_commit_lock:+ self._pending_commit_sessions.clear()++ async def get_async_client(self) -> Any:+ """Return the async client interface used by this recorder.++ Injected clients are returned unchanged and remain caller-owned.+ HTTP-backed connections return an internally managed, loop-local handle+ whose method calls support recovery. Direct attributes on that handle+ are best-effort during recovery; use ``await handle.get()`` only to read+ raw properties immediately because recovery may replace that snapshot.+ Embedded ``path=`` connections return an adapter-owned synchronous+ client whose calls are dispatched through a worker thread.+ """++ self._raise_if_closed()+ client = await ensure_async_client(+ self._connection,+ client_cache=self._async_clients,+ embedded_client_factory=lambda: self.client,+ )+ self._raise_if_closed()+ return client++ async def _get_async_client(self) -> Any:+ return await self.get_async_client()++ def close(self) -> None:+ """Release resources after exclusively synchronous use.++ Injected clients remain owned by their caller and are never closed here.+ After any async operation has initialized an owned client, callers must+ use :meth:`aclose`; this method leaves the recorder open so that async+ cleanup can still complete.+ """++ if self._closed:+ return+ uses_http_client = bool(self._connection.url) or self._connection.path is None+ if uses_http_client and self._async_clients.has_clients():+ raise RuntimeError(+ "OpenVikingSessionRecorder has an active async client; "+ "use `await recorder.aclose()`"+ )+ if not uses_http_client:+ self._async_clients.pop_all()+ self._closed = True+ self._clear_pending_commits()+ with self._client_cache_lock:+ client = self._client_cache+ self._client_cache = None+ if client is None or not self._owns_client:+ return+ close = getattr(client, "close", None)+ if callable(close):+ close()++ async def aclose(self) -> None:+ """Release internally created sync and async clients."""++ if self._closed:+ return+ self._closed = True+ self._clear_pending_commits()+ with self._client_cache_lock:+ sync_client = self._client_cache+ self._client_cache = None+ async_clients = await asyncio.to_thread(self._async_clients.pop_all)++ await aclose_openviking_clients(+ sync_client if self._owns_client else None,+ *async_clients,+ )++ def _raise_if_closed(self) -> None:+ if self._closed:+ raise RuntimeError("OpenVikingSessionRecorder is closed")+++def _prepare_messages(+ messages: Sequence[BaseMessage],+ *,+ peer_id: str | None,+ context_parts: Sequence[dict[str, Any]],+) -> list[_PreparedMessage]:+ normalized_peer_id = _normalize_peer_id(peer_id)+ pending_context = deepcopy(list(context_parts))+ prepared_messages: list[_PreparedMessage] = []++ for index, message in enumerate(messages):+ context_carrier = is_context_carrier_langchain_message(message)+ recordable = is_recordable_langchain_message(message)+ if not recordable and not (pending_context and context_carrier):+ continue+ payloads = langchain_message_to_openviking(message)+ message_context_attached = False+ for payload in payloads:+ if pending_context and context_carrier and payload["role"] == "assistant":+ payload["parts"].extend(pending_context)+ pending_context = []+ message_context_attached = True+ if normalized_peer_id is not None:+ payload["peer_id"] = normalized_peer_id+ if payloads:+ prepared_messages.append(+ _PreparedMessage(+ input_end=index + 1,+ payloads=payloads,+ context_attached=message_context_attached,+ )+ )+ return prepared_messages+++def _prepare_batches(+ messages: Sequence[_PreparedMessage],+ *,+ batch_size: int,+) -> list[_PreparedBatch]:+ batches: list[_PreparedBatch] = []+ payloads: list[dict[str, Any]] = []+ input_end = 0+ context_attached = False++ for message in messages:+ payload_count = len(message.payloads)+ if payload_count > batch_size:+ raise ValueError(+ "one LangChain message produced more OpenViking payloads "+ f"({payload_count}) than batch_size ({batch_size})"+ )+ if payloads and len(payloads) + payload_count > batch_size:+ batches.append(+ _PreparedBatch(+ input_end=input_end,+ payloads=payloads,+ context_attached=context_attached,+ )+ )+ payloads = []+ context_attached = False+ payloads.extend(message.payloads)+ input_end = message.input_end+ context_attached = context_attached or message.context_attached++ if payloads:+ batches.append(+ _PreparedBatch(+ input_end=input_end,+ payloads=payloads,+ context_attached=context_attached,+ )+ )+ return batches+++def _normalize_peer_id(peer_id: str | None) -> str | None:+ if peer_id is None:+ return None+ text = str(peer_id).strip()+ return text or Nonediff --git a/integrations/langchain/src/langchain_openviking/retrievers.py b/integrations/langchain/src/langchain_openviking/retrievers.pynew file mode 100644index 000000000..06d127cbd--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/retrievers.py@@ -0,0 +1,309 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""LangChain retriever backed by OpenViking retrieval."""++from __future__ import annotations++import asyncio+import threading+from typing import Any, Literal++from pydantic import ConfigDict, Field, PrivateAttr++try:+ from langchain_core.documents import Document+ from langchain_core.retrievers import BaseRetriever+except ImportError as exc: # pragma: no cover - exercised by optional import path+ from langchain_openviking.client import missing_dependency++ raise missing_dependency("langchain", "langchain-core") from exc++from langchain_openviking._async_client_cache import LoopScopedAsyncClientCache+from langchain_openviking.client import (+ OpenVikingConnection,+ acall_openviking,+ aclose_openviking_clients,+ call_openviking,+ ensure_async_client,+ ensure_client,+ item_value,+ iter_result_items,+ stringify,+)+++class _SharedSyncClientCache:+ """Share one lazily created sync client across shallow retriever copies."""++ def __init__(self) -> None:+ self._client: Any = None+ self._owned = False+ self._lock = threading.Lock()++ def __deepcopy__(self, memo: dict[int, Any]) -> _SharedSyncClientCache:+ copied = type(self)()+ memo[id(self)] = copied+ return copied++ def get(self, factory: Any, *, owned: bool) -> Any:+ with self._lock:+ if self._client is None:+ self._client = factory()+ self._owned = owned+ return self._client++ def pop_owned(self) -> Any:+ with self._lock:+ client = self._client+ owned = self._owned+ self._client = None+ self._owned = False+ return client if owned else None+++class OpenVikingRetriever(BaseRetriever):+ """Retrieve LangChain ``Document`` objects from OpenViking contexts."""++ model_config = ConfigDict(arbitrary_types_allowed=True)++ client: Any = None+ async_client: Any = None+ url: str | None = None+ api_key: str | None = None+ account: str | None = None+ user: str | None = None+ user_id: str | None = None+ actor_peer_id: str | None = None+ path: str | None = None+ timeout: float = 60.0+ extra_headers: dict[str, str] | None = None+ auto_initialize: bool = True++ target_uri: str | list[str] = ""+ search_mode: Literal["find", "search"] = "find"+ session_id: str | None = None+ limit: int = 10+ score_threshold: float | None = None+ filter: dict[str, Any] | None = None+ context_types: tuple[str, ...] = ("memory", "resource", "skill")+ content_mode: Literal["auto", "abstract", "overview", "read"] = "auto"+ max_content_chars: int = 12_000+ metadata_prefix: str = "openviking"+ tags: list[str] | None = Field(default=None, exclude=True)++ _sync_client_cache: _SharedSyncClientCache = PrivateAttr(default_factory=_SharedSyncClientCache)+ _async_clients: LoopScopedAsyncClientCache = PrivateAttr(+ default_factory=LoopScopedAsyncClientCache+ )+ _closed: bool = PrivateAttr(default=False)++ def __deepcopy__(+ self,+ memo: dict[int, Any] | None = None,+ ) -> OpenVikingRetriever:+ """Copy configuration without cloning clients or cached runtime state."""++ memo = {} if memo is None else memo+ for client in (self.client, self.async_client):+ if client is not None:+ memo[id(client)] = client++ sync_client_cache = getattr(self, "_client_cache", None)+ if getattr(self, "_owns_client_cache", False) and sync_client_cache is not None:+ memo[id(sync_client_cache)] = None++ copied = super().__deepcopy__(memo)+ private_attributes = getattr(type(copied), "__private_attributes__", {})+ private_state = copied.__pydantic_private__+ if private_state is not None and "_client_cache" in private_attributes:+ private_state["_client_cache"] = None+ private_state["_owns_client_cache"] = False+ return copied++ def _get_client(self) -> Any:+ self._raise_if_closed()+ return self._sync_client_cache.get(+ lambda: ensure_client(+ OpenVikingConnection(+ client=self.client,+ url=self.url,+ api_key=self.api_key,+ account=self.account,+ user=self.user,+ user_id=self.user_id,+ actor_peer_id=self.actor_peer_id,+ path=self.path,+ timeout=self.timeout,+ extra_headers=self.extra_headers,+ auto_initialize=self.auto_initialize,+ )+ ),+ owned=self.client is None,+ )++ async def get_async_client(self) -> Any:+ """Return the async client interface used by this retriever.++ Injected clients are returned unchanged and remain caller-owned.+ HTTP-backed connections return an internally managed, loop-local handle+ whose method calls support recovery. Direct attributes on that handle+ are best-effort during recovery; use ``await handle.get()`` only to read+ raw properties immediately because recovery may replace that snapshot.+ Embedded ``path=`` connections return an adapter-owned synchronous+ client whose calls are dispatched through a worker thread.+ """++ self._raise_if_closed()+ client = await ensure_async_client(+ OpenVikingConnection(+ client=self.client,+ async_client=self.async_client,+ url=self.url,+ api_key=self.api_key,+ account=self.account,+ user=self.user,+ user_id=self.user_id,+ actor_peer_id=self.actor_peer_id,+ path=self.path,+ timeout=self.timeout,+ extra_headers=self.extra_headers,+ auto_initialize=self.auto_initialize,+ ),+ client_cache=self._async_clients,+ embedded_client_factory=self._get_client,+ )+ self._raise_if_closed()+ return client++ async def _get_async_client(self) -> Any:+ return await self.get_async_client()++ async def aclose(self) -> None:+ """Release clients created internally by this retriever."""++ if self._closed:+ return+ self._closed = True+ sync_client = self._sync_client_cache.pop_owned()+ async_clients = await asyncio.to_thread(self._async_clients.pop_all)++ await aclose_openviking_clients(+ sync_client,+ *async_clients,+ )++ def _raise_if_closed(self) -> None:+ if self._closed:+ raise RuntimeError("OpenVikingRetriever is closed")++ def _get_relevant_documents(self, query: str, *, run_manager: Any) -> list[Document]:+ client = self._get_client()+ method = "search" if self.search_mode == "search" else "find"+ result = call_openviking(+ client,+ method,+ query=query,+ target_uri=self.target_uri,+ session_id=self.session_id,+ limit=self.limit,+ score_threshold=self.score_threshold,+ filter=self.filter,+ tags=self.tags,+ )+ documents: list[Document] = []+ for context_type, item in iter_result_items(result, self.context_types):+ content = self._content_for_item(client, item)+ documents.append(self._document_from_item(context_type, item, content))+ return documents++ async def _aget_relevant_documents(self, query: str, *, run_manager: Any) -> list[Document]:+ client = await self._get_async_client()+ method = "search" if self.search_mode == "search" else "find"+ result = await acall_openviking(+ client,+ method,+ query=query,+ target_uri=self.target_uri,+ session_id=self.session_id,+ limit=self.limit,+ score_threshold=self.score_threshold,+ filter=self.filter,+ tags=self.tags,+ )+ documents: list[Document] = []+ for context_type, item in iter_result_items(result, self.context_types):+ content = await self._acontent_for_item(client, item)+ documents.append(self._document_from_item(context_type, item, content))+ return documents++ def _document_from_item(+ self,+ context_type: str,+ item: Any,+ content: str,+ ) -> Document:+ uri = item_value(item, "uri", "")+ return Document(+ page_content=content,+ metadata={+ "source": uri,+ f"{self.metadata_prefix}_uri": uri,+ f"{self.metadata_prefix}_context_type": context_type,+ f"{self.metadata_prefix}_level": item_value(item, "level"),+ f"{self.metadata_prefix}_category": item_value(item, "category"),+ f"{self.metadata_prefix}_score": item_value(item, "score"),+ f"{self.metadata_prefix}_match_reason": item_value(item, "match_reason"),+ f"{self.metadata_prefix}_abstract": item_value(item, "abstract"),+ f"{self.metadata_prefix}_overview": item_value(item, "overview"),+ },+ )++ def _content_for_item(self, client: Any, item: Any) -> str:+ uri = item_value(item, "uri", "")+ abstract = item_value(item, "abstract", "")+ overview = item_value(item, "overview", "")+ level = item_value(item, "level")++ if self.content_mode == "abstract":+ return stringify(abstract or overview, max_chars=self.max_content_chars)+ if self.content_mode == "overview":+ return stringify(overview or abstract, max_chars=self.max_content_chars)+ if self.content_mode == "read":+ return self._read_or_fallback(client, uri, overview or abstract)+ if level == 2 and uri:+ return self._read_or_fallback(client, uri, overview or abstract)+ return stringify(overview or abstract, max_chars=self.max_content_chars)++ async def _acontent_for_item(self, client: Any, item: Any) -> str:+ uri = item_value(item, "uri", "")+ abstract = item_value(item, "abstract", "")+ overview = item_value(item, "overview", "")+ level = item_value(item, "level")++ if self.content_mode == "abstract":+ return stringify(abstract or overview, max_chars=self.max_content_chars)+ if self.content_mode == "overview":+ return stringify(overview or abstract, max_chars=self.max_content_chars)+ if self.content_mode == "read":+ return await self._aread_or_fallback(client, uri, overview or abstract)+ if level == 2 and uri:+ return await self._aread_or_fallback(client, uri, overview or abstract)+ return stringify(overview or abstract, max_chars=self.max_content_chars)++ def _read_or_fallback(self, client: Any, uri: str, fallback: Any) -> str:+ if uri:+ try:+ content = call_openviking(client, "read", uri=uri)+ return stringify(content, max_chars=self.max_content_chars)+ except Exception:+ pass+ return stringify(fallback, max_chars=self.max_content_chars)++ async def _aread_or_fallback(self, client: Any, uri: str, fallback: Any) -> str:+ if uri:+ try:+ content = await acall_openviking(client, "read", uri=uri)+ return stringify(content, max_chars=self.max_content_chars)+ except Exception:+ pass+ return stringify(fallback, max_chars=self.max_content_chars)diff --git a/integrations/langchain/src/langchain_openviking/store.py b/integrations/langchain/src/langchain_openviking/store.pynew file mode 100644index 000000000..00f231421--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/store.py@@ -0,0 +1,599 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""LangGraph Store implementation backed by OpenViking."""++from __future__ import annotations++import asyncio+import json+import logging+from datetime import datetime, timezone+from typing import TYPE_CHECKING, Any, Iterable+from urllib.parse import quote, unquote++from langchain_openviking._uri import UriClassification, classify_uri+from langchain_openviking.client import (+ OpenVikingConnection,+ OptionalDependencyError,+ call_openviking,+ ensure_client,+ item_value,+ iter_result_items,+ missing_dependency,+)++_LANGGRAPH_IMPORT_ERROR: OptionalDependencyError | None = None+if TYPE_CHECKING:+ from langgraph.store.base import (+ BaseStore,+ GetOp,+ Item,+ ListNamespacesOp,+ PutOp,+ SearchItem,+ SearchOp,+ )+else:+ try:+ from langgraph.store.base import (+ BaseStore,+ GetOp,+ Item,+ ListNamespacesOp,+ PutOp,+ SearchItem,+ SearchOp,+ )+ except ImportError: # pragma: no cover - exercised by optional import path+ _LANGGRAPH_IMPORT_ERROR = missing_dependency("langgraph", "langgraph")+ BaseStore = object+ GetOp = PutOp = SearchOp = ListNamespacesOp = object+ Item = SearchItem = object++logger = logging.getLogger(__name__)+++class OpenVikingStore(BaseStore):+ """LangGraph ``BaseStore`` persisted and indexed through OpenViking.++ Values are stored as JSON records under ``<root_uri>/data``. A separate+ markdown projection under ``<root_uri>/index`` gives OpenViking semantic+ retrieval a compact document to index for query-based ``search`` calls.+ """++ def __init__(+ self,+ *,+ client: Any = None,+ url: str | None = None,+ api_key: str | None = None,+ account: str | None = None,+ user: str | None = None,+ user_id: str | None = None,+ actor_peer_id: str | None = None,+ path: str | None = None,+ root_uri: str = "viking://user/memories/langgraph_store",+ index: bool | list[str] | None = None,+ wait: bool = True,+ timeout: float | None = None,+ search_fetch_limit: int = 50,+ auto_initialize: bool = True,+ ):+ if _LANGGRAPH_IMPORT_ERROR is not None:+ raise _LANGGRAPH_IMPORT_ERROR+ super().__init__()+ self._connection: OpenVikingConnection = OpenVikingConnection(+ client=client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ auto_initialize=auto_initialize,+ )+ self.root_uri: str = root_uri.rstrip("/")+ self.index: bool | list[str] | None = index+ self.wait: bool = wait+ self.timeout: float | None = timeout+ self.search_fetch_limit: int = search_fetch_limit+ self._client_cache: Any = None++ def batch(self, ops: Iterable[Any]) -> list[Any]:+ results: list[Any] = []+ for op in ops:+ if isinstance(op, GetOp):+ results.append(self.get(op.namespace, op.key))+ elif isinstance(op, PutOp):+ if op.value is None:+ self.delete(op.namespace, op.key)+ else:+ self.put(op.namespace, op.key, op.value, index=op.index, ttl=op.ttl)+ results.append(None)+ elif isinstance(op, SearchOp):+ results.append(+ self.search(+ op.namespace_prefix,+ query=op.query,+ filter=op.filter,+ limit=op.limit,+ offset=op.offset,+ )+ )+ elif isinstance(op, ListNamespacesOp):+ prefix, suffix = self._match_conditions_to_prefix_suffix(op.match_conditions)+ results.append(+ self.list_namespaces(+ prefix=prefix,+ suffix=suffix,+ max_depth=op.max_depth,+ limit=op.limit,+ offset=op.offset,+ )+ )+ else:+ raise TypeError(f"Unsupported LangGraph store operation: {type(op)!r}")+ return results++ async def abatch(self, ops: Iterable[Any]) -> list[Any]:+ return await asyncio.to_thread(lambda: self.batch(list(ops)))++ def get(self, namespace: tuple[str, ...], key: str, *, refresh_ttl: Any = None) -> Any:+ try:+ record = self._read_record(self._data_uri(namespace, key))+ except Exception:+ return None+ return Item(+ namespace=tuple(record["namespace"]),+ key=record["key"],+ value=record["value"],+ created_at=_parse_dt(record["created_at"]),+ updated_at=_parse_dt(record["updated_at"]),+ )++ def put(+ self,+ namespace: tuple[str, ...],+ key: str,+ value: dict[str, Any],+ index: bool | list[str] | None = None,+ *,+ ttl: Any = None,+ ) -> None:+ if ttl is not None:+ raise NotImplementedError(+ "TTL is not supported by OpenVikingStore. "+ "OpenViking stores LangGraph values as durable content records."+ )+ namespace = tuple(namespace)+ now = datetime.now(timezone.utc)+ data_uri = self._data_uri(namespace, key)+ record = self._write_record(data_uri, namespace, key, value, now)++ effective_index = self.index if index is None else index+ index_uri = self._index_uri(namespace, key)+ if effective_index is False:+ self._remove(index_uri)+ return+ self._write(index_uri, self._index_document(record, effective_index))++ def delete(self, namespace: tuple[str, ...], key: str) -> None:+ self._remove(self._data_uri(namespace, key))+ self._remove(self._index_uri(namespace, key))++ def search(+ self,+ namespace_prefix: tuple[str, ...],+ *,+ query: str | None = None,+ filter: dict[str, Any] | None = None,+ limit: int = 10,+ offset: int = 0,+ refresh_ttl: Any = None,+ ) -> list[Any]:+ namespace_prefix = tuple(namespace_prefix)+ if query:+ return self._semantic_search(namespace_prefix, query, filter, limit, offset)+ items = [+ self._item_to_search_item(item, score=None)+ for item in self._list_items(namespace_prefix)+ if _matches_filter(item.value, filter)+ ]+ items.sort(key=lambda item: (item.updated_at, item.namespace, item.key), reverse=True)+ return items[offset : offset + limit]++ def list_namespaces(+ self,+ *,+ prefix: tuple[str, ...] | None = None,+ suffix: tuple[str, ...] | None = None,+ max_depth: int | None = None,+ limit: int = 100,+ offset: int = 0,+ ) -> list[tuple[str, ...]]:+ namespaces = set()+ for uri in self._all_data_uris(prefix or ()):+ parsed = self._parse_data_uri(uri)+ if parsed is None:+ continue+ namespace, _key = parsed+ if prefix and not _tuple_matches_prefix(namespace, prefix):+ continue+ if suffix and not _tuple_matches_suffix(namespace, suffix):+ continue+ if max_depth is not None and len(namespace) > max_depth:+ namespace = namespace[:max_depth]+ namespaces.add(namespace)+ ordered = sorted(namespaces)+ return ordered[offset : offset + limit]++ def _semantic_search(+ self,+ namespace_prefix: tuple[str, ...],+ query: str,+ filter: dict[str, Any] | None,+ limit: int,+ offset: int,+ ) -> list[Any]:+ result = call_openviking(+ self._client(),+ "find",+ query=query,+ target_uri=self._index_prefix_uri(namespace_prefix),+ limit=max(limit + offset, self.search_fetch_limit),+ )+ items: list[Any] = []+ for _context_type, result_item in iter_result_items(+ result, ("memory", "resource", "skill")+ ):+ uri = item_value(result_item, "uri", "")+ parsed = self._parse_index_uri(uri)+ if parsed is None:+ continue+ namespace, key = parsed+ item = self.get(namespace, key)+ if item is None or not _matches_filter(item.value, filter):+ continue+ items.append(self._item_to_search_item(item, score=item_value(result_item, "score")))+ return items[offset : offset + limit]++ def _list_items(self, namespace_prefix: tuple[str, ...]) -> list[Any]:+ items = []+ for uri in self._all_data_uris(namespace_prefix):+ parsed = self._parse_data_uri(uri)+ if parsed is None:+ continue+ namespace, key = parsed+ item = self.get(namespace, key)+ if item is not None:+ items.append(item)+ return items++ def _all_data_uris(self, namespace_prefix: tuple[str, ...]) -> list[str]:+ base_uri = self._data_prefix_uri(namespace_prefix)+ uris: list[str] = []+ seen: set[str] = set()+ for pattern in ("*.json", "**/*.json"):+ try:+ result = call_openviking(self._client(), "glob", pattern=pattern, uri=base_uri)+ except Exception:+ continue+ for uri in _extract_uris(result):+ if uri not in seen:+ seen.add(uri)+ uris.append(uri)+ return uris++ def _client(self) -> Any:+ if self._client_cache is None:+ self._client_cache = ensure_client(self._connection)+ return self._client_cache++ def _read_record(self, uri: str) -> dict[str, Any]:+ content = call_openviking(self._client(), "read", uri=uri)+ if isinstance(content, bytes):+ content = content.decode("utf-8")+ return json.loads(str(content))++ def _write_record(+ self,+ uri: str,+ namespace: tuple[str, ...],+ key: str,+ value: dict[str, Any],+ now: datetime,+ ) -> dict[str, Any]:+ record = _store_record(namespace, key, value, created_at=now, updated_at=now)+ content = json.dumps(record, ensure_ascii=False, indent=2)+ try:+ self._write_create(uri, content)+ return record+ except Exception as create_exc:+ try:+ existing = self._read_record(uri)+ except Exception:+ raise create_exc++ created_at = _parse_dt(existing["created_at"])+ record = _store_record(namespace, key, value, created_at=created_at, updated_at=now)+ self._write_replace(uri, json.dumps(record, ensure_ascii=False, indent=2))+ return record++ def _write(self, uri: str, content: str) -> None:+ try:+ self._write_create(uri, content)+ return+ except Exception as create_exc:+ try:+ self._write_replace(uri, content)+ return+ except Exception:+ raise create_exc++ def _write_create(self, uri: str, content: str) -> None:+ call_openviking(+ self._client(),+ "write",+ uri=uri,+ content=content,+ mode="create",+ wait=self.wait,+ timeout=self.timeout,+ )++ def _write_replace(self, uri: str, content: str) -> None:+ call_openviking(+ self._client(),+ "write",+ uri=uri,+ content=content,+ mode="replace",+ wait=self.wait,+ timeout=self.timeout,+ )++ def _remove(self, uri: str) -> None:+ try:+ call_openviking(self._client(), "rm", uri=uri, recursive=False)+ except Exception:+ logger.debug("OpenVikingStore remove ignored missing/unavailable URI", exc_info=True)+ pass++ def _data_uri(self, namespace: tuple[str, ...], key: str) -> str:+ return f"{self._data_prefix_uri(namespace)}/{_segment(key)}.json"++ def _index_uri(self, namespace: tuple[str, ...], key: str) -> str:+ return f"{self._index_prefix_uri(namespace)}/{_segment(key)}.md"++ def _data_prefix_uri(self, namespace: tuple[str, ...]) -> str:+ return _join_uri(self.root_uri, "data", *namespace)++ def _index_prefix_uri(self, namespace: tuple[str, ...]) -> str:+ return _join_uri(self.root_uri, "index", *namespace)++ def _parse_data_uri(self, uri: str) -> tuple[tuple[str, ...], str] | None:+ return self._parse_record_uri(uri, "data", ".json")++ def _parse_index_uri(self, uri: str) -> tuple[tuple[str, ...], str] | None:+ return self._parse_record_uri(uri, "index", ".md")++ def _parse_record_uri(+ self, uri: str, collection: str, suffix: str+ ) -> tuple[tuple[str, ...], str] | None:+ prefix = _join_uri(self.root_uri, collection) + "/"+ if not uri.startswith(prefix) or not uri.endswith(suffix):+ return _parse_canonicalized_record_uri(+ root_uri=self.root_uri,+ uri=uri,+ collection=collection,+ suffix=suffix,+ )+ return _parse_record_parts(uri[len(prefix) : -len(suffix)].split("/"))++ def _index_document(self, record: dict[str, Any], index: bool | list[str] | None) -> str:+ value = record["value"]+ projected = _project_value(value, index)+ return "\n".join(+ [+ f"# {record['key']}",+ "",+ f"Namespace: {'/'.join(record['namespace'])}",+ f"Key: {record['key']}",+ "",+ json.dumps(projected, ensure_ascii=False, indent=2),+ ]+ )++ def _item_to_search_item(self, item: Any, score: float | None) -> Any:+ return SearchItem(+ namespace=item.namespace,+ key=item.key,+ value=item.value,+ created_at=item.created_at,+ updated_at=item.updated_at,+ score=score,+ )++ def _match_conditions_to_prefix_suffix(+ self, conditions: Iterable[Any] | None+ ) -> tuple[tuple[str, ...] | None, tuple[str, ...] | None]:+ prefix = None+ suffix = None+ for condition in conditions or []:+ match_type = getattr(condition, "match_type", None)+ path = tuple(getattr(condition, "path", ()) or ())+ if match_type == "prefix":+ prefix = path+ elif match_type == "suffix":+ suffix = path+ return prefix, suffix+++def _segment(value: str) -> str:+ return quote(str(value), safe="")+++def _join_uri(root: str, *segments: str) -> str:+ suffix = "/".join(_segment(segment) for segment in segments if segment)+ return root.rstrip("/") if not suffix else f"{root.rstrip('/')}/{suffix}"+++def _parse_canonicalized_record_uri(+ *,+ root_uri: str,+ uri: str,+ collection: str,+ suffix: str,+) -> tuple[tuple[str, ...], str] | None:+ root = classify_uri(root_uri)+ root_tail = _identity_relative_root_tail(root)+ if root_tail is None:+ return None++ candidate = classify_uri(uri)+ if candidate.scope != root.scope or candidate.content_index is None:+ return None++ candidate_tail = candidate.parts[candidate.content_index :]+ if len(candidate_tail) < len(root_tail) + 2:+ return None+ if candidate_tail[: len(root_tail)] != root_tail:+ return None++ collection_index = len(root_tail)+ if candidate_tail[collection_index] != collection:+ return None++ rel_parts = list(candidate_tail[collection_index + 1 :])+ if not rel_parts or not rel_parts[-1].endswith(suffix):+ return None+ rel_parts = [*rel_parts[:-1], rel_parts[-1][: -len(suffix)]]+ return _parse_record_parts(rel_parts)+++def _identity_relative_root_tail(classification: UriClassification) -> tuple[str, ...] | None:+ if classification.scope != "user":+ return None+ if classification.content_index != 1:+ return None+ return classification.parts[classification.content_index :]+++def _parse_record_parts(parts: list[str]) -> tuple[tuple[str, ...], str] | None:+ if not parts or not parts[-1]:+ return None+ namespace = tuple(unquote(part) for part in parts[:-1])+ key = unquote(parts[-1])+ return namespace, key+++def _parse_dt(value: str) -> datetime:+ parsed = datetime.fromisoformat(value)+ if parsed.tzinfo is None:+ return parsed.replace(tzinfo=timezone.utc)+ return parsed+++def _store_record(+ namespace: tuple[str, ...],+ key: str,+ value: dict[str, Any],+ *,+ created_at: datetime,+ updated_at: datetime,+) -> dict[str, Any]:+ return {+ "namespace": list(namespace),+ "key": key,+ "value": value,+ "created_at": created_at.isoformat(),+ "updated_at": updated_at.isoformat(),+ }+++def _extract_uris(value: Any) -> list[str]:+ if value is None:+ return []+ if isinstance(value, str):+ return [value] if value.startswith("viking://") else []+ if isinstance(value, dict):+ if isinstance(value.get("uri"), str):+ return [value["uri"]]+ uris: list[str] = []+ for key in ("matches", "result", "files", "items"):+ uris.extend(_extract_uris(value.get(key)))+ return uris+ if isinstance(value, list):+ nested_uris: list[str] = []+ for item in value:+ nested_uris.extend(_extract_uris(item))+ return nested_uris+ return []+++def _project_value(value: dict[str, Any], index: bool | list[str] | None) -> dict[str, Any]:+ if isinstance(index, list):+ return {field: _nested_value(value, field) for field in index}+ return value+++def _nested_value(value: dict[str, Any], path: str) -> Any:+ current: Any = value+ for part in path.split("."):+ if not isinstance(current, dict):+ return None+ current = current.get(part)+ return current+++def _matches_filter(value: dict[str, Any], filter: dict[str, Any] | None) -> bool:+ if not filter:+ return True+ for path, expected in filter.items():+ actual = _nested_value(value, path)+ if isinstance(expected, dict):+ for op, target in expected.items():+ if not _compare(actual, op, target):+ return False+ elif actual != expected:+ return False+ return True+++def _compare(actual: Any, op: str, target: Any) -> bool:+ if op in {"$eq", "eq"}:+ return actual == target+ if op in {"$ne", "ne"}:+ return actual != target+ if op in {"$gt", "gt"}:+ return _safe_ordered_compare(actual, target, lambda left, right: left > right)+ if op in {"$gte", "gte"}:+ return _safe_ordered_compare(actual, target, lambda left, right: left >= right)+ if op in {"$lt", "lt"}:+ return _safe_ordered_compare(actual, target, lambda left, right: left < right)+ if op in {"$lte", "lte"}:+ return _safe_ordered_compare(actual, target, lambda left, right: left <= right)+ if op in {"$in", "in"}:+ try:+ return actual in target+ except TypeError:+ return False+ return actual == target+++def _safe_ordered_compare(actual: Any, target: Any, compare) -> bool:+ if actual is None:+ return False+ try:+ return bool(compare(actual, target))+ except TypeError:+ return False+++def _tuple_matches_prefix(value: tuple[str, ...], prefix: tuple[str, ...]) -> bool:+ return len(value) >= len(prefix) and value[: len(prefix)] == prefix+++def _tuple_matches_suffix(value: tuple[str, ...], suffix: tuple[str, ...]) -> bool:+ return len(value) >= len(suffix) and value[-len(suffix) :] == suffixdiff --git a/integrations/langchain/src/langchain_openviking/testing.py b/integrations/langchain/src/langchain_openviking/testing.pynew file mode 100644index 000000000..b802c4287--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/testing.py@@ -0,0 +1,409 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Deterministic test utilities for framework smoke tests."""++from __future__ import annotations++import fnmatch+import re+import uuid+from collections import defaultdict+from datetime import datetime, timezone+from typing import Any++from openviking_sdk.errors import NotFoundError++from langchain_openviking._testing_utils import estimate_text_tokens, normalize_peer_id+++class InMemoryOpenVikingClient:+ """Small OpenViking-compatible client for examples and CI smoke tests.++ This class intentionally implements the OpenViking methods used by the+ LangChain/LangGraph adapters. It is not a replacement for OpenViking.+ """++ def __init__(self, records: dict[str, str] | None = None):+ self.records: dict[str, str] = dict(records or {})+ self.sessions: dict[str, list[dict[str, Any]]] = defaultdict(list)+ self.archives: dict[str, list[dict[str, Any]]] = defaultdict(list)+ self.pending_tokens: dict[str, int] = defaultdict(int)+ self.find_calls: list[dict[str, Any]] = []+ self.search_calls: list[dict[str, Any]] = []+ self._initialized = False++ def initialize(self) -> None:+ self._initialized = True++ def close(self) -> None:+ self._initialized = False++ def find(+ self,+ query: str,+ target_uri: str | list[str] = "",+ limit: int = 10,+ score_threshold: float | None = None,+ filter: dict[str, Any] | None = None,+ tags: list[str] | None = None,+ **_: Any,+ ) -> dict[str, Any]:+ self.find_calls.append(+ {+ "query": query,+ "target_uri": target_uri,+ "limit": limit,+ "score_threshold": score_threshold,+ "filter": filter,+ "tags": tags,+ }+ )+ return self._search(query, target_uri, limit, score_threshold)++ def search(+ self,+ query: str,+ target_uri: str | list[str] = "",+ session_id: str | None = None,+ limit: int = 10,+ score_threshold: float | None = None,+ filter: dict[str, Any] | None = None,+ tags: list[str] | None = None,+ **_: Any,+ ) -> dict[str, Any]:+ self.search_calls.append(+ {+ "query": query,+ "target_uri": target_uri,+ "session_id": session_id,+ "limit": limit,+ "score_threshold": score_threshold,+ "filter": filter,+ "tags": tags,+ }+ )+ session_text = " ".join(+ _message_text(message) for message in self.sessions.get(session_id or "", [])+ )+ return self._search(f"{query} {session_text}", target_uri, limit, score_threshold)++ def _search(+ self,+ query: str,+ target_uri: str | list[str],+ limit: int,+ score_threshold: float | None,+ ) -> dict[str, Any]:+ targets = [target_uri] if isinstance(target_uri, str) else list(target_uri)+ targets = [target.rstrip("/") for target in targets if target]+ tokens = {token for token in re.findall(r"[a-z0-9_]+", query.lower()) if len(token) > 1}+ scored: list[tuple[float, str, str]] = []+ for uri, content in self.records.items():+ if targets and not any(uri.startswith(target) for target in targets):+ continue+ haystack = f"{uri}\n{content}".lower()+ score = sum(1 for token in tokens if token in haystack)+ if score == 0 and tokens:+ continue+ normalized = float(score or 1)+ if score_threshold is not None and normalized < score_threshold:+ continue+ scored.append((normalized, uri, content))+ scored.sort(key=lambda row: (-row[0], row[1]))+ result: dict[str, Any] = {"memories": [], "resources": [], "skills": [], "total": 0}+ for result_score, uri, content in scored[:limit]:+ item = {+ "uri": uri,+ "level": 2,+ "abstract": content[:240],+ "overview": content,+ "score": result_score,+ "match_reason": "deterministic token match",+ }+ if "/skills/" in uri:+ result["skills"].append(item)+ elif "/memories/" in uri:+ result["memories"].append(item)+ else:+ result["resources"].append(item)+ result["total"] = sum(len(result[key]) for key in ("memories", "resources", "skills"))+ return result++ def read(self, uri: str, offset: int = 0, limit: int = -1) -> str:+ if uri not in self.records:+ raise FileNotFoundError(uri)+ lines = self.records[uri].splitlines()+ if offset or limit >= 0:+ end = None if limit < 0 else offset + limit+ return "\n".join(lines[offset:end])+ return self.records[uri]++ def abstract(self, uri: str) -> str:+ return self.read(uri)[:240]++ def overview(self, uri: str) -> str:+ return self.read(uri)++ def write(+ self,+ uri: str,+ content: str,+ mode: str = "replace",+ wait: bool = False,+ timeout: float | None = None,+ **_: Any,+ ) -> dict[str, Any]:+ if mode == "create" and uri in self.records:+ raise FileExistsError(uri)+ if mode == "replace" and uri not in self.records:+ raise FileNotFoundError(uri)+ if mode == "append":+ self.records[uri] = self.records.get(uri, "") + content+ else:+ self.records[uri] = content+ return {"uri": uri, "mode": mode, "content_updated": True}++ def mkdir(self, uri: str, description: str | None = None) -> None:+ return None++ def rm(self, uri: str, recursive: bool = False) -> None:+ if recursive:+ prefix = uri.rstrip("/") + "/"+ for key in list(self.records):+ if key == uri or key.startswith(prefix):+ del self.records[key]+ return+ self.records.pop(uri, None)++ def ls(self, uri: str, simple: bool = False, recursive: bool = False, **_: Any) -> list[Any]:+ prefix = uri.rstrip("/") + "/"+ seen: set[str] = set()+ values: list[Any] = []+ for key in sorted(self.records):+ if not key.startswith(prefix):+ continue+ rel = key[len(prefix) :]+ if not recursive and "/" in rel:+ rel = rel.split("/", 1)[0]+ child_uri = prefix + rel+ if child_uri in seen:+ continue+ seen.add(child_uri)+ values.append(child_uri if simple else {"uri": child_uri, "rel_path": rel})+ return values++ def glob(self, pattern: str, uri: str = "viking://") -> dict[str, Any]:+ prefix = uri.rstrip("/") + "/"+ matches = []+ for key in sorted(self.records):+ if not key.startswith(prefix):+ continue+ rel = key[len(prefix) :]+ if fnmatch.fnmatch(rel, pattern):+ matches.append(key)+ return {"matches": matches, "count": len(matches)}++ def grep(+ self,+ uri: str,+ pattern: str,+ case_insensitive: bool = False,+ node_limit: int | None = None,+ **_: Any,+ ) -> dict[str, Any]:+ flags = re.IGNORECASE if case_insensitive else 0+ regex = re.compile(pattern, flags)+ prefix = uri.rstrip("/") + "/"+ matches: list[dict[str, Any]] = []+ for key, content in sorted(self.records.items()):+ if key != uri and not key.startswith(prefix):+ continue+ for line_number, line in enumerate(content.splitlines(), start=1):+ if regex.search(line):+ matches.append({"uri": key, "line_number": line_number, "line": line})+ if node_limit and len(matches) >= node_limit:+ return {"matches": matches, "count": len(matches)}+ return {"matches": matches, "count": len(matches)}++ def create_session(self, session_id: str | None = None) -> dict[str, Any]:+ session_id = session_id or f"session-{uuid.uuid4().hex[:12]}"+ self.sessions.setdefault(session_id, [])+ return {"session_id": session_id, "uri": self._session_uri(session_id)}++ @staticmethod+ def _session_uri(session_id: str) -> str:+ return f"viking://user/default/sessions/{session_id}"++ def add_message(+ self,+ session_id: str,+ role: str,+ content: str | None = None,+ parts: list[dict] | None = None,+ created_at: str | None = None,+ peer_id: str | None = None,+ **_: Any,+ ) -> dict[str, Any]:+ message_parts = list(parts or [{"type": "text", "text": content or ""}])+ normalized_peer_id = normalize_peer_id(peer_id)+ message = {+ "id": f"msg_{uuid.uuid4().hex}",+ "role": role,+ "parts": message_parts,+ "created_at": created_at or datetime.now(timezone.utc).isoformat(),+ }+ if normalized_peer_id is not None:+ message["peer_id"] = normalized_peer_id+ self.sessions.setdefault(session_id, []).append(message)+ self.pending_tokens[session_id] += max(1, estimate_text_tokens(_message_text(message)))+ return {+ "session_id": session_id,+ "role": role,+ "message_count": len(self.sessions[session_id]),+ "pending_tokens": self.pending_tokens[session_id],+ }++ def batch_add_messages(+ self,+ session_id: str,+ messages: list[dict[str, Any]],+ **_: Any,+ ) -> dict[str, Any]:+ added = 0+ for message in messages:+ self.add_message(+ session_id=session_id,+ role=message["role"],+ content=message.get("content"),+ parts=message.get("parts"),+ created_at=message.get("created_at"),+ peer_id=message.get("peer_id"),+ )+ added += 1+ return {+ "session_id": session_id,+ "message_count": len(self.sessions[session_id]),+ "added": added,+ "pending_tokens": self.pending_tokens[session_id],+ }++ def get_session(self, session_id: str, auto_create: bool = False) -> dict[str, Any]:+ if auto_create:+ self.create_session(session_id=session_id)+ return {+ "session_id": session_id,+ "uri": self._session_uri(session_id),+ "message_count": len(self.sessions.get(session_id, [])),+ "pending_tokens": self.pending_tokens.get(session_id, 0),+ }++ def get_session_context(+ self,+ session_id: str,+ token_budget: int = 128_000,+ **_: Any,+ ) -> dict[str, Any]:+ del token_budget+ if session_id not in self.sessions:+ raise NotFoundError(session_id, "session")+ latest_archive = self.archives.get(session_id, [])[-1:] or []+ latest = latest_archive[0] if latest_archive else {}+ messages = list(self.sessions.get(session_id, []))+ active_tokens = sum(+ max(1, estimate_text_tokens(_message_text(message))) for message in messages+ )+ archive_tokens = max(0, estimate_text_tokens(str(latest.get("overview", ""))))+ return {+ "latest_archive_overview": latest.get("overview", ""),+ "pre_archive_abstracts": [+ {"archive_id": archive["archive_id"], "abstract": archive["abstract"]}+ for archive in self.archives.get(session_id, [])[:-1]+ ],+ "messages": messages,+ "estimatedTokens": active_tokens + archive_tokens,+ "stats": {+ "totalArchives": len(self.archives.get(session_id, [])),+ "includedArchives": 1 if latest else 0,+ "droppedArchives": 0,+ "failedArchives": 0,+ "activeTokens": active_tokens,+ "archiveTokens": archive_tokens,+ },+ }++ def get_session_archive(self, session_id: str, archive_id: str, **_: Any) -> dict[str, Any]:+ for archive in self.archives.get(session_id, []):+ if archive["archive_id"] == archive_id:+ return dict(archive)+ raise FileNotFoundError(archive_id)++ def commit_session(+ self,+ session_id: str,+ **_: Any,+ ) -> dict[str, Any]:+ messages = list(self.sessions.get(session_id, []))+ archive_id = f"archive_{len(self.archives[session_id]) + 1:03d}"+ overview = "\n".join(_message_text(message) for message in messages)+ if messages:+ archive_uri = f"{self._session_uri(session_id)}/history/{archive_id}"+ self.archives[session_id].append(+ {+ "archive_id": archive_id,+ "abstract": overview[:240],+ "overview": overview,+ "messages": messages,+ }+ )+ self.records[f"{archive_uri}/messages.jsonl"] = (+ "\n".join(_message_text(message) for message in messages) + "\n"+ )+ self.records[f"{archive_uri}/.abstract.md"] = overview[:240]+ self.records[f"{archive_uri}/.overview.md"] = overview+ self.records[f"{archive_uri}/.done"] = "{}"+ self.sessions[session_id] = []+ self.pending_tokens[session_id] = 0+ return {+ "session_id": session_id,+ "status": "completed",+ "archive_id": archive_id if messages else None,+ "archived": bool(messages),+ }++ def delete_session(self, session_id: str) -> None:+ self.sessions.pop(session_id, None)+ self.archives.pop(session_id, None)+ self.pending_tokens.pop(session_id, None)+ session_uri = self._session_uri(session_id)+ for uri in list(self.records):+ if uri == session_uri or uri.startswith(f"{session_uri}/"):+ del self.records[uri]++ def add_resource(self, path: str, to: str | None = None, **_: Any) -> dict[str, Any]:+ uri = to or f"viking://resources/{path.rstrip('/').split('/')[-1]}"+ self.records.setdefault(uri, f"Resource imported from {path}")+ return {"status": "completed", "root_uri": uri}++ def add_skill(self, data: Any, **_: Any) -> dict[str, Any]:+ name = data.get("name", "skill") if isinstance(data, dict) else "skill"+ uri = f"viking://user/skills/{name}.md"+ self.records[uri] = str(data)+ return {"status": "completed", "uri": uri, "name": name}++ def get_status(self) -> dict[str, Any]:+ return {"healthy": True, "backend": "in-memory"}++ def is_healthy(self) -> bool:+ return True+++def _message_text(message: dict[str, Any]) -> str:+ chunks: list[str] = []+ for part in message.get("parts") or []:+ if part.get("type") == "text" and part.get("text"):+ chunks.append(str(part["text"]))+ elif part.get("type") == "context" and part.get("abstract"):+ chunks.append(str(part["abstract"]))+ elif part.get("type") == "tool" and part.get("tool_output"):+ chunks.append(str(part["tool_output"]))+ return "\n".join(chunks)diff --git a/integrations/langchain/src/langchain_openviking/tools.py b/integrations/langchain/src/langchain_openviking/tools.pynew file mode 100644index 000000000..9fad578bd--- /dev/null+++ b/integrations/langchain/src/langchain_openviking/tools.py@@ -0,0 +1,878 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""LangChain tool factory for OpenViking primitives."""++from __future__ import annotations++import logging+import re+from pathlib import Path+from typing import Annotated, Any, Iterable, Literal+from urllib.parse import urlparse+from urllib.request import url2pathname++from pydantic import BeforeValidator, Field++try:+ from langchain_core.tools import StructuredTool+except ImportError as exc: # pragma: no cover - exercised by optional import path+ from langchain_openviking.client import missing_dependency++ raise missing_dependency("langchain", "langchain-core") from exc++from langchain_openviking.client import (+ OpenVikingConnection,+ call_openviking,+ compact_json,+ ensure_client,+ item_value,+ iter_result_items,+ stringify,+)++logger = logging.getLogger(__name__)+++def _normalize_read_mode_input(value: Any) -> str:+ return str(value or "read").lower().strip()+++OpenVikingReadMode = Literal["abstract", "overview", "read"]+OpenVikingReadModeInput = Annotated[+ OpenVikingReadMode,+ BeforeValidator(_normalize_read_mode_input),+]+++def create_openviking_tools(+ *,+ client: Any = None,+ url: str | None = None,+ api_key: str | None = None,+ account: str | None = None,+ user: str | None = None,+ user_id: str | None = None,+ actor_peer_id: str | None = None,+ path: str | None = None,+ timeout: float = 60.0,+ extra_headers: dict[str, str] | None = None,+ auto_initialize: bool = True,+ profile: str = "agent",+ peer_id: str | None = None,+ tool_names: Iterable[str] | None = None,+ allow_forget: bool = False,+) -> list[StructuredTool]:+ """Create LangChain tools exposing OpenViking's common agent primitives.++ Tool names intentionally use the ``viking_*`` prefix so models see the same+ conceptual operations that OpenViking users know from plugins and MCP:+ find/search, browse/read, grep, store, add_resource, add_skill, and health.+ """++ cached_client: Any = None++ def get_client() -> Any:+ nonlocal cached_client+ if cached_client is None:+ cached_client = ensure_client(+ OpenVikingConnection(+ client=client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ timeout=timeout,+ extra_headers=extra_headers,+ auto_initialize=auto_initialize,+ )+ )+ return cached_client++ def viking_find(+ query: Annotated[str, Field(description="Natural-language query to match semantically.")],+ target_uri: Annotated[+ str,+ Field(description="Optional OpenViking URI scope to search within."),+ ] = "",+ limit: Annotated[int, Field(description="Maximum number of matches to return.")] = 8,+ min_score: Annotated[+ float | None,+ Field(description="Optional backend relevance threshold."),+ ] = None,+ ) -> str:+ """Run stateless semantic retrieval over OpenViking targets."""++ result = call_openviking(+ get_client(),+ "find",+ query=query,+ target_uri=target_uri,+ limit=limit,+ score_threshold=min_score,+ )+ return _format_retrieval_result(result)++ def viking_search(+ query: Annotated[str, Field(description="Natural-language query to match semantically.")],+ target_uri: Annotated[+ str,+ Field(description="Optional OpenViking URI scope to search within."),+ ] = "",+ session_id: Annotated[+ str | None,+ Field(description="Optional OpenViking session id for session-aware retrieval."),+ ] = None,+ limit: Annotated[int, Field(description="Maximum number of matches to return.")] = 8,+ min_score: Annotated[+ float | None,+ Field(description="Optional backend relevance threshold."),+ ] = None,+ ) -> str:+ """Run session-aware semantic retrieval over OpenViking targets."""++ result = call_openviking(+ get_client(),+ "search",+ query=query,+ target_uri=target_uri,+ session_id=session_id,+ limit=limit,+ score_threshold=min_score,+ )+ return _format_retrieval_result(result)++ def viking_browse(+ uri: Annotated[+ str,+ Field(description="OpenViking namespace or directory URI to list."),+ ] = "viking://",+ recursive: Annotated[+ bool,+ Field(description="Whether to include nested descendants in the listing."),+ ] = False,+ pattern: Annotated[+ str | None,+ Field(description="Optional glob pattern for discovering matching OpenViking URIs."),+ ] = None,+ ) -> str:+ """List child entries under an OpenViking namespace or directory URI.++ Use this to inspect structure and discover file/document URIs. When+ pattern is set, the tool returns glob matches instead of a direct+ directory listing.+ """++ active_client = get_client()+ if pattern:+ result = call_openviking(active_client, "glob", pattern=pattern, uri=uri)+ else:+ result = call_openviking(active_client, "ls", uri=uri, recursive=recursive)+ return stringify(result, max_chars=12_000)++ def viking_read(+ uris: Annotated[+ str | list[str],+ Field(description="One or more file/document OpenViking URIs to read."),+ ],+ max_chars: Annotated[+ int,+ Field(description="Maximum characters to include per URI result."),+ ] = 12_000,+ content_mode: Annotated[+ OpenVikingReadModeInput,+ Field(+ description="Content depth: abstract is shortest, overview is medium, read is full."+ ),+ ] = "read",+ ) -> str:+ """Read file/document OpenViking URIs.++ Directory URIs are not readable; call viking_browse on directories to+ list children, then call viking_read on returned file/document URIs.+ """++ active_client = get_client()+ uri_list = [uris] if isinstance(uris, str) else uris+ mode = str(content_mode or "read").lower().strip()+ payload = []+ for uri in uri_list:+ try:+ content = call_openviking(active_client, mode, uri=uri)+ except Exception as exc:+ if not _is_directory_read_error(exc):+ raise+ payload.append(+ {+ "uri": uri,+ "content_mode": mode,+ "error": "directory_uri_not_readable",+ "message": (+ "This URI is a directory. Use viking_browse on this URI to list "+ "children, then call viking_read on file/document URIs."+ ),+ }+ )+ else:+ payload.append(+ {+ "uri": uri,+ "content_mode": mode,+ "content": stringify(content, max_chars=max_chars),+ }+ )+ return stringify(payload, max_chars=max_chars * max(1, len(uri_list)))++ def viking_grep(+ uri: Annotated[+ str,+ Field(description="File/document OpenViking URI whose content should be searched."),+ ],+ pattern: Annotated[+ str,+ Field(description="Grep-style text or regex pattern to search for."),+ ],+ case_insensitive: Annotated[+ bool,+ Field(description="Whether to match pattern without case sensitivity."),+ ] = False,+ node_limit: Annotated[+ int,+ Field(description="Maximum number of matching content nodes to return."),+ ] = 20,+ ) -> str:+ """Search OpenViking file content with a grep-style pattern."""++ result = call_openviking(+ get_client(),+ "grep",+ uri=uri,+ pattern=pattern,+ case_insensitive=case_insensitive,+ node_limit=node_limit,+ )+ return stringify(result, max_chars=12_000)++ def viking_store(+ messages: Annotated[+ str | list[dict[str, Any]],+ Field(description="Message text or role/content message objects to append."),+ ],+ session_id: Annotated[+ str | None,+ Field(description="OpenViking session id. A new session is created when omitted."),+ ] = None,+ commit: Annotated[+ bool,+ Field(description="Whether to commit the appended session messages immediately."),+ ] = True,+ ) -> str:+ """Append explicit durable memories or conversation messages to an OpenViking session.++ This is a write operation. User-facing hosts should expose it only for+ confirmed "remember/save this" workflows because normal conversation+ capture is usually handled by lifecycle hooks.+ """++ active_client = get_client()+ if not session_id:+ created = call_openviking(active_client, "create_session")+ session_id = created.get("session_id") if isinstance(created, dict) else str(created)+ normalized_messages = _normalize_messages(messages)+ for message in normalized_messages:+ call_openviking(+ active_client,+ "add_message",+ session_id=session_id,+ role=message["role"],+ content=message.get("content"),+ parts=message.get("parts"),+ peer_id=peer_id,+ )+ result: dict[str, Any] = {+ "session_id": session_id,+ "messages_added": len(normalized_messages),+ }+ if commit:+ result["commit"] = call_openviking(+ active_client,+ "commit_session",+ session_id=session_id,+ )+ return compact_json(result)++ def viking_archive_search(+ session_id: Annotated[+ str,+ Field(description="OpenViking session id whose committed archive context to search."),+ ],+ query: Annotated[+ str,+ Field(description="Natural-language query to match against committed session context."),+ ],+ archive_id: Annotated[+ str | None,+ Field(description="Optional specific archive id to search instead of all history."),+ ] = None,+ token_budget: Annotated[+ int,+ Field(description="Maximum session context token budget to inspect when needed."),+ ] = 128_000,+ max_matches: Annotated[+ int,+ Field(description="Maximum number of archive matches to return."),+ ] = 8,+ ) -> str:+ """Search committed OpenViking session archive context."""++ active_client = get_client()+ if archive_id:+ archive = call_openviking(+ active_client,+ "get_session_archive",+ session_id=session_id,+ archive_id=archive_id,+ )+ matches = _search_archive_payload(archive, query, max_matches=max_matches)+ else:+ matches = _grep_session_history(+ active_client,+ session_id=session_id,+ query=query,+ max_matches=max_matches,+ )+ if _match_count(matches) > 0:+ return stringify(matches, max_chars=12_000)+ context = call_openviking(+ active_client,+ "get_session_context",+ session_id=session_id,+ token_budget=token_budget,+ )+ matches = _search_archive_payload(context, query, max_matches=max_matches)+ return stringify(matches or {"matches": [], "count": 0}, max_chars=12_000)++ def viking_archive_expand(+ session_id: Annotated[+ str,+ Field(description="OpenViking session id that owns the archive."),+ ],+ archive_id: Annotated[+ str,+ Field(description="Committed archive id to expand."),+ ],+ max_chars: Annotated[+ int,+ Field(description="Maximum characters to include in the expanded archive result."),+ ] = 20_000,+ ) -> str:+ """Expand one OpenViking session archive by archive ID."""++ archive = call_openviking(+ get_client(),+ "get_session_archive",+ session_id=session_id,+ archive_id=archive_id,+ )+ return stringify(archive, max_chars=max_chars)++ def viking_add_resource(+ path: Annotated[+ str,+ Field(+ description=(+ "Resource source to import, such as a URL, repository, uploaded file, "+ "directory, or client-visible local path."+ )+ ),+ ],+ to: Annotated[+ str | None,+ Field(description="Optional destination OpenViking URI for the imported resource."),+ ] = None,+ parent: Annotated[+ str | None,+ Field(description="Optional parent OpenViking URI under which to place the resource."),+ ] = None,+ reason: Annotated[+ str,+ Field(description="Short reason for importing this resource."),+ ] = "",+ instruction: Annotated[+ str,+ Field(description="Optional indexing or extraction instruction for the resource."),+ ] = "",+ wait: Annotated[+ bool,+ Field(description="Whether to wait for resource ingestion to finish before returning."),+ ] = False,+ timeout: Annotated[+ float | None,+ Field(description="Optional wait timeout in seconds for resource ingestion."),+ ] = None,+ ) -> str:+ """Import an explicit resource into OpenViking.++ This is a resource-management operation for user-approved URLs,+ repositories, uploaded files, or local paths available to the client. It+ is not for ordinary chat facts or ad hoc memory notes.+ """++ 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."+ ),+ }+ )+ raise+ return stringify(result, max_chars=8_000)++ def viking_add_skill(+ data: Annotated[+ dict[str, Any] | str,+ Field(description="Skill definition as a mapping or serialized skill document."),+ ],+ wait: Annotated[+ bool,+ Field(description="Whether to wait for skill registration to finish before returning."),+ ] = False,+ timeout: Annotated[+ float | None,+ Field(description="Optional wait timeout in seconds for skill registration."),+ ] = None,+ ) -> str:+ """Register a reusable OpenViking skill for trusted admin workflows."""++ result = call_openviking(+ get_client(),+ "add_skill",+ data=data,+ wait=wait,+ timeout=timeout,+ )+ return stringify(result, max_chars=8_000)++ def viking_health() -> str:+ """Check OpenViking health/status for diagnostics."""++ active_client = get_client()+ if hasattr(active_client, "get_status"):+ status = call_openviking(active_client, "get_status")+ return stringify(_format_openviking_health(status), max_chars=8_000)+ if hasattr(active_client, "is_healthy"):+ return compact_json(+ _format_openviking_health({"healthy": call_openviking(active_client, "is_healthy")})+ )+ return compact_json(_format_openviking_health({"healthy": True}))++ def viking_forget(+ uri: Annotated[+ str,+ Field(description="OpenViking URI to remove."),+ ],+ recursive: Annotated[+ bool,+ Field(description="Whether to remove descendants recursively."),+ ] = False,+ ) -> str:+ """Remove a URI from OpenViking. Only expose this to trusted agents."""++ call_openviking(get_client(), "rm", uri=uri, recursive=recursive)+ return compact_json({"removed": uri, "recursive": recursive})++ all_tools: dict[str, StructuredTool] = {+ "viking_find": StructuredTool.from_function(viking_find),+ "viking_search": StructuredTool.from_function(viking_search),+ "viking_browse": StructuredTool.from_function(viking_browse),+ "viking_read": StructuredTool.from_function(viking_read),+ "viking_grep": StructuredTool.from_function(viking_grep),+ "viking_archive_search": StructuredTool.from_function(viking_archive_search),+ "viking_archive_expand": StructuredTool.from_function(viking_archive_expand),+ "viking_store": StructuredTool.from_function(viking_store),+ "viking_add_resource": StructuredTool.from_function(viking_add_resource),+ "viking_add_skill": StructuredTool.from_function(viking_add_skill),+ "viking_health": StructuredTool.from_function(viking_health),+ "viking_forget": StructuredTool.from_function(viking_forget),+ }++ if tool_names is None:+ selected = _profile_tool_names(profile, allow_forget=allow_forget)+ else:+ selected = list(tool_names)+ return [all_tools[name] for name in selected if name in all_tools]+++def _profile_tool_names(profile: str, *, allow_forget: bool) -> list[str]:+ retrieval = [+ "viking_find",+ "viking_search",+ "viking_browse",+ "viking_read",+ "viking_grep",+ "viking_archive_search",+ "viking_archive_expand",+ ]+ if profile == "retrieval":+ names = retrieval + ["viking_health"]+ elif profile == "admin":+ names = retrieval + [+ "viking_store",+ "viking_add_resource",+ "viking_add_skill",+ "viking_health",+ "viking_forget",+ ]+ else:+ names = retrieval + [+ "viking_store",+ "viking_add_resource",+ "viking_add_skill",+ "viking_health",+ ]+ if allow_forget and "viking_forget" not in names:+ names.append("viking_forget")+ return names+++def _is_directory_read_error(exc: Exception) -> bool:+ details = getattr(exc, "details", {}) or {}+ return (+ getattr(exc, "code", None) == "INVALID_ARGUMENT"+ and details.get("expected") == "file"+ and details.get("actual") == "directory"+ )+++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 {+ "backend": "OpenViking",+ "healthy": state == "healthy",+ "state": state,+ "note": "OpenViking is the context memory backend; VikingDB is internal vector/index storage.",+ "summary": _safe_status_summary(status),+ }+++def _infer_health_state(status: Any) -> str:+ if isinstance(status, dict):+ for key in ("healthy", "ok"):+ value = status.get(key)+ if isinstance(value, bool):+ return "healthy" if value else "unhealthy"+ state = str(status.get("status") or status.get("state") or "").lower()+ if state in {"ok", "healthy", "ready", "running"}:+ return "healthy"+ if state in {"error", "failed", "unhealthy"}:+ return "unhealthy"+ if state in {"degraded", "initializing", "starting", "pending"}:+ return state+ return "unknown"+++def _safe_status_summary(status: Any) -> dict[str, Any]:+ if not isinstance(status, dict):+ return {"type": type(status).__name__}++ summary: dict[str, Any] = {}+ for key in ("healthy", "ok", "status", "state", "state_detail"):+ if key in status:+ value = _safe_status_value(status[key])+ if value is not None:+ summary[key] = value++ components = status.get("components") or status.get("services")+ if isinstance(components, dict | list | tuple):+ summary["component_count"] = len(components)++ return summary or {"type": "dict"}+++def _safe_status_value(value: Any) -> Any:+ if value is None or isinstance(value, bool | int | float):+ return value+ if isinstance(value, str):+ lowered = value.lower()+ if "://" in lowered or "@" in lowered:+ return None+ return value if len(value) <= 64 else f"{value[:61]}..."+ return None+++def _normalize_messages(messages: str | list[dict[str, Any]]) -> list[dict[str, Any]]:+ if isinstance(messages, str):+ return [{"role": "user", "parts": [{"type": "text", "text": messages}]}]+ normalized = []+ for message in messages:+ role = str(message.get("role") or "user")+ if role not in {"user", "assistant", "system", "tool"}:+ role = "user"+ if message.get("parts") is not None:+ normalized.append(+ {+ "role": "assistant" if role in {"system", "tool"} else role,+ "parts": list(message.get("parts") or []),+ }+ )+ continue+ content = str(message.get("content", ""))+ if role == "tool":+ normalized.append(+ {+ "role": "assistant",+ "parts": [+ {+ "type": "tool",+ "tool_id": str(message.get("tool_call_id") or message.get("id") or ""),+ "tool_name": str(message.get("name") or ""),+ "tool_output": content,+ "tool_status": "completed",+ }+ ],+ }+ )+ elif role == "system":+ normalized.append({"role": "assistant", "parts": [{"type": "text", "text": content}]})+ else:+ normalized.append({"role": role, "parts": [{"type": "text", "text": content}]})+ return normalized+++def _format_retrieval_result(result: Any) -> str:+ lines: list[str] = []+ for index, (context_type, item) in enumerate(iter_result_items(result), start=1):+ uri = item_value(item, "uri", "")+ score = item_value(item, "score")+ abstract = item_value(item, "abstract") or item_value(item, "overview") or ""+ score_text = "" if score is None else f" score={score}"+ lines.append(f"[{index}] {context_type}{score_text} {uri}\n{abstract}".strip())+ if not lines:+ return "No OpenViking contexts matched."+ return "\n\n".join(lines)+++def _search_archive_payload(+ payload: dict[str, Any],+ query: str,+ *,+ max_matches: int,+) -> dict[str, Any]:+ tokens = [token for token in re.findall(r"[a-z0-9_]+", query.lower()) if len(token) > 1]+ sections = _archive_sections(payload)+ matches: list[dict[str, str]] = []+ for label, text in sections:+ haystack = text.lower()+ if tokens and not all(token in haystack for token in tokens):+ continue+ matches.append({"section": label, "snippet": _snippet(text, tokens)})+ if len(matches) >= max_matches:+ break+ return {"matches": matches, "count": len(matches)}+++def _grep_session_history(+ client: Any,+ *,+ session_id: str,+ query: str,+ max_matches: int,+) -> dict[str, Any]:+ session = call_openviking(client, "get_session", session_id=session_id, auto_create=False)+ session_uri = item_value(session, "uri", f"viking://user/sessions/{session_id}")+ history_uri = f"{str(session_uri).rstrip('/')}/history"+ tokens = _archive_query_tokens(query)+ try:+ result = call_openviking(+ client,+ "grep",+ uri=history_uri,+ pattern=_archive_grep_pattern(query),+ case_insensitive=True,+ node_limit=None,+ )+ except Exception:+ logger.debug("OpenViking archive history grep failed", exc_info=True)+ return {"matches": [], "count": 0, "source": history_uri}+ return _filter_grep_result(result, tokens=tokens, max_matches=max_matches, source=history_uri)+++def _match_count(result: dict[str, Any] | None) -> int:+ if not result:+ return 0+ for key in ("count", "match_count"):+ value = result.get(key)+ if value is not None:+ return int(value or 0)+ matches = result.get("matches")+ return len(matches) if isinstance(matches, list) else 0+++def _archive_grep_pattern(query: str) -> str:+ tokens = _archive_query_tokens(query)+ if not tokens:+ return re.escape(query) or ".*"+ return re.escape(tokens[0])+++def _archive_query_tokens(query: str) -> list[str]:+ return [token for token in re.findall(r"[a-z0-9_]+", query.lower()) if len(token) > 1]+++def _filter_grep_result(+ result: Any,+ *,+ tokens: list[str],+ max_matches: int,+ source: str,+) -> dict[str, Any]:+ raw_matches = result.get("matches", []) if isinstance(result, dict) else result+ matches: list[Any] = []+ for match in raw_matches if isinstance(raw_matches, list) else []:+ text = _grep_match_text(match).lower()+ if tokens and not all(token in text for token in tokens):+ continue+ matches.append(match)+ if len(matches) >= max_matches:+ break++ filtered: dict[str, Any] = {"source": source}+ if isinstance(result, dict):+ filtered.update({key: value for key, value in result.items() if key != "matches"})+ filtered["matches"] = matches+ filtered["count"] = len(matches)+ filtered["match_count"] = len(matches)+ return filtered+++def _grep_match_text(match: Any) -> str:+ if isinstance(match, dict):+ return str(+ match.get("content")+ or match.get("line")+ or match.get("text")+ or match.get("snippet")+ or ""+ )+ return str(match)+++def _archive_sections(payload: dict[str, Any]) -> list[tuple[str, str]]:+ sections: list[tuple[str, str]] = []+ if payload.get("overview"):+ sections.append(+ (f"archive:{payload.get('archive_id', 'archive')}:overview", payload["overview"])+ )+ if payload.get("abstract"):+ sections.append(+ (f"archive:{payload.get('archive_id', 'archive')}:abstract", payload["abstract"])+ )+ if payload.get("latest_archive_overview"):+ sections.append(("latest_archive_overview", payload["latest_archive_overview"]))+ for archive in payload.get("pre_archive_abstracts") or []:+ sections.append(+ (+ f"archive:{archive.get('archive_id', 'archive')}:abstract",+ str(archive.get("abstract") or ""),+ )+ )+ for index, message in enumerate(payload.get("messages") or [], start=1):+ text_parts: list[str] = []+ for part in message.get("parts") or []:+ text_parts.extend(+ str(part.get(key) or "")+ for key in ("text", "abstract", "tool_output")+ if part.get(key)+ )+ if text_parts:+ sections.append((f"message:{index}:{message.get('role', '')}", "\n".join(text_parts)))+ return sections+++def _snippet(text: str, tokens: list[str], *, radius: int = 240) -> str:+ if not text:+ return ""+ lower = text.lower()+ positions = [lower.find(token) for token in tokens if token and lower.find(token) >= 0]+ start = max(0, min(positions) - radius) if positions else 0+ end = min(len(text), start + radius * 2)+ prefix = "..." if start else ""+ suffix = "..." if end < len(text) else ""+ return prefix + text[start:end] + suffixdiff --git a/integrations/langchain/tests/installed_base_smoke.py b/integrations/langchain/tests/installed_base_smoke.pynew file mode 100644index 000000000..0c28391a1--- /dev/null+++ b/integrations/langchain/tests/installed_base_smoke.py@@ -0,0 +1,45 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Exercise the installed base distribution without LangGraph dependencies."""++from __future__ import annotations++import sys++import langchain_openviking+from langchain_openviking import InMemoryOpenVikingClient, OpenVikingRetriever+++def main() -> None:+ """Verify base exports, retrieval, and the optional-dependency error."""+ assert "OpenVikingContextMiddleware" not in langchain_openviking.__all__++ namespace: dict[str, object] = {}+ exec("from langchain_openviking import *", namespace)+ assert "OpenVikingRetriever" in namespace+ assert "OpenVikingContextMiddleware" not in namespace++ client = InMemoryOpenVikingClient(+ {"viking://resources/runbooks/deploy.md": "Deploy production with ArgoCD."}+ )+ documents = OpenVikingRetriever(client=client, target_uri="viking://resources").invoke(+ "How do we deploy production?"+ )+ assert documents+ assert "ArgoCD" in documents[0].page_content++ try:+ from langchain_openviking import OpenVikingContextMiddleware # noqa: F401+ except ImportError as exc:+ assert "langchain-openviking[langgraph]" in str(exc)+ else:+ raise AssertionError("middleware import succeeded without the langgraph extra")++ assert "openviking" not in sys.modules+ assert not any(+ name == "openviking_cli" or name.startswith("openviking_cli.") for name in sys.modules+ )+++if __name__ == "__main__":+ main()diff --git a/integrations/langchain/tests/installed_smoke.py b/integrations/langchain/tests/installed_smoke.pynew file mode 100644index 000000000..40421644f--- /dev/null+++ b/integrations/langchain/tests/installed_smoke.py@@ -0,0 +1,59 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Exercise the built wheel without the full OpenViking package on ``sys.path``."""++from __future__ import annotations++import sys++from langchain.agents import create_agent+from langchain_core.language_models.fake_chat_models import FakeListChatModel+from langchain_core.messages import HumanMessage++from langchain_openviking import (+ InMemoryOpenVikingClient,+ OpenVikingContextMiddleware,+ OpenVikingRetriever,+)+++def main() -> None:+ """Run one retrieval and one agent turn through the installed distribution."""+ client = InMemoryOpenVikingClient(+ {"viking://resources/runbooks/deploy.md": "Deploy production with ArgoCD."}+ )+ retriever = OpenVikingRetriever(client=client, target_uri="viking://resources")++ documents = retriever.invoke("How do we deploy production?")++ assert documents+ assert "ArgoCD" in documents[0].page_content++ middleware = OpenVikingContextMiddleware(+ client=client,+ session_id_resolver=lambda _state, _runtime: "installed-wheel-smoke",+ )+ agent = create_agent(+ model=FakeListChatModel(responses=["Stored by the installed wheel."]),+ tools=[],+ middleware=[middleware],+ )++ result = agent.invoke(+ {"messages": [HumanMessage(content="Remember this installed-wheel turn.")]},+ config={"configurable": {"thread_id": "installed-wheel-smoke"}},+ )++ assert result["messages"][-1].content == "Stored by the installed wheel."+ assert [message["role"] for message in client.sessions["installed-wheel-smoke"]] == [+ "user",+ "assistant",+ ]+ assert "openviking" not in sys.modules+ assert not any(+ name == "openviking_cli" or name.startswith("openviking_cli.") for name in sys.modules+ )+++if __name__ == "__main__":+ main()diff --git a/openviking/integrations/langchain/__init__.py b/openviking/integrations/langchain/__init__.pyindex dde70bfa9..31a2587ea 100644--- a/openviking/integrations/langchain/__init__.py+++ b/openviking/integrations/langchain/__init__.py@@ -1,20 +1,13 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""LangChain and LangGraph integrations for OpenViking.--The objects in this package depend on optional framework packages. Importing-``openviking`` itself does not install or import LangChain/LangGraph.-"""+"""Compatibility imports for the standalone ``langchain-openviking`` package."""from __future__ import annotations+from importlib import import_modulefrom typing import Any-from openviking.integrations.langchain.actor_peer import (- has_request_actor_peer_support,-)--__all__ = [+_LEGACY_EXPORTS = ["InMemoryOpenVikingClient","OpenVikingChatMessageHistory","OpenVikingCancellationProgress",@@ -34,69 +27,49 @@ __all__ = []-def __getattr__(name: str) -> Any:- if name == "OpenVikingRetriever":- from openviking.integrations.langchain.retrievers import OpenVikingRetriever+def _missing_standalone_error() -> ImportError:+ return ImportError(+ "The legacy OpenViking LangChain integration requires the standalone "+ "langchain-openviking package. Install it with "+ '`pip install "openviking[langchain]"` or `pip install langchain-openviking` '+ '(use the corresponding "langgraph" extra for LangGraph support).'+ )- return OpenVikingRetriever- if name == "create_openviking_tools":- from openviking.integrations.langchain.tools import create_openviking_tools- return create_openviking_tools- if name == "OpenVikingStore":- from openviking.integrations.langchain.store import OpenVikingStore+def _forward_legacy_module(module_name: str, namespace: dict[str, Any]) -> None:+ """Populate a legacy submodule with the canonical package's public names."""- return OpenVikingStore- if name == "OpenVikingChatMessageHistory":- from openviking.integrations.langchain.history import OpenVikingChatMessageHistory+ try:+ canonical = import_module(f"langchain_openviking.{module_name}")+ except ModuleNotFoundError as exc:+ if exc.name != "langchain_openviking":+ raise+ raise _missing_standalone_error() from exc- return OpenVikingChatMessageHistory- if name == "OpenVikingSessionContextAssembler":- from openviking.integrations.langchain.context import OpenVikingSessionContextAssembler+ public_names = getattr(canonical, "__all__", None)+ if public_names is None:+ public_names = (name for name in vars(canonical) if not name.startswith("_"))+ namespace.update({name: getattr(canonical, name) for name in public_names})- return OpenVikingSessionContextAssembler- if name == "OpenVikingContextRunnable":- from openviking.integrations.langchain.context import OpenVikingContextRunnable- return OpenVikingContextRunnable- if name == "OpenVikingSessionRecorder":- from openviking.integrations.langchain.recording import OpenVikingSessionRecorder+try:+ from langchain_openviking import __all__, __getattr__, has_request_actor_peer_support+except ModuleNotFoundError as exc:+ if exc.name != "langchain_openviking":+ raise- return OpenVikingSessionRecorder- if name == "OpenVikingPartialWriteError":- from openviking.integrations.langchain.recording import OpenVikingPartialWriteError+ __all__ = _LEGACY_EXPORTS- return OpenVikingPartialWriteError- if name == "OpenVikingRecordResult":- from openviking.integrations.langchain.recording import OpenVikingRecordResult-- return OpenVikingRecordResult- if name == "OpenVikingCancellationProgress":- from openviking.integrations.langchain.recording import (- OpenVikingCancellationProgress,- )+ def has_request_actor_peer_support() -> bool:+ """Return whether the installed SDK supports request-scoped actor peers."""- return OpenVikingCancellationProgress- if name == "get_openviking_cancellation_progress":- from openviking.integrations.langchain.recording import (- get_openviking_cancellation_progress,+ openviking_sdk = import_module("openviking_sdk")+ return (+ getattr(openviking_sdk, "get_actor_peer_id", None) is not None+ and getattr(openviking_sdk, "use_actor_peer", None) is not None)- return get_openviking_cancellation_progress- if name == "OpenVikingCommitPolicy":- from openviking.integrations.langchain.client import OpenVikingCommitPolicy-- return OpenVikingCommitPolicy- if name == "with_openviking_context":- from openviking.integrations.langchain.context import with_openviking_context-- return with_openviking_context- if name == "OpenVikingContextMiddleware":- from openviking.integrations.langchain.middleware import OpenVikingContextMiddleware-- return OpenVikingContextMiddleware- if name == "InMemoryOpenVikingClient":- from openviking.integrations.langchain.testing import InMemoryOpenVikingClient-- return InMemoryOpenVikingClient- raise AttributeError(name)+ def __getattr__(name: str) -> Any:+ if name in __all__:+ raise _missing_standalone_error()+ raise AttributeError(name)diff --git a/openviking/integrations/langchain/actor_peer.py b/openviking/integrations/langchain/actor_peer.pyindex dd6bdd81f..2c263911e 100644--- a/openviking/integrations/langchain/actor_peer.py+++ b/openviking/integrations/langchain/actor_peer.py@@ -1,49 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Compatibility bridge for request-scoped actor peers in openviking-sdk."""+"""Compatibility wrapper for :mod:`langchain_openviking.actor_peer`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-from contextlib import AbstractContextManager-from typing import Callable, cast--from openviking._sdk_import import import_openviking_sdk--_openviking_sdk = import_openviking_sdk()-_actor_peer_getter = getattr(_openviking_sdk, "get_actor_peer_id", None)-_actor_peer_scope = getattr(_openviking_sdk, "use_actor_peer", None)---def has_request_actor_peer_support() -> bool:- """Return whether the installed SDK supports request-scoped actor peers."""-- return _actor_peer_getter is not None and _actor_peer_scope is not None---def require_request_actor_peer_support() -> None:- """Raise an actionable error when request-scoped actor peers are unavailable."""-- if not has_request_actor_peer_support():- raise ImportError(- "Runtime actor peers require an openviking-sdk release with "- "request-scoped actor-peer support. Upgrade openviking-sdk and retry."- )---def get_actor_peer_id() -> str | None:- """Return the active SDK actor peer, tolerating older SDKs when unused."""-- if _actor_peer_getter is None:- return None- return cast(Callable[[], str | None], _actor_peer_getter)()---def use_actor_peer(actor_peer_id: str | None) -> AbstractContextManager[None]:- """Apply an SDK actor-peer scope after confirming SDK support."""-- require_request_actor_peer_support()- scope_factory = cast(- Callable[[str | None], AbstractContextManager[None]],- _actor_peer_scope,- )- return scope_factory(actor_peer_id)+_forward_legacy_module("actor_peer", globals())diff --git a/openviking/integrations/langchain/client.py b/openviking/integrations/langchain/client.pyindex 35be0442a..8f21bfc81 100644--- a/openviking/integrations/langchain/client.py+++ b/openviking/integrations/langchain/client.py@@ -1,860 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Shared helpers for LangChain/LangGraph integration adapters."""+"""Compatibility wrapper for :mod:`langchain_openviking.client`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-import asyncio-import copy-import inspect-import json-import logging-import threading-from dataclasses import dataclass-from typing import Any, Callable, Iterable, Literal--from openviking.utils.async_client_cache import LoopScopedAsyncClientCache--logger = logging.getLogger(__name__)--_RETRYABLE_READ_METHODS = {- "abstract",- "archive_expand",- "archive_search",- "find",- "get_session",- "get_session_archive",- "get_session_context",- "get_status",- "glob",- "health",- "is_healthy",- "ls",- "overview",- "read",- "relations",- "search",- "session_exists",- "stat",-}--_RECOVERABLE_OPENVIKING_CODES = {"DEADLINE_EXCEEDED", "UNAVAILABLE"}-_RECOVERABLE_RUNTIME_MESSAGE_FRAGMENTS = (- "event loop is closed",- "attached to a different loop",- "bound to a different event loop",-)-_ASYNC_INITIALIZATION_LOCKS_ATTR = "_openviking_integration_initialize_locks"---class OptionalDependencyError(ImportError):- """Raised when an optional framework dependency is not installed."""---def missing_dependency(extra: str, package: str | None = None) -> OptionalDependencyError:- package = package or extra- return OptionalDependencyError(- f"{package} is required for this OpenViking integration. "- f'Install it with `pip install "openviking[{extra}]"`.'- )---@dataclass(slots=True)-class OpenVikingConnection:- """Connection settings for lazily creating an OpenViking client."""-- client: Any = None- url: str | None = None- api_key: str | None = None- account: str | None = None- user: str | None = None- user_id: str | None = None- actor_peer_id: str | None = None- path: str | None = None- timeout: float = 60.0- extra_headers: dict[str, str] | None = None- auto_initialize: bool = True- async_client: Any = None-- def __deepcopy__(self, memo: dict[int, Any]) -> OpenVikingConnection:- """Copy configuration while preserving caller-owned client identities."""-- copied = type(self)(- client=self.client,- async_client=self.async_client,- url=self.url,- api_key=self.api_key,- account=self.account,- user=self.user,- user_id=self.user_id,- actor_peer_id=self.actor_peer_id,- path=self.path,- timeout=self.timeout,- extra_headers=copy.deepcopy(self.extra_headers, memo),- auto_initialize=self.auto_initialize,- )- memo[id(self)] = copied- return copied---@dataclass(slots=True)-class OpenVikingCommitPolicy:- """Commit behavior for OpenViking-backed agent sessions."""-- mode: Literal["never", "always", "pending_tokens"] = "never"- pending_token_threshold: int = 8_000---class OpenVikingClientHandle:- """Lazy OpenViking client wrapper with one-shot recovery for safe reads."""-- def __init__(self, connection: OpenVikingConnection):- self._connection = connection- self._client: Any = None- self._client_lock = threading.Lock()-- @property- def supports_request_actor_peer(self) -> bool:- """Return whether this handle supports request-scoped actor peers."""-- return _uses_http_client(self._connection)-- @property- def _initialized(self) -> bool:- client = self._client- return bool(client is not None and getattr(client, "_initialized", False))-- def close(self) -> None:- self.reset()-- def reset(self) -> None:- with self._client_lock:- client = self._client- self._client = None- self._close_client(client)-- def _reset_if_current(self, client: Any) -> None:- with self._client_lock:- if self._client is not client:- return- self._client = None- self._close_client(client)-- @staticmethod- def _close_client(client: Any) -> None:- if client is None:- return- close = getattr(client, "close", None)- if not callable(close):- return- try:- close()- except Exception:- logger.debug("OpenViking client close during recovery failed", exc_info=True)-- def get(self) -> Any:- with self._client_lock:- if self._client is None:- self._client = _create_client_from_connection(self._connection)- return self._client-- def _openviking_call(self, method_name: str, /, **kwargs: Any) -> Any:- return self._call_with_recovery(method_name, **kwargs)-- def _call_with_recovery(self, method_name: str, /, *args: Any, **kwargs: Any) -> Any:- client = self.get()- try:- return _call_client_method(client, method_name, *args, **kwargs)- except Exception as exc:- if not _is_recoverable_client_error(exc):- raise- self._reset_if_current(client)- if not _should_retry_method(method_name):- raise- retry_client = self.get()- try:- return _call_client_method(retry_client, method_name, *args, **kwargs)- except Exception as retry_exc:- if _is_recoverable_client_error(retry_exc):- self._reset_if_current(retry_client)- raise-- def __copy__(self) -> OpenVikingClientHandle:- return self-- def __deepcopy__(self, memo: dict[int, Any]) -> OpenVikingClientHandle:- copied = type(self)(copy.deepcopy(self._connection, memo))- memo[id(self)] = copied- return copied-- def __getattr__(self, name: str) -> Any:- attr = getattr(self.get(), name)- if not callable(attr):- return attr-- def recovered_method(*args: Any, **kwargs: Any) -> Any:- return self._call_with_recovery(name, *args, **kwargs)-- return recovered_method---class OpenVikingAsyncClientHandle:- """Lazy, loop-local async client wrapper with one-shot recovery for safe reads.-- Method calls through the handle are recovery-safe. Direct client attribute- access is best-effort and may be unavailable while recovery replaces the- underlying client.- """-- def __init__(self, connection: OpenVikingConnection):- self._connection = connection- self._client: Any = None- self._client_lock = asyncio.Lock()- try:- self._loop: asyncio.AbstractEventLoop | None = asyncio.get_running_loop()- except RuntimeError:- self._loop = None-- @property- def supports_request_actor_peer(self) -> bool:- """Return whether this handle supports request-scoped actor peers."""-- return _uses_http_client(self._connection)-- @property- def _initialized(self) -> bool:- client = self._client- return bool(client is not None and _async_client_is_initialized(client))-- async def initialize(self) -> None:- """Initialize the underlying client once."""-- await self.get()-- async def close(self) -> None:- owner_loop = self._loop- current_loop = asyncio.get_running_loop()- if owner_loop is None or owner_loop is current_loop:- await self.reset()- return- if owner_loop.is_running():- reset = self.reset()- try:- future = asyncio.run_coroutine_threadsafe(reset, owner_loop)- except RuntimeError:- reset.close()- else:- await asyncio.wrap_future(future)- return- await self._reset_without_lock()-- async def reset(self) -> None:- async with self._client_lock:- client = self._client- self._client = None- await self._close_client(client)-- async def _reset_if_current(self, client: Any) -> None:- """Reset only when ``client`` is still the active snapshot."""-- async with self._client_lock:- if self._client is not client:- return- self._client = None- await self._close_client(client)-- async def _reset_without_lock(self) -> None:- """Detach a client after its originating loop has stopped."""-- client = self._client- self._client = None- await self._close_client(client)-- async def _close_client(self, client: Any) -> None:- if client is None:- return- try:- await aclose_openviking_client(client)- except Exception:- logger.debug("OpenViking async client close during recovery failed", exc_info=True)-- async def get(self) -> Any:- """Return the current client snapshot, initializing it when necessary.-- Read raw properties immediately and do not retain this client: a later- recovery may replace and close it.- """-- current_loop = asyncio.get_running_loop()- if self._loop is None:- self._loop = current_loop- elif self._loop is not current_loop:- raise RuntimeError(- "OpenVikingAsyncClientHandle is loop-local and cannot be reused "- "from another event loop"- )- if self._client is None:- async with self._client_lock:- if self._client is None:- self._client = await _create_async_client_from_connection(self._connection)- return self._client-- async def _openviking_acall(self, method_name: str, /, **kwargs: Any) -> Any:- return await self._call_with_recovery(method_name, **kwargs)-- async def _call_with_recovery(- self,- method_name: str,- /,- *args: Any,- **kwargs: Any,- ) -> Any:- client = await self.get()- try:- return await _acall_client_method(- client,- method_name,- *args,- **kwargs,- )- except Exception as exc:- if not _is_recoverable_client_error(exc):- raise- await self._reset_if_current(client)- if not _should_retry_method(method_name):- raise- retry_client = await self.get()- try:- return await _acall_client_method(- retry_client,- method_name,- *args,- **kwargs,- )- except Exception as retry_exc:- if _is_recoverable_client_error(retry_exc):- await self._reset_if_current(retry_client)- raise-- def __copy__(self) -> OpenVikingAsyncClientHandle:- return self-- def __deepcopy__(self, memo: dict[int, Any]) -> OpenVikingAsyncClientHandle:- copied = type(self)(copy.deepcopy(self._connection, memo))- memo[id(self)] = copied- return copied-- def __getattr__(self, name: str) -> Any:- if name.startswith("__") and name.endswith("__"):- raise AttributeError(name)- client = self._client- if client is not None:- attr = getattr(client, name)- if not callable(attr):- return attr-- async def recovered_method(*args: Any, **kwargs: Any) -> Any:- return await self._call_with_recovery(name, *args, **kwargs)-- return recovered_method---def ensure_client(connection: OpenVikingConnection) -> Any:- """Return an initialized OpenViking client from explicit or connection settings."""-- client = connection.client- if client is None:- if connection.url or connection.path is None:- handle = OpenVikingClientHandle(connection)- if connection.auto_initialize:- handle.get()- return handle- return _create_client_from_connection(connection)- if connection.auto_initialize and hasattr(client, "initialize"):- if not getattr(client, "_initialized", False):- client.initialize()- return client---async def ensure_async_client(- connection: OpenVikingConnection,- *,- client_cache: LoopScopedAsyncClientCache | None = None,- embedded_client_factory: Callable[[], Any] | None = None,-) -> Any:- """Return a client suitable for non-blocking OpenViking calls.-- An explicitly supplied async client is preferred. Existing synchronous- clients remain supported and are dispatched through a worker thread by- :func:`acall_openviking`. Internally created HTTP handles can be scoped to- the running loop with ``client_cache``. Embedded ``path=`` connections- intentionally use the synchronous client so their stateful async internals- remain on OpenViking's shared background loop.- """-- client = connection.async_client- if client is None and connection.client is not None:- client = connection.client- if client is None:- if _uses_http_client(connection):- if client_cache is None:- handle = OpenVikingAsyncClientHandle(connection)- else:- handle = client_cache.get(lambda: OpenVikingAsyncClientHandle(connection))- if connection.auto_initialize:- await handle.get()- return handle- if embedded_client_factory is not None:- if client_cache is not None:- # The thread hop is load-bearing: without a running event loop,- # the embedded singleton occupies the cache's shared fallback slot.- return await asyncio.to_thread(- client_cache.get,- embedded_client_factory,- )- return await asyncio.to_thread(embedded_client_factory)- return await asyncio.to_thread(_create_client_from_connection, connection)- if connection.auto_initialize and hasattr(client, "initialize"):- await _ainitialize_client(client)- return client---def is_not_found_error(exc: BaseException) -> bool:- """True for OpenViking NOT_FOUND across cli/sdk exception classes."""-- if isinstance(exc, FileNotFoundError):- return True- return str(getattr(exc, "code", "") or "").upper() == "NOT_FOUND"---def apply_commit_policy(- client: Any,- session_id: str,- policy: OpenVikingCommitPolicy | None,- *,- persisted_pending_tokens: Any = None,-) -> dict[str, Any] | None:- """Apply the configured session commit policy after message persistence.-- ``persisted_pending_tokens`` is the post-write value returned by- ``add_message`` or ``batch_add_messages``. When an older client does not- return it, the pending-token policy falls back to the legacy session lookup.- Committing remains a separate operation from message persistence.- """-- if policy is None or policy.mode == "never":- return None- if policy.mode == "always":- return call_openviking(- client,- "commit_session",- session_id=session_id,- )- if policy.mode != "pending_tokens":- raise ValueError(f"Unsupported OpenViking commit policy: {policy.mode}")-- pending_tokens: int | None = None- if persisted_pending_tokens is not None:- try:- pending_tokens = int(persisted_pending_tokens or 0)- except (TypeError, ValueError):- logger.debug(- "Ignoring invalid persisted pending-token value and falling back "- "to session lookup: %r",- persisted_pending_tokens,- )-- if pending_tokens is None:- try:- session = call_openviking(- client, "get_session", session_id=session_id, auto_create=False- )- except Exception:- logger.debug(- "Skipping OpenViking pending-token commit because session lookup failed",- exc_info=True,- )- return None- pending_tokens = int(item_value(session, "pending_tokens", 0) or 0)- if pending_tokens < policy.pending_token_threshold:- return None- return call_openviking(- client,- "commit_session",- session_id=session_id,- )---async def aapply_commit_policy(- client: Any,- session_id: str,- policy: OpenVikingCommitPolicy | None,- *,- persisted_pending_tokens: Any = None,-) -> dict[str, Any] | None:- """Apply the configured session commit policy without blocking the event loop."""-- if policy is None or policy.mode == "never":- return None- if policy.mode == "always":- return await acall_openviking(- client,- "commit_session",- session_id=session_id,- )- if policy.mode != "pending_tokens":- raise ValueError(f"Unsupported OpenViking commit policy: {policy.mode}")-- pending_tokens: int | None = None- if persisted_pending_tokens is not None:- try:- pending_tokens = int(persisted_pending_tokens or 0)- except (TypeError, ValueError):- logger.debug(- "Ignoring invalid persisted pending-token value and falling back "- "to session lookup: %r",- persisted_pending_tokens,- )-- if pending_tokens is None:- try:- session = await acall_openviking(- client,- "get_session",- session_id=session_id,- auto_create=False,- )- except Exception:- logger.debug(- "Skipping OpenViking pending-token commit because session lookup failed",- exc_info=True,- )- return None- pending_tokens = int(item_value(session, "pending_tokens", 0) or 0)- if pending_tokens < policy.pending_token_threshold:- return None- return await acall_openviking(- client,- "commit_session",- session_id=session_id,- )---def call_openviking(client: Any, method_name: str, /, **kwargs: Any) -> Any:- """Call a client method, filtering kwargs unsupported by local/HTTP variants."""-- openviking_call = getattr(client, "_openviking_call", None)- if callable(openviking_call):- return openviking_call(method_name, **kwargs)- return _call_client_method(client, method_name, **kwargs)---async def acall_openviking(client: Any, method_name: str, /, **kwargs: Any) -> Any:- """Call an async or sync client method without blocking the event loop."""-- openviking_call = getattr(client, "_openviking_acall", None)- if callable(openviking_call):- return await openviking_call(method_name, **kwargs)- return await _acall_client_method(client, method_name, **kwargs)---def _create_client_from_connection(connection: OpenVikingConnection) -> Any:- client: Any- if connection.url or connection.path is None:- from openviking.client import SyncHTTPClient-- client = SyncHTTPClient(- url=connection.url,- api_key=connection.api_key,- account=connection.account,- user=connection.user,- user_id=connection.user_id,- actor_peer_id=connection.actor_peer_id,- timeout=connection.timeout,- extra_headers=connection.extra_headers,- )- else:- from openviking.sync_client import SyncOpenViking-- client = SyncOpenViking(path=connection.path, actor_peer_id=connection.actor_peer_id)-- if connection.auto_initialize and hasattr(client, "initialize"):- if not getattr(client, "_initialized", False):- client.initialize()- return client---async def _create_async_client_from_connection(connection: OpenVikingConnection) -> Any:- if not _uses_http_client(connection):- raise ValueError("Native async clients are created automatically only for HTTP connections")-- from openviking.client import AsyncHTTPClient-- client: Any = AsyncHTTPClient(- url=connection.url,- api_key=connection.api_key,- account=connection.account,- user=connection.user,- user_id=connection.user_id,- actor_peer_id=connection.actor_peer_id,- timeout=connection.timeout,- extra_headers=connection.extra_headers,- )-- try:- if connection.auto_initialize and hasattr(client, "initialize"):- await _ainitialize_client(client)- except BaseException:- try:- await aclose_openviking_client(client)- except Exception:- logger.debug(- "OpenViking async client close after initialization failure failed",- exc_info=True,- )- raise- return client---async def aclose_openviking_client(client: Any) -> None:- """Close an async or sync OpenViking client without blocking the event loop."""-- close = getattr(client, "close", None)- if not callable(close):- return- if inspect.iscoroutinefunction(close):- await close()- return- result = await asyncio.to_thread(close)- if inspect.isawaitable(result):- await result---async def aclose_openviking_clients(*clients: Any) -> None:- """Close every distinct client and re-raise the first cleanup failure."""-- seen: set[int] = set()- first_error: BaseException | None = None- for client in clients:- if client is None or id(client) in seen:- continue- seen.add(id(client))- try:- await aclose_openviking_client(client)- except BaseException as exc:- if first_error is None:- first_error = exc- if first_error is not None:- raise first_error---def _call_client_method(- client: Any,- method_name: str,- /,- *args: Any,- **kwargs: Any,-) -> Any:- method = getattr(client, method_name)- return method(*args, **_filter_client_kwargs(method, kwargs))---async def _acall_client_method(- client: Any,- method_name: str,- /,- *args: Any,- **kwargs: Any,-) -> Any:- method = getattr(client, method_name)- filtered_kwargs = _filter_client_kwargs(method, kwargs)- if inspect.iscoroutinefunction(method):- return await method(*args, **filtered_kwargs)- result = await asyncio.to_thread(method, *args, **filtered_kwargs)- if inspect.isawaitable(result):- return await result- return result---async def _ainitialize_client(client: Any) -> None:- if _async_client_is_initialized(client):- return- lock = _async_client_initialization_lock(client)- async with lock:- if _async_client_is_initialized(client):- return- await _acall_client_method(client, "initialize")- try:- client._openviking_integration_initialized = True- except Exception:- pass---def _async_client_initialization_lock(client: Any) -> asyncio.Lock:- try:- locks = inspect.getattr_static(client, _ASYNC_INITIALIZATION_LOCKS_ATTR)- except AttributeError:- locks = LoopScopedAsyncClientCache()- try:- setattr(client, _ASYNC_INITIALIZATION_LOCKS_ATTR, locks)- except Exception:- return asyncio.Lock()- if not isinstance(locks, LoopScopedAsyncClientCache):- locks = LoopScopedAsyncClientCache()- try:- setattr(client, _ASYNC_INITIALIZATION_LOCKS_ATTR, locks)- except Exception:- return asyncio.Lock()- return locks.get(asyncio.Lock)---def _uses_http_client(connection: OpenVikingConnection) -> bool:- """Return whether connection settings select the HTTP transport."""-- return bool(connection.url) or connection.path is None---def _async_client_is_initialized(client: Any) -> bool:- for name in ("_initialized", "_http"):- try:- inspect.getattr_static(client, name)- except AttributeError:- continue- value = getattr(client, name, None)- if name == "_http":- return value is not None- return bool(value)- try:- inspect.getattr_static(client, "_openviking_integration_initialized")- except AttributeError:- return False- return bool(getattr(client, "_openviking_integration_initialized", False))---def _filter_client_kwargs(method: Any, kwargs: dict[str, Any]) -> dict[str, Any]:- """Drop ``None`` and arguments unsupported by a concrete client variant."""-- try:- signature = inspect.signature(method)- except (TypeError, ValueError):- return {key: value for key, value in kwargs.items() if value is not None}-- accepts_kwargs = any(- parameter.kind == inspect.Parameter.VAR_KEYWORD- for parameter in signature.parameters.values()- )- if accepts_kwargs:- return {key: value for key, value in kwargs.items() if value is not None}- return {- key: value- for key, value in kwargs.items()- if value is not None and key in signature.parameters- }---def _should_retry_method(method_name: str) -> bool:- return method_name in _RETRYABLE_READ_METHODS---def _is_recoverable_client_error(exc: BaseException) -> bool:- code = getattr(exc, "code", None)- if isinstance(code, str) and code.upper() in _RECOVERABLE_OPENVIKING_CODES:- return True- if isinstance(exc, (ConnectionError, TimeoutError, OSError)):- return True- if isinstance(exc, RuntimeError):- message = str(exc).lower()- return any(fragment in message for fragment in _RECOVERABLE_RUNTIME_MESSAGE_FRAGMENTS)- try:- import httpx- except Exception: # pragma: no cover - httpx is available in HTTP installs- return False- return isinstance(exc, (httpx.TimeoutException, httpx.TransportError))---def result_groups(result: Any) -> list[tuple[str, list[Any]]]:- """Normalize OpenViking retrieval results into named context groups."""-- if result is None:- return []- if isinstance(result, dict):- return [- ("memory", list(result.get("memories") or [])),- ("resource", list(result.get("resources") or [])),- ("skill", list(result.get("skills") or [])),- ]- return [- ("memory", list(getattr(result, "memories", []) or [])),- ("resource", list(getattr(result, "resources", []) or [])),- ("skill", list(getattr(result, "skills", []) or [])),- ]---def item_value(item: Any, key: str, default: Any = None) -> Any:- if isinstance(item, dict):- return item.get(key, default)- return getattr(item, key, default)---def iter_result_items(- result: Any,- context_types: Iterable[str] = ("memory", "resource", "skill"),-) -> Iterable[tuple[str, Any]]:- allowed = set(context_types)- for context_type, items in result_groups(result):- if context_type not in allowed:- continue- for item in items:- yield context_type, item---def compact_json(value: Any) -> str:- return json.dumps(value, ensure_ascii=False, default=str, separators=(",", ":"))---def stringify(value: Any, *, max_chars: int = 12_000) -> str:- if value is None:- text = ""- elif isinstance(value, str):- text = value- else:- text = json.dumps(value, ensure_ascii=False, default=str, indent=2)- if max_chars > 0 and len(text) > max_chars:- return text[:max_chars] + "\n...[truncated]"- return text---def extract_message_text(content: Any) -> str:- """Extract text from LangChain/OpenAI-style message content."""-- if isinstance(content, str):- return content- if isinstance(content, list):- chunks: list[str] = []- for block in content:- if isinstance(block, str):- chunks.append(block)- elif isinstance(block, dict):- if block.get("type") == "text" and isinstance(block.get("text"), str):- chunks.append(block["text"])- elif isinstance(block.get("content"), str):- chunks.append(block["content"])- return "\n".join(chunk for chunk in chunks if chunk)- if content is None:- return ""- return str(content)---def get_latest_user_text(messages: Iterable[Any]) -> str:- for message in reversed(list(messages)):- role = getattr(message, "type", None) or getattr(message, "role", None)- if isinstance(message, dict):- role = message.get("type") or message.get("role")- content = message.get("content")- else:- content = getattr(message, "content", "")- if role in {"human", "user"}:- text = extract_message_text(content).strip()- if text:- return text- return ""+_forward_legacy_module("client", globals())diff --git a/openviking/integrations/langchain/context.py b/openviking/integrations/langchain/context.pyindex 707554f4e..9b80429bf 100644--- a/openviking/integrations/langchain/context.py+++ b/openviking/integrations/langchain/context.py@@ -1,944 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""High-level OpenViking context lifecycle helpers for LangChain."""+"""Compatibility wrapper for :mod:`langchain_openviking.context`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-import asyncio-import logging-import threading-from collections.abc import AsyncIterator, Callable, Sequence-from contextlib import asynccontextmanager, contextmanager-from copy import deepcopy-from dataclasses import dataclass, field-from typing import Any, Iterator--from pydantic import PrivateAttr--try:- from langchain_core.messages import BaseMessage, SystemMessage- from langchain_core.runnables import ConfigurableFieldSpec, RunnableLambda- from langchain_core.runnables.history import RunnableWithMessageHistory-except ImportError as exc: # pragma: no cover - exercised by optional import path- from openviking.integrations.langchain.client import missing_dependency-- raise missing_dependency("langchain", "langchain-core") from exc--from openviking.integrations.langchain.client import (- OpenVikingCommitPolicy,- OpenVikingConnection,- acall_openviking,- aclose_openviking_clients,- call_openviking,- ensure_async_client,- ensure_client,- extract_message_text,- get_latest_user_text,- is_not_found_error,-)-from openviking.integrations.langchain.history import (- OpenVikingChatMessageHistory,- context_parts_from_documents,-)-from openviking.integrations.langchain.messages import OPENVIKING_CONTEXT_MARKER-from openviking.integrations.langchain.recording import OpenVikingSessionRecorder-from openviking.integrations.langchain.retrievers import OpenVikingRetriever-from openviking.utils.async_client_cache import LoopScopedAsyncClientCache--logger = logging.getLogger(__name__)---@dataclass(slots=True)-class OpenVikingAssembledContext:- """Context block plus structured references assembled before an agent turn."""-- block: str = ""- context_parts: list[dict[str, Any]] = field(default_factory=list)- session_context: dict[str, Any] = field(default_factory=dict)- recall_documents: list[Any] = field(default_factory=list)---@dataclass(slots=True)-class _AsyncSessionWriteLockEntry:- lock: asyncio.Lock = field(default_factory=asyncio.Lock)- users: int = 0---class _AsyncSessionWriteLockPool:- """Serialize completed writes without retaining inactive session IDs."""-- def __init__(self) -> None:- self._entries: dict[str, _AsyncSessionWriteLockEntry] = {}-- @asynccontextmanager- async def acquire(self, session_id: str) -> AsyncIterator[None]:- entry = self._entries.get(session_id)- if entry is None:- entry = _AsyncSessionWriteLockEntry()- self._entries[session_id] = entry- entry.users += 1- acquired = False- try:- await entry.lock.acquire()- acquired = True- yield- finally:- if acquired:- entry.lock.release()- entry.users -= 1- if entry.users == 0 and self._entries.get(session_id) is entry:- self._entries.pop(session_id, None)---@dataclass(slots=True)-class _SyncSessionWriteLockEntry:- lock: threading.Lock = field(default_factory=threading.Lock)- users: int = 0---class _SyncSessionWriteLockPool:- """Serialize synchronous writes without retaining inactive session IDs."""-- def __init__(self) -> None:- self._entries: dict[str, _SyncSessionWriteLockEntry] = {}- self._entries_lock = threading.Lock()-- @contextmanager- def acquire(self, session_id: str) -> Iterator[None]:- with self._entries_lock:- entry = self._entries.get(session_id)- if entry is None:- entry = _SyncSessionWriteLockEntry()- self._entries[session_id] = entry- entry.users += 1- try:- with entry.lock:- yield- finally:- with self._entries_lock:- entry.users -= 1- if entry.users == 0 and self._entries.get(session_id) is entry:- self._entries.pop(session_id, None)---class _InvocationOpenVikingChatMessageHistory(OpenVikingChatMessageHistory):- """Hold the entry history snapshot for one runnable invocation."""-- def __init__(- self,- *args: Any,- recorder: OpenVikingSessionRecorder,- sync_write_lock_pool: _SyncSessionWriteLockPool,- async_write_lock_pools: LoopScopedAsyncClientCache,- **kwargs: Any,- ):- super().__init__(*args, _recorder=recorder, **kwargs)- self._entry_snapshot: list[BaseMessage] | None = None- self._sync_write_lock_pool = sync_write_lock_pool- self._async_write_lock_pools = async_write_lock_pools-- @property- def messages(self) -> list[BaseMessage]:- if self._entry_snapshot is None:- self._entry_snapshot = list(super().messages)- return list(self._entry_snapshot)-- async def aget_messages(self) -> list[BaseMessage]:- if self._entry_snapshot is None:- self._entry_snapshot = list(await super().aget_messages())- return list(self._entry_snapshot)-- def add_messages(self, messages: Sequence[BaseMessage]) -> None:- try:- with self._sync_write_lock_pool.acquire(self.session_id):- super().add_messages(messages)- finally:- self._entry_snapshot = None-- async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:- try:- lock_pool = self._async_write_lock_pools.get(_AsyncSessionWriteLockPool)- async with lock_pool.acquire(self.session_id):- await super().aadd_messages(messages)- finally:- self._entry_snapshot = None---class OpenVikingSessionContextAssembler:- """Assemble session working memory, archive context, and recall results."""-- def __init__(- self,- *,- client: Any = None,- async_client: Any = None,- retriever: OpenVikingRetriever | None = None,- url: str | None = None,- api_key: str | None = None,- account: str | None = None,- user: str | None = None,- user_id: str | None = None,- actor_peer_id: str | None = None,- path: str | None = None,- timeout: float = 60.0,- extra_headers: dict[str, str] | None = None,- auto_initialize: bool = True,- target_uri: str | list[str] = "",- limit: int = 5,- score_threshold: float | None = None,- token_budget: int = 128_000,- include_session_context: bool = True,- include_active_messages: bool = True,- include_recall: bool = True,- recall_header: str = "Relevant OpenViking context:",- ):- self._connection = OpenVikingConnection(- client=client,- async_client=async_client,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- timeout=timeout,- extra_headers=extra_headers,- auto_initialize=auto_initialize,- )- self.retriever = retriever or OpenVikingRetriever(- client=client,- async_client=async_client,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- timeout=timeout,- extra_headers=extra_headers,- auto_initialize=auto_initialize,- target_uri=target_uri,- limit=limit,- score_threshold=score_threshold,- search_mode="search",- )- self.token_budget = token_budget- self.include_session_context = include_session_context- self.include_active_messages = include_active_messages- self.include_recall = include_recall- self.recall_header = recall_header- self._owns_client = client is None- self._owns_retriever = retriever is None- self._client_cache: Any = None- self._client_cache_lock = threading.Lock()- self._async_clients = LoopScopedAsyncClientCache()- self._closed = False-- def __deepcopy__(- self,- memo: dict[int, Any] | None = None,- ) -> OpenVikingSessionContextAssembler:- """Copy configuration with fresh caches and preserved injected ownership."""-- memo = {} if memo is None else memo- for client in (self._connection.client, self._connection.async_client):- if client is not None:- memo[id(client)] = client- if not self._owns_retriever:- memo[id(self.retriever)] = self.retriever-- copied = type(self).__new__(type(self))- memo[id(self)] = copied- copied.__dict__ = {- name: (- None- if name == "_client_cache"- else threading.Lock()- if name == "_client_cache_lock"- else LoopScopedAsyncClientCache()- if name == "_async_clients"- else deepcopy(value, memo)- )- for name, value in self.__dict__.items()- }- return copied-- def assemble(- self,- *,- session_id: str,- query: str = "",- ) -> OpenVikingAssembledContext:- client = self._get_client()- session_context = self._get_session_context(client, session_id)- recall_documents = self._get_recall_documents(- session_id,- query,- )- return self._assembled_context(session_context, recall_documents)-- async def aassemble(- self,- *,- session_id: str,- query: str = "",- ) -> OpenVikingAssembledContext:- """Asynchronously assemble session and recall context."""-- client = await self._get_async_client()- session_context = await self._aget_session_context(client, session_id)- recall_documents = await self._aget_recall_documents(- session_id,- query,- )- return self._assembled_context(session_context, recall_documents)-- def _assembled_context(- self,- session_context: dict[str, Any],- recall_documents: list[Any],- ) -> OpenVikingAssembledContext:- block = self._format_context_block(session_context, recall_documents)- return OpenVikingAssembledContext(- block=block,- context_parts=context_parts_from_documents(recall_documents),- session_context=session_context,- recall_documents=recall_documents,- )-- def _get_client(self) -> Any:- self._raise_if_closed()- if self._client_cache is None:- with self._client_cache_lock:- self._raise_if_closed()- if self._client_cache is None:- self._client_cache = ensure_client(self._connection)- client = self._client_cache- self._raise_if_closed()- return client-- async def get_async_client(self) -> Any:- """Return the async client interface used by this assembler.-- Injected clients are returned unchanged and remain caller-owned.- HTTP-backed connections return an internally managed, loop-local handle- whose method calls support recovery. Direct attributes on that handle- are best-effort during recovery; use ``await handle.get()`` only to read- raw properties immediately because recovery may replace that snapshot.- Embedded ``path=`` connections return an adapter-owned synchronous- client whose calls are dispatched through a worker thread.- """-- self._raise_if_closed()- client = await ensure_async_client(- self._connection,- client_cache=self._async_clients,- embedded_client_factory=self._get_client,- )- self._raise_if_closed()- return client-- async def _get_async_client(self) -> Any:- return await self.get_async_client()-- async def aclose(self) -> None:- """Release clients and the default retriever owned by this assembler."""-- if self._closed:- return- self._closed = True- with self._client_cache_lock:- sync_client = self._client_cache- self._client_cache = None- async_clients = await asyncio.to_thread(self._async_clients.pop_all)-- first_error: BaseException | None = None- try:- await aclose_openviking_clients(- sync_client if self._owns_client else None,- *async_clients,- )- except BaseException as exc:- first_error = exc- if self._owns_retriever:- try:- await self.retriever.aclose()- except BaseException as exc:- if first_error is None:- first_error = exc- if first_error is not None:- raise first_error-- def _raise_if_closed(self) -> None:- if self._closed:- raise RuntimeError("OpenVikingSessionContextAssembler is closed")-- def _ensure_session(self, client: Any, session_id: str) -> None:- try:- call_openviking(client, "create_session", session_id=session_id)- except Exception:- logger.debug("OpenViking session ensure failed", exc_info=True)- pass-- async def _aensure_session(self, client: Any, session_id: str) -> None:- try:- await acall_openviking(client, "create_session", session_id=session_id)- except Exception:- logger.debug("OpenViking session ensure failed", exc_info=True)-- def _get_session_context(self, client: Any, session_id: str) -> dict[str, Any]:- if not self.include_session_context:- # Without a context read there is no NOT_FOUND signal to create from.- # Preserve the previous guarantee that recall receives a valid session.- self._ensure_session(client, session_id)- return {}- try:- return call_openviking(- client,- "get_session_context",- session_id=session_id,- token_budget=self.token_budget,- )- except Exception as exc:- if is_not_found_error(exc):- # First use: materialize the empty session, but do not issue a second- # context read because the newly created session has no context yet.- self._ensure_session(client, session_id)- return {}- logger.debug("OpenViking session context assembly failed", exc_info=True)- return {}-- async def _aget_session_context(- self,- client: Any,- session_id: str,- ) -> dict[str, Any]:- if not self.include_session_context:- # Without a context read there is no NOT_FOUND signal to create from.- # Preserve the previous guarantee that recall receives a valid session.- await self._aensure_session(client, session_id)- return {}- try:- return await acall_openviking(- client,- "get_session_context",- session_id=session_id,- token_budget=self.token_budget,- )- except Exception as exc:- if is_not_found_error(exc):- # First use: materialize the empty session, but do not issue a second- # context read because the newly created session has no context yet.- await self._aensure_session(client, session_id)- return {}- logger.debug("OpenViking session context assembly failed", exc_info=True)- return {}-- def _get_recall_documents(- self,- session_id: str,- query: str,- ) -> list[Any]:- if not self.include_recall or not query:- return []- try:- return list(- _retriever_for_session(- self.retriever,- session_id,- ).invoke(query)- )- except Exception:- logger.debug("OpenViking recall retrieval failed", exc_info=True)- return []-- async def _aget_recall_documents(- self,- session_id: str,- query: str,- ) -> list[Any]:- if not self.include_recall or not query:- return []- try:- return list(- await _retriever_for_session(- self.retriever,- session_id,- ).ainvoke(query)- )- except Exception:- logger.debug("OpenViking recall retrieval failed", exc_info=True)- return []-- def _format_context_block(- self,- session_context: dict[str, Any],- recall_documents: Sequence[Any],- ) -> str:- sections: list[str] = []- latest_archive = str(session_context.get("latest_archive_overview") or "").strip()- if latest_archive:- sections.append("Session archive overview:\n" + latest_archive)-- abstracts = []- for archive in session_context.get("pre_archive_abstracts") or []:- archive_id = archive.get("archive_id") or "archive"- abstract = str(archive.get("abstract") or "").strip()- if abstract:- abstracts.append(f"[{archive_id}] {abstract}")- if abstracts:- sections.append("Older archive abstracts:\n" + "\n".join(abstracts))-- if self.include_active_messages:- active_messages = [- _format_session_message(message)- for message in session_context.get("messages") or []- ]- active_messages = [message for message in active_messages if message]- if active_messages:- sections.append("Active session messages:\n" + "\n".join(active_messages))-- if recall_documents:- recall_lines = []- for index, doc in enumerate(recall_documents, start=1):- metadata = getattr(doc, "metadata", {}) or {}- uri = metadata.get("openviking_uri") or metadata.get("source") or ""- recall_lines.append(f"[{index}] {uri}\n{doc.page_content}".strip())- sections.append(self.recall_header + "\n\n" + "\n\n".join(recall_lines))-- if not sections:- return ""- return f"{OPENVIKING_CONTEXT_MARKER}\n" + "\n\n".join(sections) + "\n</openviking_context>"---class _OpenVikingContextResources:- """Share one lifecycle owner across derived runnable copies."""-- def __init__(- self,- assembler: OpenVikingSessionContextAssembler,- recorder: OpenVikingSessionRecorder,- ) -> None:- self._assembler = assembler- self._recorder = recorder- self._closed = False- self._close_lock = threading.Lock()-- def __copy__(self) -> _OpenVikingContextResources:- return self-- def __deepcopy__(self, memo: dict[int, Any]) -> _OpenVikingContextResources:- memo[id(self)] = self- return self-- def close(self) -> None:- with self._close_lock:- if self._closed:- return- try:- asyncio.get_running_loop()- except RuntimeError:- asyncio.run(self.aclose())- return- raise RuntimeError(- "OpenVikingContextRunnable.close() cannot run inside an active event loop; "- "use `await runnable.aclose()`"- )-- async def aclose(self) -> None:- with self._close_lock:- if self._closed:- return- self._closed = True-- first_error: BaseException | None = None- for component in (self._assembler, self._recorder):- try:- await component.aclose()- except BaseException as exc:- if first_error is None:- first_error = exc- if first_error is not None:- raise first_error-- def raise_if_closed(self) -> None:- with self._close_lock:- if self._closed:- raise RuntimeError("OpenVikingContextRunnable is closed")---class OpenVikingContextRunnable(RunnableWithMessageHistory):- """LangChain history wrapper with deterministic OpenViking cleanup."""-- _resources: _OpenVikingContextResources = PrivateAttr()-- def __init__(- self,- *args: Any,- _resources: _OpenVikingContextResources,- **kwargs: Any,- ) -> None:- super().__init__(*args, **kwargs)- self._resources = _resources-- def close(self) -> None:- """Release internally created resources outside a running event loop."""-- self._resources.close()-- async def aclose(self) -> None:- """Release internally created context and recording resources."""-- await self._resources.aclose()-- def __enter__(self) -> OpenVikingContextRunnable:- """Enter a synchronous managed lifecycle."""-- self._resources.raise_if_closed()- return self-- def __exit__(- self,- _exc_type: type[BaseException] | None,- _exc: BaseException | None,- _traceback: Any,- ) -> None:- self.close()-- async def __aenter__(self) -> OpenVikingContextRunnable:- """Enter an asynchronous managed lifecycle."""-- self._resources.raise_if_closed()- return self-- async def __aexit__(- self,- _exc_type: type[BaseException] | None,- _exc: BaseException | None,- _traceback: Any,- ) -> None:- await self.aclose()---def with_openviking_context(- runnable: Any,- *,- client: Any = None,- async_client: Any = None,- url: str | None = None,- api_key: str | None = None,- account: str | None = None,- user: str | None = None,- user_id: str | None = None,- path: str | None = None,- timeout: float = 60.0,- extra_headers: dict[str, str] | None = None,- auto_initialize: bool = True,- session_id: str | None = None,- peer_id: str | None = None,- actor_peer_id: str | None = None,- target_uri: str | list[str] = "",- limit: int = 5,- score_threshold: float | None = None,- token_budget: int = 128_000,- input_messages_key: str | None = None,- output_messages_key: str | None = None,- history_messages_key: str | None = None,- commit_policy: OpenVikingCommitPolicy | None = None,- session_id_config_key: str = "session_id",- peer_id_config_key: str = "peer_id",- inject_context: bool = True,-) -> OpenVikingContextRunnable:- """Wrap a runnable with invocation-scoped history and managed resources.-- Use the returned runnable as a context manager, or call ``close()`` /- ``await aclose()`` when it is no longer needed.- """-- assembler = OpenVikingSessionContextAssembler(- client=client,- async_client=async_client,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- timeout=timeout,- extra_headers=extra_headers,- auto_initialize=auto_initialize,- target_uri=target_uri,- limit=limit,- score_threshold=score_threshold,- token_budget=token_budget,- include_active_messages=False,- include_recall=inject_context,- )- recorder = OpenVikingSessionRecorder(- client=client,- async_client=async_client,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- timeout=timeout,- extra_headers=extra_headers,- auto_initialize=auto_initialize,- commit_policy=commit_policy,- )- resources = _OpenVikingContextResources(assembler, recorder)- sync_write_lock_pool = _SyncSessionWriteLockPool()- async_write_lock_pools = LoopScopedAsyncClientCache()-- def make_history(active_session_id: str) -> OpenVikingChatMessageHistory:- resources.raise_if_closed()- return _InvocationOpenVikingChatMessageHistory(- session_id=active_session_id,- recorder=recorder,- sync_write_lock_pool=sync_write_lock_pool,- async_write_lock_pools=async_write_lock_pools,- peer_id=peer_id,- token_budget=token_budget,- )-- if session_id is None:-- def dynamic_session_history_factory(- resolved_session_id: str,- ) -> OpenVikingChatMessageHistory:- return make_history(- _validate_session_id(resolved_session_id, key=session_id_config_key)- )-- session_history_factory: Callable[..., OpenVikingChatMessageHistory] = (- dynamic_session_history_factory- )- history_factory_config = [- ConfigurableFieldSpec(- id=session_id_config_key,- annotation=str,- name="Session ID",- description=("Required OpenViking session ID for dynamic chat history and recall."),- default="",- is_shared=True,- )- ]- else:-- def fixed_session_history_factory() -> OpenVikingChatMessageHistory:- return make_history(session_id)-- session_history_factory = fixed_session_history_factory- history_factory_config = None-- def prepare_injection(- input_value: Any,- config: dict[str, Any] | None,- ) -> tuple[str, _InvocationOpenVikingChatMessageHistory, str] | None:- resolved_session_id = session_id or _session_id_from_config(- config,- key=session_id_config_key,- )- resolved_peer_id = _peer_id_from_config(- config,- key=peer_id_config_key,- default=peer_id,- )- history = _invocation_history_from_config(config)- history._prepare_invocation(peer_id=resolved_peer_id)- if not inject_context:- return None- query = _latest_user_text_from_input(input_value, input_messages_key)- return resolved_session_id, history, query-- def apply_injection(- input_value: Any,- history: _InvocationOpenVikingChatMessageHistory,- assembled: OpenVikingAssembledContext,- ) -> Any:- if not assembled.block:- return input_value- if assembled.context_parts:- history._prepare_invocation(- peer_id=history.peer_id,- context_parts=assembled.context_parts,- )- return _inject_system_context(input_value, assembled.block, input_messages_key)-- def inject(input_value: Any, config: dict[str, Any] | None = None) -> Any:- prepared = prepare_injection(input_value, config)- if prepared is None:- return input_value- resolved_session_id, history, query = prepared- assembled = assembler.assemble(- session_id=resolved_session_id,- query=query,- )- return apply_injection(input_value, history, assembled)-- async def ainject(input_value: Any, config: dict[str, Any] | None = None) -> Any:- prepared = prepare_injection(input_value, config)- if prepared is None:- return input_value- resolved_session_id, history, query = prepared- assembled = await assembler.aassemble(- session_id=resolved_session_id,- query=query,- )- return apply_injection(input_value, history, assembled)-- def clear_pending_on_error(_run: Any, config: dict[str, Any] | None = None) -> None:- try:- history = _invocation_history_from_config(config)- except Exception:- logger.debug(- "OpenViking pending context cleanup could not resolve invocation history",- exc_info=True,- )- return- history._discard_invocation_context()-- bound = (RunnableLambda(inject, afunc=ainject) | runnable).with_listeners(- on_error=clear_pending_on_error- )- wrapped = OpenVikingContextRunnable(- bound,- session_history_factory,- input_messages_key=input_messages_key,- output_messages_key=output_messages_key,- history_messages_key=history_messages_key,- history_factory_config=history_factory_config,- _resources=resources,- )- return wrapped---def _session_id_from_config(config: dict[str, Any] | None, *, key: str) -> str:- configurable = (config or {}).get("configurable") or {}- return _validate_session_id(configurable.get(key), key=key)---def _peer_id_from_config(- config: dict[str, Any] | None,- *,- key: str,- default: str | None,-) -> str | None:- configurable = (config or {}).get("configurable") or {}- value = configurable.get(key, default)- if value is None:- return None- text = str(value).strip()- return text or None---def _validate_session_id(value: Any, *, key: str) -> str:- session_id = str(value or "").strip()- if not session_id:- raise ValueError(- "OpenViking dynamic sessions require "- f"config={{'configurable': {{'{key}': '<session-id>'}}}}. "- "Pass session_id='...' to with_openviking_context for no-config usage."- )- return session_id---def _invocation_history_from_config(- config: dict[str, Any] | None,-) -> _InvocationOpenVikingChatMessageHistory:- configurable = (config or {}).get("configurable") or {}- history = configurable.get("message_history")- if not isinstance(history, _InvocationOpenVikingChatMessageHistory):- raise RuntimeError("OpenViking runnable invocation history is unavailable")- return history---def _retriever_for_session(- retriever: Any,- session_id: str,-) -> Any:- if hasattr(retriever, "model_copy"):- update = {- "session_id": session_id,- "search_mode": "search",- }- return retriever.model_copy(update=update)- return retriever---def _latest_user_text_from_input(input_value: Any, input_messages_key: str | None) -> str:- messages = _input_messages(input_value, input_messages_key)- if messages:- return get_latest_user_text(messages)- if isinstance(input_value, str):- return input_value- if isinstance(input_value, dict):- for value in input_value.values():- if isinstance(value, str) and value.strip():- return value.strip()- return ""---def _input_messages(input_value: Any, input_messages_key: str | None) -> list[Any]:- if isinstance(input_value, list):- return list(input_value)- if isinstance(input_value, dict):- key = input_messages_key or "messages"- value = input_value.get(key)- if isinstance(value, list):- return list(value)- return []---def _inject_system_context(- input_value: Any,- context_block: str,- input_messages_key: str | None,-) -> Any:- if isinstance(input_value, list):- return _merge_system_message(input_value, context_block)- if isinstance(input_value, dict):- key = input_messages_key or "messages"- if isinstance(input_value.get(key), list):- updated = dict(input_value)- updated[key] = _merge_system_message(input_value[key], context_block)- return updated- updated = dict(input_value)- updated["openviking_context"] = context_block- return updated- return input_value---def _merge_system_message(messages: Sequence[Any], context_block: str) -> list[Any]:- updated = list(messages)- for index, message in enumerate(updated):- if isinstance(message, SystemMessage):- content = extract_message_text(message.content)- updated[index] = SystemMessage(content=f"{content}\n\n{context_block}".strip())- return updated- return [SystemMessage(content=context_block), *updated]---def _format_session_message(message: dict[str, Any]) -> str:- role = str(message.get("role") or "assistant")- parts = message.get("parts") or []- chunks: list[str] = []- for part in parts:- part_type = part.get("type")- if part_type == "text" and part.get("text"):- chunks.append(str(part["text"]))- elif part_type == "context" and part.get("abstract"):- chunks.append(f"[context] {part['abstract']}")- elif part_type == "tool":- tool_name = part.get("tool_name") or "tool"- status = part.get("tool_status") or "completed"- output = part.get("tool_output") or ""- chunks.append(f"[tool:{tool_name} ({status})] {output}".strip())- text = "\n".join(chunk for chunk in chunks if chunk).strip()- return f"[{role}] {text}" if text else ""+_forward_legacy_module("context", globals())diff --git a/openviking/integrations/langchain/history.py b/openviking/integrations/langchain/history.pyindex 6c05f9c5a..74a079669 100644--- a/openviking/integrations/langchain/history.py+++ b/openviking/integrations/langchain/history.py@@ -1,292 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""LangChain chat history backed by OpenViking sessions."""+"""Compatibility wrapper for :mod:`langchain_openviking.history`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-import asyncio-import logging-from collections.abc import Sequence-from typing import Any, Callable--try:- from langchain_core.chat_history import BaseChatMessageHistory- from langchain_core.messages import BaseMessage-except ImportError as exc: # pragma: no cover - exercised by optional import path- from openviking.integrations.langchain.client import missing_dependency-- raise missing_dependency("langchain", "langchain-core") from exc--from openviking.integrations.langchain.client import (- OpenVikingCommitPolicy,- acall_openviking,- call_openviking,- is_not_found_error,-)-from openviking.integrations.langchain.messages import (- langchain_message_to_openviking as langchain_message_to_openviking,-)-from openviking.integrations.langchain.messages import (- openviking_message_to_langchain as openviking_message_to_langchain,-)-from openviking.integrations.langchain.messages import (- restore_openviking_messages,-)-from openviking.integrations.langchain.recording import (- OpenVikingPartialWriteError,- OpenVikingSessionRecorder,- get_openviking_cancellation_progress,-)--logger = logging.getLogger(__name__)---class OpenVikingChatMessageHistory(BaseChatMessageHistory):- """LangChain chat history implementation stored in an OpenViking session."""-- def __init__(- self,- session_id: str,- *,- client: Any = None,- async_client: Any = None,- url: str | None = None,- api_key: str | None = None,- account: str | None = None,- user: str | None = None,- user_id: str | None = None,- actor_peer_id: str | None = None,- path: str | None = None,- timeout: float = 60.0,- extra_headers: dict[str, str] | None = None,- auto_initialize: bool = True,- token_budget: int = 128_000,- persist_system_messages: bool = False,- commit_policy: OpenVikingCommitPolicy | None = None,- context_parts_provider: Callable[[str], list[dict[str, Any]]] | None = None,- context_parts_acknowledger: Callable[[str], None] | None = None,- peer_id: str | None = None,- peer_id_provider: Callable[[str], str | None] | None = None,- _recorder: OpenVikingSessionRecorder | None = None,- ):- self.session_id = session_id- self.peer_id = peer_id- self.peer_id_provider = peer_id_provider- self.token_budget = token_budget- # Retained for constructor compatibility. System messages are runtime- # policy, not conversation memory, so they are never persisted.- self.persist_system_messages = False- self.context_parts_provider = context_parts_provider- self.context_parts_acknowledger = context_parts_acknowledger- self._pending_context_parts: list[dict[str, Any]] = []- self._owns_recorder = _recorder is None- self._recorder = _recorder or OpenVikingSessionRecorder(- client=client,- async_client=async_client,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- timeout=timeout,- extra_headers=extra_headers,- auto_initialize=auto_initialize,- commit_policy=commit_policy,- )-- @property- def commit_policy(self) -> OpenVikingCommitPolicy | None:- """Return the recorder commit policy used by this history."""-- return self._recorder.commit_policy-- @commit_policy.setter- def commit_policy(self, value: OpenVikingCommitPolicy | None) -> None:- self._recorder.commit_policy = value-- @property- def messages(self) -> list[BaseMessage]:- client = self._get_client()- try:- context = call_openviking(- client,- "get_session_context",- session_id=self.session_id,- token_budget=self.token_budget,- )- except Exception as exc:- logger.debug("OpenViking chat history context fetch failed", exc_info=True)- if is_not_found_error(exc):- self._ensure_session(client)- return []-- return restore_openviking_messages(context.get("messages") or [])-- async def aget_messages(self) -> list[BaseMessage]:- """Asynchronously return active messages from the OpenViking session."""-- client = await self._get_async_client()- try:- context = await acall_openviking(- client,- "get_session_context",- session_id=self.session_id,- token_budget=self.token_budget,- )- except Exception as exc:- logger.debug("OpenViking chat history context fetch failed", exc_info=True)- if is_not_found_error(exc):- await self._aensure_session(client)- return []-- return restore_openviking_messages(context.get("messages") or [])-- def add_messages(self, messages: Sequence[BaseMessage]) -> None:- if not self._pending_context_parts and self.context_parts_provider:- self._pending_context_parts = list(self.context_parts_provider(self.session_id))- try:- result = self._recorder.record(- self.session_id,- messages,- peer_id=self._effective_peer_id(),- context_parts=self._pending_context_parts,- )- except OpenVikingPartialWriteError as exc:- if exc.context_attached:- self._acknowledge_context_parts()- raise- if result.context_attached:- self._acknowledge_context_parts()-- async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:- """Asynchronously persist messages through the shared session recorder."""-- if not self._pending_context_parts and self.context_parts_provider:- self._pending_context_parts = list(self.context_parts_provider(self.session_id))- try:- result = await self._recorder.arecord(- self.session_id,- messages,- peer_id=self._effective_peer_id(),- context_parts=self._pending_context_parts,- )- except OpenVikingPartialWriteError as exc:- if exc.context_attached:- self._acknowledge_context_parts()- raise- except asyncio.CancelledError as exc:- progress = get_openviking_cancellation_progress(exc)- if progress is not None and progress.context_attached:- self._acknowledge_context_parts()- raise- if result.context_attached:- self._acknowledge_context_parts()-- def clear(self) -> None:- client = self._get_client()- call_openviking(client, "delete_session", session_id=self.session_id)- self._ensure_session(client)- self._acknowledge_context_parts()-- async def aclear(self) -> None:- """Asynchronously reset this OpenViking session."""-- client = await self._get_async_client()- await acall_openviking(client, "delete_session", session_id=self.session_id)- await self._aensure_session(client)- self._acknowledge_context_parts()-- def close(self) -> None:- """Release resources owned by this history adapter."""-- self._acknowledge_context_parts()- if self._owns_recorder:- self._recorder.close()-- async def aclose(self) -> None:- """Asynchronously release resources owned by this history adapter."""-- self._acknowledge_context_parts()- if self._owns_recorder:- await self._recorder.aclose()-- def _get_client(self) -> Any:- return self._recorder.client-- async def _get_async_client(self) -> Any:- return await self._recorder.get_async_client()-- def _ensure_session(self, client: Any) -> None:- try:- call_openviking(client, "create_session", session_id=self.session_id)- except Exception:- logger.debug("OpenViking chat history session ensure failed", exc_info=True)- pass-- async def _aensure_session(self, client: Any) -> None:- try:- await acall_openviking(client, "create_session", session_id=self.session_id)- except Exception:- logger.debug("OpenViking chat history session ensure failed", exc_info=True)-- def _effective_peer_id(self) -> str | None:- if self.peer_id_provider is None:- value = self.peer_id- else:- value = self.peer_id_provider(self.session_id)- if value is None:- return None- text = str(value).strip()- return text or None-- def _prepare_invocation(- self,- *,- peer_id: str | None,- context_parts: Sequence[dict[str, Any]] = (),- ) -> None:- """Set invocation-local attribution and recalled context."""-- self.peer_id = peer_id- self._pending_context_parts = list(context_parts)-- def _discard_invocation_context(self) -> None:- """Discard recalled context owned by an interrupted invocation."""-- self._pending_context_parts = []-- def _acknowledge_context_parts(self) -> None:- had_pending_context = bool(self._pending_context_parts)- self._pending_context_parts = []- if not had_pending_context or self.context_parts_acknowledger is None:- return- try:- self.context_parts_acknowledger(self.session_id)- except Exception:- logger.warning(- "OpenViking context-parts acknowledgement failed",- exc_info=True,- )---def context_parts_from_documents(documents: Sequence[Any]) -> list[dict[str, Any]]:- """Build OpenViking ContextPart dictionaries from LangChain Documents."""-- parts: list[dict[str, Any]] = []- for doc in documents:- metadata = getattr(doc, "metadata", {}) or {}- uri = metadata.get("openviking_uri") or metadata.get("source") or ""- if not uri:- continue- parts.append(- {- "type": "context",- "uri": uri,- "context_type": metadata.get("openviking_context_type") or "resource",- "abstract": metadata.get("openviking_abstract")- or getattr(doc, "page_content", "")[:500],- }- )- return parts+_forward_legacy_module("history", globals())diff --git a/openviking/integrations/langchain/messages.py b/openviking/integrations/langchain/messages.pyindex 4cd348eeb..006cd29c1 100644--- a/openviking/integrations/langchain/messages.py+++ b/openviking/integrations/langchain/messages.py@@ -1,206 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""LangChain message conversion and recording filters."""+"""Compatibility wrapper for :mod:`langchain_openviking.messages`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-from collections.abc import Sequence-from copy import deepcopy-from typing import Any--try:- from langchain_core.messages import (- AIMessage,- BaseMessage,- HumanMessage,- SystemMessage,- ToolMessage,- )-except ImportError as exc: # pragma: no cover - exercised by optional import path- from openviking.integrations.langchain.client import missing_dependency-- raise missing_dependency("langchain", "langchain-core") from exc--from openviking.integrations.langchain.client import extract_message_text--OPENVIKING_CONTEXT_MARKER = "<openviking_context>"-LANGCHAIN_SUMMARIZATION_SOURCE = "summarization"---def is_recordable_langchain_message(message: BaseMessage) -> bool:- """Return whether a framework message belongs in OpenViking session history."""-- if isinstance(message, SystemMessage):- return False- additional_kwargs = getattr(message, "additional_kwargs", {}) or {}- if additional_kwargs.get("lc_source") == LANGCHAIN_SUMMARIZATION_SOURCE:- return False- if isinstance(message, AIMessage):- return bool(- extract_message_text(message.content)- or message.tool_calls- or additional_kwargs.get("tool_calls")- )- return bool(langchain_message_to_openviking(message))---def is_context_carrier_langchain_message(message: BaseMessage) -> bool:- """Return whether an otherwise-empty assistant can carry recalled context."""-- if not isinstance(message, AIMessage):- return False- additional_kwargs = getattr(message, "additional_kwargs", {}) or {}- return additional_kwargs.get("lc_source") != LANGCHAIN_SUMMARIZATION_SOURCE---def langchain_message_to_openviking(- message: BaseMessage,- *,- persist_system_messages: bool = False,-) -> list[dict[str, Any]]:- """Convert a LangChain message into one or more OpenViking message payloads."""-- del persist_system_messages # Retained for compatibility; system policy is never persisted.-- if isinstance(message, HumanMessage):- human_parts = _text_parts(message.content)- return [{"role": "user", "parts": human_parts or [{"type": "text", "text": ""}]}]-- if isinstance(message, AIMessage):- parts: list[dict[str, Any]] = _text_parts(message.content)- for tool_call in message.tool_calls or []:- parts.append(- {- "type": "tool",- "tool_id": str(tool_call.get("id") or ""),- "tool_name": str(tool_call.get("name") or ""),- "tool_input": _tool_args(tool_call.get("args")),- "tool_status": "pending",- }- )- return [{"role": "assistant", "parts": parts or [{"type": "text", "text": ""}]}]-- if isinstance(message, ToolMessage):- return [- {- "role": "assistant",- "parts": [- {- "type": "tool",- "tool_id": str(message.tool_call_id or ""),- "tool_name": str(message.name or ""),- "tool_output": extract_message_text(message.content),- "tool_status": _tool_status(message),- }- ],- }- ]-- if isinstance(message, SystemMessage):- return []-- text = extract_message_text(getattr(message, "content", ""))- if not text:- return []- role = "user" if getattr(message, "type", "") == "human" else "assistant"- return [{"role": role, "parts": [{"type": "text", "text": text}]}]---def openviking_message_to_langchain(message: dict[str, Any]) -> list[BaseMessage]:- """Convert one OpenViking session message into LangChain messages."""-- role = str(message.get("role") or "")- parts = list(message.get("parts") or [])- text = _parts_text(parts)- if role == "user":- return [HumanMessage(content=text)]-- tool_calls = []- tool_messages = []- for part in parts:- if part.get("type") != "tool":- continue- tool_id = str(part.get("tool_id") or "")- tool_name = str(part.get("tool_name") or "")- status = str(part.get("tool_status") or "")- has_output = part.get("tool_output") is not None- is_completed_result = has_output or status in {"completed", "error"}- if is_completed_result:- tool_messages.append(- ToolMessage(- content=str(part.get("tool_output") or ""),- tool_call_id=tool_id or "openviking-tool",- name=tool_name or None,- status="error" if status == "error" else "success",- )- )- else:- tool_calls.append(- {- "id": tool_id,- "name": tool_name,- "args": _tool_args(part.get("tool_input")),- }- )-- messages: list[BaseMessage] = []- if text or tool_calls or not tool_messages:- messages.append(- AIMessage(content=text, tool_calls=tool_calls or [])- if tool_calls- else AIMessage(content=text)- )- messages.extend(tool_messages)- return messages---def restore_openviking_messages(messages: Sequence[dict[str, Any]]) -> list[BaseMessage]:- """Restore a valid LangChain message sequence from OpenViking session messages."""-- restored: list[BaseMessage] = []- active_tool_call_ids: set[str] = set()- for message in messages:- for langchain_message in openviking_message_to_langchain(message):- if isinstance(langchain_message, AIMessage):- restored.append(langchain_message)- for tool_call in langchain_message.tool_calls or []:- tool_call_id = str(tool_call.get("id") or "")- if tool_call_id:- active_tool_call_ids.add(tool_call_id)- elif isinstance(langchain_message, ToolMessage):- tool_call_id = str(langchain_message.tool_call_id or "")- if tool_call_id and tool_call_id in active_tool_call_ids:- restored.append(langchain_message)- active_tool_call_ids.discard(tool_call_id)- else:- restored.append(langchain_message)- return restored---def _text_parts(content: Any) -> list[dict[str, Any]]:- text = extract_message_text(content)- return [{"type": "text", "text": text}] if text else []---def _parts_text(parts: Sequence[dict[str, Any]]) -> str:- chunks: list[str] = []- for part in parts:- part_type = part.get("type")- if part_type == "text" and part.get("text"):- chunks.append(str(part["text"]))- elif part_type == "context" and part.get("abstract"):- uri = part.get("uri") or "context"- chunks.append(f"[context:{uri}] {part['abstract']}")- return "\n".join(chunks)---def _tool_args(value: Any) -> dict[str, Any]:- if value is None:- return {}- if isinstance(value, dict):- return deepcopy(value)- return {"value": deepcopy(value)}---def _tool_status(message: ToolMessage) -> str:- return "error" if getattr(message, "status", "") == "error" else "completed"+_forward_legacy_module("messages", globals())diff --git a/openviking/integrations/langchain/middleware.py b/openviking/integrations/langchain/middleware.pyindex 794f88262..ed5ddfa49 100644--- a/openviking/integrations/langchain/middleware.py+++ b/openviking/integrations/langchain/middleware.py@@ -1,598 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""LangGraph agent middleware for OpenViking recall and capture."""+"""Compatibility wrapper for :mod:`langchain_openviking.middleware`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-import asyncio-import json-from contextlib import AbstractContextManager, nullcontext-from dataclasses import dataclass-from typing import Any, Callable--try:- from langchain.agents.middleware import AgentMiddleware- from langchain.agents.middleware.types import AgentState, ModelRequest- from langchain_core.messages import (- AIMessage,- BaseMessage,- HumanMessage,- SystemMessage,- ToolMessage,- )-except ImportError as exc: # pragma: no cover - exercised by optional import path- from openviking.integrations.langchain.client import missing_dependency-- raise missing_dependency("langgraph", "langchain/langgraph") from exc--from openviking.integrations.langchain.actor_peer import (- get_actor_peer_id,- require_request_actor_peer_support,- use_actor_peer,-)-from openviking.integrations.langchain.client import (- OpenVikingCommitPolicy,- extract_message_text,- get_latest_user_text,-)-from openviking.integrations.langchain.context import (- OpenVikingAssembledContext,- OpenVikingSessionContextAssembler,-)-from openviking.integrations.langchain.recording import (- OpenVikingCancellationProgress,- OpenVikingPartialWriteError,- OpenVikingSessionRecorder,- get_openviking_cancellation_progress,-)-from openviking.integrations.langchain.retrievers import OpenVikingRetriever--_SESSION_ID_ERROR = (- "OpenVikingContextMiddleware requires a LangGraph session id. Pass "- 'config={"configurable": {"thread_id": "..."}}, set state["session_id"], '- "or provide session_id_resolver."-)-_CaptureKey = tuple[str, str] | tuple[str, str, str]-_ActorPeerResolver = Callable[- [dict[str, Any], Any],- str | None,-]---@dataclass(slots=True)-class _CapturePlan:- session_id: str- peer_id: str | None- actor_peer_id: str | None- key: _CaptureKey- messages: list[Any]- signatures: tuple[str, ...]- start: int- context_parts: list[dict[str, Any]]- unchanged: bool = False---class OpenVikingContextMiddleware(AgentMiddleware):- """Inject OpenViking recall into LangGraph agent model calls.-- The middleware mirrors the OpenClaw-style lifecycle at LangGraph's extension- points: recall before model calls and optional session capture after agent- execution.- """-- def __init__(- self,- *,- client: Any = None,- async_client: Any = None,- retriever: OpenVikingRetriever | None = None,- url: str | None = None,- api_key: str | None = None,- account: str | None = None,- user: str | None = None,- user_id: str | None = None,- actor_peer_id: str | None = None,- path: str | None = None,- target_uri: str | list[str] = "",- limit: int = 5,- peer_id: str | None = None,- score_threshold: float | None = None,- token_budget: int = 128_000,- session_id_resolver: Callable[[dict[str, Any], Any], str] | None = None,- peer_id_resolver: Callable[[dict[str, Any], Any], str | None] | None = None,- actor_peer_resolver: _ActorPeerResolver | None = None,- capture_on_after_agent: bool = True,- commit_on_after_agent: bool = False,- commit_policy: OpenVikingCommitPolicy | None = None,- recall_header: str = "Relevant OpenViking context:",- include_active_messages: bool = False,- ):- super().__init__()- _validate_actor_peer_transport(- actor_peer_resolver=actor_peer_resolver,- client=client,- async_client=async_client,- retriever=retriever,- path=path,- )- self.recorder = OpenVikingSessionRecorder(- client=client,- async_client=async_client,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- commit_policy=None,- )- self._owns_retriever = retriever is None- self.retriever = retriever or OpenVikingRetriever(- client=client,- async_client=async_client,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- target_uri=target_uri,- limit=limit,- score_threshold=score_threshold,- search_mode="search",- )- self.assembler = OpenVikingSessionContextAssembler(- client=client,- async_client=async_client,- retriever=self.retriever,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- target_uri=target_uri,- limit=limit,- score_threshold=score_threshold,- token_budget=token_budget,- include_session_context=True,- include_active_messages=include_active_messages,- include_recall=True,- recall_header=recall_header,- )- self.session_id_resolver = session_id_resolver- self.peer_id = peer_id- self.peer_id_resolver = peer_id_resolver- self.actor_peer_resolver = actor_peer_resolver- self.capture_on_after_agent = capture_on_after_agent- self.commit_policy = commit_policy- if commit_on_after_agent and self.commit_policy is None:- self.commit_policy = OpenVikingCommitPolicy(mode="always")- self.recall_header = recall_header- self._captured_signatures: dict[_CaptureKey, tuple[str, ...]] = {}- self._pending_context_parts: dict[_CaptureKey, list[dict[str, Any]]] = {}-- async def aclose(self) -> None:- """Release all clients internally owned by this middleware."""-- first_error: BaseException | None = None- components: list[Any] = [self.recorder, self.assembler]- if self._owns_retriever:- components.append(self.retriever)- for component in components:- try:- await component.aclose()- except BaseException as exc:- if first_error is None:- first_error = exc- if first_error is not None:- raise first_error-- def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], Any]) -> Any:- plan = self._model_context_plan(request)- if plan is None:- return handler(request)- session_id, pending_key, query, actor_peer_id = plan- with self._actor_peer_scope(actor_peer_id):- assembled = self.assembler.assemble(- session_id=session_id,- query=query,- )- updated_request = self._request_with_context(request, pending_key, assembled)- if updated_request is None:- return handler(request)- try:- return handler(updated_request)- except Exception:- self._pending_context_parts.pop(pending_key, None)- raise-- async def awrap_model_call(- self,- request: ModelRequest,- handler: Callable[[ModelRequest], Any],- ) -> Any:- """Asynchronously inject OpenViking context before a model call."""-- plan = self._model_context_plan(request)- if plan is None:- return await handler(request)- session_id, pending_key, query, actor_peer_id = plan- with self._actor_peer_scope(actor_peer_id):- assembled = await self.assembler.aassemble(- session_id=session_id,- query=query,- )- updated_request = self._request_with_context(request, pending_key, assembled)- if updated_request is None:- return await handler(request)- try:- return await handler(updated_request)- except BaseException:- # CancelledError is a BaseException, so cancellation must also discard- # context references prepared for the interrupted model call.- self._pending_context_parts.pop(pending_key, None)- raise-- def _model_context_plan(- self,- request: ModelRequest,- ) -> tuple[str, _CaptureKey, str, str | None] | None:- query = get_latest_user_text(request.messages)- if not query:- return None- state = getattr(request, "state", {}) or {}- runtime = getattr(request, "runtime", None)- session_id = self._resolve_session_id(state, runtime)- peer_id = self._resolve_peer_id(state, runtime)- actor_peer_id = self._resolve_actor_peer_id(state, runtime)- pending_key = _capture_key(session_id, peer_id, actor_peer_id)- self._pending_context_parts.pop(pending_key, None)- return session_id, pending_key, query, actor_peer_id-- def _request_with_context(- self,- request: ModelRequest,- pending_key: _CaptureKey,- assembled: OpenVikingAssembledContext,- ) -> ModelRequest | None:- context_block = assembled.block- if not context_block:- return None- if assembled.context_parts:- self._pending_context_parts[pending_key] = assembled.context_parts-- system_message = request.system_message- if system_message is None:- updated_system = SystemMessage(content=context_block)- else:- content = extract_message_text(system_message.content)- updated_system = SystemMessage(content=f"{content}\n\n{context_block}".strip())- return request.override(system_message=updated_system)-- def after_agent(self, state: AgentState[Any], runtime: Any) -> dict[str, Any] | None:- plan = self._capture_plan(state, runtime)- if plan is None:- return None- self.recorder.commit_policy = self.commit_policy- if plan.unchanged:- with self._actor_peer_scope(plan.actor_peer_id):- self.recorder.record(plan.session_id, ())- self._pending_context_parts.pop(plan.key, None)- return None- try:- with self._actor_peer_scope(plan.actor_peer_id):- result = self.recorder.record(- plan.session_id,- plan.messages[plan.start :],- peer_id=plan.peer_id,- context_parts=plan.context_parts,- )- except OpenVikingPartialWriteError as exc:- self._handle_partial_capture(plan, exc)- raise-- self._complete_capture(plan, context_attached=result.context_attached)- return None-- async def aafter_agent(- self,- state: AgentState[Any],- runtime: Any,- ) -> dict[str, Any] | None:- """Asynchronously capture messages after an agent run."""-- plan = self._capture_plan(state, runtime)- if plan is None:- return None- self.recorder.commit_policy = self.commit_policy- if plan.unchanged:- with self._actor_peer_scope(plan.actor_peer_id):- await self.recorder.arecord(plan.session_id, ())- self._pending_context_parts.pop(plan.key, None)- return None- try:- with self._actor_peer_scope(plan.actor_peer_id):- result = await self.recorder.arecord(- plan.session_id,- plan.messages[plan.start :],- peer_id=plan.peer_id,- context_parts=plan.context_parts,- )- except OpenVikingPartialWriteError as exc:- self._handle_partial_capture(plan, exc)- raise- except asyncio.CancelledError as exc:- progress = get_openviking_cancellation_progress(exc)- if progress is not None:- self._handle_partial_capture(plan, progress)- raise-- self._complete_capture(plan, context_attached=result.context_attached)- return None-- def _capture_plan(- self,- state: AgentState[Any],- runtime: Any,- ) -> _CapturePlan | None:- if not self.capture_on_after_agent:- return None- messages = list(state.get("messages") or [])- if not messages:- return None- session_id = self._resolve_session_id(state, runtime)- peer_id = self._resolve_peer_id(state, runtime)- actor_peer_id = self._resolve_actor_peer_id(state, runtime)- key = _capture_key(session_id, peer_id, actor_peer_id)- previous_signatures = self._captured_signatures.get(key, ())- signatures = tuple(_message_signature(message) for message in messages)- unchanged = signatures == previous_signatures- start = 0- if (- not unchanged- and previous_signatures- and len(signatures) > len(previous_signatures)- and signatures[: len(previous_signatures)] == previous_signatures- ):- start = len(previous_signatures)- return _CapturePlan(- session_id=session_id,- peer_id=peer_id,- actor_peer_id=actor_peer_id,- key=key,- messages=messages,- signatures=signatures,- start=start,- context_parts=list(self._pending_context_parts.get(key, [])),- unchanged=unchanged,- )-- def _handle_partial_capture(- self,- plan: _CapturePlan,- error: OpenVikingPartialWriteError | OpenVikingCancellationProgress,- ) -> None:- if error.input_messages_consumed:- consumed_end = plan.start + error.input_messages_consumed- self._captured_signatures[plan.key] = plan.signatures[:consumed_end]- if error.context_attached:- self._pending_context_parts.pop(plan.key, None)-- def _complete_capture(- self,- plan: _CapturePlan,- *,- context_attached: bool,- ) -> None:- self._captured_signatures[plan.key] = plan.signatures- if context_attached:- self._pending_context_parts.pop(plan.key, None)-- def _resolve_session_id(self, state: Any, runtime: Any) -> str:- if self.session_id_resolver:- resolved = _normalize_session_id(self.session_id_resolver(state, runtime))- if resolved:- return resolved- raise ValueError(_SESSION_ID_ERROR)- candidates = [- state.get("thread_id"),- state.get("session_id"),- _nested_get(getattr(runtime, "context", None), "thread_id"),- _nested_get(getattr(runtime, "config", None), "configurable", "thread_id"),- _nested_get(getattr(runtime, "config", None), "configurable", "session_id"),- ]- for candidate in candidates:- resolved = _normalize_session_id(candidate)- if resolved:- return resolved- raise ValueError(_SESSION_ID_ERROR)-- def _resolve_peer_id(self, state: Any, runtime: Any) -> str | None:- if self.peer_id_resolver:- return _normalize_peer_id(self.peer_id_resolver(state, runtime))- candidates = [- state.get("peer_id"),- state.get("peerId"),- _nested_get(getattr(runtime, "context", None), "peer_id"),- _nested_get(getattr(runtime, "context", None), "peerId"),- _nested_get(getattr(runtime, "config", None), "configurable", "peer_id"),- _nested_get(getattr(runtime, "config", None), "configurable", "peerId"),- self.peer_id,- ]- for candidate in candidates:- resolved = _normalize_peer_id(candidate)- if resolved:- return resolved- return None-- def _resolve_actor_peer_id(- self,- state: Any,- runtime: Any,- ) -> str | None:- if self.actor_peer_resolver is None:- return get_actor_peer_id()- actor_peer_id = self.actor_peer_resolver(state, runtime)- if actor_peer_id is None:- return None- if not isinstance(actor_peer_id, str):- raise TypeError("OpenViking actor_peer_resolver must return a string or None")- normalized = actor_peer_id.strip()- if not normalized:- raise ValueError("OpenViking actor_peer_resolver must not return an empty string")- return normalized-- def _actor_peer_scope(- self,- actor_peer_id: str | None,- ) -> AbstractContextManager[None]:- if self.actor_peer_resolver is None:- return nullcontext()- return use_actor_peer(actor_peer_id)---def _nested_get(value: Any, *keys: str) -> Any:- current = value- for key in keys:- if current is None:- return None- if isinstance(current, dict):- current = current.get(key)- else:- current = getattr(current, key, None)- return current---def _normalize_session_id(value: Any) -> str | None:- if value is None:- return None- text = str(value).strip()- return text or None---def _normalize_peer_id(value: Any) -> str | None:- if value is None:- return None- text = str(value).strip()- return text or None---def _capture_key(- session_id: str,- peer_id: str | None,- actor_peer_id: str | None,-) -> _CaptureKey:- if actor_peer_id is None:- return (session_id, peer_id or "")- return (actor_peer_id, session_id, peer_id or "")---def _validate_actor_peer_transport(- *,- actor_peer_resolver: _ActorPeerResolver | None,- client: Any,- async_client: Any,- retriever: OpenVikingRetriever | None,- path: str | None,-) -> None:- if actor_peer_resolver is None:- return- require_request_actor_peer_support()- if path is not None or (retriever is not None and retriever.path is not None):- raise ValueError("actor_peer_resolver requires an OpenViking HTTP connection")- transports = [client, async_client]- if retriever is not None:- transports.extend([retriever.client, retriever.async_client])- for transport in transports:- if transport is not None and not getattr(- transport,- "supports_request_actor_peer",- False,- ):- raise ValueError(- "actor_peer_resolver requires OpenViking HTTP clients that support "- "request-scoped actor peers"- )---def _message_role(message: Any) -> str:- if isinstance(message, HumanMessage):- return "user"- if isinstance(message, AIMessage):- return "assistant"- if isinstance(message, BaseMessage):- if message.type == "human":- return "user"- if message.type == "ai":- return "assistant"- return message.type- if isinstance(message, dict):- role = str(message.get("role") or message.get("type") or "")- return {"human": "user", "ai": "assistant"}.get(role, role)- return str(getattr(message, "role", "") or getattr(message, "type", ""))---def _message_content(message: Any) -> str:- if isinstance(message, dict):- return extract_message_text(message.get("content"))- return extract_message_text(getattr(message, "content", ""))---def _message_stable_id(message: Any) -> str | None:- if isinstance(message, dict):- value = message.get("id")- else:- value = getattr(message, "id", None)- return str(value) if value else None---def _message_signature(message: Any) -> str:- return _stable_json(- {- "id": _message_stable_id(message),- "role": _message_role(message),- "content": _message_content(message),- "tool_calls": _message_tool_calls(message),- "tool_result": _message_tool_result(message),- }- )---def _message_tool_calls(message: Any) -> Any:- if isinstance(message, AIMessage):- calls = getattr(message, "tool_calls", None) or []- if not calls:- calls = (getattr(message, "additional_kwargs", {}) or {}).get("tool_calls") or []- return calls- if isinstance(message, dict):- return message.get("tool_calls") or []- return getattr(message, "tool_calls", None) or []---def _message_tool_result(message: Any) -> dict[str, Any]:- if isinstance(message, ToolMessage):- return {- "tool_call_id": getattr(message, "tool_call_id", None),- "name": getattr(message, "name", None),- "status": getattr(message, "status", None),- }- if isinstance(message, dict):- return {- "tool_call_id": message.get("tool_call_id") or message.get("tool_id"),- "name": message.get("name") or message.get("tool_name"),- "output": message.get("tool_output") or message.get("output"),- "status": message.get("status") or message.get("tool_status"),- }- return {- "tool_call_id": getattr(message, "tool_call_id", None),- "name": getattr(message, "name", None),- "status": getattr(message, "status", None),- }---def _stable_json(value: Any) -> str:- return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)+_forward_legacy_module("middleware", globals())diff --git a/openviking/integrations/langchain/recording.py b/openviking/integrations/langchain/recording.pyindex 90083159a..6167d0718 100644--- a/openviking/integrations/langchain/recording.py+++ b/openviking/integrations/langchain/recording.py@@ -1,697 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Reusable OpenViking session recording for LangChain messages."""+"""Compatibility wrapper for :mod:`langchain_openviking.recording`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-import asyncio-import threading-from collections.abc import Iterable, Sequence-from copy import deepcopy-from dataclasses import dataclass-from typing import Any, Literal--try:- from langchain_core.messages import BaseMessage-except ImportError as exc: # pragma: no cover - exercised by optional import path- from openviking.integrations.langchain.client import missing_dependency-- raise missing_dependency("langchain", "langchain-core") from exc--from openviking.integrations.langchain.client import (- OpenVikingCommitPolicy,- OpenVikingConnection,- aapply_commit_policy,- acall_openviking,- aclose_openviking_clients,- apply_commit_policy,- call_openviking,- ensure_async_client,- ensure_client,- item_value,-)-from openviking.integrations.langchain.messages import (- is_context_carrier_langchain_message,- is_recordable_langchain_message,- langchain_message_to_openviking,-)-from openviking.utils.async_client_cache import LoopScopedAsyncClientCache--MAX_RECORDING_BATCH_SIZE = 100---@dataclass(frozen=True, slots=True)-class OpenVikingRecordResult:- """Confirmed progress from a recorder call."""-- messages_written: int = 0- input_messages_consumed: int = 0- context_attached: bool = False---class OpenVikingPartialWriteError(RuntimeError):- """Report confirmed progress when recording cannot finish."""-- def __init__(- self,- *,- session_id: str,- result: OpenVikingRecordResult,- cause: Exception,- stage: Literal["batch", "commit"] = "batch",- ):- if stage == "batch":- detail = "before a later batch failed"- else:- detail = "before the commit policy failed"- super().__init__(- f"OpenViking recorded {result.messages_written} messages for session "- f"{session_id!r} {detail}: {cause}"- )- self.session_id = session_id- self.result = result- self.stage = stage-- @property- def messages_written(self) -> int:- """Return the number of payloads confirmed written before failure."""-- return self.result.messages_written-- @property- def input_messages_consumed(self) -> int:- """Return the caller-message prefix that is safe to skip on retry."""-- return self.result.input_messages_consumed-- @property- def context_attached(self) -> bool:- """Return whether recalled context was confirmed persisted."""-- return self.result.context_attached-- @property- def commit_pending(self) -> bool:- """Return whether only the post-write commit remains incomplete."""-- return self.stage == "commit"---@dataclass(frozen=True, slots=True)-class OpenVikingCancellationProgress:- """Confirmed recording progress attached to an original cancellation."""-- session_id: str- result: OpenVikingRecordResult- stage: Literal["batch", "commit"] = "batch"-- @property- def messages_written(self) -> int:- """Return the number of payloads confirmed written before cancellation."""-- return self.result.messages_written-- @property- def input_messages_consumed(self) -> int:- """Return the caller-message prefix that is safe to skip on retry."""-- return self.result.input_messages_consumed-- @property- def context_attached(self) -> bool:- """Return whether recalled context was confirmed persisted."""-- return self.result.context_attached-- @property- def commit_pending(self) -> bool:- """Return whether only the post-write commit remains incomplete."""-- return self.stage == "commit"---_CANCELLATION_PROGRESS_ATTRIBUTE = "_openviking_recording_progress"---def get_openviking_cancellation_progress(- error: BaseException,-) -> OpenVikingCancellationProgress | None:- """Return recording progress from a cancellation or a timeout wrapping it."""-- current: BaseException | None = error- seen: set[int] = set()- while current is not None and id(current) not in seen:- seen.add(id(current))- progress = getattr(current, _CANCELLATION_PROGRESS_ATTRIBUTE, None)- if isinstance(progress, OpenVikingCancellationProgress):- return progress- current = current.__cause__ or current.__context__- return None---def _attach_cancellation_progress(- error: asyncio.CancelledError,- *,- session_id: str,- result: OpenVikingRecordResult,- stage: Literal["batch", "commit"] = "batch",-) -> None:- """Annotate the original cancellation without changing its identity."""-- setattr(- error,- _CANCELLATION_PROGRESS_ATTRIBUTE,- OpenVikingCancellationProgress(- session_id=session_id,- result=result,- stage=stage,- ),- )---@dataclass(slots=True)-class _PreparedMessage:- input_end: int- payloads: list[dict[str, Any]]- context_attached: bool = False---@dataclass(slots=True)-class _PreparedBatch:- input_end: int- payloads: list[dict[str, Any]]- context_attached: bool = False---class OpenVikingSessionRecorder:- """Persist caller-selected LangChain messages to OpenViking sessions.-- The recorder intentionally does not decide which messages form a turn or- deduplicate transcript snapshots. Callers own that policy and pass only the- messages they want persisted.- """-- def __init__(- self,- *,- client: Any = None,- async_client: Any = None,- url: str | None = None,- api_key: str | None = None,- account: str | None = None,- user: str | None = None,- user_id: str | None = None,- actor_peer_id: str | None = None,- path: str | None = None,- timeout: float = 60.0,- extra_headers: dict[str, str] | None = None,- auto_initialize: bool = True,- commit_policy: OpenVikingCommitPolicy | None = None,- batch_size: int = MAX_RECORDING_BATCH_SIZE,- ):- if batch_size <= 0 or batch_size > MAX_RECORDING_BATCH_SIZE:- raise ValueError(f"batch_size must be between 1 and {MAX_RECORDING_BATCH_SIZE}")- self._connection = OpenVikingConnection(- client=client,- async_client=async_client,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- timeout=timeout,- extra_headers=extra_headers,- auto_initialize=auto_initialize,- )- self._owns_client = client is None- self._client_cache: Any = None- self._client_cache_lock = threading.Lock()- self._async_clients = LoopScopedAsyncClientCache()- self._pending_commit_sessions: set[str] = set()- self._pending_commit_lock = threading.Lock()- self._closed = False- self.commit_policy = commit_policy- self.batch_size = batch_size-- def __deepcopy__(- self,- memo: dict[int, Any] | None = None,- ) -> OpenVikingSessionRecorder:- """Copy configuration and logical state with fresh runtime resources."""-- memo = {} if memo is None else memo- for client in (self._connection.client, self._connection.async_client):- if client is not None:- memo[id(client)] = client- with self._pending_commit_lock:- pending_commit_sessions = set(self._pending_commit_sessions)-- copied = type(self).__new__(type(self))- memo[id(self)] = copied- copied.__dict__ = {- name: (- None- if name == "_client_cache"- else threading.Lock()- if name in {"_client_cache_lock", "_pending_commit_lock"}- else LoopScopedAsyncClientCache()- if name == "_async_clients"- else pending_commit_sessions- if name == "_pending_commit_sessions"- else deepcopy(value, memo)- )- for name, value in self.__dict__.items()- }- return copied-- @property- def client(self) -> Any:- """Return the lazily initialized OpenViking client used by this recorder."""-- self._raise_if_closed()- if self._client_cache is None:- with self._client_cache_lock:- self._raise_if_closed()- if self._client_cache is None:- self._client_cache = ensure_client(self._connection)- client = self._client_cache- self._raise_if_closed()- return client-- def record(- self,- session_id: str,- messages: Iterable[BaseMessage],- peer_id: str | None = None,- context_parts: Sequence[dict[str, Any]] = (),- ) -> OpenVikingRecordResult:- """Persist a caller-selected batch and apply the configured commit policy."""-- self._raise_if_closed()- self._retry_pending_commit(session_id)- input_messages = list(messages)- prepared_messages = _prepare_messages(- input_messages,- peer_id=peer_id,- context_parts=context_parts,- )- if not prepared_messages:- return OpenVikingRecordResult(input_messages_consumed=len(input_messages))-- batches = _prepare_batches(prepared_messages, batch_size=self.batch_size)- client = self.client- messages_written = 0- input_messages_consumed = 0- context_attached = False- persisted_pending_tokens: Any = None- for batch in batches:- try:- write_result = call_openviking(- client,- "batch_add_messages",- session_id=session_id,- messages=batch.payloads,- )- except Exception as exc:- if messages_written == 0:- raise- result = OpenVikingRecordResult(- messages_written=messages_written,- input_messages_consumed=input_messages_consumed,- context_attached=context_attached,- )- raise OpenVikingPartialWriteError(- session_id=session_id,- result=result,- cause=exc,- ) from exc- messages_written += len(batch.payloads)- input_messages_consumed = batch.input_end- context_attached = context_attached or batch.context_attached- if isinstance(write_result, dict) and "pending_tokens" in write_result:- persisted_pending_tokens = write_result.get("pending_tokens")- else:- hint = item_value(write_result, "pending_tokens")- if hint is not None:- persisted_pending_tokens = hint- result = OpenVikingRecordResult(- messages_written=messages_written,- input_messages_consumed=len(input_messages),- context_attached=context_attached,- )- try:- apply_commit_policy(- client,- session_id,- self.commit_policy,- persisted_pending_tokens=persisted_pending_tokens,- )- except Exception as exc:- self._mark_commit_pending(session_id)- raise OpenVikingPartialWriteError(- session_id=session_id,- result=result,- cause=exc,- stage="commit",- ) from exc- return result-- async def arecord(- self,- session_id: str,- messages: Iterable[BaseMessage],- peer_id: str | None = None,- context_parts: Sequence[dict[str, Any]] = (),- ) -> OpenVikingRecordResult:- """Asynchronously persist messages and apply the configured commit policy."""-- self._raise_if_closed()- await self._aretry_pending_commit(session_id)- input_messages = list(messages)- prepared_messages = _prepare_messages(- input_messages,- peer_id=peer_id,- context_parts=context_parts,- )- if not prepared_messages:- return OpenVikingRecordResult(input_messages_consumed=len(input_messages))-- batches = _prepare_batches(prepared_messages, batch_size=self.batch_size)- client = await self.get_async_client()- messages_written = 0- input_messages_consumed = 0- context_attached = False- persisted_pending_tokens: Any = None- for batch in batches:- try:- write_result = await acall_openviking(- client,- "batch_add_messages",- session_id=session_id,- messages=batch.payloads,- )- except asyncio.CancelledError as exc:- if messages_written == 0:- raise- result = OpenVikingRecordResult(- messages_written=messages_written,- input_messages_consumed=input_messages_consumed,- context_attached=context_attached,- )- _attach_cancellation_progress(- exc,- session_id=session_id,- result=result,- )- raise- except Exception as exc:- if messages_written == 0:- raise- result = OpenVikingRecordResult(- messages_written=messages_written,- input_messages_consumed=input_messages_consumed,- context_attached=context_attached,- )- raise OpenVikingPartialWriteError(- session_id=session_id,- result=result,- cause=exc,- ) from exc- messages_written += len(batch.payloads)- input_messages_consumed = batch.input_end- context_attached = context_attached or batch.context_attached- if isinstance(write_result, dict) and "pending_tokens" in write_result:- persisted_pending_tokens = write_result.get("pending_tokens")- else:- hint = item_value(write_result, "pending_tokens")- if hint is not None:- persisted_pending_tokens = hint- result = OpenVikingRecordResult(- messages_written=messages_written,- input_messages_consumed=len(input_messages),- context_attached=context_attached,- )- try:- await aapply_commit_policy(- client,- session_id,- self.commit_policy,- persisted_pending_tokens=persisted_pending_tokens,- )- except asyncio.CancelledError as exc:- self._mark_commit_pending(session_id)- _attach_cancellation_progress(- exc,- session_id=session_id,- result=result,- stage="commit",- )- raise- except Exception as exc:- self._mark_commit_pending(session_id)- raise OpenVikingPartialWriteError(- session_id=session_id,- result=result,- cause=exc,- stage="commit",- ) from exc- return result-- def flush(self, session_id: str) -> dict[str, Any] | None:- """Commit a session only when it contains pending, uncommitted content."""-- result = self._flush_pending_content(session_id)- self._discard_pending_commit(session_id)- return result-- async def aflush(self, session_id: str) -> dict[str, Any] | None:- """Asynchronously commit pending, uncommitted session content."""-- result = await self._aflush_pending_content(session_id)- self._discard_pending_commit(session_id)- return result-- def _flush_pending_content(self, session_id: str) -> dict[str, Any] | None:- client = self.client- try:- session = call_openviking(- client,- "get_session",- session_id=session_id,- auto_create=False,- )- except Exception as exc:- error_code = str(getattr(exc, "code", "")).upper()- if isinstance(exc, FileNotFoundError) or error_code == "NOT_FOUND":- return None- raise- if int(item_value(session, "pending_tokens", 0) or 0) <= 0:- return None- return call_openviking(client, "commit_session", session_id=session_id)-- async def _aflush_pending_content(self, session_id: str) -> dict[str, Any] | None:- client = await self.get_async_client()- try:- session = await acall_openviking(- client,- "get_session",- session_id=session_id,- auto_create=False,- )- except Exception as exc:- error_code = str(getattr(exc, "code", "")).upper()- if isinstance(exc, FileNotFoundError) or error_code == "NOT_FOUND":- return None- raise- if int(item_value(session, "pending_tokens", 0) or 0) <= 0:- return None- return await acall_openviking(client, "commit_session", session_id=session_id)-- def _retry_pending_commit(self, session_id: str) -> None:- if not self._is_commit_pending(session_id):- return- self._flush_pending_content(session_id)- self._discard_pending_commit(session_id)-- async def _aretry_pending_commit(self, session_id: str) -> None:- if not self._is_commit_pending(session_id):- return- await self._aflush_pending_content(session_id)- self._discard_pending_commit(session_id)-- def _is_commit_pending(self, session_id: str) -> bool:- with self._pending_commit_lock:- return session_id in self._pending_commit_sessions-- def _mark_commit_pending(self, session_id: str) -> None:- with self._pending_commit_lock:- self._pending_commit_sessions.add(session_id)-- def _discard_pending_commit(self, session_id: str) -> None:- with self._pending_commit_lock:- self._pending_commit_sessions.discard(session_id)-- def _clear_pending_commits(self) -> None:- with self._pending_commit_lock:- self._pending_commit_sessions.clear()-- async def get_async_client(self) -> Any:- """Return the async client interface used by this recorder.-- Injected clients are returned unchanged and remain caller-owned.- HTTP-backed connections return an internally managed, loop-local handle- whose method calls support recovery. Direct attributes on that handle- are best-effort during recovery; use ``await handle.get()`` only to read- raw properties immediately because recovery may replace that snapshot.- Embedded ``path=`` connections return an adapter-owned synchronous- client whose calls are dispatched through a worker thread.- """-- self._raise_if_closed()- client = await ensure_async_client(- self._connection,- client_cache=self._async_clients,- embedded_client_factory=lambda: self.client,- )- self._raise_if_closed()- return client-- async def _get_async_client(self) -> Any:- return await self.get_async_client()-- def close(self) -> None:- """Release resources after exclusively synchronous use.-- Injected clients remain owned by their caller and are never closed here.- After any async operation has initialized an owned client, callers must- use :meth:`aclose`; this method leaves the recorder open so that async- cleanup can still complete.- """-- if self._closed:- return- uses_http_client = bool(self._connection.url) or self._connection.path is None- if uses_http_client and self._async_clients.has_clients():- raise RuntimeError(- "OpenVikingSessionRecorder has an active async client; "- "use `await recorder.aclose()`"- )- if not uses_http_client:- self._async_clients.pop_all()- self._closed = True- self._clear_pending_commits()- with self._client_cache_lock:- client = self._client_cache- self._client_cache = None- if client is None or not self._owns_client:- return- close = getattr(client, "close", None)- if callable(close):- close()-- async def aclose(self) -> None:- """Release internally created sync and async clients."""-- if self._closed:- return- self._closed = True- self._clear_pending_commits()- with self._client_cache_lock:- sync_client = self._client_cache- self._client_cache = None- async_clients = await asyncio.to_thread(self._async_clients.pop_all)-- await aclose_openviking_clients(- sync_client if self._owns_client else None,- *async_clients,- )-- def _raise_if_closed(self) -> None:- if self._closed:- raise RuntimeError("OpenVikingSessionRecorder is closed")---def _prepare_messages(- messages: Sequence[BaseMessage],- *,- peer_id: str | None,- context_parts: Sequence[dict[str, Any]],-) -> list[_PreparedMessage]:- normalized_peer_id = _normalize_peer_id(peer_id)- pending_context = deepcopy(list(context_parts))- prepared_messages: list[_PreparedMessage] = []-- for index, message in enumerate(messages):- context_carrier = is_context_carrier_langchain_message(message)- recordable = is_recordable_langchain_message(message)- if not recordable and not (pending_context and context_carrier):- continue- payloads = langchain_message_to_openviking(message)- message_context_attached = False- for payload in payloads:- if pending_context and context_carrier and payload["role"] == "assistant":- payload["parts"].extend(pending_context)- pending_context = []- message_context_attached = True- if normalized_peer_id is not None:- payload["peer_id"] = normalized_peer_id- if payloads:- prepared_messages.append(- _PreparedMessage(- input_end=index + 1,- payloads=payloads,- context_attached=message_context_attached,- )- )- return prepared_messages---def _prepare_batches(- messages: Sequence[_PreparedMessage],- *,- batch_size: int,-) -> list[_PreparedBatch]:- batches: list[_PreparedBatch] = []- payloads: list[dict[str, Any]] = []- input_end = 0- context_attached = False-- for message in messages:- payload_count = len(message.payloads)- if payload_count > batch_size:- raise ValueError(- "one LangChain message produced more OpenViking payloads "- f"({payload_count}) than batch_size ({batch_size})"- )- if payloads and len(payloads) + payload_count > batch_size:- batches.append(- _PreparedBatch(- input_end=input_end,- payloads=payloads,- context_attached=context_attached,- )- )- payloads = []- context_attached = False- payloads.extend(message.payloads)- input_end = message.input_end- context_attached = context_attached or message.context_attached-- if payloads:- batches.append(- _PreparedBatch(- input_end=input_end,- payloads=payloads,- context_attached=context_attached,- )- )- return batches---def _normalize_peer_id(peer_id: str | None) -> str | None:- if peer_id is None:- return None- text = str(peer_id).strip()- return text or None+_forward_legacy_module("recording", globals())diff --git a/openviking/integrations/langchain/retrievers.py b/openviking/integrations/langchain/retrievers.pyindex 572696246..6edea1341 100644--- a/openviking/integrations/langchain/retrievers.py+++ b/openviking/integrations/langchain/retrievers.py@@ -1,309 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""LangChain retriever backed by OpenViking retrieval."""+"""Compatibility wrapper for :mod:`langchain_openviking.retrievers`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-import asyncio-import threading-from typing import Any, Literal--from pydantic import ConfigDict, Field, PrivateAttr--try:- from langchain_core.documents import Document- from langchain_core.retrievers import BaseRetriever-except ImportError as exc: # pragma: no cover - exercised by optional import path- from openviking.integrations.langchain.client import missing_dependency-- raise missing_dependency("langchain", "langchain-core") from exc--from openviking.integrations.langchain.client import (- OpenVikingConnection,- acall_openviking,- aclose_openviking_clients,- call_openviking,- ensure_async_client,- ensure_client,- item_value,- iter_result_items,- stringify,-)-from openviking.utils.async_client_cache import LoopScopedAsyncClientCache---class _SharedSyncClientCache:- """Share one lazily created sync client across shallow retriever copies."""-- def __init__(self) -> None:- self._client: Any = None- self._owned = False- self._lock = threading.Lock()-- def __deepcopy__(self, memo: dict[int, Any]) -> _SharedSyncClientCache:- copied = type(self)()- memo[id(self)] = copied- return copied-- def get(self, factory: Any, *, owned: bool) -> Any:- with self._lock:- if self._client is None:- self._client = factory()- self._owned = owned- return self._client-- def pop_owned(self) -> Any:- with self._lock:- client = self._client- owned = self._owned- self._client = None- self._owned = False- return client if owned else None---class OpenVikingRetriever(BaseRetriever):- """Retrieve LangChain ``Document`` objects from OpenViking contexts."""-- model_config = ConfigDict(arbitrary_types_allowed=True)-- client: Any = None- async_client: Any = None- url: str | None = None- api_key: str | None = None- account: str | None = None- user: str | None = None- user_id: str | None = None- actor_peer_id: str | None = None- path: str | None = None- timeout: float = 60.0- extra_headers: dict[str, str] | None = None- auto_initialize: bool = True-- target_uri: str | list[str] = ""- search_mode: Literal["find", "search"] = "find"- session_id: str | None = None- limit: int = 10- score_threshold: float | None = None- filter: dict[str, Any] | None = None- context_types: tuple[str, ...] = ("memory", "resource", "skill")- content_mode: Literal["auto", "abstract", "overview", "read"] = "auto"- max_content_chars: int = 12_000- metadata_prefix: str = "openviking"- tags: list[str] | None = Field(default=None, exclude=True)-- _sync_client_cache: _SharedSyncClientCache = PrivateAttr(default_factory=_SharedSyncClientCache)- _async_clients: LoopScopedAsyncClientCache = PrivateAttr(- default_factory=LoopScopedAsyncClientCache- )- _closed: bool = PrivateAttr(default=False)-- def __deepcopy__(- self,- memo: dict[int, Any] | None = None,- ) -> OpenVikingRetriever:- """Copy configuration without cloning clients or cached runtime state."""-- memo = {} if memo is None else memo- for client in (self.client, self.async_client):- if client is not None:- memo[id(client)] = client-- sync_client_cache = getattr(self, "_client_cache", None)- if getattr(self, "_owns_client_cache", False) and sync_client_cache is not None:- memo[id(sync_client_cache)] = None-- copied = super().__deepcopy__(memo)- private_attributes = getattr(type(copied), "__private_attributes__", {})- private_state = copied.__pydantic_private__- if private_state is not None and "_client_cache" in private_attributes:- private_state["_client_cache"] = None- private_state["_owns_client_cache"] = False- return copied-- def _get_client(self) -> Any:- self._raise_if_closed()- return self._sync_client_cache.get(- lambda: ensure_client(- OpenVikingConnection(- client=self.client,- url=self.url,- api_key=self.api_key,- account=self.account,- user=self.user,- user_id=self.user_id,- actor_peer_id=self.actor_peer_id,- path=self.path,- timeout=self.timeout,- extra_headers=self.extra_headers,- auto_initialize=self.auto_initialize,- )- ),- owned=self.client is None,- )-- async def get_async_client(self) -> Any:- """Return the async client interface used by this retriever.-- Injected clients are returned unchanged and remain caller-owned.- HTTP-backed connections return an internally managed, loop-local handle- whose method calls support recovery. Direct attributes on that handle- are best-effort during recovery; use ``await handle.get()`` only to read- raw properties immediately because recovery may replace that snapshot.- Embedded ``path=`` connections return an adapter-owned synchronous- client whose calls are dispatched through a worker thread.- """-- self._raise_if_closed()- client = await ensure_async_client(- OpenVikingConnection(- client=self.client,- async_client=self.async_client,- url=self.url,- api_key=self.api_key,- account=self.account,- user=self.user,- user_id=self.user_id,- actor_peer_id=self.actor_peer_id,- path=self.path,- timeout=self.timeout,- extra_headers=self.extra_headers,- auto_initialize=self.auto_initialize,- ),- client_cache=self._async_clients,- embedded_client_factory=self._get_client,- )- self._raise_if_closed()- return client-- async def _get_async_client(self) -> Any:- return await self.get_async_client()-- async def aclose(self) -> None:- """Release clients created internally by this retriever."""-- if self._closed:- return- self._closed = True- sync_client = self._sync_client_cache.pop_owned()- async_clients = await asyncio.to_thread(self._async_clients.pop_all)-- await aclose_openviking_clients(- sync_client,- *async_clients,- )-- def _raise_if_closed(self) -> None:- if self._closed:- raise RuntimeError("OpenVikingRetriever is closed")-- def _get_relevant_documents(self, query: str, *, run_manager: Any) -> list[Document]:- client = self._get_client()- method = "search" if self.search_mode == "search" else "find"- result = call_openviking(- client,- method,- query=query,- target_uri=self.target_uri,- session_id=self.session_id,- limit=self.limit,- score_threshold=self.score_threshold,- filter=self.filter,- tags=self.tags,- )- documents: list[Document] = []- for context_type, item in iter_result_items(result, self.context_types):- content = self._content_for_item(client, item)- documents.append(self._document_from_item(context_type, item, content))- return documents-- async def _aget_relevant_documents(self, query: str, *, run_manager: Any) -> list[Document]:- client = await self._get_async_client()- method = "search" if self.search_mode == "search" else "find"- result = await acall_openviking(- client,- method,- query=query,- target_uri=self.target_uri,- session_id=self.session_id,- limit=self.limit,- score_threshold=self.score_threshold,- filter=self.filter,- tags=self.tags,- )- documents: list[Document] = []- for context_type, item in iter_result_items(result, self.context_types):- content = await self._acontent_for_item(client, item)- documents.append(self._document_from_item(context_type, item, content))- return documents-- def _document_from_item(- self,- context_type: str,- item: Any,- content: str,- ) -> Document:- uri = item_value(item, "uri", "")- return Document(- page_content=content,- metadata={- "source": uri,- f"{self.metadata_prefix}_uri": uri,- f"{self.metadata_prefix}_context_type": context_type,- f"{self.metadata_prefix}_level": item_value(item, "level"),- f"{self.metadata_prefix}_category": item_value(item, "category"),- f"{self.metadata_prefix}_score": item_value(item, "score"),- f"{self.metadata_prefix}_match_reason": item_value(item, "match_reason"),- f"{self.metadata_prefix}_abstract": item_value(item, "abstract"),- f"{self.metadata_prefix}_overview": item_value(item, "overview"),- },- )-- def _content_for_item(self, client: Any, item: Any) -> str:- uri = item_value(item, "uri", "")- abstract = item_value(item, "abstract", "")- overview = item_value(item, "overview", "")- level = item_value(item, "level")-- if self.content_mode == "abstract":- return stringify(abstract or overview, max_chars=self.max_content_chars)- if self.content_mode == "overview":- return stringify(overview or abstract, max_chars=self.max_content_chars)- if self.content_mode == "read":- return self._read_or_fallback(client, uri, overview or abstract)- if level == 2 and uri:- return self._read_or_fallback(client, uri, overview or abstract)- return stringify(overview or abstract, max_chars=self.max_content_chars)-- async def _acontent_for_item(self, client: Any, item: Any) -> str:- uri = item_value(item, "uri", "")- abstract = item_value(item, "abstract", "")- overview = item_value(item, "overview", "")- level = item_value(item, "level")-- if self.content_mode == "abstract":- return stringify(abstract or overview, max_chars=self.max_content_chars)- if self.content_mode == "overview":- return stringify(overview or abstract, max_chars=self.max_content_chars)- if self.content_mode == "read":- return await self._aread_or_fallback(client, uri, overview or abstract)- if level == 2 and uri:- return await self._aread_or_fallback(client, uri, overview or abstract)- return stringify(overview or abstract, max_chars=self.max_content_chars)-- def _read_or_fallback(self, client: Any, uri: str, fallback: Any) -> str:- if uri:- try:- content = call_openviking(client, "read", uri=uri)- return stringify(content, max_chars=self.max_content_chars)- except Exception:- pass- return stringify(fallback, max_chars=self.max_content_chars)-- async def _aread_or_fallback(self, client: Any, uri: str, fallback: Any) -> str:- if uri:- try:- content = await acall_openviking(client, "read", uri=uri)- return stringify(content, max_chars=self.max_content_chars)- except Exception:- pass- return stringify(fallback, max_chars=self.max_content_chars)+_forward_legacy_module("retrievers", globals())diff --git a/openviking/integrations/langchain/store.py b/openviking/integrations/langchain/store.pyindex ab80d012b..738318509 100644--- a/openviking/integrations/langchain/store.py+++ b/openviking/integrations/langchain/store.py@@ -1,589 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""LangGraph Store implementation backed by OpenViking."""+"""Compatibility wrapper for :mod:`langchain_openviking.store`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-import asyncio-import json-import logging-from datetime import datetime, timezone-from typing import Any, Iterable-from urllib.parse import quote, unquote--from openviking.core.namespace import UriClassification, classify_uri-from openviking.integrations.langchain.client import (- OpenVikingConnection,- call_openviking,- ensure_client,- item_value,- iter_result_items,-)--try:- from langgraph.store.base import (- BaseStore,- GetOp,- Item,- ListNamespacesOp,- PutOp,- SearchItem,- SearchOp,- )-except ImportError: # pragma: no cover - exercised by optional import path- from openviking.integrations.langchain.client import missing_dependency-- _LANGGRAPH_IMPORT_ERROR = missing_dependency("langgraph", "langgraph")- BaseStore = object # type: ignore[assignment,misc]- GetOp = PutOp = SearchOp = ListNamespacesOp = object # type: ignore[misc,assignment]- Item = SearchItem = object # type: ignore[misc,assignment]-else:- _LANGGRAPH_IMPORT_ERROR = None--logger = logging.getLogger(__name__)---class OpenVikingStore(BaseStore):- """LangGraph ``BaseStore`` persisted and indexed through OpenViking.-- Values are stored as JSON records under ``<root_uri>/data``. A separate- markdown projection under ``<root_uri>/index`` gives OpenViking semantic- retrieval a compact document to index for query-based ``search`` calls.- """-- def __init__(- self,- *,- client: Any = None,- url: str | None = None,- api_key: str | None = None,- account: str | None = None,- user: str | None = None,- user_id: str | None = None,- actor_peer_id: str | None = None,- path: str | None = None,- root_uri: str = "viking://user/memories/langgraph_store",- index: bool | list[str] | None = None,- wait: bool = True,- timeout: float | None = None,- search_fetch_limit: int = 50,- auto_initialize: bool = True,- ):- if _LANGGRAPH_IMPORT_ERROR is not None:- raise _LANGGRAPH_IMPORT_ERROR- super().__init__()- self._connection = OpenVikingConnection(- client=client,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- auto_initialize=auto_initialize,- )- self.root_uri = root_uri.rstrip("/")- self.index = index- self.wait = wait- self.timeout = timeout- self.search_fetch_limit = search_fetch_limit- self._client_cache: Any = None-- def batch(self, ops: Iterable[Any]) -> list[Any]:- results: list[Any] = []- for op in ops:- if isinstance(op, GetOp):- results.append(self.get(op.namespace, op.key))- elif isinstance(op, PutOp):- if op.value is None:- self.delete(op.namespace, op.key)- else:- self.put(op.namespace, op.key, op.value, index=op.index, ttl=op.ttl)- results.append(None)- elif isinstance(op, SearchOp):- results.append(- self.search(- op.namespace_prefix,- query=op.query,- filter=op.filter,- limit=op.limit,- offset=op.offset,- )- )- elif isinstance(op, ListNamespacesOp):- prefix, suffix = self._match_conditions_to_prefix_suffix(op.match_conditions)- results.append(- self.list_namespaces(- prefix=prefix,- suffix=suffix,- max_depth=op.max_depth,- limit=op.limit,- offset=op.offset,- )- )- else:- raise TypeError(f"Unsupported LangGraph store operation: {type(op)!r}")- return results-- async def abatch(self, ops: Iterable[Any]) -> list[Any]:- return await asyncio.to_thread(lambda: self.batch(list(ops)))-- def get(self, namespace: tuple[str, ...], key: str, *, refresh_ttl: Any = None) -> Any:- try:- record = self._read_record(self._data_uri(namespace, key))- except Exception:- return None- return Item(- namespace=tuple(record["namespace"]),- key=record["key"],- value=record["value"],- created_at=_parse_dt(record["created_at"]),- updated_at=_parse_dt(record["updated_at"]),- )-- def put(- self,- namespace: tuple[str, ...],- key: str,- value: dict[str, Any],- index: bool | list[str] | None = None,- *,- ttl: Any = None,- ) -> None:- if ttl is not None:- raise NotImplementedError(- "TTL is not supported by OpenVikingStore. "- "OpenViking stores LangGraph values as durable content records."- )- namespace = tuple(namespace)- now = datetime.now(timezone.utc)- data_uri = self._data_uri(namespace, key)- record = self._write_record(data_uri, namespace, key, value, now)-- effective_index = self.index if index is None else index- index_uri = self._index_uri(namespace, key)- if effective_index is False:- self._remove(index_uri)- return- self._write(index_uri, self._index_document(record, effective_index))-- def delete(self, namespace: tuple[str, ...], key: str) -> None:- self._remove(self._data_uri(namespace, key))- self._remove(self._index_uri(namespace, key))-- def search(- self,- namespace_prefix: tuple[str, ...],- *,- query: str | None = None,- filter: dict[str, Any] | None = None,- limit: int = 10,- offset: int = 0,- refresh_ttl: Any = None,- ) -> list[Any]:- namespace_prefix = tuple(namespace_prefix)- if query:- return self._semantic_search(namespace_prefix, query, filter, limit, offset)- items = [- self._item_to_search_item(item, score=None)- for item in self._list_items(namespace_prefix)- if _matches_filter(item.value, filter)- ]- items.sort(key=lambda item: (item.updated_at, item.namespace, item.key), reverse=True)- return items[offset : offset + limit]-- def list_namespaces(- self,- *,- prefix: tuple[str, ...] | None = None,- suffix: tuple[str, ...] | None = None,- max_depth: int | None = None,- limit: int = 100,- offset: int = 0,- ) -> list[tuple[str, ...]]:- namespaces = set()- for uri in self._all_data_uris(prefix or ()):- parsed = self._parse_data_uri(uri)- if parsed is None:- continue- namespace, _key = parsed- if prefix and not _tuple_matches_prefix(namespace, prefix):- continue- if suffix and not _tuple_matches_suffix(namespace, suffix):- continue- if max_depth is not None and len(namespace) > max_depth:- namespace = namespace[:max_depth]- namespaces.add(namespace)- ordered = sorted(namespaces)- return ordered[offset : offset + limit]-- def _semantic_search(- self,- namespace_prefix: tuple[str, ...],- query: str,- filter: dict[str, Any] | None,- limit: int,- offset: int,- ) -> list[Any]:- result = call_openviking(- self._client(),- "find",- query=query,- target_uri=self._index_prefix_uri(namespace_prefix),- limit=max(limit + offset, self.search_fetch_limit),- )- items: list[Any] = []- for _context_type, result_item in iter_result_items(- result, ("memory", "resource", "skill")- ):- uri = item_value(result_item, "uri", "")- parsed = self._parse_index_uri(uri)- if parsed is None:- continue- namespace, key = parsed- item = self.get(namespace, key)- if item is None or not _matches_filter(item.value, filter):- continue- items.append(self._item_to_search_item(item, score=item_value(result_item, "score")))- return items[offset : offset + limit]-- def _list_items(self, namespace_prefix: tuple[str, ...]) -> list[Any]:- items = []- for uri in self._all_data_uris(namespace_prefix):- parsed = self._parse_data_uri(uri)- if parsed is None:- continue- namespace, key = parsed- item = self.get(namespace, key)- if item is not None:- items.append(item)- return items-- def _all_data_uris(self, namespace_prefix: tuple[str, ...]) -> list[str]:- base_uri = self._data_prefix_uri(namespace_prefix)- uris: list[str] = []- seen: set[str] = set()- for pattern in ("*.json", "**/*.json"):- try:- result = call_openviking(self._client(), "glob", pattern=pattern, uri=base_uri)- except Exception:- continue- for uri in _extract_uris(result):- if uri not in seen:- seen.add(uri)- uris.append(uri)- return uris-- def _client(self) -> Any:- if self._client_cache is None:- self._client_cache = ensure_client(self._connection)- return self._client_cache-- def _read_record(self, uri: str) -> dict[str, Any]:- content = call_openviking(self._client(), "read", uri=uri)- if isinstance(content, bytes):- content = content.decode("utf-8")- return json.loads(str(content))-- def _write_record(- self,- uri: str,- namespace: tuple[str, ...],- key: str,- value: dict[str, Any],- now: datetime,- ) -> dict[str, Any]:- record = _store_record(namespace, key, value, created_at=now, updated_at=now)- content = json.dumps(record, ensure_ascii=False, indent=2)- try:- self._write_create(uri, content)- return record- except Exception as create_exc:- try:- existing = self._read_record(uri)- except Exception:- raise create_exc-- created_at = _parse_dt(existing["created_at"])- record = _store_record(namespace, key, value, created_at=created_at, updated_at=now)- self._write_replace(uri, json.dumps(record, ensure_ascii=False, indent=2))- return record-- def _write(self, uri: str, content: str) -> None:- try:- self._write_create(uri, content)- return- except Exception as create_exc:- try:- self._write_replace(uri, content)- return- except Exception:- raise create_exc-- def _write_create(self, uri: str, content: str) -> None:- call_openviking(- self._client(),- "write",- uri=uri,- content=content,- mode="create",- wait=self.wait,- timeout=self.timeout,- )-- def _write_replace(self, uri: str, content: str) -> None:- call_openviking(- self._client(),- "write",- uri=uri,- content=content,- mode="replace",- wait=self.wait,- timeout=self.timeout,- )-- def _remove(self, uri: str) -> None:- try:- call_openviking(self._client(), "rm", uri=uri, recursive=False)- except Exception:- logger.debug("OpenVikingStore remove ignored missing/unavailable URI", exc_info=True)- pass-- def _data_uri(self, namespace: tuple[str, ...], key: str) -> str:- return f"{self._data_prefix_uri(namespace)}/{_segment(key)}.json"-- def _index_uri(self, namespace: tuple[str, ...], key: str) -> str:- return f"{self._index_prefix_uri(namespace)}/{_segment(key)}.md"-- def _data_prefix_uri(self, namespace: tuple[str, ...]) -> str:- return _join_uri(self.root_uri, "data", *namespace)-- def _index_prefix_uri(self, namespace: tuple[str, ...]) -> str:- return _join_uri(self.root_uri, "index", *namespace)-- def _parse_data_uri(self, uri: str) -> tuple[tuple[str, ...], str] | None:- return self._parse_record_uri(uri, "data", ".json")-- def _parse_index_uri(self, uri: str) -> tuple[tuple[str, ...], str] | None:- return self._parse_record_uri(uri, "index", ".md")-- def _parse_record_uri(- self, uri: str, collection: str, suffix: str- ) -> tuple[tuple[str, ...], str] | None:- prefix = _join_uri(self.root_uri, collection) + "/"- if not uri.startswith(prefix) or not uri.endswith(suffix):- return _parse_canonicalized_record_uri(- root_uri=self.root_uri,- uri=uri,- collection=collection,- suffix=suffix,- )- return _parse_record_parts(uri[len(prefix) : -len(suffix)].split("/"))-- def _index_document(self, record: dict[str, Any], index: bool | list[str] | None) -> str:- value = record["value"]- projected = _project_value(value, index)- return "\n".join(- [- f"# {record['key']}",- "",- f"Namespace: {'/'.join(record['namespace'])}",- f"Key: {record['key']}",- "",- json.dumps(projected, ensure_ascii=False, indent=2),- ]- )-- def _item_to_search_item(self, item: Any, score: float | None) -> Any:- return SearchItem(- namespace=item.namespace,- key=item.key,- value=item.value,- created_at=item.created_at,- updated_at=item.updated_at,- score=score,- )-- def _match_conditions_to_prefix_suffix(- self, conditions: Iterable[Any] | None- ) -> tuple[tuple[str, ...] | None, tuple[str, ...] | None]:- prefix = None- suffix = None- for condition in conditions or []:- match_type = getattr(condition, "match_type", None)- path = tuple(getattr(condition, "path", ()) or ())- if match_type == "prefix":- prefix = path- elif match_type == "suffix":- suffix = path- return prefix, suffix---def _segment(value: str) -> str:- return quote(str(value), safe="")---def _join_uri(root: str, *segments: str) -> str:- suffix = "/".join(_segment(segment) for segment in segments if segment)- return root.rstrip("/") if not suffix else f"{root.rstrip('/')}/{suffix}"---def _parse_canonicalized_record_uri(- *,- root_uri: str,- uri: str,- collection: str,- suffix: str,-) -> tuple[tuple[str, ...], str] | None:- root = classify_uri(root_uri)- root_tail = _identity_relative_root_tail(root)- if root_tail is None:- return None-- candidate = classify_uri(uri)- if candidate.scope != root.scope or candidate.content_index is None:- return None-- candidate_tail = candidate.parts[candidate.content_index :]- if len(candidate_tail) < len(root_tail) + 2:- return None- if candidate_tail[: len(root_tail)] != root_tail:- return None-- collection_index = len(root_tail)- if candidate_tail[collection_index] != collection:- return None-- rel_parts = list(candidate_tail[collection_index + 1 :])- if not rel_parts or not rel_parts[-1].endswith(suffix):- return None- rel_parts = [*rel_parts[:-1], rel_parts[-1][: -len(suffix)]]- return _parse_record_parts(rel_parts)---def _identity_relative_root_tail(classification: UriClassification) -> tuple[str, ...] | None:- if classification.scope != "user":- return None- if classification.content_index != 1:- return None- return classification.parts[classification.content_index :]---def _parse_record_parts(parts: list[str]) -> tuple[tuple[str, ...], str] | None:- if not parts or not parts[-1]:- return None- namespace = tuple(unquote(part) for part in parts[:-1])- key = unquote(parts[-1])- return namespace, key---def _parse_dt(value: str) -> datetime:- parsed = datetime.fromisoformat(value)- if parsed.tzinfo is None:- return parsed.replace(tzinfo=timezone.utc)- return parsed---def _store_record(- namespace: tuple[str, ...],- key: str,- value: dict[str, Any],- *,- created_at: datetime,- updated_at: datetime,-) -> dict[str, Any]:- return {- "namespace": list(namespace),- "key": key,- "value": value,- "created_at": created_at.isoformat(),- "updated_at": updated_at.isoformat(),- }---def _extract_uris(value: Any) -> list[str]:- if value is None:- return []- if isinstance(value, str):- return [value] if value.startswith("viking://") else []- if isinstance(value, dict):- if isinstance(value.get("uri"), str):- return [value["uri"]]- uris: list[str] = []- for key in ("matches", "result", "files", "items"):- uris.extend(_extract_uris(value.get(key)))- return uris- if isinstance(value, list):- uris: list[str] = []- for item in value:- uris.extend(_extract_uris(item))- return uris- return []---def _project_value(value: dict[str, Any], index: bool | list[str] | None) -> dict[str, Any]:- if isinstance(index, list):- return {field: _nested_value(value, field) for field in index}- return value---def _nested_value(value: dict[str, Any], path: str) -> Any:- current: Any = value- for part in path.split("."):- if not isinstance(current, dict):- return None- current = current.get(part)- return current---def _matches_filter(value: dict[str, Any], filter: dict[str, Any] | None) -> bool:- if not filter:- return True- for path, expected in filter.items():- actual = _nested_value(value, path)- if isinstance(expected, dict):- for op, target in expected.items():- if not _compare(actual, op, target):- return False- elif actual != expected:- return False- return True---def _compare(actual: Any, op: str, target: Any) -> bool:- if op in {"$eq", "eq"}:- return actual == target- if op in {"$ne", "ne"}:- return actual != target- if op in {"$gt", "gt"}:- return _safe_ordered_compare(actual, target, lambda left, right: left > right)- if op in {"$gte", "gte"}:- return _safe_ordered_compare(actual, target, lambda left, right: left >= right)- if op in {"$lt", "lt"}:- return _safe_ordered_compare(actual, target, lambda left, right: left < right)- if op in {"$lte", "lte"}:- return _safe_ordered_compare(actual, target, lambda left, right: left <= right)- if op in {"$in", "in"}:- try:- return actual in target- except TypeError:- return False- return actual == target---def _safe_ordered_compare(actual: Any, target: Any, compare) -> bool:- if actual is None:- return False- try:- return bool(compare(actual, target))- except TypeError:- return False---def _tuple_matches_prefix(value: tuple[str, ...], prefix: tuple[str, ...]) -> bool:- return len(value) >= len(prefix) and value[: len(prefix)] == prefix---def _tuple_matches_suffix(value: tuple[str, ...], suffix: tuple[str, ...]) -> bool:- return len(value) >= len(suffix) and value[-len(suffix) :] == suffix+_forward_legacy_module("store", globals())diff --git a/openviking/integrations/langchain/testing.py b/openviking/integrations/langchain/testing.pyindex 3d93aba12..7360e8e09 100644--- a/openviking/integrations/langchain/testing.py+++ b/openviking/integrations/langchain/testing.py@@ -1,409 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Deterministic test utilities for framework smoke tests."""+"""Compatibility wrapper for :mod:`langchain_openviking.testing`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-import fnmatch-import re-import uuid-from collections import defaultdict-from datetime import datetime, timezone-from typing import Any--from openviking.core.peer_id import normalize_peer_id-from openviking.utils.token_estimation import estimate_text_tokens-from openviking_cli.exceptions import NotFoundError---class InMemoryOpenVikingClient:- """Small OpenViking-compatible client for examples and CI smoke tests.-- This class intentionally implements the OpenViking methods used by the- LangChain/LangGraph adapters. It is not a replacement for OpenViking.- """-- def __init__(self, records: dict[str, str] | None = None):- self.records: dict[str, str] = dict(records or {})- self.sessions: dict[str, list[dict[str, Any]]] = defaultdict(list)- self.archives: dict[str, list[dict[str, Any]]] = defaultdict(list)- self.pending_tokens: dict[str, int] = defaultdict(int)- self.find_calls: list[dict[str, Any]] = []- self.search_calls: list[dict[str, Any]] = []- self._initialized = False-- def initialize(self) -> None:- self._initialized = True-- def close(self) -> None:- self._initialized = False-- def find(- self,- query: str,- target_uri: str | list[str] = "",- limit: int = 10,- score_threshold: float | None = None,- filter: dict[str, Any] | None = None,- tags: list[str] | None = None,- **_: Any,- ) -> dict[str, Any]:- self.find_calls.append(- {- "query": query,- "target_uri": target_uri,- "limit": limit,- "score_threshold": score_threshold,- "filter": filter,- "tags": tags,- }- )- return self._search(query, target_uri, limit, score_threshold)-- def search(- self,- query: str,- target_uri: str | list[str] = "",- session_id: str | None = None,- limit: int = 10,- score_threshold: float | None = None,- filter: dict[str, Any] | None = None,- tags: list[str] | None = None,- **_: Any,- ) -> dict[str, Any]:- self.search_calls.append(- {- "query": query,- "target_uri": target_uri,- "session_id": session_id,- "limit": limit,- "score_threshold": score_threshold,- "filter": filter,- "tags": tags,- }- )- session_text = " ".join(- _message_text(message) for message in self.sessions.get(session_id or "", [])- )- return self._search(f"{query} {session_text}", target_uri, limit, score_threshold)-- def _search(- self,- query: str,- target_uri: str | list[str],- limit: int,- score_threshold: float | None,- ) -> dict[str, Any]:- targets = [target_uri] if isinstance(target_uri, str) else list(target_uri)- targets = [target.rstrip("/") for target in targets if target]- tokens = {token for token in re.findall(r"[a-z0-9_]+", query.lower()) if len(token) > 1}- scored: list[tuple[float, str, str]] = []- for uri, content in self.records.items():- if targets and not any(uri.startswith(target) for target in targets):- continue- haystack = f"{uri}\n{content}".lower()- score = sum(1 for token in tokens if token in haystack)- if score == 0 and tokens:- continue- normalized = float(score or 1)- if score_threshold is not None and normalized < score_threshold:- continue- scored.append((normalized, uri, content))- scored.sort(key=lambda row: (-row[0], row[1]))- result = {"memories": [], "resources": [], "skills": [], "total": 0}- for score, uri, content in scored[:limit]:- item = {- "uri": uri,- "level": 2,- "abstract": content[:240],- "overview": content,- "score": score,- "match_reason": "deterministic token match",- }- if "/skills/" in uri:- result["skills"].append(item)- elif "/memories/" in uri:- result["memories"].append(item)- else:- result["resources"].append(item)- result["total"] = sum(len(result[key]) for key in ("memories", "resources", "skills"))- return result-- def read(self, uri: str, offset: int = 0, limit: int = -1) -> str:- if uri not in self.records:- raise FileNotFoundError(uri)- lines = self.records[uri].splitlines()- if offset or limit >= 0:- end = None if limit < 0 else offset + limit- return "\n".join(lines[offset:end])- return self.records[uri]-- def abstract(self, uri: str) -> str:- return self.read(uri)[:240]-- def overview(self, uri: str) -> str:- return self.read(uri)-- def write(- self,- uri: str,- content: str,- mode: str = "replace",- wait: bool = False,- timeout: float | None = None,- **_: Any,- ) -> dict[str, Any]:- if mode == "create" and uri in self.records:- raise FileExistsError(uri)- if mode == "replace" and uri not in self.records:- raise FileNotFoundError(uri)- if mode == "append":- self.records[uri] = self.records.get(uri, "") + content- else:- self.records[uri] = content- return {"uri": uri, "mode": mode, "content_updated": True}-- def mkdir(self, uri: str, description: str | None = None) -> None:- return None-- def rm(self, uri: str, recursive: bool = False) -> None:- if recursive:- prefix = uri.rstrip("/") + "/"- for key in list(self.records):- if key == uri or key.startswith(prefix):- del self.records[key]- return- self.records.pop(uri, None)-- def ls(self, uri: str, simple: bool = False, recursive: bool = False, **_: Any) -> list[Any]:- prefix = uri.rstrip("/") + "/"- seen: set[str] = set()- values: list[Any] = []- for key in sorted(self.records):- if not key.startswith(prefix):- continue- rel = key[len(prefix) :]- if not recursive and "/" in rel:- rel = rel.split("/", 1)[0]- child_uri = prefix + rel- if child_uri in seen:- continue- seen.add(child_uri)- values.append(child_uri if simple else {"uri": child_uri, "rel_path": rel})- return values-- def glob(self, pattern: str, uri: str = "viking://") -> dict[str, Any]:- prefix = uri.rstrip("/") + "/"- matches = []- for key in sorted(self.records):- if not key.startswith(prefix):- continue- rel = key[len(prefix) :]- if fnmatch.fnmatch(rel, pattern):- matches.append(key)- return {"matches": matches, "count": len(matches)}-- def grep(- self,- uri: str,- pattern: str,- case_insensitive: bool = False,- node_limit: int | None = None,- **_: Any,- ) -> dict[str, Any]:- flags = re.IGNORECASE if case_insensitive else 0- regex = re.compile(pattern, flags)- prefix = uri.rstrip("/") + "/"- matches: list[dict[str, Any]] = []- for key, content in sorted(self.records.items()):- if key != uri and not key.startswith(prefix):- continue- for line_number, line in enumerate(content.splitlines(), start=1):- if regex.search(line):- matches.append({"uri": key, "line_number": line_number, "line": line})- if node_limit and len(matches) >= node_limit:- return {"matches": matches, "count": len(matches)}- return {"matches": matches, "count": len(matches)}-- def create_session(self, session_id: str | None = None) -> dict[str, Any]:- session_id = session_id or f"session-{uuid.uuid4().hex[:12]}"- self.sessions.setdefault(session_id, [])- return {"session_id": session_id, "uri": self._session_uri(session_id)}-- @staticmethod- def _session_uri(session_id: str) -> str:- return f"viking://user/default/sessions/{session_id}"-- def add_message(- self,- session_id: str,- role: str,- content: str | None = None,- parts: list[dict] | None = None,- created_at: str | None = None,- peer_id: str | None = None,- **_: Any,- ) -> dict[str, Any]:- message_parts = list(parts or [{"type": "text", "text": content or ""}])- normalized_peer_id = normalize_peer_id(peer_id)- message = {- "id": f"msg_{uuid.uuid4().hex}",- "role": role,- "parts": message_parts,- "created_at": created_at or datetime.now(timezone.utc).isoformat(),- }- if normalized_peer_id is not None:- message["peer_id"] = normalized_peer_id- self.sessions.setdefault(session_id, []).append(message)- self.pending_tokens[session_id] += max(1, estimate_text_tokens(_message_text(message)))- return {- "session_id": session_id,- "role": role,- "message_count": len(self.sessions[session_id]),- "pending_tokens": self.pending_tokens[session_id],- }-- def batch_add_messages(- self,- session_id: str,- messages: list[dict[str, Any]],- **_: Any,- ) -> dict[str, Any]:- added = 0- for message in messages:- self.add_message(- session_id=session_id,- role=message["role"],- content=message.get("content"),- parts=message.get("parts"),- created_at=message.get("created_at"),- peer_id=message.get("peer_id"),- )- added += 1- return {- "session_id": session_id,- "message_count": len(self.sessions[session_id]),- "added": added,- "pending_tokens": self.pending_tokens[session_id],- }-- def get_session(self, session_id: str, auto_create: bool = False) -> dict[str, Any]:- if auto_create:- self.create_session(session_id=session_id)- return {- "session_id": session_id,- "uri": self._session_uri(session_id),- "message_count": len(self.sessions.get(session_id, [])),- "pending_tokens": self.pending_tokens.get(session_id, 0),- }-- def get_session_context(- self,- session_id: str,- token_budget: int = 128_000,- **_: Any,- ) -> dict[str, Any]:- del token_budget- if session_id not in self.sessions:- raise NotFoundError(session_id, "session")- latest_archive = self.archives.get(session_id, [])[-1:] or []- latest = latest_archive[0] if latest_archive else {}- messages = list(self.sessions.get(session_id, []))- active_tokens = sum(- max(1, estimate_text_tokens(_message_text(message))) for message in messages- )- archive_tokens = max(0, estimate_text_tokens(str(latest.get("overview", ""))))- return {- "latest_archive_overview": latest.get("overview", ""),- "pre_archive_abstracts": [- {"archive_id": archive["archive_id"], "abstract": archive["abstract"]}- for archive in self.archives.get(session_id, [])[:-1]- ],- "messages": messages,- "estimatedTokens": active_tokens + archive_tokens,- "stats": {- "totalArchives": len(self.archives.get(session_id, [])),- "includedArchives": 1 if latest else 0,- "droppedArchives": 0,- "failedArchives": 0,- "activeTokens": active_tokens,- "archiveTokens": archive_tokens,- },- }-- def get_session_archive(self, session_id: str, archive_id: str, **_: Any) -> dict[str, Any]:- for archive in self.archives.get(session_id, []):- if archive["archive_id"] == archive_id:- return dict(archive)- raise FileNotFoundError(archive_id)-- def commit_session(- self,- session_id: str,- **_: Any,- ) -> dict[str, Any]:- messages = list(self.sessions.get(session_id, []))- archive_id = f"archive_{len(self.archives[session_id]) + 1:03d}"- overview = "\n".join(_message_text(message) for message in messages)- if messages:- archive_uri = f"{self._session_uri(session_id)}/history/{archive_id}"- self.archives[session_id].append(- {- "archive_id": archive_id,- "abstract": overview[:240],- "overview": overview,- "messages": messages,- }- )- self.records[f"{archive_uri}/messages.jsonl"] = (- "\n".join(_message_text(message) for message in messages) + "\n"- )- self.records[f"{archive_uri}/.abstract.md"] = overview[:240]- self.records[f"{archive_uri}/.overview.md"] = overview- self.records[f"{archive_uri}/.done"] = "{}"- self.sessions[session_id] = []- self.pending_tokens[session_id] = 0- return {- "session_id": session_id,- "status": "completed",- "archive_id": archive_id if messages else None,- "archived": bool(messages),- }-- def delete_session(self, session_id: str) -> None:- self.sessions.pop(session_id, None)- self.archives.pop(session_id, None)- self.pending_tokens.pop(session_id, None)- session_uri = self._session_uri(session_id)- for uri in list(self.records):- if uri == session_uri or uri.startswith(f"{session_uri}/"):- del self.records[uri]-- def add_resource(self, path: str, to: str | None = None, **_: Any) -> dict[str, Any]:- uri = to or f"viking://resources/{path.rstrip('/').split('/')[-1]}"- self.records.setdefault(uri, f"Resource imported from {path}")- return {"status": "completed", "root_uri": uri}-- def add_skill(self, data: Any, **_: Any) -> dict[str, Any]:- name = data.get("name", "skill") if isinstance(data, dict) else "skill"- uri = f"viking://user/skills/{name}.md"- self.records[uri] = str(data)- return {"status": "completed", "uri": uri, "name": name}-- def get_status(self) -> dict[str, Any]:- return {"healthy": True, "backend": "in-memory"}-- def is_healthy(self) -> bool:- return True---def _message_text(message: dict[str, Any]) -> str:- chunks: list[str] = []- for part in message.get("parts") or []:- if part.get("type") == "text" and part.get("text"):- chunks.append(str(part["text"]))- elif part.get("type") == "context" and part.get("abstract"):- chunks.append(str(part["abstract"]))- elif part.get("type") == "tool" and part.get("tool_output"):- chunks.append(str(part["tool_output"]))- return "\n".join(chunks)+_forward_legacy_module("testing", globals())diff --git a/openviking/integrations/langchain/tools.py b/openviking/integrations/langchain/tools.pyindex 90ebbc555..6d87fdbb8 100644--- a/openviking/integrations/langchain/tools.py+++ b/openviking/integrations/langchain/tools.py@@ -1,878 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""LangChain tool factory for OpenViking primitives."""+"""Compatibility wrapper for :mod:`langchain_openviking.tools`."""-from __future__ import annotations+from openviking.integrations.langchain import _forward_legacy_module-import logging-import re-from pathlib import Path-from typing import Annotated, Any, Iterable, Literal-from urllib.parse import urlparse-from urllib.request import url2pathname--from pydantic import BeforeValidator, Field--try:- from langchain_core.tools import StructuredTool-except ImportError as exc: # pragma: no cover - exercised by optional import path- from openviking.integrations.langchain.client import missing_dependency-- raise missing_dependency("langchain", "langchain-core") from exc--from openviking.integrations.langchain.client import (- OpenVikingConnection,- call_openviking,- compact_json,- ensure_client,- item_value,- iter_result_items,- stringify,-)--logger = logging.getLogger(__name__)---def _normalize_read_mode_input(value: Any) -> str:- return str(value or "read").lower().strip()---OpenVikingReadMode = Literal["abstract", "overview", "read"]-OpenVikingReadModeInput = Annotated[- OpenVikingReadMode,- BeforeValidator(_normalize_read_mode_input),-]---def create_openviking_tools(- *,- client: Any = None,- url: str | None = None,- api_key: str | None = None,- account: str | None = None,- user: str | None = None,- user_id: str | None = None,- actor_peer_id: str | None = None,- path: str | None = None,- timeout: float = 60.0,- extra_headers: dict[str, str] | None = None,- auto_initialize: bool = True,- profile: str = "agent",- peer_id: str | None = None,- tool_names: Iterable[str] | None = None,- allow_forget: bool = False,-) -> list[StructuredTool]:- """Create LangChain tools exposing OpenViking's common agent primitives.-- Tool names intentionally use the ``viking_*`` prefix so models see the same- conceptual operations that OpenViking users know from plugins and MCP:- find/search, browse/read, grep, store, add_resource, add_skill, and health.- """-- cached_client: Any = None-- def get_client() -> Any:- nonlocal cached_client- if cached_client is None:- cached_client = ensure_client(- OpenVikingConnection(- client=client,- url=url,- api_key=api_key,- account=account,- user=user,- user_id=user_id,- actor_peer_id=actor_peer_id,- path=path,- timeout=timeout,- extra_headers=extra_headers,- auto_initialize=auto_initialize,- )- )- return cached_client-- def viking_find(- query: Annotated[str, Field(description="Natural-language query to match semantically.")],- target_uri: Annotated[- str,- Field(description="Optional OpenViking URI scope to search within."),- ] = "",- limit: Annotated[int, Field(description="Maximum number of matches to return.")] = 8,- min_score: Annotated[- float | None,- Field(description="Optional backend relevance threshold."),- ] = None,- ) -> str:- """Run stateless semantic retrieval over OpenViking targets."""-- result = call_openviking(- get_client(),- "find",- query=query,- target_uri=target_uri,- limit=limit,- score_threshold=min_score,- )- return _format_retrieval_result(result)-- def viking_search(- query: Annotated[str, Field(description="Natural-language query to match semantically.")],- target_uri: Annotated[- str,- Field(description="Optional OpenViking URI scope to search within."),- ] = "",- session_id: Annotated[- str | None,- Field(description="Optional OpenViking session id for session-aware retrieval."),- ] = None,- limit: Annotated[int, Field(description="Maximum number of matches to return.")] = 8,- min_score: Annotated[- float | None,- Field(description="Optional backend relevance threshold."),- ] = None,- ) -> str:- """Run session-aware semantic retrieval over OpenViking targets."""-- result = call_openviking(- get_client(),- "search",- query=query,- target_uri=target_uri,- session_id=session_id,- limit=limit,- score_threshold=min_score,- )- return _format_retrieval_result(result)-- def viking_browse(- uri: Annotated[- str,- Field(description="OpenViking namespace or directory URI to list."),- ] = "viking://",- recursive: Annotated[- bool,- Field(description="Whether to include nested descendants in the listing."),- ] = False,- pattern: Annotated[- str | None,- Field(description="Optional glob pattern for discovering matching OpenViking URIs."),- ] = None,- ) -> str:- """List child entries under an OpenViking namespace or directory URI.-- Use this to inspect structure and discover file/document URIs. When- pattern is set, the tool returns glob matches instead of a direct- directory listing.- """-- active_client = get_client()- if pattern:- result = call_openviking(active_client, "glob", pattern=pattern, uri=uri)- else:- result = call_openviking(active_client, "ls", uri=uri, recursive=recursive)- return stringify(result, max_chars=12_000)-- def viking_read(- uris: Annotated[- str | list[str],- Field(description="One or more file/document OpenViking URIs to read."),- ],- max_chars: Annotated[- int,- Field(description="Maximum characters to include per URI result."),- ] = 12_000,- content_mode: Annotated[- OpenVikingReadModeInput,- Field(- description="Content depth: abstract is shortest, overview is medium, read is full."- ),- ] = "read",- ) -> str:- """Read file/document OpenViking URIs.-- Directory URIs are not readable; call viking_browse on directories to- list children, then call viking_read on returned file/document URIs.- """-- active_client = get_client()- uri_list = [uris] if isinstance(uris, str) else uris- mode = str(content_mode or "read").lower().strip()- payload = []- for uri in uri_list:- try:- content = call_openviking(active_client, mode, uri=uri)- except Exception as exc:- if not _is_directory_read_error(exc):- raise- payload.append(- {- "uri": uri,- "content_mode": mode,- "error": "directory_uri_not_readable",- "message": (- "This URI is a directory. Use viking_browse on this URI to list "- "children, then call viking_read on file/document URIs."- ),- }- )- else:- payload.append(- {- "uri": uri,- "content_mode": mode,- "content": stringify(content, max_chars=max_chars),- }- )- return stringify(payload, max_chars=max_chars * max(1, len(uri_list)))-- def viking_grep(- uri: Annotated[- str,- Field(description="File/document OpenViking URI whose content should be searched."),- ],- pattern: Annotated[- str,- Field(description="Grep-style text or regex pattern to search for."),- ],- case_insensitive: Annotated[- bool,- Field(description="Whether to match pattern without case sensitivity."),- ] = False,- node_limit: Annotated[- int,- Field(description="Maximum number of matching content nodes to return."),- ] = 20,- ) -> str:- """Search OpenViking file content with a grep-style pattern."""-- result = call_openviking(- get_client(),- "grep",- uri=uri,- pattern=pattern,- case_insensitive=case_insensitive,- node_limit=node_limit,- )- return stringify(result, max_chars=12_000)-- def viking_store(- messages: Annotated[- str | list[dict[str, Any]],- Field(description="Message text or role/content message objects to append."),- ],- session_id: Annotated[- str | None,- Field(description="OpenViking session id. A new session is created when omitted."),- ] = None,- commit: Annotated[- bool,- Field(description="Whether to commit the appended session messages immediately."),- ] = True,- ) -> str:- """Append explicit durable memories or conversation messages to an OpenViking session.-- This is a write operation. User-facing hosts should expose it only for- confirmed "remember/save this" workflows because normal conversation- capture is usually handled by lifecycle hooks.- """-- active_client = get_client()- if not session_id:- created = call_openviking(active_client, "create_session")- session_id = created.get("session_id") if isinstance(created, dict) else str(created)- normalized_messages = _normalize_messages(messages)- for message in normalized_messages:- call_openviking(- active_client,- "add_message",- session_id=session_id,- role=message["role"],- content=message.get("content"),- parts=message.get("parts"),- peer_id=peer_id,- )- result: dict[str, Any] = {- "session_id": session_id,- "messages_added": len(normalized_messages),- }- if commit:- result["commit"] = call_openviking(- active_client,- "commit_session",- session_id=session_id,- )- return compact_json(result)-- def viking_archive_search(- session_id: Annotated[- str,- Field(description="OpenViking session id whose committed archive context to search."),- ],- query: Annotated[- str,- Field(description="Natural-language query to match against committed session context."),- ],- archive_id: Annotated[- str | None,- Field(description="Optional specific archive id to search instead of all history."),- ] = None,- token_budget: Annotated[- int,- Field(description="Maximum session context token budget to inspect when needed."),- ] = 128_000,- max_matches: Annotated[- int,- Field(description="Maximum number of archive matches to return."),- ] = 8,- ) -> str:- """Search committed OpenViking session archive context."""-- active_client = get_client()- if archive_id:- archive = call_openviking(- active_client,- "get_session_archive",- session_id=session_id,- archive_id=archive_id,- )- matches = _search_archive_payload(archive, query, max_matches=max_matches)- else:- matches = _grep_session_history(- active_client,- session_id=session_id,- query=query,- max_matches=max_matches,- )- if _match_count(matches) > 0:- return stringify(matches, max_chars=12_000)- context = call_openviking(- active_client,- "get_session_context",- session_id=session_id,- token_budget=token_budget,- )- matches = _search_archive_payload(context, query, max_matches=max_matches)- return stringify(matches or {"matches": [], "count": 0}, max_chars=12_000)-- def viking_archive_expand(- session_id: Annotated[- str,- Field(description="OpenViking session id that owns the archive."),- ],- archive_id: Annotated[- str,- Field(description="Committed archive id to expand."),- ],- max_chars: Annotated[- int,- Field(description="Maximum characters to include in the expanded archive result."),- ] = 20_000,- ) -> str:- """Expand one OpenViking session archive by archive ID."""-- archive = call_openviking(- get_client(),- "get_session_archive",- session_id=session_id,- archive_id=archive_id,- )- return stringify(archive, max_chars=max_chars)-- def viking_add_resource(- path: Annotated[- str,- Field(- description=(- "Resource source to import, such as a URL, repository, uploaded file, "- "directory, or client-visible local path."- )- ),- ],- to: Annotated[- str | None,- Field(description="Optional destination OpenViking URI for the imported resource."),- ] = None,- parent: Annotated[- str | None,- Field(description="Optional parent OpenViking URI under which to place the resource."),- ] = None,- reason: Annotated[- str,- Field(description="Short reason for importing this resource."),- ] = "",- instruction: Annotated[- str,- Field(description="Optional indexing or extraction instruction for the resource."),- ] = "",- wait: Annotated[- bool,- Field(description="Whether to wait for resource ingestion to finish before returning."),- ] = False,- timeout: Annotated[- float | None,- Field(description="Optional wait timeout in seconds for resource ingestion."),- ] = None,- ) -> str:- """Import an explicit resource into OpenViking.-- This is a resource-management operation for user-approved URLs,- repositories, uploaded files, or local paths available to the client. It- is not for ordinary chat facts or ad hoc memory notes.- """-- 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."- ),- }- )- raise- return stringify(result, max_chars=8_000)-- def viking_add_skill(- data: Annotated[- dict[str, Any] | str,- Field(description="Skill definition as a mapping or serialized skill document."),- ],- wait: Annotated[- bool,- Field(description="Whether to wait for skill registration to finish before returning."),- ] = False,- timeout: Annotated[- float | None,- Field(description="Optional wait timeout in seconds for skill registration."),- ] = None,- ) -> str:- """Register a reusable OpenViking skill for trusted admin workflows."""-- result = call_openviking(- get_client(),- "add_skill",- data=data,- wait=wait,- timeout=timeout,- )- return stringify(result, max_chars=8_000)-- def viking_health() -> str:- """Check OpenViking health/status for diagnostics."""-- active_client = get_client()- if hasattr(active_client, "get_status"):- status = call_openviking(active_client, "get_status")- return stringify(_format_openviking_health(status), max_chars=8_000)- if hasattr(active_client, "is_healthy"):- return compact_json(- _format_openviking_health({"healthy": call_openviking(active_client, "is_healthy")})- )- return compact_json(_format_openviking_health({"healthy": True}))-- def viking_forget(- uri: Annotated[- str,- Field(description="OpenViking URI to remove."),- ],- recursive: Annotated[- bool,- Field(description="Whether to remove descendants recursively."),- ] = False,- ) -> str:- """Remove a URI from OpenViking. Only expose this to trusted agents."""-- call_openviking(get_client(), "rm", uri=uri, recursive=recursive)- return compact_json({"removed": uri, "recursive": recursive})-- all_tools: dict[str, StructuredTool] = {- "viking_find": StructuredTool.from_function(viking_find),- "viking_search": StructuredTool.from_function(viking_search),- "viking_browse": StructuredTool.from_function(viking_browse),- "viking_read": StructuredTool.from_function(viking_read),- "viking_grep": StructuredTool.from_function(viking_grep),- "viking_archive_search": StructuredTool.from_function(viking_archive_search),- "viking_archive_expand": StructuredTool.from_function(viking_archive_expand),- "viking_store": StructuredTool.from_function(viking_store),- "viking_add_resource": StructuredTool.from_function(viking_add_resource),- "viking_add_skill": StructuredTool.from_function(viking_add_skill),- "viking_health": StructuredTool.from_function(viking_health),- "viking_forget": StructuredTool.from_function(viking_forget),- }-- if tool_names is None:- selected = _profile_tool_names(profile, allow_forget=allow_forget)- else:- selected = list(tool_names)- return [all_tools[name] for name in selected if name in all_tools]---def _profile_tool_names(profile: str, *, allow_forget: bool) -> list[str]:- retrieval = [- "viking_find",- "viking_search",- "viking_browse",- "viking_read",- "viking_grep",- "viking_archive_search",- "viking_archive_expand",- ]- if profile == "retrieval":- names = retrieval + ["viking_health"]- elif profile == "admin":- names = retrieval + [- "viking_store",- "viking_add_resource",- "viking_add_skill",- "viking_health",- "viking_forget",- ]- else:- names = retrieval + [- "viking_store",- "viking_add_resource",- "viking_add_skill",- "viking_health",- ]- if allow_forget and "viking_forget" not in names:- names.append("viking_forget")- return names---def _is_directory_read_error(exc: Exception) -> bool:- details = getattr(exc, "details", {}) or {}- return (- getattr(exc, "code", None) == "INVALID_ARGUMENT"- and details.get("expected") == "file"- and details.get("actual") == "directory"- )---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 {- "backend": "OpenViking",- "healthy": state == "healthy",- "state": state,- "note": "OpenViking is the context memory backend; VikingDB is internal vector/index storage.",- "summary": _safe_status_summary(status),- }---def _infer_health_state(status: Any) -> str:- if isinstance(status, dict):- for key in ("healthy", "ok"):- value = status.get(key)- if isinstance(value, bool):- return "healthy" if value else "unhealthy"- state = str(status.get("status") or status.get("state") or "").lower()- if state in {"ok", "healthy", "ready", "running"}:- return "healthy"- if state in {"error", "failed", "unhealthy"}:- return "unhealthy"- if state in {"degraded", "initializing", "starting", "pending"}:- return state- return "unknown"---def _safe_status_summary(status: Any) -> dict[str, Any]:- if not isinstance(status, dict):- return {"type": type(status).__name__}-- summary: dict[str, Any] = {}- for key in ("healthy", "ok", "status", "state", "state_detail"):- if key in status:- value = _safe_status_value(status[key])- if value is not None:- summary[key] = value-- components = status.get("components") or status.get("services")- if isinstance(components, dict | list | tuple):- summary["component_count"] = len(components)-- return summary or {"type": "dict"}---def _safe_status_value(value: Any) -> Any:- if value is None or isinstance(value, bool | int | float):- return value- if isinstance(value, str):- lowered = value.lower()- if "://" in lowered or "@" in lowered:- return None- return value if len(value) <= 64 else f"{value[:61]}..."- return None---def _normalize_messages(messages: str | list[dict[str, Any]]) -> list[dict[str, Any]]:- if isinstance(messages, str):- return [{"role": "user", "parts": [{"type": "text", "text": messages}]}]- normalized = []- for message in messages:- role = str(message.get("role") or "user")- if role not in {"user", "assistant", "system", "tool"}:- role = "user"- if message.get("parts") is not None:- normalized.append(- {- "role": "assistant" if role in {"system", "tool"} else role,- "parts": list(message.get("parts") or []),- }- )- continue- content = str(message.get("content", ""))- if role == "tool":- normalized.append(- {- "role": "assistant",- "parts": [- {- "type": "tool",- "tool_id": str(message.get("tool_call_id") or message.get("id") or ""),- "tool_name": str(message.get("name") or ""),- "tool_output": content,- "tool_status": "completed",- }- ],- }- )- elif role == "system":- normalized.append({"role": "assistant", "parts": [{"type": "text", "text": content}]})- else:- normalized.append({"role": role, "parts": [{"type": "text", "text": content}]})- return normalized---def _format_retrieval_result(result: Any) -> str:- lines: list[str] = []- for index, (context_type, item) in enumerate(iter_result_items(result), start=1):- uri = item_value(item, "uri", "")- score = item_value(item, "score")- abstract = item_value(item, "abstract") or item_value(item, "overview") or ""- score_text = "" if score is None else f" score={score}"- lines.append(f"[{index}] {context_type}{score_text} {uri}\n{abstract}".strip())- if not lines:- return "No OpenViking contexts matched."- return "\n\n".join(lines)---def _search_archive_payload(- payload: dict[str, Any],- query: str,- *,- max_matches: int,-) -> dict[str, Any]:- tokens = [token for token in re.findall(r"[a-z0-9_]+", query.lower()) if len(token) > 1]- sections = _archive_sections(payload)- matches: list[dict[str, str]] = []- for label, text in sections:- haystack = text.lower()- if tokens and not all(token in haystack for token in tokens):- continue- matches.append({"section": label, "snippet": _snippet(text, tokens)})- if len(matches) >= max_matches:- break- return {"matches": matches, "count": len(matches)}---def _grep_session_history(- client: Any,- *,- session_id: str,- query: str,- max_matches: int,-) -> dict[str, Any]:- session = call_openviking(client, "get_session", session_id=session_id, auto_create=False)- session_uri = item_value(session, "uri", f"viking://user/sessions/{session_id}")- history_uri = f"{str(session_uri).rstrip('/')}/history"- tokens = _archive_query_tokens(query)- try:- result = call_openviking(- client,- "grep",- uri=history_uri,- pattern=_archive_grep_pattern(query),- case_insensitive=True,- node_limit=None,- )- except Exception:- logger.debug("OpenViking archive history grep failed", exc_info=True)- return {"matches": [], "count": 0, "source": history_uri}- return _filter_grep_result(result, tokens=tokens, max_matches=max_matches, source=history_uri)---def _match_count(result: dict[str, Any] | None) -> int:- if not result:- return 0- for key in ("count", "match_count"):- value = result.get(key)- if value is not None:- return int(value or 0)- matches = result.get("matches")- return len(matches) if isinstance(matches, list) else 0---def _archive_grep_pattern(query: str) -> str:- tokens = _archive_query_tokens(query)- if not tokens:- return re.escape(query) or ".*"- return re.escape(tokens[0])---def _archive_query_tokens(query: str) -> list[str]:- return [token for token in re.findall(r"[a-z0-9_]+", query.lower()) if len(token) > 1]---def _filter_grep_result(- result: Any,- *,- tokens: list[str],- max_matches: int,- source: str,-) -> dict[str, Any]:- raw_matches = result.get("matches", []) if isinstance(result, dict) else result- matches: list[Any] = []- for match in raw_matches if isinstance(raw_matches, list) else []:- text = _grep_match_text(match).lower()- if tokens and not all(token in text for token in tokens):- continue- matches.append(match)- if len(matches) >= max_matches:- break-- filtered = {"source": source}- if isinstance(result, dict):- filtered.update({key: value for key, value in result.items() if key != "matches"})- filtered["matches"] = matches- filtered["count"] = len(matches)- filtered["match_count"] = len(matches)- return filtered---def _grep_match_text(match: Any) -> str:- if isinstance(match, dict):- return str(- match.get("content")- or match.get("line")- or match.get("text")- or match.get("snippet")- or ""- )- return str(match)---def _archive_sections(payload: dict[str, Any]) -> list[tuple[str, str]]:- sections: list[tuple[str, str]] = []- if payload.get("overview"):- sections.append(- (f"archive:{payload.get('archive_id', 'archive')}:overview", payload["overview"])- )- if payload.get("abstract"):- sections.append(- (f"archive:{payload.get('archive_id', 'archive')}:abstract", payload["abstract"])- )- if payload.get("latest_archive_overview"):- sections.append(("latest_archive_overview", payload["latest_archive_overview"]))- for archive in payload.get("pre_archive_abstracts") or []:- sections.append(- (- f"archive:{archive.get('archive_id', 'archive')}:abstract",- str(archive.get("abstract") or ""),- )- )- for index, message in enumerate(payload.get("messages") or [], start=1):- text_parts = []- for part in message.get("parts") or []:- text_parts.extend(- str(part.get(key) or "")- for key in ("text", "abstract", "tool_output")- if part.get(key)- )- if text_parts:- sections.append((f"message:{index}:{message.get('role', '')}", "\n".join(text_parts)))- return sections---def _snippet(text: str, tokens: list[str], *, radius: int = 240) -> str:- if not text:- return ""- lower = text.lower()- positions = [lower.find(token) for token in tokens if token and lower.find(token) >= 0]- start = max(0, min(positions) - radius) if positions else 0- end = min(len(text), start + radius * 2)- prefix = "..." if start else ""- suffix = "..." if end < len(text) else ""- return prefix + text[start:end] + suffix+_forward_legacy_module("tools", globals())diff --git a/pyproject.toml b/pyproject.tomlindex 2deda373a..1da4089d5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -185,12 +185,10 @@ benchmark = ["pandas>=2.0.0",]langchain = [- "langchain-core>=1.0.0,<2.0.0",+ "langchain-openviking>=0.1.0",]langgraph = [- "langchain>=1.0.0,<2.0.0",- "langchain-core>=1.0.0,<2.0.0",- "langgraph>=1.0.0,<2.0.0",+ "langchain-openviking[langgraph]>=0.1.0",]local-embed = ["llama-cpp-python>=0.3.0",@@ -300,3 +298,6 @@ line-ending = "auto"dev = ["pytest>=9.0.2",]++[tool.uv.sources]+langchain-openviking = { path = "integrations/langchain" }diff --git a/tests/integration/langchain_langgraph/live_e2e.py b/tests/integration/langchain_langgraph/live_e2e.pyindex 1594bf29d..e1772209f 100644--- a/tests/integration/langchain_langgraph/live_e2e.py+++ b/tests/integration/langchain_langgraph/live_e2e.py@@ -17,12 +17,7 @@ from langchain_core.language_models.chat_models import SimpleChatModelfrom langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessagefrom langchain_core.runnables import RunnableLambdafrom langchain_core.runnables.history import RunnableWithMessageHistory-from langgraph.graph import END, START, StateGraph-from langgraph.graph.message import add_messages-from openai import OpenAI-from typing_extensions import Annotated, TypedDict--from openviking.integrations.langchain import (+from langchain_openviking import (OpenVikingChatMessageHistory,OpenVikingContextMiddleware,OpenVikingRetriever,@@ -30,7 +25,11 @@ from openviking.integrations.langchain import (create_openviking_tools,with_openviking_context,)-from openviking.integrations.langchain.client import extract_message_text+from langchain_openviking.client import extract_message_text+from langgraph.graph import END, START, StateGraph+from langgraph.graph.message import add_messages+from openai import OpenAI+from typing_extensions import Annotated, TypedDictdef test_true_live_langchain_context_backend_e2e():@@ -509,7 +508,7 @@ def _require_openviking_live_env() -> None:def _build_real_client():- from openviking.client import SyncHTTPClient+ from openviking_sdk import SyncHTTPClientclient = SyncHTTPClient(url=os.environ.get("OPENVIKING_URL") or None,diff --git a/tests/integration/langchain_langgraph/test_async_recording.py b/tests/integration/langchain_langgraph/test_async_recording.pyindex 299d6942c..d49d8b85a 100644--- a/tests/integration/langchain_langgraph/test_async_recording.py+++ b/tests/integration/langchain_langgraph/test_async_recording.py@@ -8,14 +8,14 @@ import pytestpytest.importorskip("langchain")pytest.importorskip("langchain_core")pytest.importorskip("langgraph")+pytest.importorskip("langchain_openviking")from langchain.agents import create_agentfrom langchain_core.language_models.fake_chat_models import FakeListChatModelfrom langchain_core.messages import AIMessage, BaseMessage, HumanMessagefrom langchain_core.runnables import RunnableLambdafrom langchain_core.runnables.history import RunnableWithMessageHistory--from openviking.integrations.langchain import (+from langchain_openviking import (InMemoryOpenVikingClient,OpenVikingChatMessageHistory,OpenVikingContextMiddleware,diff --git a/tests/integration/langchain_langgraph/test_context_lifecycle.py b/tests/integration/langchain_langgraph/test_context_lifecycle.pyindex d447669ae..931a7ce5d 100644--- a/tests/integration/langchain_langgraph/test_context_lifecycle.py+++ b/tests/integration/langchain_langgraph/test_context_lifecycle.py@@ -8,12 +8,12 @@ from typing import Anyimport pytestpytest.importorskip("langchain_core")+pytest.importorskip("langchain_openviking")from langchain_core.messages import AIMessage, BaseMessage, HumanMessagefrom langchain_core.runnables import RunnableLambdafrom langchain_core.runnables.history import RunnableWithMessageHistory--from openviking.integrations.langchain import (+from langchain_openviking import (OpenVikingCommitPolicy,OpenVikingContextRunnable,with_openviking_context,@@ -110,7 +110,7 @@ async def _async_answer(messages: list[BaseMessage]) -> AIMessage:def test_context_wrapper_reuses_and_closes_owned_sync_clients(monkeypatch):instances: list[Any] = []- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", _sync_http_client_type(instances))@@ -143,7 +143,7 @@ def test_context_wrapper_reuses_sync_clients_across_batch_threads(monkeypatch):original_init(self, **kwargs)monkeypatch.setattr(client_type, "__init__", synchronized_init)- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", client_type)app = with_openviking_context(@@ -246,7 +246,7 @@ def test_context_wrapper_does_not_close_injected_sync_client():@pytest.mark.asyncioasync def test_context_wrapper_reuses_and_closes_owned_async_clients(monkeypatch):instances: list[Any] = []- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", _async_http_client_type(instances))@@ -268,7 +268,7 @@ async def test_context_wrapper_reuses_and_closes_owned_async_clients(monkeypatchdef test_context_wrapper_keeps_owned_async_clients_loop_scoped(monkeypatch):instances: list[Any] = []- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", _async_http_client_type(instances))app = with_openviking_context(@@ -352,7 +352,7 @@ async def test_context_wrapper_close_inside_event_loop_remains_recoverable():@pytest.mark.asyncioasync def test_context_wrapper_finishes_cleanup_when_aclose_is_cancelled(monkeypatch):instances: list[Any] = []- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", _async_http_client_type(instances))app = with_openviking_context(diff --git a/tests/integration/langchain_langgraph/test_recording.py b/tests/integration/langchain_langgraph/test_recording.pyindex 65f22a74a..a3e7d4f38 100644--- a/tests/integration/langchain_langgraph/test_recording.py+++ b/tests/integration/langchain_langgraph/test_recording.py@@ -5,14 +5,14 @@ from typing import Anyimport pytestpytest.importorskip("langchain_core")+pytest.importorskip("langchain_openviking")from langchain.agents import create_agentfrom langchain_core.language_models.fake_chat_models import FakeListChatModelfrom langchain_core.messages import AIMessage, BaseMessage, HumanMessagefrom langchain_core.runnables import RunnableLambdafrom langchain_core.runnables.history import RunnableWithMessageHistory--from openviking.integrations.langchain import (+from langchain_openviking import (InMemoryOpenVikingClient,OpenVikingChatMessageHistory,OpenVikingContextMiddleware,diff --git a/tests/integration/langchain_langgraph/test_runtime_actor_peer.py b/tests/integration/langchain_langgraph/test_runtime_actor_peer.pyindex 1c8afa997..cb56d9186 100644--- a/tests/integration/langchain_langgraph/test_runtime_actor_peer.py+++ b/tests/integration/langchain_langgraph/test_runtime_actor_peer.py@@ -8,20 +8,14 @@ import pytestpytest.importorskip("langchain")pytest.importorskip("langchain_core")pytest.importorskip("langgraph")+pytest.importorskip("langchain_openviking")from langchain.agents import create_agentfrom langchain_core.language_models.fake_chat_models import FakeListChatModelfrom langchain_core.messages import AIMessage, HumanMessage+from openviking_sdk import get_actor_peer_id, use_actor_peer-from openviking_cli._sdk_import import import_openviking_sdk--# Load the workspace SDK before the integration package so this cross-package-# feature is tested even when an older released SDK is installed.-_openviking_sdk = import_openviking_sdk()-get_actor_peer_id = _openviking_sdk.get_actor_peer_id-use_actor_peer = _openviking_sdk.use_actor_peer--_langchain_integration = import_module("openviking.integrations.langchain")+_langchain_integration = import_module("langchain_openviking")InMemoryOpenVikingClient = _langchain_integration.InMemoryOpenVikingClientOpenVikingContextMiddleware = _langchain_integration.OpenVikingContextMiddlewarediff --git a/tests/integration/langchain_langgraph/test_smoke.py b/tests/integration/langchain_langgraph/test_smoke.pyindex b955dcf2d..a519a7808 100644--- a/tests/integration/langchain_langgraph/test_smoke.py+++ b/tests/integration/langchain_langgraph/test_smoke.py@@ -7,6 +7,7 @@ import pytestpytest.importorskip("langchain_core")pytest.importorskip("langgraph")+pytest.importorskip("langchain_openviking")PROJECT_ROOT = Path(__file__).resolve().parents[3]diff --git a/tests/unit/test_langchain_async_integration.py b/tests/unit/test_langchain_async_integration.pyindex 7a79faac7..b62a35ddd 100644--- a/tests/unit/test_langchain_async_integration.py+++ b/tests/unit/test_langchain_async_integration.py@@ -4,16 +4,17 @@ import asyncioimport copyimport sysimport threading+from types import SimpleNamespacefrom typing import Anyimport pytestpytest.importorskip("langchain_core")pytest.importorskip("langgraph")+pytest.importorskip("langchain_openviking")from langchain_core.messages import AIMessage, HumanMessage--from openviking.integrations.langchain import (+from langchain_openviking import (InMemoryOpenVikingClient,OpenVikingCancellationProgress,OpenVikingChatMessageHistory,@@ -25,7 +26,7 @@ from openviking.integrations.langchain import (OpenVikingSessionRecorder,get_openviking_cancellation_progress,)-from openviking.integrations.langchain.client import (+from langchain_openviking.client import (OpenVikingAsyncClientHandle,OpenVikingConnection,acall_openviking,@@ -136,7 +137,7 @@ def test_retriever_deepcopy_discards_owned_sync_client(monkeypatch):def find(self, **_kwargs: Any) -> dict[str, Any]:return {"memories": [], "resources": [], "skills": []}- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", NonCopyableSyncHTTPClient)retriever = OpenVikingRetriever(url="http://localhost:1933")@@ -166,7 +167,7 @@ async def test_ensure_async_client_defaults_to_native_http_client(monkeypatch):async def find(self, query: str) -> dict[str, str]:return {"query": query}- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", FakeAsyncHTTPClient)@@ -274,7 +275,7 @@ async def test_async_client_handle_initializes_once_under_concurrency(monkeypatcasync def close(self) -> None:self.closed = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", SlowAsyncHTTPClient)handle = OpenVikingAsyncClientHandle(OpenVikingConnection(url="http://localhost:1933"))@@ -302,7 +303,7 @@ async def test_async_client_initialization_failure_closes_candidate(monkeypatch)async def close(self) -> None:self.closed = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", FailingAsyncHTTPClient)@@ -328,7 +329,7 @@ async def test_async_adapter_client_caches_initialize_once_under_concurrency(monasync def close(self) -> None:self.closed = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", SlowAsyncHTTPClient)recorder = OpenVikingSessionRecorder(url="http://localhost:1933")@@ -379,7 +380,7 @@ def test_async_adapter_clients_are_scoped_per_event_loop(monkeypatch):async def close(self) -> None:self.closed = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", LoopBoundAsyncHTTPClient)recorder = OpenVikingSessionRecorder(url="http://localhost:1933")@@ -420,7 +421,7 @@ def test_async_adapter_aclose_after_originating_loop_ends_is_best_effort(monkeypasync def close(self) -> None:raise RuntimeError("event loop is closed")- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", LoopBoundAsyncHTTPClient)recorder = OpenVikingSessionRecorder(url="http://localhost:1933")@@ -448,7 +449,7 @@ def test_async_adapter_aclose_routes_to_live_originating_loop(monkeypatch):async def close(self) -> None:self.closed_loop = asyncio.get_running_loop()- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", LoopBoundAsyncHTTPClient)recorder = OpenVikingSessionRecorder(url="http://localhost:1933")@@ -504,7 +505,7 @@ async def test_async_handle_copy_and_missing_attribute_behavior(monkeypatch):async def close(self) -> None:self.closed = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", FakeAsyncHTTPClient)retriever = OpenVikingRetriever(url="http://localhost:1933")@@ -547,7 +548,7 @@ async def test_async_handle_method_lookup_survives_recovery_reset(monkeypatch):reset_started.set()await release_close.wait()- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", RecoveringAsyncHTTPClient)handle = OpenVikingAsyncClientHandle(OpenVikingConnection(url="http://localhost:1933"))@@ -599,7 +600,7 @@ async def test_async_handle_stale_failure_does_not_reset_replacement(monkeypatchreset_started.set()await release_old_close.wait()- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", RecoveringAsyncHTTPClient)handle = OpenVikingAsyncClientHandle(OpenVikingConnection(url="http://localhost:1933"))@@ -636,7 +637,7 @@ async def test_async_handle_missing_method_fails_when_called(monkeypatch):async def close(self) -> None:return None- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", FakeAsyncHTTPClient)handle = OpenVikingAsyncClientHandle(OpenVikingConnection(url="http://localhost:1933"))@@ -671,7 +672,7 @@ async def test_sync_close_after_async_use_remains_recoverable(monkeypatch):def close(self) -> None:self.closed = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", FakeAsyncHTTPClient)monkeypatch.setattr(client_module, "SyncHTTPClient", FakeSyncHTTPClient)@@ -710,7 +711,7 @@ async def test_async_middleware_closes_all_internally_owned_clients(monkeypatch)async def close(self) -> None:self.closed = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", FakeAsyncHTTPClient)middleware = OpenVikingContextMiddleware(url="http://localhost:1933")@@ -776,7 +777,7 @@ async def test_async_client_retries_safe_read_with_fresh_client(monkeypatch):raise ConnectionError("OpenViking server was not ready")return {"memories": [], "resources": [], "skills": []}- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", FlakyAsyncHTTPClient)@@ -806,7 +807,7 @@ async def test_async_client_evicts_without_replaying_mutating_call(monkeypatch):async def batch_add_messages(self, **_kwargs: Any) -> dict[str, Any]:raise ConnectionError("OpenViking connection dropped during write")- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", FlakyAsyncHTTPClient)@@ -876,9 +877,13 @@ async def test_embedded_path_async_uses_owned_sync_client_in_worker(monkeypatch,def close(self) -> None:self.closed = True- import openviking.sync_client as sync_client_module+ import langchain_openviking.client as client_module- monkeypatch.setattr(sync_client_module, "SyncOpenViking", FakeSyncOpenViking)+ monkeypatch.setattr(+ client_module,+ "import_module",+ lambda name: SimpleNamespace(SyncOpenViking=FakeSyncOpenViking),+ )retriever = OpenVikingRetriever(path=str(tmp_path), actor_peer_id="assistant-a")documents = await retriever.ainvoke("embedded")@@ -1212,7 +1217,7 @@ async def test_async_recorder_closes_only_internally_created_client(monkeypatch)async def close(self) -> None:self.closed = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "AsyncHTTPClient", FakeAsyncHTTPClient)owned_recorder = OpenVikingSessionRecorder(url="http://localhost:1933")diff --git a/tests/unit/test_langchain_integration.py b/tests/unit/test_langchain_integration.pyindex 0e94df152..46389d1e7 100644--- a/tests/unit/test_langchain_integration.py+++ b/tests/unit/test_langchain_integration.py@@ -1,19 +1,19 @@from __future__ import annotationsimport json+from types import SimpleNamespacefrom typing import Anyimport pytestpytest.importorskip("langchain_core")pytest.importorskip("langgraph")+pytest.importorskip("langchain_openviking")+import langchain_openviking.client as client_helpersfrom langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessagefrom langchain_core.runnables import RunnableLambda-from langgraph.store.base import PutOp--import openviking.integrations.langchain.client as client_helpers-from openviking.integrations.langchain import (+from langchain_openviking import (InMemoryOpenVikingClient,OpenVikingChatMessageHistory,OpenVikingCommitPolicy,@@ -24,19 +24,20 @@ from openviking.integrations.langchain import (create_openviking_tools,with_openviking_context,)-from openviking.integrations.langchain.client import (+from langchain_openviking.client import (OpenVikingConnection,apply_commit_policy,call_openviking,ensure_client,)-from openviking.integrations.langchain.history import (+from langchain_openviking.history import (langchain_message_to_openviking,openviking_message_to_langchain,)-from openviking.integrations.langchain.middleware import _message_signature-from openviking.integrations.langchain.tools import _archive_grep_pattern, _resolve_resource_source-from openviking_cli.exceptions import InvalidArgumentError+from langchain_openviking.middleware import _message_signature+from langchain_openviking.tools import _archive_grep_pattern, _resolve_resource_source+from langgraph.store.base import PutOp+from openviking_sdk.errors import InvalidArgumentErrordef test_langchain_client_exposes_apply_commit_policy_without_legacy_alias():@@ -61,6 +62,16 @@ def _schema_enums(schema: dict[str, Any]) -> set[str]:return values+def _schema_has_description(schema: dict[str, Any]) -> bool:+ if schema.get("description"):+ return True+ return any(+ _schema_has_description(child)+ for child_key in ("anyOf", "oneOf", "allOf")+ for child in schema.get(child_key, [])+ )++def test_retriever_returns_langchain_documents():client = InMemoryOpenVikingClient({@@ -352,7 +363,9 @@ def test_openviking_tool_schemas_describe_model_visible_arguments():for tool in tools:schema = _tool_schema(tool)for name, property_schema in schema.get("properties", {}).items():- assert property_schema.get("description"), f"{tool.name}.{name} lacks a description"+ assert _schema_has_description(property_schema), (+ f"{tool.name}.{name} lacks a description"+ )def test_openviking_health_tool_returns_safe_summary():@@ -425,7 +438,7 @@ def test_ensure_client_defaults_to_http_client(monkeypatch):def initialize(self):self._initialized = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", FakeHTTPClient)@@ -455,9 +468,11 @@ def test_ensure_client_keeps_local_path_clients_direct(monkeypatch, tmp_path):def initialize(self):self._initialized = True- import openviking.sync_client as sync_client_module-- monkeypatch.setattr(sync_client_module, "SyncOpenViking", FakeLocalClient)+ monkeypatch.setattr(+ client_helpers,+ "import_module",+ lambda name: SimpleNamespace(SyncOpenViking=FakeLocalClient),+ )client = ensure_client(OpenVikingConnection(path=str(tmp_path)))@@ -498,7 +513,7 @@ def test_openviking_client_retries_recoverable_read_with_fresh_client(monkeypatc"skills": [],}- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", FlakyHTTPClient)@@ -522,7 +537,7 @@ def test_openviking_client_handle_filters_kwargs_for_direct_calls(monkeypatch):def find(self, query):return {"query": query}- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", FakeHTTPClient)@@ -550,7 +565,7 @@ def test_openviking_client_evicts_but_does_not_retry_mutating_call(monkeypatch):def add_message(self, **_kwargs):raise ConnectionError("OpenViking connection dropped during write")- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", FlakyHTTPClient)@@ -601,7 +616,7 @@ def test_retriever_recovers_from_stale_cached_remote_client(monkeypatch):"skills": [],}- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", FlakyHTTPClient)diff --git a/tests/unit/test_langchain_lifecycle_resources.py b/tests/unit/test_langchain_lifecycle_resources.pyindex c324a3f5b..836285ff5 100644--- a/tests/unit/test_langchain_lifecycle_resources.py+++ b/tests/unit/test_langchain_lifecycle_resources.py@@ -10,14 +10,15 @@ from typing import Anyimport pytestpytest.importorskip("langchain_core")+pytest.importorskip("langchain_openviking")-from openviking.integrations.langchain import (+from langchain_openviking import (OpenVikingCommitPolicy,OpenVikingRetriever,OpenVikingSessionContextAssembler,OpenVikingSessionRecorder,)-from openviking.integrations.langchain.client import (+from langchain_openviking.client import (OpenVikingClientHandle,OpenVikingConnection,)@@ -37,7 +38,7 @@ def test_sync_client_handle_initializes_once_under_concurrency(monkeypatch):def close(self) -> None:self.closed = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", SlowSyncHTTPClient)handle = OpenVikingClientHandle(OpenVikingConnection(url="http://localhost:1933"))@@ -78,7 +79,7 @@ def test_sync_client_handle_recovery_does_not_discard_fresh_client(monkeypatch):raise ConnectionError("replace the first client")return {"client": self.index}- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", RecoveringSyncHTTPClient)handle = OpenVikingClientHandle(OpenVikingConnection(url="http://localhost:1933"))@@ -111,7 +112,7 @@ def test_session_scoped_retriever_copies_share_owned_sync_client(monkeypatch):def find(self, **_kwargs: Any) -> dict[str, Any]:return {"memories": [], "resources": [], "skills": []}- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", TrackingSyncHTTPClient)retriever = OpenVikingRetriever(url="http://localhost:1933")@@ -227,7 +228,7 @@ def test_recorder_and_assembler_deepcopy_do_not_share_owned_sync_clients(monkeypdef close(self) -> None:self.closed = True- import openviking.client as client_module+ import openviking_sdk as client_modulemonkeypatch.setattr(client_module, "SyncHTTPClient", TrackingSyncHTTPClient)recorder = OpenVikingSessionRecorder(url="http://localhost:1933")diff --git a/tests/unit/test_langchain_package_boundary.py b/tests/unit/test_langchain_package_boundary.pynew file mode 100644index 000000000..646872dc5--- /dev/null+++ b/tests/unit/test_langchain_package_boundary.py@@ -0,0 +1,276 @@+from __future__ import annotations++import ast+import os+import subprocess+import sys+from importlib import import_module+from pathlib import Path++import pytest++PROJECT_ROOT = Path(__file__).resolve().parents[2]+PACKAGE_ROOT = PROJECT_ROOT / "integrations" / "langchain"+SOURCE_ROOT = PACKAGE_ROOT / "src"+SDK_ROOT = PROJECT_ROOT / "sdk" / "python"+++def test_standalone_package_has_no_server_imports_at_module_scope():+ violations: list[str] = []+ for source_file in sorted((SOURCE_ROOT / "langchain_openviking").glob("*.py")):+ tree = ast.parse(source_file.read_text(encoding="utf-8"), filename=str(source_file))+ for node in tree.body:+ if isinstance(node, ast.ImportFrom):+ module = node.module or ""+ if module == "openviking" or module.startswith("openviking."):+ violations.append(f"{source_file.name}:{node.lineno}: from {module}")+ if module == "openviking_cli" or module.startswith("openviking_cli."):+ violations.append(f"{source_file.name}:{node.lineno}: from {module}")+ elif isinstance(node, ast.Import):+ for alias in node.names:+ if alias.name == "openviking" or alias.name.startswith("openviking."):+ violations.append(f"{source_file.name}:{node.lineno}: import {alias.name}")+ if alias.name == "openviking_cli" or alias.name.startswith("openviking_cli."):+ violations.append(f"{source_file.name}:{node.lineno}: import {alias.name}")++ for node in ast.walk(tree):+ if not (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "import_module"+ and node.args+ and isinstance(node.args[0], ast.Constant)+ and isinstance(node.args[0].value, str)+ ):+ continue+ module = node.args[0].value+ is_full_package = module == "openviking" or module.startswith("openviking.")+ is_cli_package = module == "openviking_cli" or module.startswith("openviking_cli.")+ is_embedded_client_import = source_file.name == "client.py" and module == "openviking"+ if (is_full_package or is_cli_package) and not is_embedded_client_import:+ violations.append(f"{source_file.name}:{node.lineno}: import_module({module!r})")++ assert violations == []+++def test_standalone_package_import_does_not_load_full_openviking(tmp_path):+ env = os.environ.copy()+ env["PYTHONPATH"] = os.pathsep.join((str(SOURCE_ROOT), str(SDK_ROOT)))+ probe = """+import sys+import langchain_openviking++assert "openviking" not in sys.modules+assert not any(name.startswith("openviking_cli") for name in sys.modules)+assert langchain_openviking.has_request_actor_peer_support()+"""++ subprocess.run(+ [sys.executable, "-c", probe],+ cwd=tmp_path,+ env=env,+ check=True,+ capture_output=True,+ text=True,+ )+++def test_base_star_import_omits_optional_middleware(tmp_path):+ env = os.environ.copy()+ env["PYTHONPATH"] = os.pathsep.join((str(SOURCE_ROOT), str(SDK_ROOT)))+ probe = """+import importlib.util++real_find_spec = importlib.util.find_spec+importlib.util.find_spec = (+ lambda name, *args, **kwargs:+ None if name == "langchain" else real_find_spec(name, *args, **kwargs)+)++import langchain_openviking++assert "OpenVikingContextMiddleware" not in langchain_openviking.__all__+namespace = {}+exec("from langchain_openviking import *", namespace)+assert "OpenVikingContextMiddleware" not in namespace+assert "OpenVikingRetriever" in namespace+"""++ subprocess.run(+ [sys.executable, "-c", probe],+ cwd=tmp_path,+ env=env,+ check=True,+ capture_output=True,+ text=True,+ )+++def test_legacy_namespace_remains_importable_without_standalone_package(tmp_path):+ env = os.environ.copy()+ env["PYTHONPATH"] = os.pathsep.join((str(PROJECT_ROOT), str(SDK_ROOT)))+ probe = """+import importlib.abc+import importlib+import sys+++class BlockStandalonePackage(importlib.abc.MetaPathFinder):+ def find_spec(self, fullname, path=None, target=None):+ if fullname == "langchain_openviking" or fullname.startswith("langchain_openviking."):+ raise ModuleNotFoundError(+ "No module named 'langchain_openviking'",+ name="langchain_openviking",+ )+ return None+++sys.meta_path.insert(0, BlockStandalonePackage())++import openviking.integrations.langchain as legacy++assert "OpenVikingRetriever" in legacy.__all__+assert isinstance(legacy.has_request_actor_peer_support(), bool)++try:+ legacy.OpenVikingRetriever+except ImportError as exc:+ message = str(exc)+ assert "langchain-openviking" in message+ assert "openviking[langchain]" in message+else:+ raise AssertionError("missing standalone package should produce an installation error")++for submodule in (+ "actor_peer",+ "client",+ "context",+ "history",+ "messages",+ "middleware",+ "recording",+ "retrievers",+ "store",+ "testing",+ "tools",+):+ try:+ importlib.import_module(f"openviking.integrations.langchain.{submodule}")+ except ImportError as exc:+ assert not isinstance(exc, ModuleNotFoundError)+ message = str(exc)+ assert "langchain-openviking" in message+ assert "openviking[langchain]" in message+ else:+ raise AssertionError(f"legacy {submodule} import should produce an installation error")+"""++ subprocess.run(+ [sys.executable, "-c", probe],+ cwd=tmp_path,+ env=env,+ check=True,+ capture_output=True,+ text=True,+ )+++def test_legacy_imports_resolve_to_canonical_objects():+ pytest.importorskip("langchain_core")+ pytest.importorskip("langchain_openviking")+ canonical = import_module("langchain_openviking")+ legacy = import_module("openviking.integrations.langchain")++ for name in canonical.__all__:+ assert getattr(legacy, name) is getattr(canonical, name)++ for submodule in (+ "actor_peer",+ "client",+ "context",+ "history",+ "messages",+ "middleware",+ "recording",+ "retrievers",+ "store",+ "testing",+ "tools",+ ):+ legacy_module = import_module(f"openviking.integrations.langchain.{submodule}")+ canonical_module = import_module(f"langchain_openviking.{submodule}")+ legacy_public = {name for name in vars(legacy_module) if not name.startswith("_")}+ canonical_public = {name for name in vars(canonical_module) if not name.startswith("_")}++ assert legacy_public == canonical_public+ for name in sorted(canonical_public):+ assert getattr(legacy_module, name) is getattr(canonical_module, name)+++ ("uri", "expected_parts", "expected_scope", "expected_content_index"),+ [+ (+ "viking://user/memories/store/data/users/ada.json",+ ("user", "memories", "store", "data", "users", "ada.json"),+ "user",+ 1,+ ),+ (+ "viking://user/default/memories/store/index/users/ada.md",+ ("user", "default", "memories", "store", "index", "users", "ada.md"),+ "user",+ 2,+ ),+ (+ "viking://user/default/peers/assistant/resources/store/data.json",+ ("user", "default", "peers", "assistant", "resources", "store", "data.json"),+ "user",+ 4,+ ),+ (+ "viking://user/peers/assistant/memories/store/index.md",+ ("user", "peers", "assistant", "memories", "store", "index.md"),+ "user",+ 3,+ ),+ (+ "viking://agent/default/skills/review/SKILL.md",+ ("agent", "default", "skills", "review", "SKILL.md"),+ "agent",+ 2,+ ),+ (+ "viking://resources/shared.md",+ ("resources", "shared.md"),+ "resources",+ None,+ ),+ (+ "viking://user/default/sessions/thread-1",+ ("user", "default", "sessions", "thread-1"),+ "user",+ None,+ ),+ (+ "/user/default/memories/store/data.json?profile=1",+ ("user", "default", "memories", "store", "data.json"),+ "user",+ 2,+ ),+ ],+)+def test_private_uri_classification_preserves_server_namespace_shapes(+ uri,+ expected_parts,+ expected_scope,+ expected_content_index,+):+ pytest.importorskip("langchain_openviking")+ from langchain_openviking._uri import classify_uri++ classification = classify_uri(uri)++ assert classification.parts == expected_parts+ assert classification.scope == expected_scope+ assert classification.content_index == expected_content_indexdiff --git a/tests/unit/test_langchain_recording.py b/tests/unit/test_langchain_recording.pyindex 9d66aa1a8..fdac314df 100644--- a/tests/unit/test_langchain_recording.py+++ b/tests/unit/test_langchain_recording.py@@ -5,7 +5,9 @@ from typing import Anyimport pytestpytest.importorskip("langchain_core")+pytest.importorskip("langchain_openviking")+import langchain_openviking.recording as recording_modulefrom langchain_core.messages import (AIMessage,BaseMessage,@@ -13,9 +15,7 @@ from langchain_core.messages import (SystemMessage,ToolMessage,)--import openviking.integrations.langchain.recording as recording_module-from openviking.integrations.langchain import (+from langchain_openviking import (InMemoryOpenVikingClient,OpenVikingChatMessageHistory,OpenVikingCommitPolicy,@@ -24,7 +24,7 @@ from openviking.integrations.langchain import (OpenVikingRecordResult,OpenVikingSessionRecorder,)-from openviking.integrations.langchain.messages import OPENVIKING_CONTEXT_MARKER+from langchain_openviking.messages import OPENVIKING_CONTEXT_MARKERclass TrackingOpenVikingClient(InMemoryOpenVikingClient):diff --git a/tests/unit/test_langchain_runtime_actor_peer.py b/tests/unit/test_langchain_runtime_actor_peer.pyindex 59114a412..96a54fce2 100644--- a/tests/unit/test_langchain_runtime_actor_peer.py+++ b/tests/unit/test_langchain_runtime_actor_peer.py@@ -8,17 +8,14 @@ import pytestpytest.importorskip("langchain_core")pytest.importorskip("langgraph")+pytest.importorskip("langchain_openviking")from langchain_core.messages import AIMessage, HumanMessage-from openviking_cli._sdk_import import import_openviking_sdk--# Load the workspace SDK before the integration package so this cross-package-# feature is tested even when an older released SDK is installed.-_openviking_sdk = import_openviking_sdk()-actor_peer_module = import_module("openviking.integrations.langchain.actor_peer")-_langchain_integration = import_module("openviking.integrations.langchain")-_langchain_client = import_module("openviking.integrations.langchain.client")+_openviking_sdk = import_module("openviking_sdk")+actor_peer_module = import_module("langchain_openviking.actor_peer")+_langchain_integration = import_module("langchain_openviking")+_langchain_client = import_module("langchain_openviking.client")InMemoryOpenVikingClient = _langchain_integration.InMemoryOpenVikingClientOpenVikingContextMiddleware = _langchain_integration.OpenVikingContextMiddlewareOpenVikingClientHandle = _langchain_client.OpenVikingClientHandle@@ -36,12 +33,12 @@ def _older_sdk_actor_peer_support(def test_langchain_exports_actor_peer_capability_helper():- integration = import_module("openviking.integrations.langchain")+ integration = import_module("langchain_openviking")assert integration.has_request_actor_peer_support()assert "has_request_actor_peer_support" in integration.__all__namespace: dict[str, Any] = {}- exec("from openviking.integrations.langchain import *", namespace)+ exec("from langchain_openviking import *", namespace)assert namespace["has_request_actor_peer_support"] is (integration.has_request_actor_peer_support@@ -52,12 +49,12 @@ def test_langchain_exports_actor_peer_capability_helper():def test_langchain_star_import_remains_usable_with_older_sdk(monkeypatch: pytest.MonkeyPatch,):- integration = import_module("openviking.integrations.langchain")+ integration = import_module("langchain_openviking")with _older_sdk_actor_peer_support(monkeypatch):assert not integration.has_request_actor_peer_support()namespace: dict[str, Any] = {}- exec("from openviking.integrations.langchain import *", namespace)+ exec("from langchain_openviking import *", namespace)assert namespace["OpenVikingContextMiddleware"] is (integration.OpenVikingContextMiddleware)assert not namespace["has_request_actor_peer_support"]()diff --git a/uv.lock b/uv.lockindex 17d7c4f73..2d8e1ebf8 100644--- a/uv.lock+++ b/uv.lock@@ -2314,6 +2314,37 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/72/17/3785cbcdc81c451179247e4176d2697879cb4f45ab2c59d949ca574e072d/langchain_openai-1.1.10-py3-none-any.whl", hash = "sha256:d91b2c09e9fbc70f7af45345d3aa477744962d41c73a029beb46b4f83b824827", size = 87205, upload-time = "2026-02-17T18:03:43.502Z" },]+[[package]]+name = "langchain-openviking"+source = { directory = "integrations/langchain" }+dependencies = [+ { name = "langchain-core" },+ { name = "openviking-sdk" },+ { name = "pydantic" },+]++[package.optional-dependencies]+langgraph = [+ { name = "langchain" },+ { name = "langgraph" },+]++[package.metadata]+requires-dist = [+ { name = "build", marker = "extra == 'dev'", specifier = ">=1.2.0" },+ { name = "langchain", marker = "extra == 'langgraph'", specifier = ">=1.0.0,<2.0.0" },+ { name = "langchain-core", specifier = ">=1.0.0,<2.0.0" },+ { name = "langgraph", marker = "extra == 'langgraph'", specifier = ">=1.0.0,<2.0.0" },+ { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.0.0" },+ { name = "openviking-sdk", specifier = ">=0.1.1" },+ { name = "pydantic", specifier = ">=2.0.0" },+ { name = "pytest", marker = "extra == 'test'", specifier = ">=7.0.0" },+ { name = "pytest-asyncio", marker = "extra == 'test'", specifier = ">=0.21.0" },+ { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.1.0" },+ { name = "twine", marker = "extra == 'dev'", specifier = ">=5.0.0" },+]+provides-extras = ["langgraph", "test", "dev"]+[[package]]name = "langchain-text-splitters"version = "1.1.1"@@ -3761,12 +3792,10 @@ gemini-async = [{ name = "google-genai" },]langchain = [- { name = "langchain-core" },+ { name = "langchain-openviking" },]langgraph = [- { name = "langchain" },- { name = "langchain-core" },- { name = "langgraph" },+ { name = "langchain-openviking", extra = ["langgraph"] },]local-embed = [{ name = "llama-cpp-python" },@@ -3831,13 +3860,11 @@ requires-dist = [{ name = "jinja2", specifier = ">=3.1.6" },{ name = "json-repair", specifier = ">=0.25.0" },{ name = "langchain", marker = "extra == 'benchmark'", specifier = ">=1.0.0" },- { name = "langchain", marker = "extra == 'langgraph'", specifier = ">=1.0.0,<2.0.0" },{ name = "langchain-core", marker = "extra == 'benchmark'", specifier = ">=1.0.0" },- { name = "langchain-core", marker = "extra == 'langchain'", specifier = ">=1.0.0,<2.0.0" },- { name = "langchain-core", marker = "extra == 'langgraph'", specifier = ">=1.0.0,<2.0.0" },{ name = "langchain-openai", marker = "extra == 'benchmark'", specifier = ">=1.0.0" },+ { name = "langchain-openviking", marker = "extra == 'langchain'", directory = "integrations/langchain" },+ { name = "langchain-openviking", extras = ["langgraph"], marker = "extra == 'langgraph'", directory = "integrations/langchain" },{ name = "langfuse", marker = "extra == 'bot'", specifier = ">=3.0.0" },- { name = "langgraph", marker = "extra == 'langgraph'", specifier = ">=1.0.0,<2.0.0" },{ name = "lark-oapi", specifier = ">=1.5.3" },{ name = "lark-oapi", marker = "extra == 'bot'", specifier = ">=1.0.0" },{ name = "litellm", specifier = ">=1.83.7,<1.91.2" },