Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(bot): add unified VikingBot gateway routing and OpenViking auth (#3119)
DuTaocbfb387dc78a
diff --git a/bot/tests/test_agent_loop_outcome.py b/bot/tests/test_agent_loop_outcome.pyindex 153af3b3c..0910318fc 100644--- a/bot/tests/test_agent_loop_outcome.py+++ b/bot/tests/test_agent_loop_outcome.py@@ -111,7 +111,6 @@ def test_agent_loop_omits_spawn_tool_when_subagents_disabled(temp_dir: Path, monbus = MessageBus()provider = _RecordingProvider()config = Config(storage_workspace=str(temp_dir), agents={"subagent_enabled": False})- monkeypatch.setattr("vikingbot.agent.tools.factory.load_config", lambda: config)loop = AgentLoop(bus=bus,@@ -125,6 +124,24 @@ def test_agent_loop_omits_spawn_tool_when_subagents_disabled(temp_dir: Path, monassert "spawn" not in loop.tools.tool_names+def test_agent_loop_standalone_omits_openviking_tools(temp_dir: Path, monkeypatch):+ monkeypatch.setattr(AgentLoop, "_register_builtin_hooks", lambda self: None)+ monkeypatch.setattr("vikingbot.agent.loop.SubagentManager", _FakeSubagentManager)++ config = Config(storage_workspace=str(temp_dir))+ loop = AgentLoop(+ bus=MessageBus(),+ provider=_RecordingProvider(),+ workspace=temp_dir / "workspace",+ config=config,+ )++ assert config.ov_server.server_url == ""+ assert not any(name.startswith("openviking_") for name in loop.tools.tool_names)+ session_key = SessionKey(type="cli", channel_id="default", chat_id="standalone")+ assert loop._get_ov_tools_enable(session_key) is False++@pytest.mark.asyncioasync def test_context_prompt_omits_subagent_capability_when_disabled(temp_dir: Path):context = ContextBuilder(workspace=temp_dir / "workspace", enable_subagents=False)@@ -174,14 +191,6 @@ async def test_agent_loop_makes_final_no_tool_call_when_iteration_limit_reached(monkeypatch.setattr(AgentLoop, "_register_default_tools", lambda self: None)monkeypatch.setattr("vikingbot.agent.loop.SubagentManager", _FakeSubagentManager)- class _OVConfig:- exp_write_tools = []-- class _LoadedConfig:- ov_server = _OVConfig()-- monkeypatch.setattr(loop_module, "load_config", lambda: _LoadedConfig())-class _ToolLimitProvider(LLMProvider):def __init__(self):super().__init__()@@ -458,9 +467,7 @@ async def test_agent_loop_build_prompt_history_uses_ov_context_plus_unsynced_tai})- async def fake_get_ov_client(- self, session_key, openviking_connection=None, actor_peer_id=None- ):+ async def fake_get_ov_client(self, session_key, openviking_connection=None, actor_peer_id=None):del session_key, openviking_connection, actor_peer_idreturn fake_ov_client@@ -469,6 +476,7 @@ async def test_agent_loop_build_prompt_history_uses_ov_context_plus_unsynced_taibus = MessageBus()config = Config(storage_workspace=str(temp_dir),+ ov_server={"server_url": "http://127.0.0.1:1933"},agents={"session_context_enabled": True, "session_context_token_budget": 321},)loop = AgentLoop(@@ -513,9 +521,7 @@ async def test_agent_loop_build_prompt_history_skips_tail_when_sync_cursor_is_pacontext_payload={"messages": [{"role": "user", "content": "OV user turn"}]})- async def fake_get_ov_client(- self, session_key, openviking_connection=None, actor_peer_id=None- ):+ async def fake_get_ov_client(self, session_key, openviking_connection=None, actor_peer_id=None):del self, session_key, openviking_connection, actor_peer_idreturn fake_ov_client@@ -524,6 +530,7 @@ async def test_agent_loop_build_prompt_history_skips_tail_when_sync_cursor_is_pabus = MessageBus()config = Config(storage_workspace=str(temp_dir),+ ov_server={"server_url": "http://127.0.0.1:1933"},agents={"session_context_enabled": True, "session_context_token_budget": 321},)loop = AgentLoop(@@ -568,6 +575,7 @@ async def test_agent_loop_submits_openviking_session_through_compact_hook(bus = MessageBus()config = Config(storage_workspace=str(temp_dir),+ ov_server={"server_url": "http://127.0.0.1:1933"},agents={"session_context_enabled": True},)loop = AgentLoop(@@ -620,9 +628,7 @@ async def test_agent_loop_commits_openviking_before_model_when_pending_tokens_restate["last_synced_local_index"] = len(session.messages) - 1return kwargs- async def fake_get_ov_client(- self, session_key, openviking_connection=None, actor_peer_id=None- ):+ async def fake_get_ov_client(self, session_key, openviking_connection=None, actor_peer_id=None):del self, session_key, openviking_connection, actor_peer_idclass _Client:@@ -651,6 +657,7 @@ async def test_agent_loop_commits_openviking_before_model_when_pending_tokens_rebus = MessageBus()config = Config(storage_workspace=str(temp_dir),+ ov_server={"server_url": "http://127.0.0.1:1933"},agents={"session_context_enabled": True,"session_context_token_budget": 321,@@ -725,9 +732,7 @@ async def test_agent_loop_commits_openviking_before_model_when_memory_window_reasession.metadata["openviking"]["last_commit_performed"] = bool(kwargs["force_commit"])return kwargs- async def fake_get_ov_client(- self, session_key, openviking_connection=None, actor_peer_id=None- ):+ async def fake_get_ov_client(self, session_key, openviking_connection=None, actor_peer_id=None):del self, session_key, openviking_connection, actor_peer_idclass _Client:@@ -756,6 +761,7 @@ async def test_agent_loop_commits_openviking_before_model_when_memory_window_reabus = MessageBus()config = Config(storage_workspace=str(temp_dir),+ ov_server={"server_url": "http://127.0.0.1:1933"},agents={"session_context_enabled": True,"session_context_token_budget": 321,@@ -887,7 +893,11 @@ async def test_agent_loop_post_turn_passes_memory_window_threshold(temp_dir: Pat)bus = MessageBus()- config = Config(storage_workspace=str(temp_dir), agents={"session_context_enabled": True})+ config = Config(+ storage_workspace=str(temp_dir),+ ov_server={"server_url": "http://127.0.0.1:1933"},+ agents={"session_context_enabled": True},+ )loop = AgentLoop(bus=bus,provider=_FakeProvider(),@@ -942,7 +952,11 @@ async def test_agent_loop_post_turn_clears_local_session_after_openviking_commit)bus = MessageBus()- config = Config(storage_workspace=str(temp_dir), agents={"session_context_enabled": True})+ config = Config(+ storage_workspace=str(temp_dir),+ ov_server={"server_url": "http://127.0.0.1:1933"},+ agents={"session_context_enabled": True},+ )loop = AgentLoop(bus=bus,provider=_FakeProvider(),@@ -1001,7 +1015,10 @@ async def test_agent_loop_emits_normalized_response_completed_payload(temp_dir:monkeypatch.setattr(AgentLoop, "_run_agent_loop", fake_run_agent_loop)bus = MessageBus()- config = Config(storage_workspace=str(temp_dir))+ config = Config(+ storage_workspace=str(temp_dir),+ ov_server={"server_url": "http://127.0.0.1:1933"},+ )loop = AgentLoop(bus=bus,provider=_FakeProvider(),@@ -1081,7 +1098,10 @@ async def test_auto_openviking_memory_uses_distinct_tool_name(temp_dir: Path, momonkeypatch.setattr(AgentLoop, "_run_agent_loop", fake_run_agent_loop)bus = MessageBus()- config = Config(storage_workspace=str(temp_dir))+ config = Config(+ storage_workspace=str(temp_dir),+ ov_server={"server_url": "http://127.0.0.1:1933"},+ )loop = AgentLoop(bus=bus,provider=_FakeProvider(),diff --git a/bot/tests/test_channel_delivery_metadata.py b/bot/tests/test_channel_delivery_metadata.pyindex c2f723932..9f148cf16 100644--- a/bot/tests/test_channel_delivery_metadata.py+++ b/bot/tests/test_channel_delivery_metadata.py@@ -47,6 +47,7 @@ async def test_message_tool_preserves_channel_metadata():@pytest.mark.asyncioasync def test_spawn_tool_preserves_channel_metadata():metadata = {"reply_to": "oc_chat", "chat_type": "group", "message_id": "om_old"}+ connection = {"api_key": "request-key", "account_id": "acct", "user_id": "alice"}calls = []class FakeSubagentManager:@@ -58,18 +59,21 @@ async def test_spawn_tool_preserves_channel_metadata():context = SimpleNamespace(session_key=SessionKey(type="feishu", channel_id="cli_app", chat_id="oc_chat"),channel_metadata=metadata,+ openviking_connection=connection,)result = await tool.execute(context, task="read files", label="read")assert result == "started"assert calls[0]["channel_metadata"] == metadata+ assert calls[0]["openviking_connection"] is connection@pytest.mark.asyncioasync def test_subagent_announcement_preserves_channel_metadata(tmp_path):bus = MessageBus()metadata = {"reply_to": "oc_chat", "chat_type": "group", "message_id": "om_old"}+ connection = {"api_key": "request-key", "account_id": "acct", "user_id": "alice"}session_key = SessionKey(type="feishu", channel_id="cli_app", chat_id="oc_chat")manager = SubagentManager(provider=SimpleNamespace(get_default_model=lambda: "fake-model"),@@ -86,11 +90,13 @@ async def test_subagent_announcement_preserves_channel_metadata(tmp_path):session_key,"ok",metadata,+ connection,)inbound = await bus.consume_inbound()assert inbound.metadata == metadataassert inbound.metadata is not metadata+ assert inbound.openviking_connection is connection@pytest.mark.asyncio@@ -100,6 +106,8 @@ async def test_system_message_response_preserves_channel_metadata(tmp_path, monkmonkeypatch.setattr("vikingbot.agent.loop.SubagentManager", lambda **kwargs: SimpleNamespace())metadata = {"reply_to": "oc_chat", "chat_type": "group", "message_id": "om_old"}+ connection = {"api_key": "request-key", "account_id": "acct", "user_id": "alice"}+ captured = {}session_key = SessionKey(type="feishu", channel_id="cli_app", chat_id="oc_chat")config = Config(storage_workspace=str(tmp_path / "data"))loop = AgentLoop(@@ -121,7 +129,15 @@ async def test_system_message_response_preserves_channel_metadata(tmp_path, monkreturn "summary", None, [], {}, 1loop._build_prompt_history = fake_build_prompt_history- loop.context = SimpleNamespace(build_messages=fake_build_messages)++ class FakeContextBuilder:+ def __init__(self, *args, **kwargs):+ captured["connection"] = kwargs.get("openviking_connection")++ async def build_messages(self, **kwargs):+ return await fake_build_messages(**kwargs)++ monkeypatch.setattr("vikingbot.agent.context.ContextBuilder", FakeContextBuilder)loop._run_agent_loop = fake_run_agent_loopoutbound = await loop._process_system_message(@@ -130,12 +146,14 @@ async def test_system_message_response_preserves_channel_metadata(tmp_path, monksession_key=session_key,content="subagent done",metadata=metadata,+ openviking_connection=connection,))assert outbound.content == "summary"assert outbound.metadata == metadataassert outbound.metadata is not metadata+ assert captured["connection"] is connection@pytest.mark.asynciodiff --git a/bot/tests/test_chat_functionality.py b/bot/tests/test_chat_functionality.pyindex 7939dadff..e60ab55bf 100644--- a/bot/tests/test_chat_functionality.py+++ b/bot/tests/test_chat_functionality.py@@ -10,6 +10,7 @@ from vikingbot.bus.events import OutboundMessagefrom vikingbot.bus.queue import MessageBusfrom vikingbot.channels.chat import ChatChannel, ChatChannelConfigfrom vikingbot.channels.single_turn import SingleTurnChannel, SingleTurnChannelConfig+from vikingbot.cli.commands import _CHAT_PROMPT_MESSAGE, _CHAT_PROMPT_STYLEfrom vikingbot.config.schema import SessionKeyfrom vikingbot.session.manager import Session@@ -119,6 +120,13 @@ class TestSessionHistoryProviderSpecificFields:class TestChatChannel:+ def test_interactive_prompt_uses_terminal_foreground_and_visible_label(self):+ assert _CHAT_PROMPT_MESSAGE == [("class:user-label", "You: ")]+ rules = dict(_CHAT_PROMPT_STYLE.style_rules)+ assert rules[""] == "fg:ansidefault"+ assert rules["user-label"] == "bold fg:ansicyan"+ assert all("ansiblack" not in style for style in rules.values())+def test_chat_channel_initialization(self, message_bus, temp_workspace):"""Test that ChatChannel can be initialized correctly."""config = ChatChannelConfig()diff --git a/bot/tests/test_openapi_auth.py b/bot/tests/test_openapi_auth.pyindex ccd668070..cc43e225f 100644--- a/bot/tests/test_openapi_auth.py+++ b/bot/tests/test_openapi_auth.py@@ -8,6 +8,7 @@ import tempfilefrom pathlib import Pathfrom types import SimpleNamespace+import httpximport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -35,6 +36,19 @@ def _make_client(channel: OpenAPIChannel) -> TestClient:return TestClient(app)+class _AsyncBytesStream(httpx.AsyncByteStream):+ def __init__(self, *chunks: bytes):+ self.chunks = chunks+ self.closed = False++ async def __aiter__(self):+ for chunk in self.chunks:+ yield chunk++ async def aclose(self) -> None:+ self.closed = True++class TestOpenAPIAuth:def test_health_remains_available_without_api_key(self, message_bus, temp_workspace):channel = OpenAPIChannel(@@ -48,6 +62,80 @@ class TestOpenAPIAuth:assert response.status_code == 200+ def test_public_gateway_health_requires_gateway_token(self, message_bus, temp_workspace):+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=SimpleNamespace(+ gateway=SimpleNamespace(host="0.0.0.0", token="gateway-secret")+ ),+ )+ app = FastAPI()+ app.include_router(channel.get_router(), prefix="/bot/v1")+ app.include_router(channel.get_gateway_router())+ client = TestClient(app)++ root_challenge = client.get("/health")+ bot_challenge = client.get("/bot/v1/health")+ assert root_challenge.status_code == 401+ assert bot_challenge.status_code == 401+ assert root_challenge.headers["X-VikingBot-Gateway"] == "true"+ assert bot_challenge.headers["X-VikingBot-Gateway"] == "true"+ headers = {"X-Gateway-Token": "gateway-secret"}+ assert client.get("/health", headers=headers).status_code == 200+ assert client.get("/bot/v1/health", headers=headers).status_code == 200++ def test_trusted_sessions_are_isolated_by_request_identity(+ self, message_bus, temp_workspace, monkeypatch+ ):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token=""),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="trusted",+ api_key_type="root",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ async def fake_health(request):+ return {+ "status": "ok",+ "auth_mode": "trusted",+ "role": "user",+ "account_id": request.headers["X-OpenViking-Account"],+ "user_id": request.headers["X-OpenViking-User"],+ }++ monkeypatch.setattr(channel, "_request_upstream_health", fake_health)+ client = _make_client(channel)+ alice_headers = {+ "X-API-Key": "root-key",+ "X-OpenViking-Account": "acct",+ "X-OpenViking-User": "alice",+ }+ bob_headers = {+ "X-API-Key": "root-key",+ "X-OpenViking-Account": "acct",+ "X-OpenViking-User": "bob",+ }++ created = client.post("/bot/v1/sessions", headers=alice_headers, json={})+ assert created.status_code == 200+ session_id = created.json()["session_id"]++ assert (+ client.get(f"/bot/v1/sessions/{session_id}", headers=alice_headers).status_code == 200+ )+ assert client.get(f"/bot/v1/sessions/{session_id}", headers=bob_headers).status_code == 404+ assert client.get("/bot/v1/sessions", headers=bob_headers).json()["total"] == 0+def test_chat_accepts_requests_when_api_key_not_configured(self, message_bus, temp_workspace, monkeypatch):@@ -97,6 +185,109 @@ class TestOpenAPIAuth:assert response.status_code == 200assert response.json()["message"] == "ok"+ def test_gateway_health_reports_upstream_sources(+ self, message_bus, temp_workspace, monkeypatch+ ):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token=""),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="api_key",+ api_key_type="user",+ _source="inherited",+ _api_key_source="bot.ov_server.api_key",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ async def fake_health(_request):+ return {+ "status": "ok",+ "auth_mode": "api_key",+ "role": "user",+ "account_id": "acct",+ "user_id": "alice",+ }++ monkeypatch.setattr(channel, "_request_upstream_health", fake_health)+ app = FastAPI()+ app.include_router(channel.get_gateway_router())+ client = TestClient(app)++ response = client.get("/health")++ assert response.status_code == 200+ body = response.json()+ assert body["mode"] == "openviking_inherited"+ assert body["upstream_source"] == "inherited"+ assert body["upstream_api_key_source"] == "bot.ov_server.api_key"+ assert body["gateway_token_required"] is False++ def test_gateway_health_validates_and_returns_caller_identity(+ self, message_bus, temp_workspace, monkeypatch+ ):+ captured = []+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token=""),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="api_key",+ api_key_type="user",+ api_key="bot-user-key",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def get(self, url, headers=None):+ captured.append(dict(headers or {}))+ return httpx.Response(+ 200,+ json={+ "status": "ok",+ "auth_mode": "api_key",+ "role": "user",+ "account_id": "acct",+ "user_id": "alice",+ },+ )++ monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)+ app = FastAPI()+ app.include_router(channel.get_gateway_router())+ client = TestClient(app)++ anonymous = client.get("/health")+ authenticated = client.get("/health", headers={"X-API-Key": "caller-user-key"})++ assert anonymous.status_code == 200+ assert "role" not in anonymous.json()+ assert captured[0]["X-API-Key"] == "bot-user-key"+ assert authenticated.status_code == 200+ assert captured[1]["X-API-Key"] == "caller-user-key"+ assert authenticated.json()["role"] == "user"+ assert authenticated.json()["account_id"] == "acct"+ assert authenticated.json()["user_id"] == "alice"+def test_chat_rejects_when_non_localhost_and_token_not_configured(self, message_bus, temp_workspace):@@ -116,6 +307,718 @@ class TestOpenAPIAuth:== "OpenAPI gateway token is required when host is non-localhost")+ def test_chat_rejects_untrusted_openviking_connection_body(self, message_bus, temp_workspace):+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ )+ client = _make_client(channel)++ response = client.post(+ "/bot/v1/chat",+ json={+ "message": "hello",+ "openviking_connection": {+ "api_key": "stolen-key",+ "account_id": "acct",+ "user_id": "alice",+ "server_url": "http://ov.local",+ },+ },+ )++ assert response.status_code == 403+ assert "openviking_connection is only accepted" in response.json()["detail"]++ def test_chat_resolves_openviking_api_key_identity(+ self, message_bus, temp_workspace, monkeypatch+ ):+ captured = {}+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token=""),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="api_key",+ api_key_type="user",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def get(self, url, headers=None):+ captured["health_url"] = url+ captured["health_headers"] = headers+ return httpx.Response(+ 200,+ json={+ "status": "ok",+ "auth_mode": "api_key",+ "role": "user",+ "account_id": "acct",+ "user_id": "alice",+ },+ )++ async def fake_handle_chat(request):+ captured["connection"] = request.openviking_connection.model_dump(exclude_none=True)+ captured["sender_id"] = channel._request_user_id(request)+ captured["actor_peer_id"] = channel._request_actor_peer_id(+ request, captured["sender_id"]+ )+ return ChatResponse(+ session_id=request.session_id or "default", message="ok", events=None+ )++ monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)+ monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)+ client = _make_client(channel)++ response = client.post(+ "/bot/v1/chat",+ headers={"X-API-Key": "user-key", "X-OpenViking-Actor-Peer": "peer-a"},+ json={"message": "hello", "user_id": "display-user"},+ )++ assert response.status_code == 200+ assert captured["health_url"] == "http://ov.local/health"+ assert captured["health_headers"]["X-API-Key"] == "user-key"+ assert captured["sender_id"] == "display-user"+ assert captured["actor_peer_id"] == "peer-a"+ assert captured["connection"] == {+ "api_key": "user-key",+ "account_id": "acct",+ "user_id": "alice",+ "agent_id": "web-playground",+ "role": "user",+ "api_key_type": "user",+ "namespace_policy": {+ "isolate_user_scope_by_agent": False,+ "isolate_agent_scope_by_user": False,+ },+ "server_url": "http://ov.local",+ "actor_peer_id": "peer-a",+ }++ def test_chat_rejects_root_openviking_api_key_identity(+ self, message_bus, temp_workspace, monkeypatch+ ):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token=""),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="api_key",+ api_key_type="user",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def get(self, url, headers=None):+ return httpx.Response(+ 200,+ json={+ "status": "ok",+ "auth_mode": "api_key",+ "role": "root",+ "account_id": "acct",+ "user_id": "root",+ },+ )++ async def fake_handle_chat(_request):+ raise AssertionError("chat handler should not run for root API key")++ monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)+ monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)+ client = _make_client(channel)++ response = client.post(+ "/bot/v1/chat",+ headers={"X-API-Key": "root-key"},+ json={"message": "hello"},+ )++ assert response.status_code == 401+ assert "User/Admin identity" in response.json()["detail"]++ def test_chat_rejects_api_key_upstream_without_openviking_api_key(+ self, message_bus, temp_workspace, monkeypatch+ ):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="0.0.0.0", token="gateway-secret"),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="api_key",+ api_key_type="user",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ async def fake_handle_chat(_request):+ raise AssertionError("chat handler should not run without an OpenViking API key")++ monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)+ client = _make_client(channel)++ response = client.post(+ "/bot/v1/chat",+ headers={"X-Gateway-Token": "gateway-secret"},+ json={"message": "hello"},+ )++ assert response.status_code == 401+ assert response.json()["detail"] == "OpenViking API key header required"++ def test_chat_rejects_trusted_upstream_without_identity(+ self, message_bus, temp_workspace, monkeypatch+ ):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token=""),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="trusted",+ api_key_type="root",+ api_key="configured-root-key",+ account_id="configured-account",+ admin_user_id="configured-user",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def get(self, url, headers=None):+ return httpx.Response(+ 200,+ json={"status": "ok", "auth_mode": "trusted"},+ headers={"content-type": "application/json"},+ )++ async def fake_handle_chat(_request):+ raise AssertionError("chat handler should not run without trusted identity")++ monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)+ monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)+ client = _make_client(channel)++ response = client.post(+ "/bot/v1/chat",+ headers={"X-API-Key": "root-key"},+ json={"message": "hello"},+ )++ assert response.status_code == 401+ assert "Trusted OpenViking chat requires" in response.json()["detail"]+ assert "X-OpenViking-Account" in response.json()["detail"]+ assert "X-OpenViking-User" in response.json()["detail"]++ def test_chat_resolves_trusted_connection_from_request_identity(+ self, message_bus, temp_workspace, monkeypatch+ ):+ captured = {}+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token=""),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="trusted",+ api_key_type="root",+ api_key="configured-root-key",+ account_id="",+ admin_user_id="",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def get(self, url, headers=None):+ captured["health_headers"] = headers+ return httpx.Response(+ 200,+ json={+ "status": "ok",+ "auth_mode": "trusted",+ "role": "user",+ "account_id": "acct",+ "user_id": "alice",+ },+ headers={"content-type": "application/json"},+ )++ async def fake_handle_chat(request):+ captured["connection"] = request.openviking_connection.model_dump(exclude_none=True)+ return ChatResponse(+ session_id=request.session_id or "default", message="ok", events=None+ )++ monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)+ monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)+ client = _make_client(channel)++ response = client.post(+ "/bot/v1/chat",+ headers={+ "X-API-Key": "root-key",+ "X-OpenViking-Account": "acct",+ "X-OpenViking-User": "alice",+ },+ json={"message": "hello"},+ )++ assert response.status_code == 200+ assert captured["health_headers"]["X-API-Key"] == "root-key"+ assert captured["health_headers"]["X-OpenViking-Account"] == "acct"+ assert captured["health_headers"]["X-OpenViking-User"] == "alice"+ assert captured["connection"]["api_key"] == "root-key"+ assert captured["connection"]["account_id"] == "acct"+ assert captured["connection"]["user_id"] == "alice"+ assert captured["connection"]["api_key_type"] == "root"++ def test_chat_rejects_trusted_identity_without_request_api_key(+ self, message_bus, temp_workspace, monkeypatch+ ):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token=""),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="trusted",+ api_key_type="root",+ api_key="configured-root-key",+ account_id="configured-account",+ admin_user_id="configured-user",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def get(self, url, headers=None):+ return httpx.Response(+ 200,+ json={"status": "ok", "auth_mode": "trusted"},+ headers={"content-type": "application/json"},+ )++ async def fake_handle_chat(_request):+ raise AssertionError("chat handler should not run without a request API key")++ monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)+ monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)+ client = _make_client(channel)++ response = client.post(+ "/bot/v1/chat",+ headers={+ "X-OpenViking-Account": "acct",+ "X-OpenViking-User": "alice",+ },+ json={"message": "hello"},+ )++ assert response.status_code == 401+ assert response.json()["detail"] == "OpenViking API key header required"++ def test_public_gateway_requires_gateway_token_even_with_openviking_api_key(+ self, message_bus, temp_workspace, monkeypatch+ ):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="0.0.0.0", token="gateway-secret"),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="api_key",+ api_key_type="user",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ async def fake_handle_chat(_request):+ raise AssertionError("chat handler should not run without gateway token")++ monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)+ client = _make_client(channel)++ response = client.post(+ "/bot/v1/chat",+ headers={"X-API-Key": "user-key"},+ json={"message": "hello"},+ )++ assert response.status_code == 401+ assert response.json()["detail"] == "X-Gateway-Token header required"+ assert response.headers["X-VikingBot-Gateway"] == "true"++ def test_gateway_proxy_reports_standalone_without_openviking(self, message_bus, temp_workspace):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token=""),+ ov_server=SimpleNamespace(server_url=""),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )+ app = FastAPI()+ app.include_router(channel.get_gateway_router())+ client = TestClient(app)++ response = client.get("/api/v1/system/status")++ assert response.status_code == 503+ assert (+ response.json()["detail"]+ == "VikingBot gateway proxy is active, but no available OpenViking server is configured"+ )++ def test_chat_rejects_runtime_upstream_dev_on_public_gateway(+ self, message_bus, temp_workspace, monkeypatch+ ):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="0.0.0.0", token="gateway-secret"),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="api_key",+ api_key_type="user",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def get(self, url, headers=None):+ return httpx.Response(+ 200,+ json={"status": "ok", "auth_mode": "dev"},+ headers={"content-type": "application/json"},+ )++ async def fake_handle_chat(_request):+ raise AssertionError("chat handler should not run against unsafe dev upstream")++ monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)+ monkeypatch.setattr(channel, "_handle_chat", fake_handle_chat)+ client = _make_client(channel)++ response = client.post(+ "/bot/v1/chat",+ headers={"X-Gateway-Token": "gateway-secret", "X-API-Key": "user-key"},+ json={"message": "hello"},+ )++ assert response.status_code == 403+ assert (+ response.json()["detail"]+ == "OpenViking server auth_mode changed to dev, but dev auth can only be used when gateway and OpenViking server are localhost"+ )++ def test_gateway_proxy_forwards_openviking_request_without_gateway_token(+ self, message_bus, temp_workspace, monkeypatch+ ):+ captured = {}+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token="secret123"),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="trusted",+ api_key_type="root",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def get(self, url, headers=None):+ captured["health_url"] = url+ captured["health_headers"] = headers+ return httpx.Response(+ 200,+ json={"status": "ok", "auth_mode": "trusted"},+ headers={"content-type": "application/json"},+ )++ def build_request(self, method, url, content=None, headers=None):+ captured["method"] = method+ captured["url"] = url+ captured["headers"] = headers+ return httpx.Request(method, url, content=content, headers=headers)++ async def send(self, request, stream=False):+ captured["content"] = b"".join([chunk async for chunk in request.stream])+ upstream_stream = _AsyncBytesStream(b'{"ok":', b"true}")+ captured["upstream_stream"] = upstream_stream+ return httpx.Response(+ 201,+ stream=upstream_stream,+ headers={"content-type": "application/json"},+ request=request,+ )++ async def aclose(self):+ captured["proxy_client_closed"] = True++ monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)+ app = FastAPI()+ app.include_router(channel.get_gateway_router())+ client = TestClient(app)++ response = client.post(+ "/api/v1/search/search?profile=1",+ headers={+ "X-Gateway-Token": "secret123",+ "X-API-Key": "user-key",+ "X-OpenViking-Account": "acct",+ "Content-Type": "application/json",+ },+ json={"query": "hello"},+ )++ assert response.status_code == 201+ assert response.json() == {"ok": True}+ assert captured["health_url"] == "http://ov.local/health"+ assert captured["method"] == "POST"+ assert captured["url"] == "http://ov.local/api/v1/search/search?profile=1"+ assert json.loads(captured["content"]) == {"query": "hello"}+ forwarded_headers = {key.lower(): value for key, value in captured["headers"].items()}+ assert forwarded_headers["x-api-key"] == "user-key"+ assert forwarded_headers["x-openviking-account"] == "acct"+ assert "x-gateway-token" not in forwarded_headers+ assert captured["upstream_stream"].closed is True+ assert captured["proxy_client_closed"] is True++ def test_gateway_proxy_does_not_add_trusted_identity_from_config(+ self, message_bus, temp_workspace, monkeypatch+ ):+ captured = {}+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="127.0.0.1", token=""),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="trusted",+ api_key_type="root",+ api_key="configured-root-key",+ account_id="acct",+ admin_user_id="alice",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def aclose(self):+ captured["proxy_client_closed"] = True++ async def get(self, url, headers=None):+ captured["health_headers"] = headers+ return httpx.Response(+ 200,+ json={"status": "ok", "auth_mode": "trusted"},+ headers={"content-type": "application/json"},+ )++ def build_request(self, method, url, content=None, headers=None):+ captured["content"] = content+ captured["headers"] = headers+ return httpx.Request(method, url, content=content, headers=headers)++ async def send(self, request, stream=False):+ upstream_stream = _AsyncBytesStream(b'{"ok":true}')+ captured["upstream_stream"] = upstream_stream+ return httpx.Response(+ 200,+ stream=upstream_stream,+ headers={"content-type": "application/json"},+ request=request,+ )++ monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)+ app = FastAPI()+ app.include_router(channel.get_gateway_router())+ client = TestClient(app)++ response = client.get("/api/v1/system/status")++ assert response.status_code == 200+ assert captured["content"] is None+ assert captured["health_headers"] == {}+ forwarded_headers = {key.lower(): value for key, value in captured["headers"].items()}+ assert "x-api-key" not in forwarded_headers+ assert "authorization" not in forwarded_headers+ assert "x-openviking-account" not in forwarded_headers+ assert "x-openviking-user" not in forwarded_headers+ assert captured["upstream_stream"].closed is True+ assert captured["proxy_client_closed"] is True++ def test_gateway_proxy_rejects_runtime_upstream_dev_on_public_gateway(+ self, message_bus, temp_workspace, monkeypatch+ ):+ config = SimpleNamespace(+ gateway=SimpleNamespace(host="0.0.0.0", token="gateway-secret"),+ ov_server=SimpleNamespace(+ server_url="http://ov.local",+ effective_auth_mode="api_key",+ api_key_type="user",+ ),+ )+ channel = OpenAPIChannel(+ OpenAPIChannelConfig(),+ message_bus,+ workspace_path=temp_workspace,+ global_config=config,+ )++ class FakeAsyncClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, exc_type, exc, tb):+ return None++ async def get(self, url, headers=None):+ return httpx.Response(+ 200,+ json={"status": "ok", "auth_mode": "dev"},+ headers={"content-type": "application/json"},+ )++ async def request(self, *args, **kwargs):+ raise AssertionError("proxy should not forward requests to unsafe dev upstream")++ monkeypatch.setattr("vikingbot.channels.openapi.httpx.AsyncClient", FakeAsyncClient)+ app = FastAPI()+ app.include_router(channel.get_gateway_router())+ client = TestClient(app)++ response = client.get(+ "/api/v1/system/status",+ headers={"X-Gateway-Token": "gateway-secret"},+ )++ assert response.status_code == 403+ assert (+ response.json()["detail"]+ == "OpenViking server auth_mode changed to dev, but dev auth can only be used when gateway and OpenViking server are localhost"+ )+def test_bot_channel_accepts_requests_without_channel_api_key(self, message_bus, temp_workspace, monkeypatch):@@ -142,7 +1045,7 @@ class TestOpenAPIAuth:assert response.status_code == 200assert response.json()["message"] == "ok:alpha"- def test_bot_channel_requires_global_gateway_token_when_configured(+ def test_bot_channel_allows_localhost_without_gateway_token_when_configured(self, message_bus, temp_workspace, monkeypatch):channel = OpenAPIChannel(@@ -161,12 +1064,20 @@ class TestOpenAPIAuth:monkeypatch.setattr(channel, "_handle_bot_chat", fake_handle_bot_chat)client = _make_client(channel)- unauthorized = client.post(+ local_without_token = client.post(+ "/bot/v1/chat/channel",+ json={"message": "hello", "channel_id": "alpha"},+ )+ assert local_without_token.status_code == 200+ assert local_without_token.json()["message"] == "ok:alpha"++ invalid = client.post("/bot/v1/chat/channel",+ headers={"X-Gateway-Token": "wrong"},json={"message": "hello", "channel_id": "alpha"},)- assert unauthorized.status_code == 401- assert unauthorized.json()["detail"] == "X-Gateway-Token header required"+ assert invalid.status_code == 200+ assert invalid.json()["message"] == "ok:alpha"authorized = client.post("/bot/v1/chat/channel",diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.pyindex 155f3d83e..efca9dc02 100644--- a/bot/tests/test_openviking_api_key_type.py+++ b/bot/tests/test_openviking_api_key_type.py@@ -3,6 +3,7 @@ from pathlib import Pathfrom types import SimpleNamespaceimport pytest+from vikingbot.agent import memory as memory_modulefrom vikingbot.agent.context import ContextBuilderfrom vikingbot.agent.loop import _is_tool_result_successfrom vikingbot.agent.memory import MemoryStore@@ -153,6 +154,21 @@ def test_viking_client_init_root_mode_sets_account_and_user(monkeypatch):assert "agent_id" not in first.kwargs+def test_viking_client_uses_injected_config_without_reloading(monkeypatch):+ config = _make_config("root")++ def _unexpected_load():+ raise AssertionError("VikingClient must not reload Bot config")++ monkeypatch.setattr(ov_server_module, "load_config", _unexpected_load)++ client = VikingClient(config=config)++ assert client.config is config+ assert client.openviking_config is config.ov_server+ assert _DummyHTTPClient.instances[0].kwargs["api_key"] == "root-key"++def test_tool_result_success_only_treats_standard_error_prefix_as_failure():assert _is_tool_result_success("errorCode = 0") is Trueassert _is_tool_result_success("Error budget: 5%") is True@@ -261,37 +277,30 @@ async def test_viking_client_search_preserves_serialized_group_results(monkeypatassert [item["uri"] for item in result["resources"]] == ["viking://resources/解释信-杜涛/解释信-杜涛.md"]- assert [item["uri"] for item in result["skills"]] == [- "viking://user/default/skills/planner.md"- ]+ assert [item["uri"] for item in result["skills"]] == ["viking://user/default/skills/planner.md"]-def test_ov_server_api_key_mode_ignores_bot_root_key_and_uses_ovcli_user_key(monkeypatch):+def test_ov_server_api_key_mode_does_not_read_ovcli_user_key():bot_data = {"root_api_key": "bot-root-key"}ov_data = {"root_api_key": "server-root-key"}- monkeypatch.setattr(- config_loader_module,- "load_ovcli_config",- lambda: SimpleNamespace(api_key="stale-ovcli-key"),- )- config_loader_module._merge_ov_server_config(bot_data, ov_data)+ auth_mode, source, api_key_source = config_loader_module._merge_ov_server_config(+ bot_data, ov_data, server_section_present=True+ )+ assert auth_mode == "api_key"+ assert source == "inherited"+ assert api_key_source == "none"assert bot_data["mode"] == "remote"- assert bot_data["api_key"] == "stale-ovcli-key"+ assert "api_key" not in bot_dataassert bot_data["api_key_type"] == "user"-def test_ov_server_trusted_mode_fills_api_key_from_top_level_root_key(monkeypatch):+def test_ov_server_trusted_mode_fills_api_key_from_top_level_root_key():bot_data = {}ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}- monkeypatch.setattr(- config_loader_module,- "load_ovcli_config",- lambda: SimpleNamespace(api_key="stale-ovcli-key"),- )- config_loader_module._merge_ov_server_config(bot_data, ov_data)+ config_loader_module._merge_ov_server_config(bot_data, ov_data, server_section_present=True)assert bot_data["mode"] == "remote"assert bot_data["api_key"] == "server-root-key"@@ -299,52 +308,37 @@ def test_ov_server_trusted_mode_fills_api_key_from_top_level_root_key(monkeypatcassert bot_data["api_key_type"] == "root"-def test_ov_server_current_trusted_prefers_top_level_root_key(monkeypatch):+def test_ov_server_current_trusted_prefers_top_level_root_key():bot_data = {"api_key": "stale-bot-key"}ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}- monkeypatch.setattr(- config_loader_module,- "load_ovcli_config",- lambda: SimpleNamespace(api_key="stale-ovcli-key"),- )- config_loader_module._merge_ov_server_config(bot_data, ov_data)+ config_loader_module._merge_ov_server_config(bot_data, ov_data, server_section_present=True)assert bot_data["mode"] == "remote"assert bot_data["api_key"] == "server-root-key"assert bot_data["api_key_type"] == "root"-def test_ov_server_external_url_does_not_inherit_trusted_root_key(monkeypatch):+def test_ov_server_external_url_does_not_inherit_trusted_root_key():bot_data = {"server_url": "https://external.example"}ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}- monkeypatch.setattr(- config_loader_module,- "load_ovcli_config",- lambda: SimpleNamespace(api_key="external-user-key"),- )- config_loader_module._merge_ov_server_config(bot_data, ov_data)+ config_loader_module._merge_ov_server_config(bot_data, ov_data, server_section_present=True)assert bot_data["mode"] == "remote"- assert bot_data["api_key"] == "external-user-key"+ assert "api_key" not in bot_dataassert bot_data["api_key_type"] == "user"assert "root_api_key" not in bot_data-def test_ov_server_explicit_url_is_external_even_if_it_matches_local_url(monkeypatch):+def test_ov_server_explicit_url_is_external_even_if_it_matches_local_url():bot_data = {"server_url": "http://localhost:1933"}ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}- monkeypatch.setattr(- config_loader_module,- "load_ovcli_config",- lambda: SimpleNamespace(api_key="stale-ovcli-key"),- )- config_loader_module._merge_ov_server_config(bot_data, ov_data)+ config_loader_module._merge_ov_server_config(bot_data, ov_data, server_section_present=True)assert bot_data["mode"] == "remote"- assert bot_data["api_key"] == "stale-ovcli-key"+ assert "api_key" not in bot_dataassert bot_data["api_key_type"] == "user"assert "root_api_key" not in bot_data@@ -357,7 +351,7 @@ def test_ov_server_external_url_forces_remote_mode():}ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}- config_loader_module._merge_ov_server_config(bot_data, ov_data)+ config_loader_module._merge_ov_server_config(bot_data, ov_data, server_section_present=True)assert bot_data["mode"] == "remote"assert bot_data["api_key"] == "external-user-key"@@ -365,56 +359,178 @@ def test_ov_server_external_url_forces_remote_mode():assert "root_api_key" not in bot_data-def test_ov_server_external_url_root_key_does_not_imply_root_mode(monkeypatch):+def test_ov_server_external_url_root_key_does_not_imply_root_mode():bot_data = {"server_url": "https://external.example","root_api_key": "bot-root-key",}ov_data = {"auth_mode": "trusted", "root_api_key": "server-root-key"}- monkeypatch.setattr(- config_loader_module,- "load_ovcli_config",- lambda: SimpleNamespace(api_key="external-user-key"),- )- config_loader_module._merge_ov_server_config(bot_data, ov_data)+ config_loader_module._merge_ov_server_config(bot_data, ov_data, server_section_present=True)assert bot_data["mode"] == "remote"- assert bot_data["api_key"] == "external-user-key"+ assert "api_key" not in bot_dataassert bot_data["api_key_type"] == "user"assert bot_data["root_api_key"] == "bot-root-key"-def test_ov_server_legacy_mode_is_ignored_for_current_api_key_server(monkeypatch):+def test_ov_server_legacy_mode_is_ignored_for_current_api_key_server():bot_data = {"mode": "local"}ov_data = {"root_api_key": "server-root-key"}- monkeypatch.setattr(- config_loader_module,- "load_ovcli_config",- lambda: SimpleNamespace(api_key="ovcli-user-key"),- )- config_loader_module._merge_ov_server_config(bot_data, ov_data)+ config_loader_module._merge_ov_server_config(bot_data, ov_data, server_section_present=True)assert bot_data["mode"] == "remote"- assert bot_data["api_key"] == "ovcli-user-key"+ assert "api_key" not in bot_dataassert bot_data["api_key_type"] == "user"-def test_ov_server_current_dev_mode_ignores_legacy_api_key_for_mode(monkeypatch):+def test_ov_server_current_dev_mode_ignores_legacy_api_key_for_mode():bot_data = {"api_key": "bot-user-key"}- monkeypatch.setattr(- config_loader_module,- "load_ovcli_config",- lambda: SimpleNamespace(api_key="stale-ovcli-key"),- )- config_loader_module._merge_ov_server_config(bot_data, {})+ config_loader_module._merge_ov_server_config(bot_data, {}, server_section_present=True)assert bot_data["mode"] == "local"assert bot_data["api_key"] == "bot-user-key"+def test_ov_server_without_root_server_section_stays_standalone():+ bot_data = {}++ auth_mode, source, api_key_source = config_loader_module._merge_ov_server_config(+ bot_data,+ {},+ server_section_present=False,+ )++ assert auth_mode == ""+ assert source == "none"+ assert api_key_source == "none"+ assert "source" not in bot_data+ assert bot_data["server_url"] == ""+ assert bot_data["mode"] == "local"+ assert bot_data["api_key_type"] == "user"+++def test_server_managed_load_config_ignores_bot_ov_server(monkeypatch, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text(+ json.dumps(+ {+ "server": {+ "host": "127.0.0.1",+ "port": 1935,+ "auth_mode": "api_key",+ "root_api_key": "root-key",+ },+ "bot": {+ "ov_server": {+ "server_url": "https://remote.example",+ "api_key": "bot-key",+ }+ },+ }+ )+ )+ monkeypatch.setattr(config_loader_module, "CONFIG_PATH", config_path)+ monkeypatch.setenv(config_loader_module.VIKINGBOT_WITH_OPENVIKING_SERVER_ENV, "1")+ config = config_loader_module.load_config()++ assert config.ov_server.server_url == "http://127.0.0.1:1935"+ assert config.ov_server.api_key == ""+ assert config.ov_server.get_config_source() == "inherited"+ assert config.ov_server.get_api_key_source() == "none"+ assert config.ov_server.is_server_managed() is True+++def test_server_managed_load_config_uses_runtime_server_url(monkeypatch, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text(+ json.dumps(+ {+ "server": {+ "host": "127.0.0.1",+ "port": 1935,+ "auth_mode": "api_key",+ "root_api_key": "root-key",+ }+ }+ )+ )+ monkeypatch.setattr(config_loader_module, "CONFIG_PATH", config_path)+ monkeypatch.setenv(config_loader_module.VIKINGBOT_WITH_OPENVIKING_SERVER_ENV, "1")+ monkeypatch.setenv(+ config_loader_module.VIKINGBOT_MANAGED_OV_SERVER_URL_ENV,+ "http://127.0.0.1:1940",+ )++ config = config_loader_module.load_config()++ assert config.ov_server.server_url == "http://127.0.0.1:1940"+ assert config.ov_server.is_server_managed() is True+++def test_vikingbot_load_config_does_not_read_ovcli_conf(monkeypatch, tmp_path):+ config_path = tmp_path / "ov.conf"+ config_path.write_text(+ json.dumps(+ {+ "server": {+ "host": "127.0.0.1",+ "port": 1935,+ "auth_mode": "api_key",+ "root_api_key": "root-key",+ },+ "bot": {"ov_server": {"api_key": "bot-user-key"}},+ }+ )+ )+ invalid_cli_path = tmp_path / "ovcli.conf"+ invalid_cli_path.write_text(json.dumps({"account_id": "legacy-account"}))+ monkeypatch.setattr(config_loader_module, "CONFIG_PATH", config_path)+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(invalid_cli_path))++ config = config_loader_module.load_config()++ assert not hasattr(config_loader_module, "load_ovcli_config")+ assert config.ov_server.api_key == "bot-user-key"+ assert config.ov_server.get_api_key_source() == "bot.ov_server.api_key"+++async def test_memory_store_passes_injected_config_to_request_client(monkeypatch, tmp_path):+ config = _make_config("root")+ captured = {}++ def _unexpected_load():+ raise AssertionError("MemoryStore must not reload Bot config")++ class _FakeClient:+ async def read_peer_profile(self, peer_id):+ return f"profile:{peer_id}"++ async def close(self):+ return None++ async def _create(**kwargs):+ captured.update(kwargs)+ return _FakeClient()++ monkeypatch.setattr(memory_module, "load_config", _unexpected_load)+ monkeypatch.setattr(memory_module, "VikingClient", SimpleNamespace(create=_create))++ store = MemoryStore(tmp_path, config=config)+ result = await store.get_viking_peer_profile(+ workspace_id="workspace",+ peer_id="peer-a",+ openviking_connection={"api_key": "request-key"},+ )++ assert result == "profile:peer-a"+ assert captured["config"] is config+ assert captured["connection"] == {"api_key": "request-key"}++def _auth_probe(*, ok=True, status_code=200, data=None, error=""):return config_loader_module._OpenVikingHTTPResult(ok=ok,@@ -427,6 +543,7 @@ def _auth_probe(*, ok=True, status_code=200, data=None, error=""):def test_validate_openviking_auth_warns_when_server_unavailable(monkeypatch, capsys):config = SimpleNamespace(ov_server=SimpleNamespace(+ _source="inherited",mode="remote",api_key_type="user",api_key="user-key",@@ -444,13 +561,89 @@ def test_validate_openviking_auth_warns_when_server_unavailable(monkeypatch, capcaptured = capsys.readouterr()assert "OpenViking server at http://ov.local is unavailable" in captured.err- assert "Only basic VikingBot features are available" in captured.err+ assert "standalone mode" in captured.errassert "user-key" not in captured.err+ assert config.ov_server.server_url == ""+ assert config.ov_server.mode == "local"+++def test_validate_openviking_auth_exits_when_explicit_server_unavailable(monkeypatch, capsys):+ config = SimpleNamespace(+ ov_server=SimpleNamespace(+ _source="explicit",+ mode="remote",+ api_key_type="user",+ api_key="user-key",+ root_api_key="",+ server_url="http://ov.remote",+ )+ )+ monkeypatch.setattr(+ config_loader_module,+ "_request_openviking_json",+ lambda *_args, **_kwargs: _auth_probe(ok=False, error="ConnectError"),+ )++ with pytest.raises(SystemExit):+ config_loader_module.validate_openviking_auth(config)++ captured = capsys.readouterr()+ assert "configured bot.ov_server.server_url is unavailable" in captured.err+ assert "OpenViking server URL: http://ov.remote" in captured.err+ assert "user-key" not in captured.err+++def test_validate_openviking_auth_keeps_managed_upstream_while_server_starts(monkeypatch, capsys):+ config = SimpleNamespace(+ ov_server=SimpleNamespace(+ _source="inherited",+ _server_managed=True,+ mode="remote",+ api_key_type="user",+ api_key="",+ root_api_key="",+ server_url="http://127.0.0.1:1935",+ )+ )+ monkeypatch.setattr(+ config_loader_module,+ "_request_openviking_json",+ lambda *_args, **_kwargs: _auth_probe(ok=False, status_code=None, error="ConnectError"),+ )++ config_loader_module.validate_openviking_auth(config)++ assert config.ov_server.server_url == "http://127.0.0.1:1935"+ assert "keep the inherited upstream" in capsys.readouterr().err+++def test_validate_openviking_auth_does_not_downgrade_inherited_auth_failure(monkeypatch):+ config = SimpleNamespace(+ ov_server=SimpleNamespace(+ _source="inherited",+ mode="remote",+ api_key_type="user",+ api_key="bad-user-key",+ root_api_key="",+ server_url="http://ov.local",+ )+ )+ monkeypatch.setattr(+ config_loader_module,+ "_request_openviking_json",+ lambda *_args, **_kwargs: _auth_probe(ok=False, status_code=401),+ )++ with pytest.raises(SystemExit):+ config_loader_module.validate_openviking_auth(config)++ assert config.ov_server.server_url == "http://ov.local"def test_validate_openviking_auth_exits_for_auth_mode_mismatch(monkeypatch, capsys):config = SimpleNamespace(ov_server=SimpleNamespace(+ _source="inherited",mode="remote",api_key_type="user",api_key="user-key",@@ -468,15 +661,47 @@ def test_validate_openviking_auth_exits_for_auth_mode_mismatch(monkeypatch, capsconfig_loader_module.validate_openviking_auth(config)captured = capsys.readouterr()- assert "auth mode mismatch" in captured.err+ assert "does not match the current ov.conf" in captured.errassert "OpenViking server URL: http://ov.local" in captured.err- assert "Actual server auth_mode: trusted" in captured.err- assert "VikingBot current auth_mode: api_key" in captured.err- assert "bot.ov_server.api_key_type to 'root'" in captured.err+ assert "Running server auth_mode: trusted" in captured.err+ assert "Current ov.conf server auth_mode: api_key" in captured.err+ assert "restart OpenViking server with the current ov.conf" in captured.err+ assert "server.auth_mode='trusted'" in captured.err+ assert "bot.ov_server.api_key_type" not in captured.errassert "user-key" not in captured.err-def test_validate_openviking_auth_warns_for_api_key_mode_without_user_key(monkeypatch, capsys):+def test_inherited_dev_config_mismatch_explains_stale_api_key_server(monkeypatch, capsys):+ config = SimpleNamespace(+ ov_server=SimpleNamespace(+ _source="inherited",+ effective_auth_mode="dev",+ mode="local",+ api_key_type="user",+ api_key="",+ root_api_key="",+ server_url="http://127.0.0.1:1935",+ )+ )+ monkeypatch.setattr(+ config_loader_module,+ "_request_openviking_json",+ lambda *_args, **_kwargs: _auth_probe(data={"auth_mode": "api_key"}),+ )++ with pytest.raises(SystemExit):+ config_loader_module.validate_openviking_auth(config)++ captured = capsys.readouterr()+ assert "Running server auth_mode: api_key" in captured.err+ assert "Current ov.conf server auth_mode: dev" in captured.err+ assert "started with different authentication settings" in captured.err+ assert "configure bot.ov_server.api_key with an OpenViking User/Admin API key" in captured.err+ assert "dev-mode VikingBot gateway must listen on localhost" in captured.err+ assert "bot.ov_server.api_key_type" not in captured.err+++def test_validate_openviking_auth_exits_for_api_key_mode_without_user_key(monkeypatch, capsys):config = SimpleNamespace(ov_server=SimpleNamespace(mode="remote",@@ -492,16 +717,17 @@ def test_validate_openviking_auth_warns_for_api_key_mode_without_user_key(monkeylambda *_args, **_kwargs: _auth_probe(data={"auth_mode": "api_key"}),)- config_loader_module.validate_openviking_auth(config)+ with pytest.raises(SystemExit):+ config_loader_module.validate_openviking_auth(config)captured = capsys.readouterr()- assert "Warning:" in captured.err- assert "OpenViking User API key" in captured.err+ assert "Error:" in captured.err+ assert "OpenViking User/Admin API key" in captured.errassert "bot.ov_server.api_key" in captured.errassert "Root API keys cannot access" in captured.err-def test_validate_openviking_auth_warns_when_user_key_is_root(monkeypatch, capsys):+def test_validate_openviking_auth_exits_when_user_key_is_root(monkeypatch, capsys):config = SimpleNamespace(ov_server=SimpleNamespace(mode="remote",@@ -528,7 +754,8 @@ def test_validate_openviking_auth_warns_when_user_key_is_root(monkeypatch, capsymonkeypatch.setattr(config_loader_module, "_request_openviking_json", _fake_probe)- config_loader_module.validate_openviking_auth(config)+ with pytest.raises(SystemExit):+ config_loader_module.validate_openviking_auth(config)captured = capsys.readouterr()assert "resolves to a ROOT API key" in captured.err@@ -575,7 +802,7 @@ def test_validate_openviking_auth_uses_effective_auth_mode_not_legacy_mode(monkeapi_key_type="user",api_key="configured-key",root_api_key="",- server_url="http://ov.local",+ server_url="http://127.0.0.1:1935",))monkeypatch.setattr(@@ -590,7 +817,7 @@ def test_validate_openviking_auth_uses_effective_auth_mode_not_legacy_mode(monkeassert captured.err == ""-def test_validate_openviking_auth_warns_for_trusted_bad_root_key(monkeypatch, capsys):+def test_validate_openviking_auth_exits_for_trusted_bad_root_key(monkeypatch, capsys):config = SimpleNamespace(ov_server=SimpleNamespace(mode="remote",@@ -615,10 +842,11 @@ def test_validate_openviking_auth_warns_for_trusted_bad_root_key(monkeypatch, camonkeypatch.setattr(config_loader_module, "_request_openviking_json", _fake_probe)- config_loader_module.validate_openviking_auth(config)+ with pytest.raises(SystemExit):+ config_loader_module.validate_openviking_auth(config)captured = capsys.readouterr()- assert "configured root API key was rejected" in captured.err+ assert "no valid root API key is available" in captured.errassert "configured-root" not in captured.err@@ -724,9 +952,11 @@ def test_viking_client_request_connection_uses_active_identity(monkeypatch):assert client.should_sender_fanout() is Falseassert client._memory_target_uri(None) == "viking://user/memories/"assert first.kwargs == {- "url": "http://studio.local",+ "url": "http://ov.local","api_key": "anonymous-key","profile_enabled": False,+ "account": "acct",+ "user": "anonymous",}@@ -748,7 +978,7 @@ def test_viking_client_request_connection_preserves_trusted_scope(monkeypatch):first = _DummyHTTPClient.instances[0]assert first.kwargs == {- "url": "http://studio.local",+ "url": "http://ov.local","api_key": "admin-key","profile_enabled": False,"account": "acct",@@ -773,13 +1003,34 @@ def test_viking_client_request_connection_allows_trusted_no_key(monkeypatch):first = _DummyHTTPClient.instances[0]assert first.kwargs == {- "url": "http://studio.local",+ "url": "http://ov.local","profile_enabled": False,"account": "acct","user": "alice",}+def test_viking_client_request_connection_does_not_fill_identity_from_bot_config(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))++ client = VikingClient(+ connection={+ "server_url": "http://untrusted.local",+ "api_key": "request-key",+ "api_key_type": "user",+ },+ )++ first = _DummyHTTPClient.instances[0]+ assert client.account_id is None+ assert client.admin_user_id is None+ assert first.kwargs == {+ "url": "http://ov.local",+ "api_key": "request-key",+ "profile_enabled": False,+ }++@pytest.mark.asyncioasync def test_commit_user_mode_uses_user_key_client_only(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))@@ -2381,17 +2632,21 @@ async def test_openviking_search_actor_client_expands_current_peer_scope(monkeyp@pytest.mark.asyncio-async def test_openviking_tool_sender_uses_actor_scoped_one_shot_client(monkeypatch):+async def test_openviking_tool_uses_authenticated_actor_instead_of_display_sender(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))tool = VikingSearchTool()result = await tool.execute(- SimpleNamespace(workspace_id="workspace", sender_id="sender-1"),+ SimpleNamespace(+ workspace_id="workspace",+ sender_id="display-user",+ actor_peer_id="peer-a",+ ),query="hello",)first = _DummyHTTPClient.instances[0]- assert first.kwargs["actor_peer_id"] == "sender-1"+ assert first.kwargs["actor_peer_id"] == "peer-a"assert first.closed is Trueassert "No results found" in result@@ -2812,7 +3067,7 @@ async def test_experience_reminder_follows_direct_case_experience_links(monkeypacase_uri = "viking://user/admin/memories/cases/case1.md"exp_uri = "viking://user/admin/memories/experiences/exp1.md"direct_exp_uri = "viking://user/admin/memories/experiences/direct.md"- case_content = MemoryFileUtils.write(+ MemoryFileUtils.write(MemoryFile(uri=case_uri,content="# case1\n\n## Linked Experiences\n- exp1",diff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.pyindex 3d4a1b086..854537b83 100644--- a/bot/vikingbot/agent/context.py+++ b/bot/vikingbot/agent/context.py@@ -6,7 +6,7 @@ import platformimport time as _timefrom datetime import datetimefrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Anyfrom loguru import logger@@ -16,6 +16,9 @@ from vikingbot.config.schema import SessionKeyfrom vikingbot.sandbox import SandboxManagerfrom vikingbot.utils.helpers import ensure_non_empty_assistant_content+if TYPE_CHECKING:+ from vikingbot.config.schema import Config+class ContextBuilder:"""@@ -33,11 +36,13 @@ class ContextBuilder:workspace: Path,sandbox_manager: SandboxManager | None = None,sender_id: str = None,+ actor_peer_id: str = None,sender_name: str = None,is_group_chat: bool = False,eval: bool = False,openviking_connection: dict[str, Any] | None = None,enable_subagents: bool = True,+ config: "Config | None" = None,):self.workspace = workspaceself._templates_ensured = False@@ -45,18 +50,20 @@ class ContextBuilder:self._memory = Noneself._skills = Noneself._sender_id = sender_id+ self._actor_peer_id = actor_peer_id or sender_idself._sender_name = sender_nameself._is_group_chat = is_group_chatself._eval = evalself._openviking_connection = openviking_connectionself._enable_subagents = enable_subagents+ self._config = configself.latest_relevant_memories: str | None = None@propertydef memory(self):"""Lazy-load MemoryStore when first needed."""if self._memory is None:- self._memory = MemoryStore(self.workspace)+ self._memory = MemoryStore(self.workspace, config=self._config)return self._memory@property@@ -165,13 +172,13 @@ Skills with available="false" need dependencies installed first - you can try in# OpenViking identity model, the bot API key owns the User, and the# message sender is represented as a peer under that User.if ov_tools_enable:- # Fetch current sender's peer profile+ # Fetch the authenticated actor's peer profile.start = _time.time()profile = await self.memory.get_viking_peer_profile(workspace_id=workspace_id,- peer_id=self._sender_id,+ peer_id=self._actor_peer_id,openviking_connection=self._openviking_connection,- actor_peer_id=self._sender_id,+ actor_peer_id=self._actor_peer_id,)cost = round(_time.time() - start, 2)logger.info(@@ -185,14 +192,14 @@ Skills with available="false" need dependencies installed first - you can try in# is retained for compatibility with older deployments.additional_peer_ids = self._dedupe_ids([*(profile_user_list or []), *(memory_peer_ids or [])],- exclude={self._sender_id} if self._sender_id else set(),+ exclude={self._actor_peer_id} if self._actor_peer_id else set(),)if additional_peer_ids:profiles = await self.memory.get_viking_peer_profiles(workspace_id=workspace_id,peer_ids=additional_peer_ids,openviking_connection=self._openviking_connection,- use_peer_actor_scope=bool(self._sender_id),+ use_peer_actor_scope=bool(self._actor_peer_id),)if profiles:parts.append(profiles)@@ -240,7 +247,7 @@ Skills with available="false" need dependencies installed first - you can try inif ov_tools_enable:start = _time.time()# Default recall runs under the configured/request OpenViking user.- # sender_id is passed separately as peer identity.+ # actor_peer_id is passed separately as peer identity.search_peer_ids = memory_peer_ids if memory_peer_ids else Noneviking_memory = await self.memory.get_viking_memory_context(current_message=current_message,@@ -269,8 +276,6 @@ Skills with available="false" need dependencies installed first - you can try in"- For relevant summary or uri entries, use openviking_multi_read on their URIs to fetch full details to help you to resolve the query. ")--parts.append("Reply in the same language as the user's query, ignoring the language of the reference materials. User's query:")@@ -423,7 +428,7 @@ IMPORTANT:user_info = await self._build_user_memory(session_key,current_message,- self._sender_id,+ self._actor_peer_id,memory_peer_ids,memory_owner_user_ids,ov_tools_enable=ov_tools_enable,diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex 7616715ab..0122b976c 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -8,8 +8,8 @@ import reimport timeimport uuidfrom contextlib import AsyncExitStack-from datetime import datetimefrom dataclasses import dataclass+from datetime import datetimefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -22,7 +22,6 @@ from vikingbot.agent.tools import register_default_toolsfrom vikingbot.agent.tools.registry import ToolRegistryfrom vikingbot.bus.events import InboundMessage, OutboundEventType, OutboundMessagefrom vikingbot.bus.queue import MessageBus-from vikingbot.config import load_configfrom vikingbot.config.schema import BotMode, Config, SessionKeyfrom vikingbot.heartbeat.service import HEARTBEAT_METADATA_KEY, is_heartbeat_noop_responsefrom vikingbot.hooks import HookContext@@ -87,8 +86,6 @@ class _PlainTextFinal:content: str | None = None--class AgentLoop:"""The agent loop is the core processing engine.@@ -175,13 +172,14 @@ class AgentLoop:workspace,sandbox_manager=sandbox_manager,enable_subagents=self._subagents_enabled(),+ config=self.config,)self._register_builtin_hooks()self.sessions = session_manager or SessionManager(self.config.bot_data_path, sandbox_manager=sandbox_manager)- self.tools = ToolRegistry()+ self.tools = ToolRegistry(config=self.config)self._eval = evalself.subagents = SubagentManager(provider=provider,@@ -376,6 +374,7 @@ class AgentLoop:subagent_manager=self.subagents,cron_service=self.cron_service,include_spawn_tool=self._subagents_enabled(),+ include_viking_tools=self.config.ov_server.is_available(),)def _subagents_enabled(self) -> bool:@@ -384,7 +383,11 @@ class AgentLoop:def _ov_session_context_enabled(self) -> bool:agents_config = getattr(self.config, "agents", None)- return bool(agents_config and getattr(agents_config, "session_context_enabled", False))+ return bool(+ self.config.ov_server.is_available()+ and agents_config+ and getattr(agents_config, "session_context_enabled", False)+ )def _get_ov_workspace_id(self, session_key: SessionKey) -> str:if self.sandbox_manager:@@ -405,13 +408,14 @@ class AgentLoop:workspace_id,connection=openviking_connection,actor_peer_id=actor_peer_id,+ config=self.config,)client = self._ov_clients.get(workspace_id)if client is None:from vikingbot.openviking_mount.ov_server import VikingClient- client = await VikingClient.create(workspace_id)+ client = await VikingClient.create(workspace_id, config=self.config)self._ov_clients[workspace_id] = clientreturn client@@ -563,6 +567,8 @@ class AgentLoop:session_id=get_openviking_session_id(session),workspace_id=self._get_ov_workspace_id(session.key),session_key=session.key,+ config=self.config,+ openviking_connection=openviking_connection,),**kwargs,)@@ -697,6 +703,7 @@ class AgentLoop:session_key: SessionKey,publish_events: bool = True,sender_id: str | None = None,+ actor_peer_id: str | None = None,ov_tools_enable: bool = True,memory_peer_ids: list[str] | None = None,memory_owner_user_ids: list[str] | None = None,@@ -713,6 +720,7 @@ class AgentLoop:messages: Initial message listsession_key: Session key for tool execution contextpublish_events: Whether to publish ITERATION/REASONING/TOOL_CALL events to the bus+ actor_peer_id: Authenticated OpenViking peer identity for toolsov_tools_enable: Whether to enable OpenViking tools for this sessionmemory_peer_ids: List of peer IDs for memory retrievalmemory_owner_user_ids: List of explicit OpenViking user IDs for@@ -787,7 +795,7 @@ class AgentLoop:if response.has_tool_calls:# Inject experience memory before write-related tool calls (once per session)if not write_exp_injected:- _ov_cfg = load_config().ov_server+ _ov_cfg = self.config.ov_server_write_tools = set(_ov_cfg.exp_write_tools)if any(tc.name in _write_tools for tc in response.tool_calls):write_exp_injected = True@@ -853,6 +861,7 @@ class AgentLoop:session_key=session_key,sandbox_manager=self.sandbox_manager,sender_id=sender_id,+ actor_peer_id=actor_peer_id or sender_id,memory_peer_ids=memory_peer_ids,memory_owner_user_ids=memory_owner_user_ids,openviking_connection=openviking_connection,@@ -908,8 +917,7 @@ class AgentLoop:tools_used.append(tool_used_dict)if any(- tool_call.name in stop_tools- for _idx, tool_call, _result, _duration in results+ tool_call.name in stop_tools for _idx, tool_call, _result, _duration in results):final_content = ""break@@ -969,7 +977,9 @@ class AgentLoop:if final_content == "" and tools_used and tools_used[-1].get("tool_name") in stop_tools:pass- elif final_content is None or (isinstance(final_content, str) and not final_content.strip()):+ elif final_content is None or (+ isinstance(final_content, str) and not final_content.strip()+ ):if iteration >= self.max_iterations:messages.append({@@ -983,7 +993,11 @@ class AgentLoop:),})- response, _streamed_content, streamed_reasoning = await self._chat_with_stream_events(+ (+ response,+ _streamed_content,+ streamed_reasoning,+ ) = await self._chat_with_stream_events(messages=messages,tools=[],session_key=session_key,@@ -1084,11 +1098,11 @@ class AgentLoop:if not isinstance(disabled_tools, list):disabled_tools = []openviking_connection = getattr(msg, "openviking_connection", None)- if openviking_connection is None and msg.metadata:- openviking_connection = msg.metadata.get("openviking_connection")if not isinstance(openviking_connection, dict):openviking_connection = Nonemsg.openviking_connection = openviking_connection+ actor_peer_id = getattr(msg, "actor_peer_id", None) or msg.sender_id+ msg.actor_peer_id = actor_peer_idprofile_user_list = []memory_peer_ids = self._metadata_memory_peer_ids(msg.metadata)memory_owner_user_ids = self._metadata_memory_owner_user_ids(msg.metadata)@@ -1152,7 +1166,11 @@ class AgentLoop:session.clear()await self.sessions.save(session)# Run consolidation in background- await self._safe_consolidate_memory(session_clone, archive_all=True)+ await self._safe_consolidate_memory(+ session_clone,+ archive_all=True,+ openviking_connection=openviking_connection,+ )return OutboundMessage(session_key=msg.session_key,content="🐈 New session started. Memory consolidated.",@@ -1179,7 +1197,10 @@ class AgentLoop:)elif ov_tools_enable:session_clone = session.clone()- await self._consolidate_viking_memory(session_clone)+ await self._consolidate_viking_memory(+ session_clone,+ openviking_connection=openviking_connection,+ )return OutboundMessage(session_key=msg.session_key,content="This conversation has been submitted to memory storage.",@@ -1223,7 +1244,11 @@ class AgentLoop:session.messages = session.messages[-keep_count:] if keep_count else []await self.sessions.save(session)# Run consolidation in background- await self._safe_consolidate_memory(session_clone, archive_all=False)+ await self._safe_consolidate_memory(+ session_clone,+ archive_all=False,+ openviking_connection=openviking_connection,+ )if self.sandbox_manager:message_workspace = self.sandbox_manager.get_workspace_path(session_key)@@ -1236,11 +1261,13 @@ class AgentLoop:message_workspace,sandbox_manager=self.sandbox_manager,sender_id=msg.sender_id,+ actor_peer_id=actor_peer_id,sender_name=msg.sender_name,is_group_chat=is_group_chat,eval=self._eval,openviking_connection=openviking_connection,enable_subagents=self._subagents_enabled(),+ config=self.config,)# Build initial messages (use OpenViking session context when enabled)@@ -1249,7 +1276,7 @@ class AgentLoop:session,provider_name=provider_name,openviking_connection=openviking_connection,- actor_peer_id=msg.sender_id,+ actor_peer_id=actor_peer_id,)# Experience recall deduplication: URIs already recalled in this session@@ -1280,9 +1307,7 @@ class AgentLoop:# Track newly recalled experience URIs for deduplicationnewly_recalled_exp_uris = getattr(message_context, "latest_recalled_exp_uris", [])- newly_recalled_exp_content = getattr(- message_context, "latest_recalled_exp_content", ""- )+ newly_recalled_exp_content = getattr(message_context, "latest_recalled_exp_content", "")if newly_recalled_exp_uris:existing_uris = set(exp_exclude_uris)for uri in newly_recalled_exp_uris:@@ -1305,6 +1330,7 @@ class AgentLoop:session_key=session_key,publish_events=True,sender_id=msg.sender_id,+ actor_peer_id=actor_peer_id,ov_tools_enable=ov_tools_enable,memory_peer_ids=memory_peer_ids,memory_owner_user_ids=memory_owner_user_ids,@@ -1533,6 +1559,8 @@ class AgentLoop:Returns:True if ov tools should be enabled, False otherwise"""+ if not self.config.ov_server.is_available():+ return Falsechannel_config = self._get_channel_config(session_key)return getattr(channel_config, "ov_tools_enable", True) if channel_config else True@@ -1556,12 +1584,30 @@ class AgentLoop:# Build messages with the announce contentprovider_name = self.config.get_provider_name(self.model) if self.config else None+ actor_peer_id = getattr(msg, "actor_peer_id", None) or msg.sender_idhistory = await self._build_prompt_history(session,provider_name=provider_name,- actor_peer_id=msg.sender_id,+ openviking_connection=msg.openviking_connection,+ actor_peer_id=actor_peer_id,)- messages = await self.context.build_messages(+ from vikingbot.agent.context import ContextBuilder++ message_workspace = (+ self.sandbox_manager.get_workspace_path(msg.session_key)+ if self.sandbox_manager+ else self.workspace+ )+ message_context = ContextBuilder(+ message_workspace,+ sandbox_manager=self.sandbox_manager,+ sender_id=msg.sender_id,+ actor_peer_id=actor_peer_id,+ openviking_connection=msg.openviking_connection,+ enable_subagents=self._subagents_enabled(),+ config=self.config,+ )+ messages = await message_context.build_messages(history=history,current_message=msg.content,session_key=msg.session_key,@@ -1580,8 +1626,11 @@ class AgentLoop:messages=messages,session_key=msg.session_key,publish_events=False,+ sender_id=msg.sender_id,+ actor_peer_id=actor_peer_id,ov_tools_enable=ov_tools_enable,memory_peer_ids=None,+ openviking_connection=msg.openviking_connection,channel_metadata=msg.metadata,)@@ -1604,7 +1653,12 @@ class AgentLoop:metadata=dict(msg.metadata or {}),)- async def _consolidate_memory(self, session, archive_all: bool = False) -> None:+ async def _consolidate_memory(+ self,+ session,+ archive_all: bool = False,+ openviking_connection: dict[str, Any] | None = None,+ ) -> None:"""Consolidate old messages into MEMORY.md + HISTORY.md. Works on a cloned session."""try:if not session.messages:@@ -1622,14 +1676,18 @@ class AgentLoop:allow_from.extend(channel_config.allow_from)messages = [msg for msg in session.messages if msg.get("sender_id") in allow_from]session.messages = messages- await self._consolidate_viking_memory(session)+ if self.config.ov_server.is_available():+ await self._consolidate_viking_memory(+ session,+ openviking_connection=openviking_connection,+ )if self.sandbox_manager:memory_workspace = self.sandbox_manager.get_workspace_path(session.key)else:memory_workspace = self.workspace- memory = MemoryStore(memory_workspace)+ memory = MemoryStore(memory_workspace, config=self.config)if archive_all:old_messages = session.messageskeep_count = 0@@ -1695,7 +1753,7 @@ Respond with ONLY valid JSON, no markdown fences."""if entry := result.get("history_entry"):memory.append_history(entry)if update := result.get("memory_update"):- if load_config().use_local_memory and update != current_memory:+ if self.config.use_local_memory and update != current_memory:memory.write_long_term(update)# Session trimming and saving is handled by the caller before calling _consolidate_memory@@ -1704,7 +1762,11 @@ Respond with ONLY valid JSON, no markdown fences."""except Exception as e:logger.exception(f"Memory consolidation failed: {e}")- async def _consolidate_viking_memory(self, session) -> None:+ async def _consolidate_viking_memory(+ self,+ session,+ openviking_connection: dict[str, Any] | None = None,+ ) -> None:"""Consolidate old messages into MEMORY.md + HISTORY.md. Works on a cloned session."""try:if not session.messages:@@ -1718,18 +1780,30 @@ Respond with ONLY valid JSON, no markdown fences."""context=HookContext(event_type="message.compact",session_id=session.key.safe_name(),- workspace_id=self.sandbox_manager.to_workspace_id(session.key),+ workspace_id=self._get_ov_workspace_id(session.key),session_key=session.key,+ config=self.config,+ openviking_connection=openviking_connection,),session=session,+ openviking_connection=openviking_connection,)except Exception as e:logger.exception(f"Memory consolidation failed: {e}")- async def _safe_consolidate_memory(self, session, archive_all: bool = False) -> None:+ async def _safe_consolidate_memory(+ self,+ session,+ archive_all: bool = False,+ openviking_connection: dict[str, Any] | None = None,+ ) -> None:"""Safe wrapper for _consolidate_memory that ensures all exceptions are caught."""try:- await self._consolidate_memory(session, archive_all)+ await self._consolidate_memory(+ session,+ archive_all,+ openviking_connection=openviking_connection,+ )except Exception as e:logger.exception(f"Background memory consolidation task failed: {e}")diff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.pyindex 4573e898a..ad3bcd54a 100644--- a/bot/vikingbot/agent/memory.py+++ b/bot/vikingbot/agent/memory.py@@ -5,7 +5,7 @@ import jsonimport reimport timefrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Anyfrom loguru import logger@@ -13,6 +13,9 @@ from vikingbot.config.loader import load_configfrom vikingbot.openviking_mount.ov_server import VikingClientfrom vikingbot.utils.helpers import ensure_dir+if TYPE_CHECKING:+ from vikingbot.config.schema import Config+_LEGACY_MEMORY_RECALL_LIMIT = 30_TYPE_QUOTA_MEMORY_TYPES = ("events", "entities", "preferences")_TYPE_QUOTA_EVENT_CHAR_RATIO = 0.75@@ -45,10 +48,16 @@ _MEMORY_TYPE_DESCRIPTIONS = {class MemoryStore:"""Two-layer memory: MEMORY.md (long-term facts) + HISTORY.md (grep-searchable log)."""- def __init__(self, workspace: Path):+ def __init__(self, workspace: Path, config: "Config | None" = None):self.memory_dir = ensure_dir(workspace / "memory")self.memory_file = self.memory_dir / "MEMORY.md"self.history_file = self.memory_dir / "HISTORY.md"+ self._config = config++ def _get_config(self) -> "Config":+ if self._config is None:+ self._config = load_config()+ return self._config@staticmethoddef _get_score(memory: Any) -> float:@@ -501,6 +510,7 @@ class MemoryStore:agent_id=workspace_id,connection=openviking_connection,actor_peer_id=normalized_peer_id,+ config=self._get_config(),)should_close = True@@ -543,7 +553,8 @@ class MemoryStore:client = Noneread_clients: dict[str, VikingClient] = {}try:- ov_cfg = load_config().ov_server+ config = self._get_config()+ ov_cfg = config.ov_serveradmin_user_id = (str(openviking_connection.get("user_id"))if isinstance(openviking_connection, dict) and openviking_connection.get("user_id")@@ -559,6 +570,7 @@ class MemoryStore:agent_id=workspace_id,connection=openviking_connection,actor_peer_id=sender_id,+ config=config,)if sender_id:search_peer_ids = [sender_id, *(peer_ids or [])]@@ -617,6 +629,7 @@ class MemoryStore:agent_id=workspace_id,connection=openviking_connection,actor_peer_id=memory_peer_id,+ config=config,)read_clients[memory_peer_id] = peer_clientreturn await peer_client.read_content(uri, level=level)@@ -703,10 +716,12 @@ class MemoryStore:)client = Nonetry:- ov_cfg = load_config().ov_server+ config = self._get_config()+ ov_cfg = config.ov_serverclient = await VikingClient.create(agent_id=workspace_id,connection=openviking_connection,+ config=config,)case_limit = max(0, int(getattr(ov_cfg, "case_recall_limit", 0) or 0))if case_lookup:@@ -799,10 +814,12 @@ class MemoryStore:) -> tuple[str, list[str]]:client = Nonetry:- ov_cfg = load_config().ov_server+ config = self._get_config()+ ov_cfg = config.ov_serverclient = await VikingClient.create(agent_id=workspace_id,connection=openviking_connection,+ config=config,)case_limit = max(1, int(getattr(ov_cfg, "case_recall_limit", 0) or 1))cases = await self._find_cases_by_lookup(@@ -1267,6 +1284,7 @@ class MemoryStore:agent_id=workspace_id,connection=openviking_connection,actor_peer_id=actor_peer_id or peer_id,+ config=self._get_config(),)result = await client.read_peer_profile(peer_id)return result or ""@@ -1296,6 +1314,7 @@ class MemoryStore:client = await VikingClient.create(agent_id=workspace_id,connection=openviking_connection,+ config=self._get_config(),)async def fetch_profile(peer_id: str) -> tuple[str, str]:@@ -1307,6 +1326,7 @@ class MemoryStore:agent_id=workspace_id,connection=openviking_connection,actor_peer_id=peer_id,+ config=self._get_config(),)should_close = Truestart_time = time.time()diff --git a/bot/vikingbot/agent/subagent.py b/bot/vikingbot/agent/subagent.pyindex 6101eed3a..5c2f5432c 100644--- a/bot/vikingbot/agent/subagent.py+++ b/bot/vikingbot/agent/subagent.py@@ -2,9 +2,11 @@import asyncioimport json+import time as _timeimport uuid+from datetime import datetimefrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Anyfrom loguru import logger@@ -16,6 +18,9 @@ from vikingbot.providers.base import LLMProviderfrom vikingbot.sandbox.manager import SandboxManagerfrom vikingbot.utils.helpers import ensure_non_empty_assistant_content+if TYPE_CHECKING:+ from vikingbot.config.schema import Config+class SubagentManager:"""@@ -36,8 +41,6 @@ class SubagentManager:temperature: float = 0.7,sandbox_manager: "SandboxManager | None" = None,):- from vikingbot.config.schema import ExecToolConfig-self.provider = providerself.workspace = workspaceself.bus = bus@@ -53,6 +56,7 @@ class SubagentManager:session_key: SessionKey,label: str | None = None,channel_metadata: dict[str, Any] | None = None,+ openviking_connection: dict[str, Any] | None = None,) -> str:"""Spawn a subagent to execute a task in the background.@@ -77,6 +81,7 @@ class SubagentManager:display_label,session_key,dict(channel_metadata or {}),+ openviking_connection,))self._running_tasks[task_id] = bg_task@@ -94,6 +99,7 @@ class SubagentManager:label: str,session_key: SessionKey,channel_metadata: dict[str, Any] | None = None,+ openviking_connection: dict[str, Any] | None = None,) -> None:"""Execute the subagent task and announce the result."""logger.info(f"Subagent [{task_id}] starting task: {label}")@@ -102,7 +108,7 @@ class SubagentManager:# Build subagent tools (no message tool, no spawn tool)from vikingbot.agent.tools import register_subagent_tools- tools = ToolRegistry()+ tools = ToolRegistry(config=self.config)register_subagent_tools(registry=tools,config=self.config,@@ -112,14 +118,19 @@ class SubagentManager:task_content = tasktry:from vikingbot.agent.memory import MemoryStore- memory_store = MemoryStore(self.workspace)++ if not self.config.ov_server.is_available():+ raise RuntimeError("OpenViking is unavailable")+ memory_store = MemoryStore(self.workspace, config=self.config)workspace_id = (self.sandbox_manager.to_workspace_id(session_key)if self.sandbox_managerelse "shared")exp_memory = await memory_store.get_viking_experience_context(- query=task, workspace_id=workspace_id+ query=task,+ workspace_id=workspace_id,+ openviking_connection=openviking_connection,)if exp_memory:task_content = f"## Agent Experience (relevant to this task)\n{exp_memory}\n\n---\n\n{task}"@@ -181,6 +192,7 @@ class SubagentManager:tool_call.arguments,session_key=session_key,sandbox_manager=self.sandbox_manager,+ openviking_connection=openviking_connection,)messages.append({@@ -199,14 +211,28 @@ class SubagentManager:logger.info(f"Subagent [{task_id}] completed successfully")await self._announce_result(- task_id, label, task, final_result, session_key, "ok", channel_metadata+ task_id,+ label,+ task,+ final_result,+ session_key,+ "ok",+ channel_metadata,+ openviking_connection,)except Exception as e:error_msg = f"Error: {str(e)}"logger.exception(f"Subagent [{task_id}] failed: {e}")await self._announce_result(- task_id, label, task, error_msg, session_key, "error", channel_metadata+ task_id,+ label,+ task,+ error_msg,+ session_key,+ "error",+ channel_metadata,+ openviking_connection,)async def _announce_result(@@ -218,6 +244,7 @@ class SubagentManager:session_key: SessionKey,status: str,channel_metadata: dict[str, Any] | None = None,+ openviking_connection: dict[str, Any] | None = None,) -> None:"""Announce the subagent result to the main agent via the message bus."""status_text = "completed successfully" if status == "ok" else "failed"@@ -237,6 +264,7 @@ Summarize this naturally for the user. Keep it brief (1-2 sentences). Do not mensession_key=session_key,content=announce_content,metadata=dict(channel_metadata or {}),+ openviking_connection=openviking_connection,)await self.bus.publish_inbound(msg)@@ -252,9 +280,6 @@ Summarize this naturally for the user. Keep it brief (1-2 sentences). Do not mendef _build_subagent_prompt(self, task: str, workspace: Path | None = None) -> str:"""Build a focused system prompt for the subagent."""- from datetime import datetime- import time as _time-workspace = workspace or self.workspacenow = datetime.now().strftime("%Y-%m-%d %H:%M (%A)")tz = _time.strftime("%Z") or "UTC"diff --git a/bot/vikingbot/agent/tools/base.py b/bot/vikingbot/agent/tools/base.pyindex 1ee3ed4f6..7358ee344 100644--- a/bot/vikingbot/agent/tools/base.py+++ b/bot/vikingbot/agent/tools/base.py@@ -24,6 +24,7 @@ class ToolContext:and session_key. This determines the sandbox directory for the session.sender_id: Optional identifier for the message sender, used for trackingand permission checks.+ actor_peer_id: Authenticated OpenViking peer identity for memory and file tools.memory_peer_ids: Optional list of peer IDs for memory retrieval insidethe current OpenViking user scope.memory_owner_user_ids: Optional list of explicit OpenViking user IDs@@ -46,6 +47,7 @@ class ToolContext:sandbox_manager: SandboxManager | None = Noneworkspace_id: str = sandbox_manager.to_workspace_id(session_key) if sandbox_manager else Nonesender_id: str | None = None+ actor_peer_id: str | None = Nonememory_peer_ids: list[str] | None = Nonememory_owner_user_ids: list[str] | None = Nonememory_user_ids: list[str] | None = None # Deprecated alias for memory_owner_user_ids.diff --git a/bot/vikingbot/agent/tools/factory.py b/bot/vikingbot/agent/tools/factory.pyindex 648916b55..cfc9cee90 100644--- a/bot/vikingbot/agent/tools/factory.py+++ b/bot/vikingbot/agent/tools/factory.py@@ -19,7 +19,6 @@ from vikingbot.agent.tools.registry import ToolRegistryfrom vikingbot.agent.tools.shell import ExecToolfrom vikingbot.agent.tools.web import WebFetchToolfrom vikingbot.agent.tools.websearch import WebSearchTool-from vikingbot.config.loader import load_configif TYPE_CHECKING:from vikingbot.agent.subagent import SubagentManager@@ -56,6 +55,7 @@ def register_default_tools(include_viking_tools: Whether to include Viking tools"""# Derive all parameters from config+ registry.config = configexec_config = config.tools.execbrave_api_key = config.tools.web.search.api_key if config.tools.web.search else Noneexa_api_key = None # TODO: Add to config if needed@@ -63,7 +63,7 @@ def register_default_tools(# Get provider API key and base from config- agent_config = load_config().agents+ agent_config = config.agentsprovider_api_key = agent_config.api_key if agent_config else Noneprovider_api_base = agent_config.api_base if agent_config else Nonegen_image_model = agent_config.gen_image_model@@ -93,14 +93,14 @@ def register_default_tools(# Open Viking toolsif include_viking_tools:- registry.register(VikingMultiReadTool())- registry.register(VikingListTool())- registry.register(VikingSearchTool())- registry.register(VikingGrepTool())- registry.register(VikingGlobTool())- registry.register(VikingMemoryCommitTool())+ registry.register(VikingMultiReadTool(config=config))+ registry.register(VikingListTool(config=config))+ registry.register(VikingSearchTool(config=config))+ registry.register(VikingGrepTool(config=config))+ registry.register(VikingGlobTool(config=config))+ registry.register(VikingMemoryCommitTool(config=config))if not config.read_only:- registry.register(VikingAddResourceTool())+ registry.register(VikingAddResourceTool(config=config))# Image generation toolif include_image_tool:diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.pyindex b9854d218..142ea7a7a 100644--- a/bot/vikingbot/agent/tools/ov_file.py+++ b/bot/vikingbot/agent/tools/ov_file.py@@ -6,7 +6,7 @@ import jsonimport timefrom abc import ABCfrom pathlib import Path-from typing import Any, Optional+from typing import TYPE_CHECKING, Any, Optionalimport httpxfrom loguru import logger@@ -14,41 +14,53 @@ from loguru import loggerfrom vikingbot.agent.tools.base import Tool, ToolContextfrom vikingbot.openviking_mount.ov_server import VikingClient+if TYPE_CHECKING:+ from vikingbot.config.schema import Config+class OVFileTool(Tool, ABC):_memory_commit_counter = itertools.count(1)- def __init__(self):+ def __init__(self, config: "Config | None" = None):super().__init__()self._clients = {}+ self._config = config@staticmethoddef _has_request_connection(tool_context: ToolContext) -> bool:return bool(getattr(tool_context, "openviking_connection", None))+ @staticmethod+ def _actor_peer_id(tool_context: ToolContext) -> str | None:+ return getattr(tool_context, "actor_peer_id", None) or getattr(+ tool_context, "sender_id", None+ )+async def _get_client(self, tool_context: ToolContext):- actor_peer_id = getattr(tool_context, "sender_id", None)+ actor_peer_id = self._actor_peer_id(tool_context)if self._has_request_connection(tool_context):return await VikingClient.create(tool_context.workspace_id,connection=tool_context.openviking_connection,actor_peer_id=actor_peer_id,+ config=self._config,)if actor_peer_id:return await VikingClient.create(tool_context.workspace_id,actor_peer_id=actor_peer_id,+ config=self._config,)cache_key = str(tool_context.workspace_id or "__default__")client = self._clients.get(cache_key)if client is None:- client = await VikingClient.create(tool_context.workspace_id)+ client = await VikingClient.create(tool_context.workspace_id, config=self._config)self._clients[cache_key] = clientreturn clientasync def _release_client(self, tool_context: ToolContext, client: VikingClient | None) -> None:if client is not None and (- self._has_request_connection(tool_context) or getattr(tool_context, "sender_id", None)+ self._has_request_connection(tool_context) or self._actor_peer_id(tool_context)):close = getattr(client, "close", None)if callable(close):@@ -78,7 +90,7 @@ class OVFileTool(Tool, ABC):def _memory_peer_ids(self, tool_context: ToolContext) -> list[str]:return self._dedupe_strings([- getattr(tool_context, "sender_id", None),+ self._actor_peer_id(tool_context),*(getattr(tool_context, "memory_peer_ids", None) or []),])@@ -804,13 +816,14 @@ class VikingMemoryCommitTool(OVFileTool):client = Nonetry:client = await self._get_client(tool_context)- if not tool_context.sender_id:+ actor_peer_id = self._actor_peer_id(tool_context)+ if not actor_peer_id:return "Error: peer id is required for OpenViking memory commit."source_session_id = tool_context.session_key.safe_name()commit_seq = next(self._memory_commit_counter)timestamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())session_id = f"{source_session_id}__memory_commit__{timestamp}__{commit_seq:04d}"- result = await client.commit(session_id, messages, peer_id=tool_context.sender_id)+ result = await client.commit(session_id, messages, peer_id=actor_peer_id)session_id = (result.get("session_id", session_id) if isinstance(result, dict) else session_id)diff --git a/bot/vikingbot/agent/tools/registry.py b/bot/vikingbot/agent/tools/registry.pyindex 5a1088310..1180573ce 100644--- a/bot/vikingbot/agent/tools/registry.py+++ b/bot/vikingbot/agent/tools/registry.py@@ -21,9 +21,10 @@ class ToolRegistry:Allows dynamic registration and execution of tools."""- def __init__(self):+ def __init__(self, config: Any = None):self._tools: dict[str, Tool] = {}self.langfuse = LangfuseClient.get_instance()+ self.config = configdef register(self, tool: Tool) -> None:"""@@ -140,6 +141,7 @@ class ToolRegistry:session_key: SessionKey,sandbox_manager: SandboxManager | None = None,sender_id: str | None = None,+ actor_peer_id: str | None = None,memory_peer_ids: list[str] | None = None,memory_owner_user_ids: list[str] | None = None,memory_user_ids: list[str] | None = None,@@ -155,6 +157,7 @@ class ToolRegistry:session_key: Session key for the current session.sandbox_manager: Sandbox manager for file/shell operations.sender_id: Sender id for the current session.+ actor_peer_id: Authenticated OpenViking peer id for tool requests.memory_peer_ids: List of peer IDs for memory retrieval.memory_owner_user_ids: List of explicit OpenViking user IDs fortrusted-mode owner-user memory lookup.@@ -176,6 +179,7 @@ class ToolRegistry:session_key=session_key,sandbox_manager=sandbox_manager,sender_id=sender_id,+ actor_peer_id=actor_peer_id or sender_id,memory_peer_ids=memory_peer_ids,memory_owner_user_ids=memory_owner_user_ids,memory_user_ids=memory_user_ids,@@ -234,7 +238,11 @@ class ToolRegistry:context=HookContext(event_type="tool.post_call",session_key=session_key,- workspace_id=sandbox_manager.to_workspace_id(session_key),+ workspace_id=(+ sandbox_manager.to_workspace_id(session_key) if sandbox_manager else "shared"+ ),+ config=self.config,+ openviking_connection=openviking_connection,),tool_name=name,params=params,diff --git a/bot/vikingbot/agent/tools/spawn.py b/bot/vikingbot/agent/tools/spawn.pyindex 42cec5cef..c5c74c98a 100644--- a/bot/vikingbot/agent/tools/spawn.py+++ b/bot/vikingbot/agent/tools/spawn.py@@ -1,11 +1,12 @@"""Spawn tool for creating background subagents."""-from typing import Any, TYPE_CHECKING+from typing import TYPE_CHECKING, Any+from vikingbot.agent.subagent import SubagentManagerfrom vikingbot.agent.tools.base import Tool--from vikingbot.agent.subagent import SubagentManager+if TYPE_CHECKING:+ from vikingbot.agent.tools.base import ToolContextclass SpawnTool(Tool):@@ -57,4 +58,5 @@ class SpawnTool(Tool):label=label,session_key=tool_context.session_key,channel_metadata=tool_context.channel_metadata,+ openviking_connection=tool_context.openviking_connection,)diff --git a/bot/vikingbot/bus/events.py b/bot/vikingbot/bus/events.pyindex 958cba488..02da108b2 100644--- a/bot/vikingbot/bus/events.py+++ b/bot/vikingbot/bus/events.py@@ -33,6 +33,7 @@ class InboundMessage:sender_id: str # User identifiercontent: str # Message textsession_key: SessionKey+ actor_peer_id: str | None = None # Authenticated OpenViking peer identitytimestamp: datetime = field(default_factory=datetime.now)sender_name: str | None = Noneneed_reply: bool = Truediff --git a/bot/vikingbot/channels/openapi.py b/bot/vikingbot/channels/openapi.pyindex 2fc009736..3c54cc3b7 100644--- a/bot/vikingbot/channels/openapi.py+++ b/bot/vikingbot/channels/openapi.py@@ -1,14 +1,19 @@"""OpenAPI channel for HTTP-based chat API."""import asyncio+import hashlib+import ipaddressimport secretsimport uuid+from dataclasses import dataclassfrom datetime import datetimefrom pathlib import Pathfrom typing import Any, Dict, List, Optional+from urllib.parse import urlsplit-from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException-from fastapi.responses import StreamingResponse+import httpx+from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException, Request+from fastapi.responses import Response, StreamingResponsefrom loguru import loggerfrom vikingbot.bus.events import InboundMessage, OutboundEventType, OutboundMessage@@ -22,6 +27,7 @@ from vikingbot.channels.openapi_models import (FeedbackRequest,FeedbackResponse,HealthResponse,+ OpenVikingConnection,SessionCreateRequest,SessionCreateResponse,SessionDetailResponse,@@ -33,12 +39,46 @@ from vikingbot.config.schema import (BotChannelConfig,Config,SessionKey,- requires_gateway_token,)from vikingbot.integrations.langfuse import LangfuseClientfrom vikingbot.observability.outcome import evaluate_response_outcome, should_update_outcomefrom vikingbot.session.manager import SessionManager+DEFAULT_OPENVIKING_AGENT_ID = "web-playground"+DEFAULT_NAMESPACE_POLICY = {+ "isolate_user_scope_by_agent": False,+ "isolate_agent_scope_by_user": False,+}+OPENVIKING_AUTH_TIMEOUT_SECONDS = 5.0+OPENVIKING_PROXY_TIMEOUT_SECONDS = 300.0+OPENVIKING_UPSTREAM_NOT_CONFIGURED_DETAIL = (+ "VikingBot gateway proxy is active, but no available OpenViking server is configured"+)+HOP_BY_HOP_HEADERS = {+ "connection",+ "keep-alive",+ "proxy-authenticate",+ "proxy-authorization",+ "te",+ "trailer",+ "transfer-encoding",+ "upgrade",+}+++@dataclass(frozen=True)+class GatewayRequestAuth:+ """Resolved gateway-level auth facts for one HTTP request."""++ gateway_token_configured: bool+ gateway_token_valid: bool+ loopback_request: bool+ forwarded_connection_trusted: bool = False++ @property+ def can_trust_forwarded_connection(self) -> bool:+ return self.forwarded_connection_trusted+class PendingResponse:"""Tracks a pending response from the agent."""@@ -114,6 +154,7 @@ class OpenAPIChannel(BaseChannel):# BotChannel configs - key is channel_idself._bot_configs: Dict[str, BotChannelConfig] = {}self._router: Optional[APIRouter] = None+ self._gateway_router: Optional[APIRouter] = Noneself._app = app # External FastAPI app to register routes onself._server: Optional[asyncio.Task] = None # Server taskself._session_manager = SessionManager(self._resolve_bot_data_path())@@ -261,6 +302,12 @@ class OpenAPIChannel(BaseChannel):self._router = self._create_router()return self._router+ def get_gateway_router(self) -> APIRouter:+ """Get or create root-level gateway routes."""+ if self._gateway_router is None:+ self._gateway_router = self._create_gateway_router()+ return self._gateway_router+def _resolve_bot_data_path(self) -> Path:"""Resolve the bot data path used for session persistence."""if self._global_config is not None and hasattr(self._global_config, "bot_data_path"):@@ -278,32 +325,17 @@ class OpenAPIChannel(BaseChannel):router = APIRouter()channel = self # Capture for closures- async def verify_api_key(+ async def verify_gateway_request(+ http_request: Request,x_gateway_token: Optional[str] = Header(None, alias="X-Gateway-Token"),- ) -> bool:- """Verify API key for privileged HTTP chat/session routes."""- gateway_token = ""- gateway_host = "127.0.0.1"- if channel._global_config is not None:- gateway = getattr(channel._global_config, "gateway", None)- gateway_host = getattr(gateway, "host", "127.0.0.1") or "127.0.0.1"- gateway_token = getattr(gateway, "token", "") or ""- if not gateway_token:- if requires_gateway_token(gateway_host, gateway_token):- raise HTTPException(- status_code=503,- detail="OpenAPI gateway token is required when host is non-localhost",- )- return True- if not x_gateway_token:- raise HTTPException(status_code=401, detail="X-Gateway-Token header required")- # Use secrets.compare_digest for timing-safe comparison- if not secrets.compare_digest(x_gateway_token, gateway_token):- raise HTTPException(status_code=403, detail="Invalid API key")- return True+ ) -> GatewayRequestAuth:+ """Verify gateway access and resolve caller OpenViking identity when needed."""+ return await channel._verify_gateway_request(http_request, x_gateway_token)@router.get("/health", response_model=HealthResponse)- async def health_check():+ async def health_check(+ auth: GatewayRequestAuth = Depends(verify_gateway_request),+ ):"""Health check endpoint."""from vikingbot import __version__@@ -315,39 +347,65 @@ class OpenAPIChannel(BaseChannel):@router.post("/chat", response_model=ChatResponse)async def chat(request: ChatRequest,- authorized: bool = Depends(verify_api_key),+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),):"""Send a chat message and get a response."""+ await channel._prepare_chat_request(http_request, request, auth)return await channel._handle_chat(request)@router.post("/chat/stream")async def chat_stream(request: ChatRequest,- authorized: bool = Depends(verify_api_key),+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),):"""Send a chat message and get a streaming response."""if not request.stream:request.stream = True+ await channel._prepare_chat_request(http_request, request, auth)return await channel._handle_chat_stream(request)@router.post("/feedback", response_model=FeedbackResponse)async def submit_feedback(request: FeedbackRequest,- authorized: bool = Depends(verify_api_key),+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),):"""Submit explicit user feedback for a prior assistant response."""+ if request.openviking_connection is not None:+ if not auth.can_trust_forwarded_connection:+ raise HTTPException(+ status_code=403,+ detail=("openviking_connection is only accepted from trusted server proxy"),+ )+ await channel._assert_runtime_upstream_auth_mode(+ channel._identity_headers_from_connection(request.openviking_connection)+ )+ request._principal_scope = channel._connection_principal_scope(+ request.openviking_connection+ )+ else:+ request._principal_scope = await channel._resolve_request_principal(+ http_request,+ auth,+ )return await channel._handle_feedback(request)@router.get("/sessions", response_model=SessionListResponse)async def list_sessions(- authorized: bool = Depends(verify_api_key),+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),):"""List all sessions."""+ scope = await channel._resolve_request_principal(http_request, auth)sessions = []- for session_id, session_data in channel._sessions.items():+ for session_data in channel._sessions.values():+ if session_data.get("principal_scope") != scope:+ continuesessions.append(SessionInfo(- id=session_id,+ id=session_data["session_id"],created_at=session_data.get("created_at", datetime.now()),last_active=session_data.get("last_active", datetime.now()),message_count=session_data.get("message_count", 0),@@ -358,12 +416,17 @@ class OpenAPIChannel(BaseChannel):@router.post("/sessions", response_model=SessionCreateResponse)async def create_session(request: SessionCreateRequest,- authorized: bool = Depends(verify_api_key),+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),):"""Create a new session."""+ scope = await channel._resolve_request_principal(http_request, auth)session_id = str(uuid.uuid4())+ storage_key = channel._scoped_session_id(scope, session_id)now = datetime.now()- channel._sessions[session_id] = {+ channel._sessions[storage_key] = {+ "session_id": session_id,+ "principal_scope": scope,"user_id": request.user_id,"created_at": now,"last_active": now,@@ -375,13 +438,16 @@ class OpenAPIChannel(BaseChannel):@router.get("/sessions/{session_id}", response_model=SessionDetailResponse)async def get_session(session_id: str,- authorized: bool = Depends(verify_api_key),+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),):"""Get session details."""- if session_id not in channel._sessions:+ scope = await channel._resolve_request_principal(http_request, auth)+ storage_key = channel._scoped_session_id(scope, session_id)+ if storage_key not in channel._sessions:raise HTTPException(status_code=404, detail="Session not found")- session_data = channel._sessions[session_id]+ session_data = channel._sessions[storage_key]info = SessionInfo(id=session_id,created_at=session_data.get("created_at", datetime.now()),@@ -395,13 +461,16 @@ class OpenAPIChannel(BaseChannel):@router.delete("/sessions/{session_id}")async def delete_session(session_id: str,- authorized: bool = Depends(verify_api_key),+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),):"""Delete a session."""- if session_id not in channel._sessions:+ scope = await channel._resolve_request_principal(http_request, auth)+ storage_key = channel._scoped_session_id(scope, session_id)+ if storage_key not in channel._sessions:raise HTTPException(status_code=404, detail="Session not found")- del channel._sessions[session_id]+ del channel._sessions[storage_key]return {"deleted": True}# ========== Bot Channel Routes ==========@@ -409,7 +478,8 @@ class OpenAPIChannel(BaseChannel):@router.post("/chat/channel", response_model=ChatResponse)async def chat_channel(request: ChatRequest,- authorized: bool = Depends(verify_api_key),+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),):"""Send a chat message to a specific bot channel and get a response."""channel_id = request.channel_id@@ -418,12 +488,14 @@ class OpenAPIChannel(BaseChannel):if channel_id not in channel._bot_configs:raise HTTPException(status_code=404, detail=f"Channel '{channel_id}' not found")+ await channel._prepare_chat_request(http_request, request, auth)return await channel._handle_bot_chat(channel_id, request)@router.post("/chat/channel/stream")async def chat_channel_stream(request: ChatRequest,- authorized: bool = Depends(verify_api_key),+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),):"""Send a chat message to a specific bot channel and get a streaming response."""channel_id = request.channel_id@@ -434,10 +506,634 @@ class OpenAPIChannel(BaseChannel):if not request.stream:request.stream = True+ await channel._prepare_chat_request(http_request, request, auth)return await channel._handle_bot_chat_stream(channel_id, request)return router+ def _create_gateway_router(self) -> APIRouter:+ """Create root-level gateway routes for health and OpenViking proxy."""+ router = APIRouter()+ channel = self++ async def verify_gateway_request(+ http_request: Request,+ x_gateway_token: Optional[str] = Header(None, alias="X-Gateway-Token"),+ ) -> GatewayRequestAuth:+ return await channel._verify_gateway_request(http_request, x_gateway_token)++ @router.get("/health")+ async def gateway_health(+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),+ ):+ return await channel._gateway_health(http_request)++ @router.api_route(+ "/api/v1/{path:path}",+ methods=["GET", "POST", "PUT", "PATCH", "DELETE"],+ )+ async def proxy_openviking_api(+ path: str,+ http_request: Request,+ auth: GatewayRequestAuth = Depends(verify_gateway_request),+ ):+ return await channel._proxy_openviking_request(http_request, path)++ return router++ def _gateway_host(self) -> str:+ gateway = getattr(self._global_config, "gateway", None) if self._global_config else None+ return str(getattr(gateway, "host", "127.0.0.1") or "127.0.0.1").strip()++ def _gateway_token(self) -> str:+ gateway = getattr(self._global_config, "gateway", None) if self._global_config else None+ return str(getattr(gateway, "token", "") or "").strip()++ def _ov_server_config(self) -> Any | None:+ if self._global_config is None:+ return None+ return getattr(self._global_config, "ov_server", None)++ def _ov_server_url(self) -> str:+ ov_server = self._ov_server_config()+ return str(getattr(ov_server, "server_url", "") or "").strip().rstrip("/")++ def _ov_server_auth_mode(self) -> str:+ ov_server = self._ov_server_config()+ if ov_server is None or not self._ov_server_url():+ return ""+ effective = str(getattr(ov_server, "effective_auth_mode", "") or "").strip().lower()+ if effective in {"api_key", "trusted", "dev"}:+ return effective+ api_key_type = str(getattr(ov_server, "api_key_type", "") or "").strip().lower()+ if api_key_type == "root":+ return "trusted"+ return "api_key"++ def _ov_server_source(self) -> str:+ ov_server = self._ov_server_config()+ getter = getattr(ov_server, "get_config_source", None)+ source = getter() if callable(getter) else getattr(ov_server, "_source", "none")+ source = str(source or "none").strip().lower()+ return source if source in {"explicit", "inherited", "none"} else "none"++ def _ov_server_api_key_source(self) -> str:+ ov_server = self._ov_server_config()+ getter = getattr(ov_server, "get_api_key_source", None)+ source = getter() if callable(getter) else getattr(ov_server, "_api_key_source", "none")+ source = str(source or "none").strip().lower()+ allowed = {"bot.ov_server.api_key", "server.root_api_key", "none"}+ return source if source in allowed else "none"++ def _ov_server_is_server_managed(self) -> bool:+ ov_server = self._ov_server_config()+ getter = getattr(ov_server, "is_server_managed", None)+ if callable(getter):+ return bool(getter())+ return bool(getattr(ov_server, "_server_managed", False))++ @staticmethod+ def _is_loopback_host(host: str) -> bool:+ host = str(host or "").strip().lower()+ if host.startswith("[") and host.endswith("]"):+ host = host[1:-1]+ if host in {"localhost", "127.0.0.1", "::1"}:+ return True+ try:+ return ipaddress.ip_address(host).is_loopback+ except ValueError:+ return False++ @classmethod+ def _is_loopback_url(cls, url: str) -> bool:+ try:+ host = urlsplit(url).hostname or ""+ except ValueError:+ return False+ return cls._is_loopback_host(host)++ @classmethod+ def _is_loopback_request(cls, request: Request) -> bool:+ client = getattr(request, "client", None)+ return cls._is_loopback_host(getattr(client, "host", "") or "")++ def _is_gateway_localhost(self) -> bool:+ return self._is_loopback_host(self._gateway_host())++ def _is_safe_dev_boundary(self) -> bool:+ return self._is_gateway_localhost() and self._is_loopback_url(self._ov_server_url())++ @staticmethod+ def _has_openviking_auth_headers(request: Request) -> bool:+ return bool(+ request.headers.get("X-API-Key")+ or request.headers.get("x-api-key")+ or request.headers.get("Authorization")+ or request.headers.get("authorization")+ )++ @staticmethod+ def _extract_api_key(request: Request) -> str:+ api_key = request.headers.get("X-API-Key") or request.headers.get("x-api-key")+ if api_key:+ return api_key.strip()+ authorization = request.headers.get("Authorization") or request.headers.get("authorization")+ if authorization and authorization.lower().startswith("bearer "):+ return authorization[7:].strip()+ return ""++ @staticmethod+ def _identity_headers_from_request(request: Request) -> dict[str, str]:+ headers: dict[str, str] = {}+ for name in (+ "X-API-Key",+ "Authorization",+ "X-OpenViking-Account",+ "X-OpenViking-User",+ "X-OpenViking-Actor-Peer",+ ):+ value = request.headers.get(name)+ if value:+ headers[name] = value+ return headers++ async def _request_upstream_health_with_headers(+ self,+ headers: dict[str, str] | None = None,+ ) -> dict[str, Any]:+ server_url = self._ov_server_url()+ if not server_url:+ raise HTTPException(+ status_code=503,+ detail=OPENVIKING_UPSTREAM_NOT_CONFIGURED_DETAIL,+ )+ try:+ async with httpx.AsyncClient(+ timeout=OPENVIKING_AUTH_TIMEOUT_SECONDS,+ trust_env=False,+ ) as client:+ response = await client.get(+ f"{server_url}/health",+ headers=headers or {},+ )+ except httpx.HTTPError as exc:+ raise HTTPException(+ status_code=502,+ detail=f"OpenViking upstream health check failed: {exc.__class__.__name__}",+ ) from exc++ if response.status_code in {401, 403}:+ raise HTTPException(status_code=401, detail="Invalid OpenViking credentials")+ if not 200 <= response.status_code < 300:+ raise HTTPException(+ status_code=502,+ detail=f"OpenViking upstream health check failed: HTTP {response.status_code}",+ )+ try:+ data = response.json()+ except ValueError as exc:+ raise HTTPException(+ status_code=502,+ detail="OpenViking upstream health check returned non-JSON response",+ ) from exc+ if not isinstance(data, dict):+ raise HTTPException(+ status_code=502,+ detail="OpenViking upstream health check returned invalid response",+ )+ return data++ async def _request_upstream_health(self, request: Request) -> dict[str, Any]:+ return await self._request_upstream_health_with_headers(+ self._identity_headers_from_request(request)+ )++ def _runtime_probe_headers(self) -> dict[str, str]:+ ov_server = self._ov_server_config()+ if ov_server is None:+ return {}+ headers: dict[str, str] = {}+ api_key = str(getattr(ov_server, "api_key", "") or "").strip()+ if api_key:+ headers["X-API-Key"] = api_key+ if self._ov_server_auth_mode() == "trusted":+ account = str(getattr(ov_server, "account_id", "") or "").strip()+ user = str(getattr(ov_server, "admin_user_id", "") or "").strip()+ if account:+ headers["X-OpenViking-Account"] = account+ if user:+ headers["X-OpenViking-User"] = user+ return headers++ @staticmethod+ def _identity_headers_from_connection(connection: Any) -> dict[str, str]:+ if isinstance(connection, OpenVikingConnection):+ values = connection.model_dump(exclude_none=True)+ elif isinstance(connection, dict):+ values = connection+ else:+ return {}+ headers: dict[str, str] = {}+ mapping = {+ "api_key": "X-API-Key",+ "account_id": "X-OpenViking-Account",+ "user_id": "X-OpenViking-User",+ "actor_peer_id": "X-OpenViking-Actor-Peer",+ }+ for field, header in mapping.items():+ value = str(values.get(field) or "").strip()+ if value:+ headers[header] = value+ return headers++ def _assert_runtime_health_mode(self, health: dict[str, Any]) -> None:+ expected_auth_mode = self._ov_server_auth_mode()+ if not expected_auth_mode:+ return+ actual_auth_mode = str(health.get("auth_mode") or "").strip().lower()+ if not actual_auth_mode:+ raise HTTPException(+ status_code=503,+ detail="OpenViking upstream health response did not include auth_mode",+ )++ if actual_auth_mode == "dev" and not self._is_safe_dev_boundary():+ raise HTTPException(+ status_code=403,+ detail=(+ "OpenViking server auth_mode changed to dev, but dev auth can only "+ "be used when gateway and OpenViking server are localhost"+ ),+ )+ if actual_auth_mode != expected_auth_mode:+ raise HTTPException(+ status_code=503,+ detail=(+ "OpenViking server auth_mode changed after gateway startup: "+ f"gateway expects {expected_auth_mode}, server reports {actual_auth_mode}. "+ "Restart VikingBot gateway or update ov.conf."+ ),+ )++ async def _assert_runtime_upstream_auth_mode(+ self,+ headers: dict[str, str] | None = None,+ ) -> dict[str, Any]:+ if not self._ov_server_auth_mode():+ return {}+ health = await self._request_upstream_health_with_headers(+ self._runtime_probe_headers() if headers is None else headers+ )+ self._assert_runtime_health_mode(health)+ return health++ def _build_openviking_connection(+ self,+ *,+ api_key: str = "",+ account_id: str = "",+ user_id: str = "",+ role: str = "",+ api_key_type: str = "user",+ actor_peer_id: str = "",+ ) -> dict[str, Any]:+ connection: dict[str, Any] = {+ "account_id": account_id,+ "user_id": user_id,+ "agent_id": DEFAULT_OPENVIKING_AGENT_ID,+ "role": role,+ "api_key_type": api_key_type,+ "server_url": self._ov_server_url(),+ "namespace_policy": dict(DEFAULT_NAMESPACE_POLICY),+ }+ if api_key:+ connection["api_key"] = api_key+ if actor_peer_id:+ connection["actor_peer_id"] = actor_peer_id+ return {key: value for key, value in connection.items() if value not in ("", None)}++ def _resolve_api_key_connection(+ self,+ request: Request,+ health: dict[str, Any],+ ) -> dict[str, Any]:+ role = str(health.get("role") or "").strip().lower()+ account_id = str(health.get("account_id") or "").strip()+ user_id = str(health.get("user_id") or "").strip()+ if role not in {"user", "admin"} or not account_id or not user_id:+ raise HTTPException(+ status_code=401,+ detail="OpenViking credentials did not resolve to a usable User/Admin identity",+ )+ return self._build_openviking_connection(+ api_key=self._extract_api_key(request),+ account_id=account_id,+ user_id=user_id,+ role=role,+ api_key_type="user",+ actor_peer_id=request.headers.get("X-OpenViking-Actor-Peer", ""),+ )++ async def _resolve_trusted_connection(self, request: Request) -> dict[str, Any] | None:+ if not self._ov_server_url():+ return None+ api_key = self._extract_api_key(request)+ if not api_key:+ raise HTTPException(status_code=401, detail="OpenViking API key header required")+ account_id = str(request.headers.get("X-OpenViking-Account") or "").strip()+ user_id = str(request.headers.get("X-OpenViking-User") or "").strip()+ if not account_id or not user_id:+ missing = []+ if not account_id:+ missing.append("X-OpenViking-Account")+ if not user_id:+ missing.append("X-OpenViking-User")+ raise HTTPException(+ status_code=401,+ detail=(+ "Trusted OpenViking chat requires "+ + " and ".join(missing)+ + ". Configure account/user in ovcli.conf or pass the headers."+ ),+ )+ health = await self._request_upstream_health(request)+ self._assert_runtime_health_mode(health)+ resolved_account_id = str(health.get("account_id") or "").strip()+ resolved_user_id = str(health.get("user_id") or "").strip()+ role = str(health.get("role") or "").strip().lower()+ if (+ not resolved_account_id+ or not resolved_user_id+ or resolved_account_id != account_id+ or resolved_user_id != user_id+ ):+ raise HTTPException(status_code=401, detail="Invalid OpenViking credentials")+ return self._build_openviking_connection(+ api_key=api_key,+ account_id=account_id,+ user_id=user_id,+ role=role or "user",+ api_key_type="root",+ actor_peer_id=request.headers.get("X-OpenViking-Actor-Peer", ""),+ )++ async def _verify_gateway_request(+ self,+ request: Request,+ x_gateway_token: Optional[str],+ ) -> GatewayRequestAuth:+ gateway_token = self._gateway_token()+ token_configured = bool(gateway_token)+ token_valid = False++ gateway_is_localhost = self._is_gateway_localhost()+ gateway_challenge_headers = {"X-VikingBot-Gateway": "true"}+ if not gateway_is_localhost:+ if not token_configured:+ raise HTTPException(+ status_code=503,+ detail="OpenAPI gateway token is required when host is non-localhost",+ headers=gateway_challenge_headers,+ )+ if x_gateway_token:+ token_valid = secrets.compare_digest(x_gateway_token, gateway_token)+ if not token_valid:+ raise HTTPException(+ status_code=403,+ detail="Invalid X-Gateway-Token",+ headers=gateway_challenge_headers,+ )+ if not token_valid:+ raise HTTPException(+ status_code=401,+ detail="X-Gateway-Token header required",+ headers=gateway_challenge_headers,+ )++ loopback_request = self._is_loopback_request(request)+ local_forward_trust = loopback_request and gateway_is_localhost+ forwarded_trusted = loopback_request and (token_valid or local_forward_trust)++ return GatewayRequestAuth(+ gateway_token_configured=token_configured,+ gateway_token_valid=token_valid,+ loopback_request=loopback_request,+ forwarded_connection_trusted=forwarded_trusted,+ )++ async def _prepare_chat_request(+ self,+ http_request: Request,+ chat_request: ChatRequest,+ auth: GatewayRequestAuth,+ ) -> None:+ if chat_request.openviking_connection is not None:+ if not auth.can_trust_forwarded_connection:+ raise HTTPException(+ status_code=403,+ detail="openviking_connection is only accepted from trusted server proxy",+ )+ if not self._ov_server_url():+ raise HTTPException(+ status_code=503,+ detail=OPENVIKING_UPSTREAM_NOT_CONFIGURED_DETAIL,+ )+ await self._assert_runtime_upstream_auth_mode(+ self._identity_headers_from_connection(chat_request.openviking_connection)+ )+ chat_request._principal_scope = self._connection_principal_scope(+ chat_request.openviking_connection+ )+ return++ connection, scope = await self._resolve_request_identity(http_request, auth)+ chat_request._principal_scope = scope+ if connection:+ chat_request.openviking_connection = OpenVikingConnection(**connection)++ async def _resolve_request_identity(+ self,+ http_request: Request,+ auth: GatewayRequestAuth,+ ) -> tuple[dict[str, Any] | None, str]:+ auth_mode = self._ov_server_auth_mode()+ if not auth_mode:+ return None, self._principal_scope("standalone")+ if auth_mode == "dev":+ if not self._is_safe_dev_boundary():+ raise HTTPException(+ status_code=403,+ detail="OpenViking dev auth can only be used when gateway and OpenViking server are localhost",+ )+ await self._assert_runtime_upstream_auth_mode({})+ return None, self._principal_scope("dev")+ if auth_mode == "api_key":+ if not self._has_openviking_auth_headers(http_request):+ raise HTTPException(status_code=401, detail="OpenViking API key header required")+ health = await self._request_upstream_health(http_request)+ self._assert_runtime_health_mode(health)+ connection = self._resolve_api_key_connection(http_request, health)+ elif auth_mode == "trusted":+ connection = await self._resolve_trusted_connection(http_request)+ else:+ raise HTTPException(+ status_code=503,+ detail=f"Unsupported OpenViking auth mode for gateway: {auth_mode}",+ )+ if connection is None and auth_mode == "api_key":+ raise HTTPException(status_code=401, detail="OpenViking API key header required")++ return connection, self._connection_principal_scope(connection)++ async def _resolve_request_principal(+ self,+ http_request: Request,+ auth: GatewayRequestAuth,+ ) -> str:+ _connection, scope = await self._resolve_request_identity(http_request, auth)+ return scope++ @staticmethod+ def _principal_scope(value: str) -> str:+ return hashlib.sha256(value.encode("utf-8")).hexdigest()[:24]++ def _connection_principal_scope(self, connection: Any) -> str:+ if isinstance(connection, OpenVikingConnection):+ values = connection.model_dump(exclude_none=True)+ elif isinstance(connection, dict):+ values = connection+ else:+ values = {}+ account_id = str(values.get("account_id") or "").strip()+ user_id = str(values.get("user_id") or "").strip()+ if not account_id or not user_id:+ raise HTTPException(+ status_code=401,+ detail="OpenViking identity did not include account_id and user_id",+ )+ return self._principal_scope(f"openviking:{account_id}:{user_id}")++ @staticmethod+ def _scoped_session_id(principal_scope: str, session_id: str) -> str:+ return f"{principal_scope}:{session_id}"++ async def _gateway_health(self, request: Request) -> dict[str, Any]:+ from vikingbot import __version__++ server_url = self._ov_server_url()+ auth_mode = self._ov_server_auth_mode()+ source = self._ov_server_source()+ gateway_token_required = not self._is_gateway_localhost()+ payload: dict[str, Any] = {+ "status": "ok" if self._running else "unhealthy",+ "healthy": self._running,+ "version": __version__,+ "gateway": "vikingbot",+ "mode": f"openviking_{source}" if server_url else "standalone",+ "upstream_configured": bool(server_url),+ "upstream_source": source,+ "upstream_api_key_source": self._ov_server_api_key_source(),+ "gateway_token_required": gateway_token_required,+ }+ if auth_mode:+ payload["auth_mode"] = auth_mode+ if server_url:+ payload["upstream_url"] = server_url+ try:+ request_headers = self._identity_headers_from_request(request)+ caller_authenticated = self._has_openviking_auth_headers(request)+ probe_headers = (+ request_headers+ if caller_authenticated or self._ov_server_is_server_managed()+ else None+ )+ health = await self._assert_runtime_upstream_auth_mode(probe_headers)+ payload["upstream_status"] = health.get("status", "ok")+ if caller_authenticated:+ for field in ("role", "account_id", "user_id"):+ value = health.get(field)+ if value not in (None, ""):+ payload[field] = value+ except HTTPException as exc:+ payload["upstream_status"] = "unavailable"+ payload["upstream_error"] = exc.detail+ return payload++ def _proxy_request_headers(self, request: Request) -> dict[str, str]:+ # OpenViking credentials and identity are request-scoped. The gateway must+ # never fill them from bot.ov_server while proxying a client request.+ headers: dict[str, str] = {}+ for key, value in request.headers.items():+ lower = key.lower()+ if lower in HOP_BY_HOP_HEADERS:+ continue+ if lower in {"host", "content-length", "x-gateway-token"}:+ continue+ headers[key] = value+ return headers++ @staticmethod+ def _proxy_response_headers(headers: httpx.Headers) -> dict[str, str]:+ forwarded: dict[str, str] = {}+ for key, value in headers.items():+ lower = key.lower()+ if lower in HOP_BY_HOP_HEADERS:+ continue+ forwarded[key] = value+ return forwarded++ async def _proxy_openviking_request(self, request: Request, path: str) -> Response:+ server_url = self._ov_server_url()+ if not server_url:+ raise HTTPException(+ status_code=503,+ detail=OPENVIKING_UPSTREAM_NOT_CONFIGURED_DETAIL,+ )+ await self._assert_runtime_upstream_auth_mode(self._identity_headers_from_request(request))++ upstream_url = f"{server_url}/api/v1/{path}"+ if request.url.query:+ upstream_url = f"{upstream_url}?{request.url.query}"++ client = httpx.AsyncClient(+ timeout=OPENVIKING_PROXY_TIMEOUT_SECONDS,+ trust_env=False,+ )+ try:+ content = None if request.method in {"GET", "HEAD"} else request.stream()+ upstream_request = client.build_request(+ request.method,+ upstream_url,+ content=content,+ headers=self._proxy_request_headers(request),+ )+ upstream_response = await client.send(upstream_request, stream=True)+ except httpx.HTTPError as exc:+ await client.aclose()+ raise HTTPException(+ status_code=502,+ detail=f"OpenViking upstream proxy request failed: {exc.__class__.__name__}",+ ) from exc+ except BaseException:+ await client.aclose()+ raise++ async def stream_upstream_response():+ try:+ async for chunk in upstream_response.aiter_raw():+ yield chunk+ finally:+ await upstream_response.aclose()+ await client.aclose()++ return StreamingResponse(+ content=stream_upstream_response(),+ status_code=upstream_response.status_code,+ headers=self._proxy_response_headers(upstream_response.headers),+ media_type=upstream_response.headers.get("content-type"),+ )+def _setup_routes(self) -> None:"""Setup routes on the external FastAPI app."""if self._app is None:@@ -448,7 +1144,8 @@ class OpenAPIChannel(BaseChannel):# Note: openviking-server adds its own /bot/v1 prefix when proxyingrouter = self.get_router()self._app.include_router(router, prefix="/bot/v1")- logger.info("OpenAPI routes registered at root path")+ self._app.include_router(self.get_gateway_router())+ logger.info("OpenAPI routes registered at /bot/v1 and gateway root")def _request_user_id(self, request: ChatRequest) -> str:if request.user_id:@@ -470,15 +1167,21 @@ class OpenAPIChannel(BaseChannel):return connectionreturn None+ def _request_actor_peer_id(self, request: ChatRequest, fallback: str) -> str:+ connection = self._request_openviking_connection(request) or {}+ return str(connection.get("actor_peer_id") or fallback)+async def _handle_chat(self, request: ChatRequest) -> ChatResponse:"""Handle a chat request."""- # Generate or use provided session IDsession_id = request.session_id or str(uuid.uuid4())+ storage_key = self._scoped_session_id(request._principal_scope, session_id)user_id = self._request_user_id(request)# Create session if new- if session_id not in self._sessions:- self._sessions[session_id] = {+ if storage_key not in self._sessions:+ self._sessions[storage_key] = {+ "session_id": session_id,+ "principal_scope": request._principal_scope,"user_id": user_id,"created_at": datetime.now(),"last_active": datetime.now(),@@ -487,19 +1190,19 @@ class OpenAPIChannel(BaseChannel):}# Update session activity- self._sessions[session_id]["last_active"] = datetime.now()- self._sessions[session_id]["message_count"] += 1+ self._sessions[storage_key]["last_active"] = datetime.now()+ self._sessions[storage_key]["message_count"] += 1# Create pending response trackerpending = PendingResponse()- self._pending[session_id] = pending+ self._pending[storage_key] = pendingtry:# Build session keysession_key = SessionKey(type="cli",channel_id=self.config.channel_id(),- chat_id=session_id,+ chat_id=storage_key,)# Build content with context if provided@@ -512,6 +1215,7 @@ class OpenAPIChannel(BaseChannel):msg = InboundMessage(session_key=session_key,sender_id=user_id,+ actor_peer_id=self._request_actor_peer_id(request, user_id),content=content,metadata=self._request_metadata(request),openviking_connection=self._request_openviking_connection(request),@@ -544,16 +1248,19 @@ class OpenAPIChannel(BaseChannel):raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")finally:# Clean up pending- self._pending.pop(session_id, None)+ self._pending.pop(storage_key, None)async def _handle_chat_stream(self, request: ChatRequest) -> StreamingResponse:"""Handle a streaming chat request."""session_id = request.session_id or str(uuid.uuid4())+ storage_key = self._scoped_session_id(request._principal_scope, session_id)user_id = self._request_user_id(request)# Create session if new- if session_id not in self._sessions:- self._sessions[session_id] = {+ if storage_key not in self._sessions:+ self._sessions[storage_key] = {+ "session_id": session_id,+ "principal_scope": request._principal_scope,"user_id": user_id,"created_at": datetime.now(),"last_active": datetime.now(),@@ -561,11 +1268,11 @@ class OpenAPIChannel(BaseChannel):"messages": [],}- self._sessions[session_id]["last_active"] = datetime.now()- self._sessions[session_id]["message_count"] += 1+ self._sessions[storage_key]["last_active"] = datetime.now()+ self._sessions[storage_key]["message_count"] += 1pending = PendingResponse()- self._pending[session_id] = pending+ self._pending[storage_key] = pendingasync def event_generator():try:@@ -573,12 +1280,13 @@ class OpenAPIChannel(BaseChannel):session_key = SessionKey(type="cli",channel_id=self.config.channel_id(),- chat_id=session_id,+ chat_id=storage_key,)msg = InboundMessage(session_key=session_key,sender_id=user_id,+ actor_peer_id=self._request_actor_peer_id(request, user_id),content=request.message,metadata=self._request_metadata(request),openviking_connection=self._request_openviking_connection(request),@@ -602,7 +1310,7 @@ class OpenAPIChannel(BaseChannel):error_event = ChatStreamEvent(event=EventType.RESPONSE, data={"error": str(e)})yield f"data: {error_event.model_dump_json()}\n\n"finally:- self._pending.pop(session_id, None)+ self._pending.pop(storage_key, None)return StreamingResponse(event_generator(),@@ -610,13 +1318,14 @@ class OpenAPIChannel(BaseChannel):headers={"Cache-Control": "no-cache","Connection": "keep-alive",+ "X-VikingBot-Session-ID": session_id,},)async def _handle_bot_chat(self, channel_id: str, request: ChatRequest) -> ChatResponse:"""Handle a BotChannel chat request."""- # Generate or use provided session IDsession_id = request.session_id or str(uuid.uuid4())+ storage_key = self._scoped_session_id(request._principal_scope, session_id)user_id = self._request_user_id(request)# Ensure channel has session storage@@ -624,8 +1333,10 @@ class OpenAPIChannel(BaseChannel):self._bot_sessions[channel_id] = {}# Create session if new- if session_id not in self._bot_sessions[channel_id]:- self._bot_sessions[channel_id][session_id] = {+ if storage_key not in self._bot_sessions[channel_id]:+ self._bot_sessions[channel_id][storage_key] = {+ "session_id": session_id,+ "principal_scope": request._principal_scope,"user_id": user_id,"created_at": datetime.now(),"last_active": datetime.now(),@@ -634,19 +1345,19 @@ class OpenAPIChannel(BaseChannel):}# Update session activity- self._bot_sessions[channel_id][session_id]["last_active"] = datetime.now()- self._bot_sessions[channel_id][session_id]["message_count"] += 1+ self._bot_sessions[channel_id][storage_key]["last_active"] = datetime.now()+ self._bot_sessions[channel_id][storage_key]["message_count"] += 1# Create pending response trackerpending = PendingResponse()- self._bot_pending[channel_id][session_id] = pending+ self._bot_pending[channel_id][storage_key] = pendingtry:# Build session key with bot_api typesession_key = SessionKey(type="bot_api",channel_id=channel_id,- chat_id=session_id,+ chat_id=storage_key,)# Build content with context if provided@@ -659,6 +1370,7 @@ class OpenAPIChannel(BaseChannel):msg = InboundMessage(session_key=session_key,sender_id=user_id,+ actor_peer_id=self._request_actor_peer_id(request, user_id),content=content,need_reply=request.need_reply,metadata=self._request_metadata(request),@@ -693,13 +1405,14 @@ class OpenAPIChannel(BaseChannel):finally:# Clean up pendingif channel_id in self._bot_pending:- self._bot_pending[channel_id].pop(session_id, None)+ self._bot_pending[channel_id].pop(storage_key, None)async def _handle_bot_chat_stream(self, channel_id: str, request: ChatRequest) -> StreamingResponse:"""Handle a BotChannel streaming chat request."""session_id = request.session_id or str(uuid.uuid4())+ storage_key = self._scoped_session_id(request._principal_scope, session_id)user_id = self._request_user_id(request)# Ensure channel has session storage@@ -707,8 +1420,10 @@ class OpenAPIChannel(BaseChannel):self._bot_sessions[channel_id] = {}# Create session if new- if session_id not in self._bot_sessions[channel_id]:- self._bot_sessions[channel_id][session_id] = {+ if storage_key not in self._bot_sessions[channel_id]:+ self._bot_sessions[channel_id][storage_key] = {+ "session_id": session_id,+ "principal_scope": request._principal_scope,"user_id": user_id,"created_at": datetime.now(),"last_active": datetime.now(),@@ -716,11 +1431,11 @@ class OpenAPIChannel(BaseChannel):"messages": [],}- self._bot_sessions[channel_id][session_id]["last_active"] = datetime.now()- self._bot_sessions[channel_id][session_id]["message_count"] += 1+ self._bot_sessions[channel_id][storage_key]["last_active"] = datetime.now()+ self._bot_sessions[channel_id][storage_key]["message_count"] += 1pending = PendingResponse()- self._bot_pending[channel_id][session_id] = pending+ self._bot_pending[channel_id][storage_key] = pendingasync def event_generator():try:@@ -728,12 +1443,13 @@ class OpenAPIChannel(BaseChannel):session_key = SessionKey(type="bot_api",channel_id=channel_id,- chat_id=session_id,+ chat_id=storage_key,)msg = InboundMessage(session_key=session_key,sender_id=user_id,+ actor_peer_id=self._request_actor_peer_id(request, user_id),content=request.message,metadata=self._request_metadata(request),openviking_connection=self._request_openviking_connection(request),@@ -759,7 +1475,7 @@ class OpenAPIChannel(BaseChannel):finally:# Clean up pendingif channel_id in self._bot_pending:- self._bot_pending[channel_id].pop(session_id, None)+ self._bot_pending[channel_id].pop(storage_key, None)return StreamingResponse(event_generator(),@@ -767,6 +1483,7 @@ class OpenAPIChannel(BaseChannel):headers={"Cache-Control": "no-cache","Connection": "keep-alive",+ "X-VikingBot-Session-ID": session_id,},)@@ -846,13 +1563,25 @@ class OpenAPIChannel(BaseChannel):def _get_feedback_session_key(self, request: FeedbackRequest) -> SessionKey:"""Resolve the persisted session key for a feedback request."""- if request.channel_id:- return SessionKey(- type="bot_api", channel_id=request.channel_id, chat_id=request.session_id- )- return SessionKey(- type="cli", channel_id=self.config.channel_id(), chat_id=request.session_id+ storage_key = self._scoped_session_id(request._principal_scope, request.session_id)+ session_type = "bot_api" if request.channel_id else "cli"+ channel_id = request.channel_id or self.config.channel_id()+ scoped_key = SessionKey(+ type=session_type,+ channel_id=channel_id,+ chat_id=storage_key,)+ if request._principal_scope == self._principal_scope("standalone"):+ legacy_key = SessionKey(+ type=session_type,+ channel_id=channel_id,+ chat_id=request.session_id,+ )+ if not self._session_manager.has_persisted(+ scoped_key+ ) and self._session_manager.has_persisted(legacy_key):+ return legacy_key+ return scoped_key@staticmethoddef _find_response_message(diff --git a/bot/vikingbot/channels/openapi_models.py b/bot/vikingbot/channels/openapi_models.pyindex 336fae522..4abd9b34b 100644--- a/bot/vikingbot/channels/openapi_models.py+++ b/bot/vikingbot/channels/openapi_models.py@@ -4,7 +4,7 @@ from datetime import datetimefrom enum import Enumfrom typing import Any, Dict, List, Optional-from pydantic import BaseModel, Field, model_validator+from pydantic import BaseModel, Field, PrivateAttr, model_validatorclass MessageRole(str, Enum):@@ -53,6 +53,7 @@ class OpenVikingConnection(BaseModel):account_id: Optional[str] = Field(default=None, description="Effective account ID")user_id: Optional[str] = Field(default=None, description="Effective user ID")agent_id: Optional[str] = Field(default=None, description="Effective agent ID")+ actor_peer_id: Optional[str] = Field(default=None, description="Effective actor peer ID")role: Optional[str] = Field(default=None, description="Effective OpenViking role")api_key_type: Optional[str] = Field(default=None, description="OpenViking API key type")namespace_policy: Optional[Dict[str, bool]] = Field(@@ -67,8 +68,9 @@ class ChatRequest(BaseModel):message: str = Field(..., description="User message to send", min_length=1)session_id: Optional[str] = Field(- default="default", description="Session ID (optional, will create new if not provided)"+ default=None, description="Session ID (optional, will create new if not provided)")+ _principal_scope: str = PrivateAttr(default="local")user_id: Optional[str] = Field(default=None, description="User identifier (optional)")stream: bool = Field(default=False, description="Whether to stream the response")context: Optional[List[ChatMessage]] = Field(@@ -122,6 +124,11 @@ class FeedbackRequest(BaseModel):default=None,description="Bot channel ID for multi-channel routing (optional)",)+ openviking_connection: Optional[OpenVikingConnection] = Field(+ default=None,+ description="Authenticated OpenViking connection forwarded by the server proxy",+ )+ _principal_scope: str = PrivateAttr(default="local")@model_validator(mode="after")def validate_rating_feedback(self) -> "FeedbackRequest":diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.pyindex e6b4b708b..7b41658ea 100644--- a/bot/vikingbot/cli/commands.py+++ b/bot/vikingbot/cli/commands.py@@ -14,9 +14,10 @@ from typing import Any, Optionalimport typerfrom loguru import loggerfrom prompt_toolkit import PromptSession-from prompt_toolkit.formatted_text import HTML+from prompt_toolkit.formatted_text import FormattedTextfrom prompt_toolkit.history import FileHistoryfrom prompt_toolkit.patch_stdout import patch_stdout+from prompt_toolkit.styles import Style as PromptStylefrom rich.console import Consolefrom rich.markdown import Markdownfrom rich.table import Table@@ -71,6 +72,13 @@ app = typer.Typer(console = Console()EXIT_COMMANDS = {"exit", "quit", "/exit", "/quit", ":q"}+_CHAT_PROMPT_MESSAGE = FormattedText([("class:user-label", "You: ")])+_CHAT_PROMPT_STYLE = PromptStyle.from_dict(+ {+ "": "fg:ansidefault",+ "user-label": "bold fg:ansicyan",+ }+)def _warn_deprecated_memory_user(memory_user: list[str] | None) -> None:@@ -98,9 +106,7 @@ def _redirect_openviking_logs_to_stderr() -> None:# If it already has handlers, swap any stdout StreamHandlers to stderr.if not root_logger.handlers:handler = logging.StreamHandler(sys.stderr)- formatter = logging.Formatter(- "%(asctime)s - %(name)s - %(levelname)s - %(message)s"- )+ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")handler.setFormatter(formatter)root_logger.addHandler(handler)root_logger.propagate = False@@ -177,6 +183,19 @@ def _get_gateway_token(config) -> str:return getattr(gateway, "token", "") or ""+def _gateway_startup_mode(config, host: str) -> str:+ ov_server = getattr(config, "ov_server", None)+ server_url = str(getattr(ov_server, "server_url", "") or "").strip()+ source_getter = getattr(ov_server, "get_config_source", None)+ source = source_getter() if callable(source_getter) else getattr(ov_server, "_source", "none")+ source = str(source or "none").strip().lower()+ if server_url:+ if source == "explicit":+ return "openviking_explicit"+ return "openviking_inherited"+ return "standalone_public" if requires_gateway_token(host, "") else "standalone_local"++# ---------------------------------------------------------------------------# CLI input: prompt_toolkit for editing, paste, history, and display# ---------------------------------------------------------------------------@@ -275,7 +294,8 @@ async def _read_interactive_input_async() -> str:try:with patch_stdout():return await _PROMPT_SESSION.prompt_async(- HTML("<b fg='ansiblack'>You:</b> "),+ _CHAT_PROMPT_MESSAGE,+ style=_CHAT_PROMPT_STYLE,)except EOFError as exc:raise KeyboardInterrupt from exc@@ -386,9 +406,10 @@ def gateway(bus = MessageBus()path = Path(config_path).expanduser() if config_path is not None else Noneconfig = ensure_config(path)- validate_openviking_auth(config)effective_host = host if host is not None else config.gateway.hosteffective_port = port if port is not None else config.gateway.port+ config.gateway.host = effective_host+ config.gateway.port = effective_portgateway_token = _get_gateway_token(config)if requires_gateway_token(effective_host, gateway_token):print(@@ -397,8 +418,8 @@ def gateway(file=sys.stderr,)sys.exit(1)- config.gateway.host = effective_host- config.gateway.port = effective_port+ validate_openviking_auth(config)+ console.print(f"[green]✓[/green] Gateway mode: {_gateway_startup_mode(config, effective_host)}")_abort_if_port_in_use(effective_port, "vikingbot gateway")_init_bot_data(config)session_manager = SessionManager(config.bot_data_path)diff --git a/bot/vikingbot/config/loader.py b/bot/vikingbot/config/loader.pyindex 669bc2c44..0456a8e5b 100644--- a/bot/vikingbot/config/loader.py+++ b/bot/vikingbot/config/loader.py@@ -1,11 +1,13 @@"""Configuration loading utilities."""+import ipaddressimport jsonimport osimport sysfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any+from urllib.parse import urlsplitimport httpxfrom loguru import logger@@ -14,11 +16,12 @@ from openviking.server.config import (ServerConfig,get_server_url_from_server_data,)-from openviking_cli.utils.config.ovcli_config import load_ovcli_configfrom vikingbot.config.schema import ConfigCONFIG_PATH = NoneOPENVIKING_AUTH_CHECK_TIMEOUT_SECONDS = 2.0+VIKINGBOT_WITH_OPENVIKING_SERVER_ENV = "VIKINGBOT_WITH_OPENVIKING_SERVER"+VIKINGBOT_MANAGED_OV_SERVER_URL_ENV = "VIKINGBOT_MANAGED_OV_SERVER_URL"def get_config_path() -> Path:@@ -111,13 +114,29 @@ def load_config() -> Config:if vlm_data:_merge_vlm_model_config(bot_data, vlm_data)- bot_server_data = bot_data.get("ov_server", {})- ov_server_data = full_data.get("server", {})- effective_auth_mode = _merge_ov_server_config(bot_server_data, ov_server_data)+ server_managed = _is_truthy_env(VIKINGBOT_WITH_OPENVIKING_SERVER_ENV)+ bot_server_data = {} if server_managed else bot_data.get("ov_server", {})+ server_section_present = "server" in full_data and isinstance(+ full_data.get("server"), dict+ )+ ov_server_data = full_data.get("server", {}) if server_section_present else {}+ effective_auth_mode, ov_server_source, api_key_source = _merge_ov_server_config(+ bot_server_data,+ ov_server_data,+ server_section_present=server_section_present,+ )+ managed_server_url = str(+ os.environ.get(VIKINGBOT_MANAGED_OV_SERVER_URL_ENV) or ""+ ).strip()+ if server_managed and managed_server_url:+ bot_server_data["server_url"] = managed_server_url.rstrip("/")bot_data["ov_server"] = bot_server_dataconfig = Config.model_validate(bot_data)config.ov_server.set_effective_auth_mode(effective_auth_mode)+ config.ov_server.set_config_source(ov_server_source)+ config.ov_server.set_api_key_source(api_key_source)+ config.ov_server.set_server_managed(server_managed)return configexcept (json.JSONDecodeError, ValueError) as e:@@ -158,7 +177,12 @@ def _merge_vlm_model_config(bot_data: dict, vlm_data: dict) -> None:agents["extra_headers"] = vlm_data["extra_headers"]-def _merge_ov_server_config(bot_data: dict, ov_data: dict) -> str:+def _merge_ov_server_config(+ bot_data: dict,+ ov_data: dict,+ *,+ server_section_present: bool,+) -> tuple[str, str, str]:"""Merge ov_server config into bot config."""@@ -167,20 +191,40 @@ def _merge_ov_server_config(bot_data: dict, ov_data: dict) -> str:if configured_server_url:return _merge_external_ov_server_config(bot_data, configured_server_url)+ if not server_section_present:+ return _merge_no_ov_server_config(bot_data)return _merge_current_ov_server_config(bot_data, server_data)-def _merge_external_ov_server_config(bot_data: dict, server_url: str) -> str:+def _merge_external_ov_server_config(bot_data: dict, server_url: str) -> tuple[str, str, str]:bot_data["server_url"] = server_urlbot_data["mode"] = "remote"bot_data["api_key_type"] = _normalize_api_key_type(bot_data.get("api_key_type")) or "user"- if bot_data["api_key_type"] == "user":- _fill_user_api_key_from_ovcli(bot_data)- return _bot_auth_mode_from_api_key_type(bot_data["api_key_type"], "api_key")+ api_key_source = (+ "bot.ov_server.api_key" if str(bot_data.get("api_key") or "").strip() else "none"+ )+ return (+ _bot_auth_mode_from_api_key_type(bot_data["api_key_type"], "api_key"),+ "explicit",+ api_key_source,+ )-def _merge_current_ov_server_config(bot_data: dict, server_data: dict) -> str:+def _merge_no_ov_server_config(bot_data: dict) -> tuple[str, str, str]:+ bot_data["server_url"] = str(bot_data.get("server_url") or "").strip()+ bot_data["mode"] = "local"+ bot_data["api_key_type"] = _normalize_api_key_type(bot_data.get("api_key_type")) or "user"+ api_key_source = (+ "bot.ov_server.api_key" if str(bot_data.get("api_key") or "").strip() else "none"+ )+ return "", "none", api_key_source+++def _merge_current_ov_server_config(+ bot_data: dict,+ server_data: dict,+) -> tuple[str, str, str]:bot_data["server_url"] = get_server_url_from_server_data(server_data)server_auth_mode = ServerConfig(@@ -192,40 +236,22 @@ def _merge_current_ov_server_config(bot_data: dict, server_data: dict) -> str:)bot_data["api_key_type"] = api_key_type+ api_key_source = (+ "bot.ov_server.api_key" if str(bot_data.get("api_key") or "").strip() else "none"+ )server_root_api_key = str(server_data.get("root_api_key") or "").strip()if api_key_type == "root" and server_auth_mode == "trusted" and server_root_api_key:bot_data["api_key"] = server_root_api_key+ api_key_source = "server.root_api_key"effective_auth_mode = _bot_auth_mode_from_api_key_type(api_key_type, server_auth_mode)mode = "local" if effective_auth_mode == "dev" else "remote"bot_data["mode"] = mode- if effective_auth_mode == "api_key":- _fill_user_api_key_from_ovcli(bot_data)- return effective_auth_mode+ return effective_auth_mode, "inherited", api_key_source-def _fill_user_api_key_from_ovcli(bot_data: dict) -> None:- if str(bot_data.get("api_key") or "").strip():- return- try:- cli_config = load_ovcli_config()- except ValueError as e:- # A missing or invalid ovcli identity only affects OpenViking memory/file- # tools. It must NOT abort loading the rest of the bot config (LLM/vlm- # provider, agents, channels): load_config() would otherwise catch this- # ValueError, discard the whole config and silently fall back to defaults,- # so a user who only configured `vlm` ends up on the default- # `openai/*` model with no credentials ("Missing credentials ... set- # OPENAI_API_KEY") instead of their configured provider. Degraded- # OpenViking auth is surfaced separately by validate_openviking_auth().- print(- f"Warning: could not load OpenViking user API key from ovcli config: {e}\n"- "OpenViking memory and file tools may not work until this is fixed.",- file=sys.stderr,- )- return- if cli_config and cli_config.api_key:- bot_data["api_key"] = cli_config.api_key+def _is_truthy_env(name: str) -> bool:+ return str(os.environ.get(name) or "").strip().lower() in {"1", "true", "yes", "on"}def _normalize_api_key_type(value: Any) -> str:@@ -252,6 +278,34 @@ def _ov_server_auth_mode(ov_server: Any) -> str:return "api_key"+def _ov_server_config_source(ov_server: Any) -> str:+ getter = getattr(ov_server, "get_config_source", None)+ if callable(getter):+ source = getter()+ else:+ source = getattr(ov_server, "_source", "none")+ source = str(source or "none").strip().lower()+ return source if source in {"explicit", "inherited", "none"} else "none"+++def _ov_server_api_key_source(ov_server: Any) -> str:+ getter = getattr(ov_server, "get_api_key_source", None)+ if callable(getter):+ source = getter()+ else:+ source = getattr(ov_server, "_api_key_source", "none")+ source = str(source or "none").strip().lower()+ allowed = {"bot.ov_server.api_key", "server.root_api_key", "none"}+ return source if source in allowed else "none"+++def _ov_server_is_server_managed(ov_server: Any) -> bool:+ getter = getattr(ov_server, "is_server_managed", None)+ if callable(getter):+ return bool(getter())+ return bool(getattr(ov_server, "_server_managed", False))++def _ov_server_trusted_api_key(ov_server: Any) -> str:if _normalize_api_key_type(getattr(ov_server, "api_key_type", "")) == "root":return str(getattr(ov_server, "api_key", "") or "").strip()@@ -300,23 +354,74 @@ def _request_openviking_json(def _result_reason(result: _OpenVikingHTTPResult) -> str:- if result.status_code is not None:- return f"HTTP {result.status_code}"if result.error:return result.error+ if result.status_code is not None:+ return f"HTTP {result.status_code}"return "unknown error"def _server_unavailable_warning(server_url: str, result: _OpenVikingHTTPResult) -> None:print(f"Warning: OpenViking server at {server_url} is unavailable "- f"({_result_reason(result)}). Only basic VikingBot features are available; "- "OpenViking memory and file tools may not work.",+ f"({_result_reason(result)}). VikingBot will start in standalone mode; "+ "OpenViking memory and file tools are disabled.",file=sys.stderr,)-def _auth_mode_change_hint(actual_auth_mode: str, current_auth_mode: str) -> str:+def _raise_server_unavailable(server_url: str, result: _OpenVikingHTTPResult) -> None:+ print(+ "Error: configured bot.ov_server.server_url is unavailable.\n"+ f"OpenViking server URL: {server_url}\n"+ f"Reason: {_result_reason(result)}\n"+ "Start the configured OpenViking server or update bot.ov_server.server_url.",+ file=sys.stderr,+ )+ raise SystemExit(1)+++def _raise_server_unhealthy(server_url: str, result: _OpenVikingHTTPResult) -> None:+ print(+ "Error: OpenViking server is reachable but not usable by VikingBot.\n"+ f"OpenViking server URL: {server_url}\n"+ f"Reason: {_result_reason(result)}\n"+ "Check the OpenViking server status and authentication configuration.",+ file=sys.stderr,+ )+ raise SystemExit(1)+++def _inherited_auth_mode_change_hint(actual_auth_mode: str, current_auth_mode: str) -> str:+ hint = (+ "VikingBot inherits the OpenViking auth mode from the current ov.conf server section. "+ "The running OpenViking process was started with different authentication settings.\n"+ f"Fix: restart OpenViking server with the current ov.conf to apply auth_mode="+ f"'{current_auth_mode}', or update ov.conf server.auth_mode/root_api_key so it "+ f"resolves to '{actual_auth_mode}', then start the gateway again."+ )+ if actual_auth_mode == "api_key":+ hint += (+ " If api_key mode is intended, also configure bot.ov_server.api_key with an "+ "OpenViking User/Admin API key."+ )+ elif actual_auth_mode == "trusted":+ hint += (+ " If trusted mode is intended, configure server.auth_mode='trusted' and "+ "server.root_api_key in the same ov.conf."+ )+ if current_auth_mode == "dev":+ hint += " A dev-mode VikingBot gateway must listen on localhost."+ return hint+++def _auth_mode_change_hint(+ actual_auth_mode: str,+ current_auth_mode: str,+ source: str,+) -> str:+ if source == "inherited":+ return _inherited_auth_mode_change_hint(actual_auth_mode, current_auth_mode)if actual_auth_mode == "trusted":return ("To use this server, set bot.ov_server.api_key_type to 'root' and configure "@@ -327,7 +432,7 @@ def _auth_mode_change_hint(actual_auth_mode: str, current_auth_mode: str) -> strif actual_auth_mode == "api_key":return ("To use this server, set bot.ov_server.api_key_type to 'user' and configure "- "bot.ov_server.api_key with an OpenViking User API key, or change the "+ "bot.ov_server.api_key with an OpenViking User/Admin API key, or change the ""OpenViking server.auth_mode and restart the server.")if actual_auth_mode == "dev":@@ -345,34 +450,145 @@ def _raise_auth_mode_mismatch(server_url: str,actual_auth_mode: str,current_auth_mode: str,+ source: str,) -> None:+ if source == "inherited":+ print(+ "Error: running OpenViking auth mode does not match the current ov.conf.\n"+ f"OpenViking server URL: {server_url}\n"+ f"Running server auth_mode: {actual_auth_mode}\n"+ f"Current ov.conf server auth_mode: {current_auth_mode}\n"+ f"{_auth_mode_change_hint(actual_auth_mode, current_auth_mode, source)}",+ file=sys.stderr,+ )+ raise SystemExit(1)+print("Error: OpenViking auth mode mismatch.\n"f"OpenViking server URL: {server_url}\n"f"Actual server auth_mode: {actual_auth_mode}\n"f"VikingBot current auth_mode: {current_auth_mode}\n"- f"{_auth_mode_change_hint(actual_auth_mode, current_auth_mode)}",+ f"{_auth_mode_change_hint(actual_auth_mode, current_auth_mode, source)}",file=sys.stderr,)raise SystemExit(1)-def _warn_api_key_mode_requires_user_key() -> None:+def _mark_standalone_mode(ov_server: Any) -> None:+ ov_server.server_url = ""+ ov_server.mode = "local"+ setter = getattr(ov_server, "set_effective_auth_mode", None)+ if callable(setter):+ setter("")+ else:+ ov_server._effective_auth_mode = ""+ source_setter = getattr(ov_server, "set_config_source", None)+ if callable(source_setter):+ source_setter("none")+ else:+ ov_server._source = "none"+ key_source_setter = getattr(ov_server, "set_api_key_source", None)+ if callable(key_source_setter):+ key_source_setter("none")+ else:+ ov_server._api_key_source = "none"+++def _set_runtime_auth_mode(ov_server: Any, auth_mode: str) -> None:+ auth_mode = str(auth_mode or "").strip().lower()+ setter = getattr(ov_server, "set_effective_auth_mode", None)+ if callable(setter):+ setter(auth_mode)+ else:+ ov_server._effective_auth_mode = auth_mode+ if auth_mode == "trusted":+ ov_server.api_key_type = "root"+ elif auth_mode == "api_key":+ ov_server.api_key_type = "user"+ if auth_mode == "dev":+ ov_server.mode = "local"+ elif auth_mode:+ ov_server.mode = "remote"+++def _is_loopback_host(host: str) -> bool:+ host = str(host or "").strip().lower()+ if host.startswith("[") and host.endswith("]"):+ host = host[1:-1]+ if host in {"localhost", "127.0.0.1", "::1"}:+ return True+ try:+ return ipaddress.ip_address(host).is_loopback+ except ValueError:+ return False+++def _is_loopback_url(url: str) -> bool:+ try:+ host = urlsplit(url).hostname or ""+ except ValueError:+ return False+ return _is_loopback_host(host)+++def _validate_dev_boundary(config: Config, server_url: str) -> None:+ gateway = getattr(config, "gateway", None)+ gateway_host = str(getattr(gateway, "host", "127.0.0.1") or "127.0.0.1").strip()+ if _is_loopback_host(gateway_host) and _is_loopback_url(server_url):+ returnprint(- "Warning: OpenViking is configured for api_key mode, but bot.ov_server.api_key "- "is not configured with a valid OpenViking User API key. OpenViking memory and "- "file tools may not work correctly. Configure bot.ov_server.api_key with a User "- "API key. Root API keys cannot access OpenViking data APIs in api_key mode.",+ "Error: OpenViking dev auth can only be used when gateway and OpenViking server "+ "are localhost.",file=sys.stderr,)+ raise SystemExit(1)+++def _raise_api_key_mode_requires_user_key(ov_server: Any) -> None:+ key_source = _ov_server_api_key_source(ov_server)+ key_hint = "bot.ov_server.api_key"+ print(+ "Error: OpenViking is configured for api_key mode, but VikingBot does not have "+ "a valid OpenViking User/Admin API key.\n"+ f"API key source: {key_source}\n"+ f"Fix: configure {key_hint} with a User/Admin API key. "+ "Root API keys cannot access OpenViking data APIs in api_key mode.",+ file=sys.stderr,+ )+ raise SystemExit(1)+++def _raise_api_key_mode_root_key() -> None:+ print(+ "Error: bot.ov_server.api_key resolves to a ROOT API key, but OpenViking "+ "api_key mode requires a User/Admin API key for memory and file data APIs. "+ "Configure bot.ov_server.api_key with a User/Admin API key.",+ file=sys.stderr,+ )+ raise SystemExit(1)+++def _raise_trusted_mode_requires_root_key(ov_server: Any) -> None:+ key_source = _ov_server_api_key_source(ov_server)+ print(+ "Error: VikingBot is configured for trusted OpenViking access, but no valid "+ "root API key is available.\n"+ f"API key source: {key_source}\n"+ "Fix: configure bot.ov_server.api_key with the OpenViking root API key for an "+ "explicit bot.ov_server, or configure server.root_api_key when inheriting the "+ "same ov.conf.",+ file=sys.stderr,+ )+ raise SystemExit(1)def _validate_api_key_mode_key(ov_server: Any, server_url: str) -> None:api_key = str(getattr(ov_server, "api_key", "") or "").strip()api_key_type = _normalize_api_key_type(getattr(ov_server, "api_key_type", "user")) or "user"- if not api_key or api_key_type != "user":- _warn_api_key_mode_requires_user_key()+ if _ov_server_is_server_managed(ov_server):return+ if not api_key or api_key_type != "user":+ _raise_api_key_mode_requires_user_key(ov_server)result = _request_openviking_json(server_url,@@ -380,8 +596,7 @@ def _validate_api_key_mode_key(ov_server: Any, server_url: str) -> None:headers={"X-API-Key": api_key},)if not result.ok:- _server_unavailable_warning(server_url, result)- return+ _raise_api_key_mode_requires_user_key(ov_server)data = result.data or {}role = str(data.get("role") or "").strip().lower()@@ -390,18 +605,14 @@ def _validate_api_key_mode_key(ov_server: Any, server_url: str) -> None:if role in {"user", "admin"} and account_id and user_id:returnif role == "root":- print(- "Warning: bot.ov_server.api_key resolves to a ROOT API key, but OpenViking "- "api_key mode requires a User/Admin API key for memory and file data APIs. "- "Configure bot.ov_server.api_key with a User API key.",- file=sys.stderr,- )- return- _warn_api_key_mode_requires_user_key()+ _raise_api_key_mode_root_key()+ _raise_api_key_mode_requires_user_key(ov_server)def _validate_trusted_mode_key(ov_server: Any, server_url: str) -> None:root_api_key = _ov_server_trusted_api_key(ov_server)+ if not root_api_key:+ _raise_trusted_mode_requires_root_key(ov_server)account_id = str(getattr(ov_server, "account_id", "") or "default").strip()user_id = str(getattr(ov_server, "admin_user_id", "") or "default").strip()headers = {@@ -416,40 +627,25 @@ def _validate_trusted_mode_key(ov_server: Any, server_url: str) -> None:returnif result.status_code in {401, 403}:- if root_api_key:- print(- "Warning: VikingBot is configured for trusted OpenViking access "- "(api_key_type=root), but the configured root API key was rejected. "- "OpenViking memory and file tools may not work correctly. Configure "- "bot.ov_server.api_key with the OpenViking root API key.",- file=sys.stderr,- )- else:- print(- "Warning: VikingBot is configured for trusted OpenViking access "- "(api_key_type=root), but no usable root API key is configured. "- "OpenViking memory and file tools may not work correctly. Configure "- "bot.ov_server.api_key with the OpenViking root API key, or use localhost "- "trusted mode without a root key.",- file=sys.stderr,- )- return+ _raise_trusted_mode_requires_root_key(ov_server)print(- f"Warning: VikingBot could not validate trusted OpenViking access at {server_url} "- f"({_result_reason(result)}). OpenViking memory and file tools may not work correctly.",+ f"Error: VikingBot could not validate trusted OpenViking access at {server_url} "+ f"({_result_reason(result)}).",file=sys.stderr,)+ raise SystemExit(1)def validate_openviking_auth(config: Config) -> None:"""Validate VikingBot's OpenViking server, auth mode, and API key wiring."""ov_server = config.ov_serverserver_url = str(getattr(ov_server, "server_url", "") or "").strip()+ source = _ov_server_config_source(ov_server)if not server_url:print(- "Warning: bot.ov_server.server_url is not configured. Only basic VikingBot "- "features are available; OpenViking memory and file tools may not work.",+ "Warning: no available OpenViking server is configured. VikingBot will run "+ "in standalone mode; OpenViking memory and file tools are disabled.",file=sys.stderr,)return@@ -465,20 +661,43 @@ def validate_openviking_auth(config: Config) -> None:health = _request_openviking_json(server_url, "/health", headers=headers)if not health.ok:+ if _ov_server_is_server_managed(ov_server):+ print(+ f"Warning: managed OpenViking server at {server_url} is not ready yet "+ f"({_result_reason(health)}). VikingBot will keep the inherited upstream "+ "and wait for openviking-server to start.",+ file=sys.stderr,+ )+ return+ if health.status_code in {401, 403}:+ if auth_mode == "trusted":+ _raise_trusted_mode_requires_root_key(ov_server)+ if auth_mode == "api_key":+ _raise_api_key_mode_requires_user_key(ov_server)+ _raise_server_unhealthy(server_url, health)+ if health.status_code is not None and not health.error:+ _raise_server_unhealthy(server_url, health)+ if source == "explicit":+ _raise_server_unavailable(server_url, health)_server_unavailable_warning(server_url, health)+ _mark_standalone_mode(ov_server)returnhealth_data = health.data or {}actual_auth_mode = str(health_data.get("auth_mode") or "").strip().lower()if not actual_auth_mode:- print(- f"Warning: OpenViking server at {server_url} is reachable, but /health did not "- "return auth_mode. OpenViking memory and file tools may not work correctly.",- file=sys.stderr,+ _raise_server_unhealthy(+ server_url,+ _OpenVikingHTTPResult(+ ok=False, status_code=health.status_code, error="missing auth_mode"+ ),)- returnif actual_auth_mode != auth_mode:- _raise_auth_mode_mismatch(server_url, actual_auth_mode, auth_mode)+ if source == "explicit":+ _set_runtime_auth_mode(ov_server, actual_auth_mode)+ auth_mode = actual_auth_mode+ else:+ _raise_auth_mode_mismatch(server_url, actual_auth_mode, auth_mode, source)if auth_mode == "trusted":_validate_trusted_mode_key(ov_server, server_url)@@ -486,6 +705,9 @@ def validate_openviking_auth(config: Config) -> None:if auth_mode == "api_key":_validate_api_key_mode_key(ov_server, server_url)return+ if auth_mode == "dev":+ _validate_dev_boundary(config, server_url)+ returnreturndiff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.pyindex 405bca4f4..a8ea1a12f 100644--- a/bot/vikingbot/config/schema.py+++ b/bot/vikingbot/config/schema.py@@ -546,6 +546,12 @@ class OpenVikingConfig(BaseModel):_effective_auth_mode: str = PrivateAttr(default="")+ _source: str = PrivateAttr(default="none")++ _api_key_source: str = PrivateAttr(default="none")++ _server_managed: bool = PrivateAttr(default=False)+# Deprecated as user config. Kept for compatibility; load_config derives it# from OpenViking's effective dev auth mode.mode: str = "remote"@@ -604,6 +610,34 @@ class OpenVikingConfig(BaseModel):def set_effective_auth_mode(self, auth_mode: str) -> None:self._effective_auth_mode = str(auth_mode or "").strip().lower()+ def get_config_source(self) -> str:+ return self._source++ def set_config_source(self, source: str) -> None:+ source = str(source or "none").strip().lower()+ if source not in {"explicit", "inherited", "none"}:+ source = "none"+ self._source = source++ def get_api_key_source(self) -> str:+ return self._api_key_source++ def set_api_key_source(self, source: str) -> None:+ source = str(source or "none").strip().lower()+ allowed = {"bot.ov_server.api_key", "server.root_api_key", "none"}+ if source not in allowed:+ source = "none"+ self._api_key_source = source++ def is_server_managed(self) -> bool:+ return self._server_managed++ def set_server_managed(self, value: bool) -> None:+ self._server_managed = bool(value)++ def is_available(self) -> bool:+ return bool(str(self.server_url or "").strip())+class WebToolsConfig(BaseModel):"""Web tools configuration."""diff --git a/bot/vikingbot/hooks/base.py b/bot/vikingbot/hooks/base.pyindex ce48192e2..6d42586b6 100644--- a/bot/vikingbot/hooks/base.py+++ b/bot/vikingbot/hooks/base.py@@ -15,6 +15,8 @@ class HookContext:session_key: SessionKey = Nonemetadata: Dict[str, Any] = Nonetimestamp: datetime = None+ config: Any = None+ openviking_connection: Dict[str, Any] | None = Nonedef __post_init__(self):if self.metadata is None:diff --git a/bot/vikingbot/hooks/builtins/openviking_hooks.py b/bot/vikingbot/hooks/builtins/openviking_hooks.pyindex 0fc8de747..261eb64f4 100644--- a/bot/vikingbot/hooks/builtins/openviking_hooks.py+++ b/bot/vikingbot/hooks/builtins/openviking_hooks.py@@ -28,10 +28,10 @@ except Exception:VikingClient = Noneov = None-_global_clients: dict[str, Any] = {}+_global_clients: dict[tuple[str, int, int], Any] = {}-async def get_global_client(workspace_id: str | None) -> VikingClient:+async def get_global_client(workspace_id: str | None, config: Any = None) -> VikingClient:"""Get or create the shared VikingClient."""# VikingClient (and its underlying AsyncHTTPClient / streaming updater / connection# pool) creates asyncio.Event/Lock/Semaphore bound to the running loop at creation@@ -39,10 +39,17 @@ async def get_global_client(workspace_id: str | None) -> VikingClient:# multi-threaded rollout workers in tau2 training) raises# "<asyncio.locks.Event ... [unset]> is bound to a different event loop". Key the# cache by (workspace_id, running_loop) so each loop gets its own client.- cache_key = (str(workspace_id or "__default__"), id(asyncio.get_running_loop()))+ cache_key = (+ str(workspace_id or "__default__"),+ id(asyncio.get_running_loop()),+ id(config),+ )client = _global_clients.get(cache_key)if client is None:- client = await VikingClient.create(workspace_id)+ if config is None:+ client = await VikingClient.create(workspace_id)+ else:+ client = await VikingClient.create(workspace_id, config=config)_global_clients[cache_key] = clientreturn client@@ -54,16 +61,18 @@ class OpenVikingCompactHook(Hook):self,workspace_id: str,openviking_connection: dict[str, Any] | None = None,+ config: Any = None,) -> tuple[VikingClient, bool]:if openviking_connection:return (await VikingClient.create(workspace_id,connection=openviking_connection,+ config=config,),True,)- return await get_global_client(workspace_id), False+ return await get_global_client(workspace_id, config=config), Falseasync def _execute_session_context_commit(self,@@ -163,11 +172,13 @@ class OpenVikingCompactHook(Hook):async def execute(self, context: HookContext, **kwargs) -> Any:vikingbot_session: Session = kwargs.get("session", {})session_id = context.session_key.safe_name()- config = load_config()+ config = context.config or load_config()ov_config = config.ov_server+ if not str(getattr(ov_config, "server_url", "") or "").strip():+ return {"success": False, "skipped": "standalone"}agents_config = config.agentsadmin_user_id = ov_config.admin_user_id- openviking_connection = kwargs.get("openviking_connection")+ openviking_connection = context.openviking_connection or kwargs.get("openviking_connection")if not isinstance(openviking_connection, dict):openviking_connection = Noneforce_commit = bool(kwargs.get("force_commit", False))@@ -184,12 +195,22 @@ class OpenVikingCompactHook(Hook):try:if openviking_connection:- client_result = await self._get_client(- context.workspace_id,- openviking_connection=openviking_connection,- )+ if context.config is None:+ client_result = await self._get_client(+ context.workspace_id,+ openviking_connection=openviking_connection,+ )+ else:+ client_result = await self._get_client(+ context.workspace_id,+ openviking_connection=openviking_connection,+ config=config,+ )else:- client_result = await self._get_client(context.workspace_id)+ if context.config is None:+ client_result = await self._get_client(context.workspace_id)+ else:+ client_result = await self._get_client(context.workspace_id, config=config)if isinstance(client_result, tuple):client, should_close_client = client_resultelse:@@ -240,17 +261,40 @@ class OpenVikingPostCallHook(Hook):# hooks instead of the sequential sync_hooks path.is_sync = False- async def _get_client(self, workspace_id: str) -> VikingClient:- return await get_global_client(workspace_id)+ async def _get_client(self, workspace_id: str, config: Any = None) -> VikingClient:+ return await get_global_client(workspace_id, config=config)- async def _search_skill_experiences(self, workspace_id: str, query: str) -> str:+ async def _search_skill_experiences(+ self,+ workspace_id: str,+ query: str,+ config: Any = None,+ openviking_connection: dict[str, Any] | None = None,+ ) -> str:"""用 skill 描述检索 experience 记忆,只检索 experiences 目录。"""if not query:return ""started_at = time.perf_counter()query_preview = query.replace("\n", "\\n")[:120]+ ov_client = None+ should_close = Falsetry:- ov_client = await self._get_client(workspace_id)+ if (+ config is not None+ and not str(getattr(config.ov_server, "server_url", "") or "").strip()+ ):+ return ""+ if openviking_connection:+ ov_client = await VikingClient.create(+ workspace_id,+ connection=openviking_connection,+ config=config,+ )+ should_close = True+ elif config is None:+ ov_client = await self._get_client(workspace_id)+ else:+ ov_client = await self._get_client(workspace_id, config=config)logger.debug("[SKILL_EXP]: start workspace_id=%s query_len=%d query=%r",workspace_id,@@ -332,6 +376,9 @@ class OpenVikingPostCallHook(Hook):query_preview,)return ""+ finally:+ if should_close and ov_client is not None:+ await ov_client.close()async def execute(self, context: HookContext, tool_name, params, result) -> Any:if tool_name == "read_file":@@ -345,7 +392,10 @@ class OpenVikingPostCallHook(Hook):skill_query = desc_match.group(1).strip() if desc_match else skill_nameexp_memory = await self._search_skill_experiences(- context.workspace_id, skill_query+ context.workspace_id,+ skill_query,+ config=context.config,+ openviking_connection=context.openviking_connection,)if exp_memory:result = f"{result}\n\n---\n## Related Experiences\n{exp_memory}"diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.pyindex 5e785666f..416bdb330 100644--- a/bot/vikingbot/openviking_mount/ov_server.py+++ b/bot/vikingbot/openviking_mount/ov_server.py@@ -2,7 +2,7 @@ import base64import jsonimport reimport uuid-from typing import Any, Dict, List, Mapping, Optional+from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optionalfrom loguru import logger@@ -11,6 +11,9 @@ from openviking.core.namespace import uri_partsfrom openviking.core.peer_id import normalize_peer_idfrom vikingbot.config.loader import load_config+if TYPE_CHECKING:+ from vikingbot.config.schema import Config+viking_resource_prefix = "viking://resources/"@@ -43,15 +46,19 @@ class VikingClient:agent_id: Optional[str] = None,connection: Optional[Mapping[str, Any]] = None,actor_peer_id: Optional[str] = None,+ config: "Config | None" = None,):if agent_id is None:agent_id = workspace_idif agent_id and "#" in agent_id:agent_id = agent_id.split("#", 1)[0]- config = load_config()+ config = config or load_config()+ self.config = configopenviking_config = config.ov_serverself.openviking_config = openviking_config+ if not str(getattr(openviking_config, "server_url", "") or "").strip():+ raise RuntimeError("OpenViking is unavailable in VikingBot standalone mode")self.workspace_id = agent_idself.agent_id = agent_idself.ov_path = config.ov_data_path@@ -182,8 +189,8 @@ class VikingClient:self.auth_mode = "trusted" if self.api_key_type == "root" else "api_key"self.agent_id = connection.get("agent_id") or agent_idself.workspace_id = self.agent_id- self.account_id = connection.get("account_id") or self.openviking_config.account_id- self.admin_user_id = connection.get("user_id") or self.openviking_config.admin_user_id+ self.account_id = connection.get("account_id")+ self.admin_user_id = connection.get("user_id")policy = connection.get("namespace_policy")if isinstance(policy, dict):@@ -191,14 +198,14 @@ class VikingClient:self._namespace_policy_loaded = Trueremote_client_kwargs = {- "url": connection.get("server_url") or self.openviking_config.server_url,+ "url": self.openviking_config.server_url,"profile_enabled": False,}if connection.get("api_key"):remote_client_kwargs["api_key"] = connection["api_key"]- if self.api_key_type == "root" and self.account_id:+ if self.account_id:remote_client_kwargs["account"] = self.account_id- if self.api_key_type == "root" and self.admin_user_id:+ if self.admin_user_id:remote_client_kwargs["user"] = self.admin_user_idself._apply_actor_peer_scope(remote_client_kwargs)@@ -217,6 +224,7 @@ class VikingClient:agent_id: Optional[str] = None,connection: Optional[Mapping[str, Any]] = None,actor_peer_id: Optional[str] = None,+ config: "Config | None" = None,):"""Factory method to create and initialize a VikingClient instance."""instance = cls(@@ -224,6 +232,7 @@ class VikingClient:agent_id=agent_id,connection=connection,actor_peer_id=actor_peer_id,+ config=config,)await instance._initialize()return instance@@ -235,9 +244,7 @@ class VikingClient:return {"uri": str(matched_context.get("uri", "") or ""),"context_type": str(- matched_context.get("context_type")- or matched_context.get("type")- or ""+ matched_context.get("context_type") or matched_context.get("type") or ""),"is_leaf": bool(matched_context.get("is_leaf", False)),"abstract": str(matched_context.get("abstract", "") or ""),@@ -245,9 +252,9 @@ class VikingClient:"category": str(matched_context.get("category", "") or ""),"score": matched_context.get("score", 0.0),"match_reason": str(matched_context.get("match_reason", "") or ""),- "relations": [- self._relation_to_dict(r) for r in relations if r is not None- ] if isinstance(relations, list) else [],+ "relations": [self._relation_to_dict(r) for r in relations if r is not None]+ if isinstance(relations, list)+ else [],}return {"uri": getattr(matched_context, "uri", ""),diff --git a/bot/vikingbot/session/manager.py b/bot/vikingbot/session/manager.pyindex 9e401f038..aadd07a33 100644--- a/bot/vikingbot/session/manager.py+++ b/bot/vikingbot/session/manager.py@@ -154,6 +154,9 @@ class SessionManager:def _get_session_path(self, session_key: SessionKey) -> Path:return self.sessions_dir / f"{session_key.safe_name()}.jsonl"+ def has_persisted(self, session_key: SessionKey) -> bool:+ return self._get_session_path(session_key).exists()+def get_or_create(self, key: SessionKey, skip_heartbeat: bool = False) -> Session:"""Get an existing session or create a new one.diff --git a/bot/vikingbot/tests/unit/test_config/test_vlm_only_config_survives_ovcli_error.py b/bot/vikingbot/tests/unit/test_config/test_vlm_only_config_survives_ovcli_error.pyindex 8ed43bf1e..33737a1c7 100644--- a/bot/vikingbot/tests/unit/test_config/test_vlm_only_config_survives_ovcli_error.py+++ b/bot/vikingbot/tests/unit/test_config/test_vlm_only_config_survives_ovcli_error.py@@ -1,16 +1,8 @@-"""Regression test for vlm-only ov.conf losing its provider on ovcli errors.+"""Bot configuration must remain independent from ovcli.conf.-Repro: with only a `vlm` section configured (no `bot.agents`) and a `server`-section whose effective auth mode is `api_key`, load_config() used to call-_fill_user_api_key_from_ovcli() -> load_ovcli_config(), which raises ValueError-when no valid ovcli identity exists. load_config()'s broad-`except (json.JSONDecodeError, ValueError)` then swallowed it and fell back to a-default Config(), discarding the vlm-derived model/provider/credentials. The bot-then ran on the default `openai/*` model with no key and failed with-"Missing credentials ... set OPENAI_API_KEY".--An ovcli/user-identity problem must only degrade OpenViking memory/file tools,-never discard the unrelated LLM/vlm provider config.+VLM settings and the static OpenViking upstream are loaded from ov.conf. An+invalid ovcli.conf must not discard VLM settings, and a valid ovcli user key+must not be copied into the Bot process configuration."""import json@@ -38,13 +30,11 @@ def _write_conf(tmp_path, monkeypatch):return conf-def test_vlm_config_preserved_when_ovcli_lookup_fails(tmp_path, monkeypatch):+def test_vlm_config_preserved_when_ovcli_config_is_invalid(tmp_path, monkeypatch):_write_conf(tmp_path, monkeypatch)-- def _raise(*_args, **_kwargs):- raise ValueError("Invalid CLI config: no ovcli identity configured")-- monkeypatch.setattr(loader, "load_ovcli_config", _raise)+ ovcli_conf = tmp_path / "ovcli.conf"+ ovcli_conf.write_text("{invalid json")+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(ovcli_conf))config = loader.load_config()@@ -53,19 +43,17 @@ def test_vlm_config_preserved_when_ovcli_lookup_fails(tmp_path, monkeypatch):assert config.agents.provider == "deepseek"assert config.agents.api_key == "sk-deepseek-test-key"assert config.agents.api_base == "https://api.deepseek.com"+ assert not config.ov_server.api_key-def test_vlm_config_used_when_ovcli_supplies_user_key(tmp_path, monkeypatch):+def test_ovcli_user_key_is_not_copied_into_bot_config(tmp_path, monkeypatch):_write_conf(tmp_path, monkeypatch)-- class _Cli:- api_key = "user-api-key"-- monkeypatch.setattr(loader, "load_ovcli_config", lambda *a, **k: _Cli())+ ovcli_conf = tmp_path / "ovcli.conf"+ ovcli_conf.write_text(json.dumps({"url": "http://ov.local", "api_key": "user-api-key"}))+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(ovcli_conf))config = loader.load_config()- # LLM provider still comes from vlm; ovcli only fills the OpenViking user key.assert config.agents.provider == "deepseek"assert config.agents.model == "deepseek-chat"- assert config.ov_server.api_key == "user-api-key"+ assert not config.ov_server.api_keydiff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rsindex 1cf5e58ef..101969254 100644--- a/crates/ov_cli/src/base_client.rs+++ b/crates/ov_cli/src/base_client.rs@@ -13,6 +13,9 @@ use indicatif::{ProgressBar, ProgressStyle};use crate::error::{Error, Result};+const GATEWAY_MARKER_HEADER: &str = "X-VikingBot-Gateway";+const GATEWAY_TOKEN_HEADER: &str = "X-Gateway-Token";+fn parse_ignore_dirs(ignore_dirs: Option<&str>) -> Vec<String> {ignore_dirs.map(|s| {@@ -162,6 +165,7 @@ pub struct BaseClient {pub(crate) actor_peer_id: Option<String>,pub(crate) profile_enabled: bool,pub(crate) extra_headers: Option<std::collections::HashMap<String, String>>,+ gateway_token: Option<String>,}impl BaseClient {@@ -189,9 +193,17 @@ impl BaseClient {actor_peer_id,profile_enabled,extra_headers,+ gateway_token: None,}}+ pub fn with_gateway_token(mut self, gateway_token: Option<String>) -> Self {+ self.gateway_token = gateway_token+ .map(|token| token.trim().to_string())+ .filter(|token| !token.is_empty());+ self+ }+fn append_profile_query<'a>(&self, params: &'a [(String, String)]) -> Vec<(String, String)> {let mut merged = params.to_vec();if self.profile_enabled && !merged.iter().any(|(k, _)| k == "profile") {@@ -250,6 +262,63 @@ impl BaseClient {headers}+ fn is_gateway_token_challenge(response: &reqwest::Response) -> bool {+ response.status() == StatusCode::UNAUTHORIZED+ && response+ .headers()+ .get(GATEWAY_MARKER_HEADER)+ .and_then(|value| value.to_str().ok())+ .is_some_and(|value| value.eq_ignore_ascii_case("true"))+ }++ pub(crate) async fn send_request(+ &self,+ request: reqwest::RequestBuilder,+ error_context: &str,+ ) -> Result<reqwest::Response> {+ let retry = request.try_clone();+ let response = request+ .send()+ .await+ .map_err(|e| Error::Network(format!("{}: {}", error_context, e)))?;+ if !Self::is_gateway_token_challenge(&response) {+ return Ok(response);+ }++ let Some(gateway_token) = self.gateway_token.as_deref() else {+ return Ok(response);+ };+ let Some(retry) = retry else {+ return Ok(response);+ };+ retry+ .header(GATEWAY_TOKEN_HEADER, gateway_token)+ .send()+ .await+ .map_err(|e| Error::Network(format!("{}: {}", error_context, e)))+ }++ async fn headers_for_uncloneable_request(&self) -> Result<reqwest::header::HeaderMap> {+ let mut headers = self.build_headers();+ let Some(gateway_token) = self.gateway_token.as_deref() else {+ return Ok(headers);+ };+ let health_url = format!("{}/health", self.base_url);+ let response = self+ .http+ .get(health_url)+ .headers(headers.clone())+ .send()+ .await+ .map_err(|e| Error::Network(format!("Gateway detection request failed: {}", e)))?;+ if Self::is_gateway_token_challenge(&response) {+ if let Ok(value) = reqwest::header::HeaderValue::from_str(gateway_token) {+ headers.insert(GATEWAY_TOKEN_HEADER, value);+ }+ }+ Ok(headers)+ }+pub(crate) async fn handle_response<T: DeserializeOwned + 'static>(&self,response: reqwest::Response,@@ -341,14 +410,12 @@ impl BaseClient {) -> Result<T> {let url = format!("{}{}", self.base_url, path);let params = self.append_profile_query(params);- let response = self+ let request = self.http.get(&url).headers(self.build_headers())- .query(¶ms)- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ .query(¶ms);+ let response = self.send_request(request, "HTTP request failed").await?;self.handle_response(response).await}@@ -369,10 +436,7 @@ impl BaseClient {} else {request};- let response = request- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ let response = self.send_request(request, "HTTP request failed").await?;self.handle_response(response).await}@@ -392,10 +456,7 @@ impl BaseClient {} else {request};- let response = request- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ let response = self.send_request(request, "HTTP request failed").await?;self.handle_response(response).await}@@ -412,10 +473,7 @@ impl BaseClient {} else {request};- let response = request- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ let response = self.send_request(request, "HTTP request failed").await?;self.handle_response(response).await}@@ -427,14 +485,12 @@ impl BaseClient {) -> Result<T> {let url = format!("{}{}", self.base_url, path);let params = self.append_profile_query(params);- let response = self+ let request = self.http.delete(&url).headers(self.build_headers())- .query(¶ms)- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ .query(¶ms);+ let response = self.send_request(request, "HTTP request failed").await?;self.handle_response(response).await}@@ -455,10 +511,7 @@ impl BaseClient {} else {request};- let response = request- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ let response = self.send_request(request, "HTTP request failed").await?;self.handle_response(response).await}@@ -471,15 +524,13 @@ impl BaseClient {) -> Result<T> {let url = format!("{}{}", self.base_url, path);let params = self.append_profile_query(params);- let response = self+ let request = self.http.patch(&url).headers(self.build_headers()).query(¶ms)- .json(body)- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ .json(body);+ let response = self.send_request(request, "HTTP request failed").await?;self.handle_response(response).await}@@ -492,15 +543,13 @@ impl BaseClient {) -> Result<T> {let url = format!("{}{}", self.base_url, path);let params = self.append_profile_query(params);- let response = self+ let request = self.http.post(&url).headers(self.build_headers()).query(¶ms)- .json(body)- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ .json(body);+ let response = self.send_request(request, "HTTP request failed").await?;self.handle_response(response).await}@@ -840,7 +889,7 @@ impl<'a> FileUploader<'a> {form = form.text("upload_mode", upload_mode.clone());}- let mut headers = self.client.build_headers();+ let mut headers = self.client.headers_for_uncloneable_request().await?;headers.remove(reqwest::header::CONTENT_TYPE);let upload_timeout = TimeoutConfig::for_upload().calculate(file_path)?;@@ -908,7 +957,7 @@ impl<'a> FileUploader<'a> {form = form.text("upload_mode", upload_mode.clone());}- let mut headers = self.client.build_headers();+ let mut headers = self.client.headers_for_uncloneable_request().await?;headers.remove(reqwest::header::CONTENT_TYPE);let upload_timeout = TimeoutConfig::for_upload().calculate(file_path)?;diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex a9d96efb6..1f7d92afd 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -90,7 +90,11 @@ pub struct SnapshotRestoreReq {pub enum SnapshotShowResult {Metadata(Value),- Blob { oid: String, size: u64, bytes: Vec<u8> },+ Blob {+ oid: String,+ size: u64,+ bytes: Vec<u8>,+ },}// ============ HttpClient ============@@ -126,6 +130,11 @@ impl HttpClient {}}+ pub fn with_gateway_token(mut self, gateway_token: Option<String>) -> Self {+ self.base = self.base.with_gateway_token(gateway_token);+ self+ }+pub fn user_id(&self) -> Option<&str> {self.base.user_id()}@@ -364,15 +373,16 @@ impl HttpClient {("profile".to_string(), "0".to_string()),];- let response = self+ let request = self.base.http.get(&url).headers(self.base.build_headers())- .query(¶ms)- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ .query(¶ms);+ let response = self+ .base+ .send_request(request, "HTTP request failed")+ .await?;let status = response.status();if !status.is_success() {@@ -1130,16 +1140,17 @@ impl HttpClient {default_name: &str,) -> Result<String> {let url = format!("{}{}", self.base.base_url, endpoint);- let response = self+ let request = self.base.http.post(&url).headers(self.base.build_headers()).json(&body)- .query(&[("profile", "0")])- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ .query(&[("profile", "0")]);+ let response = self+ .base+ .send_request(request, "HTTP request failed")+ .await?;let status = response.status();if !status.is_success() {@@ -1605,8 +1616,11 @@ impl HttpClient {}pub async fn snapshot_ignore_set(&self, content: &str) -> Result<Value> {- self.put("/api/v1/snapshot/ignore", &serde_json::json!({ "content": content }))- .await+ self.put(+ "/api/v1/snapshot/ignore",+ &serde_json::json!({ "content": content }),+ )+ .await}pub async fn snapshot_ignore_delete(&self) -> Result<Value> {@@ -1617,21 +1631,24 @@ impl HttpClient {&self,target_ref: &str,path: Option<&str>,- ) -> Result<SnapshotShowResult> { let url = format!("{}/api/v1/snapshot/show", self.base.base_url);- let mut query: Vec<(String, String)> = vec![("target_ref".to_string(), target_ref.to_string())];+ ) -> Result<SnapshotShowResult> {+ let url = format!("{}/api/v1/snapshot/show", self.base.base_url);+ let mut query: Vec<(String, String)> =+ vec![("target_ref".to_string(), target_ref.to_string())];if let Some(p) = path {query.push(("path".to_string(), p.to_string()));}- let response = self+ let request = self.base.http.get(&url).headers(self.base.build_headers())- .query(&query)- .send()- .await- .map_err(|e| Error::Network(format!("HTTP request failed: {}", e)))?;+ .query(&query);+ let response = self+ .base+ .send_request(request, "HTTP request failed")+ .await?;let status = response.status();let content_type = response@@ -1641,7 +1658,10 @@ impl HttpClient {.unwrap_or("").to_string();- if path.is_some() && status.is_success() && content_type.starts_with("application/octet-stream") {+ if path.is_some()+ && status.is_success()+ && content_type.starts_with("application/octet-stream")+ {let oid = response.headers().get("x-snapshot-oid")@@ -1845,6 +1865,99 @@ mod tests {assert!(!request.contains("include_mod_time_iso="));}+ #[tokio::test]+ async fn gateway_token_is_not_sent_without_a_gateway_challenge() {+ let (base_url, request_rx) = spawn_request_capture_server().await;+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None)+ .with_gateway_token(Some("gateway-secret".to_string()));++ let _: serde_json::Value = client+ .get("/health", &[])+ .await+ .expect("direct OpenViking request should succeed");++ let request = request_rx.await.expect("request should be captured");+ assert!(!request.to_ascii_lowercase().contains("x-gateway-token"));+ }++ #[tokio::test]+ async fn gateway_token_is_retried_for_marked_gateway_challenge() {+ let (base_url, requests_rx) = spawn_gateway_challenge_server().await;+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None)+ .with_gateway_token(Some("gateway-secret".to_string()));++ let _: serde_json::Value = client+ .get("/health", &[])+ .await+ .expect("gateway retry should succeed");++ let requests = requests_rx.await.expect("requests should be captured");+ assert_gateway_token_retry(&requests);+ }++ #[tokio::test]+ async fn file_download_retries_marked_gateway_challenge() {+ let (base_url, requests_rx) = spawn_gateway_challenge_server().await;+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None)+ .with_gateway_token(Some("gateway-secret".to_string()));++ client+ .get_bytes("viking://resources/file.bin")+ .await+ .expect("file download should retry through gateway");++ let requests = requests_rx.await.expect("requests should be captured");+ assert_gateway_token_retry(&requests);+ }++ #[tokio::test]+ async fn pack_download_retries_marked_gateway_challenge() {+ let (base_url, requests_rx) = spawn_gateway_challenge_server().await;+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None)+ .with_gateway_token(Some("gateway-secret".to_string()));+ let output = tempfile::tempdir().expect("tempdir should be created");++ client+ .export_ovpack(+ "viking://resources",+ output+ .path()+ .to_str()+ .expect("tempdir path should be valid"),+ false,+ )+ .await+ .expect("pack export should retry through gateway");++ let requests = requests_rx.await.expect("requests should be captured");+ assert_gateway_token_retry(&requests);+ }++ #[tokio::test]+ async fn snapshot_show_retries_marked_gateway_challenge() {+ let (base_url, requests_rx) = spawn_gateway_challenge_server().await;+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None)+ .with_gateway_token(Some("gateway-secret".to_string()));++ client+ .snapshot_show("HEAD", None)+ .await+ .expect("snapshot show should retry through gateway");++ let requests = requests_rx.await.expect("requests should be captured");+ assert_gateway_token_retry(&requests);+ }++ fn assert_gateway_token_retry(requests: &[String]) {+ assert_eq!(requests.len(), 2);+ assert!(!requests[0].to_ascii_lowercase().contains("x-gateway-token"));+ assert!(+ requests[1]+ .to_ascii_lowercase()+ .contains("x-gateway-token: gateway-secret")+ );+ }+#[tokio::test]async fn tree_does_not_send_display_time_query() {let (base_url, request_rx) = spawn_request_capture_server().await;@@ -1983,4 +2096,44 @@ mod tests {(format!("http://{addr}"), request_rx)}++ async fn spawn_gateway_challenge_server() -> (String, oneshot::Receiver<Vec<String>>) {+ let listener = TcpListener::bind("127.0.0.1:0")+ .await+ .expect("test server should bind");+ let addr = listener.local_addr().expect("test server should have addr");+ let (request_tx, request_rx) = oneshot::channel();++ tokio::spawn(async move {+ let mut requests = Vec::new();+ for attempt in 0..2 {+ let Ok((mut stream, _)) = listener.accept().await else {+ return;+ };+ let mut buffer = vec![0; 4096];+ let Ok(read) = stream.read(&mut buffer).await else {+ return;+ };+ requests.push(String::from_utf8_lossy(&buffer[..read]).to_string());++ let (status, marker, body) = if attempt == 0 {+ (+ "401 Unauthorized",+ "X-VikingBot-Gateway: true\r\n",+ r#"{"detail":"X-Gateway-Token header required"}"#,+ )+ } else {+ ("200 OK", "", r#"{"status":"ok","result":{"ok":true}}"#)+ };+ let response = format!(+ "HTTP/1.1 {status}\r\ncontent-type: application/json\r\n{marker}content-length: {}\r\nconnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = stream.write_all(response.as_bytes()).await;+ }+ let _ = request_tx.send(requests);+ });++ (format!("http://{addr}"), request_rx)+ }}diff --git a/crates/ov_cli/src/commands/chat.rs b/crates/ov_cli/src/commands/chat.rsindex b64df88be..36293dfc6 100644--- a/crates/ov_cli/src/commands/chat.rs+++ b/crates/ov_cli/src/commands/chat.rs@@ -6,29 +6,35 @@//! - Command history support//! - Streaming response support-use std::time::Duration;+use std::{collections::HashMap, time::Duration};use clap::Parser;+use colored::Colorize;use reqwest::Client;use rustyline::DefaultEditor;use rustyline::error::ReadlineError;use serde::{Deserialize, Serialize};use termimad::MadSkin;+use unicode_width::UnicodeWidthStr;+use uuid::Uuid;use crate::config::Config;+use crate::i18n::{Language, copy};+use crate::theme;use crate::utils;use crate::error::{Error, Result};-const DEFAULT_ENDPOINT: &str = "http://localhost:1933/bot/v1";const HISTORY_FILE: &str = ".ov_chat_history";+const CHAT_LABEL_WIDTH: usize = 12;+const CHAT_ACTION_WIDTH: usize = 16;/// Chat with Vikingbot via OpenAPI#[derive(Debug, Parser)]pub struct ChatCommand {/// API endpoint URL- #[arg(short, long, default_value = DEFAULT_ENDPOINT)]- pub endpoint: String,+ #[arg(short, long)]+ pub endpoint: Option<String>,/// API key for authentication#[arg(short, long, env = "VIKINGBOT_API_KEY")]@@ -42,6 +48,10 @@ pub struct ChatCommand {#[arg(long)]pub user: Option<String>,+ /// Actor peer scope to send as X-OpenViking-Actor-Peer+ #[arg(long, hide = true)]+ pub actor_peer_id: Option<String>,+/// Session ID to use (creates new if not provided)#[arg(short, long)]pub session: Option<String>,@@ -103,7 +113,7 @@ struct ChatStreamEvent {data: serde_json::Value,}-#[derive(Debug, Deserialize)]+#[derive(Debug, Deserialize, Default)]struct OpenVikingHealth {#[serde(default)]auth_mode: Option<String>,@@ -113,42 +123,102 @@ struct OpenVikingHealth {account_id: Option<String>,#[serde(default)]user_id: Option<String>,+ #[serde(default)]+ gateway: Option<String>,+ #[serde(default)]+ upstream_configured: Option<bool>,+ #[serde(default)]+ upstream_url: Option<String>,+ #[serde(default)]+ gateway_token_required: bool,}struct ChatAuth {api_key: Option<String>,account: Option<String>,user: Option<String>,+ actor_peer_id: Option<String>,+ extra_headers: HashMap<String, String>,+ gateway_token: Option<String>,+ gateway_token_required: bool,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ChatAuthWarning {+ MissingUserKey,+ CannotValidateKey,+ RootKey,+ InvalidUserKey,+}++#[derive(Debug, Clone, PartialEq, Eq)]+struct ChatOpenVikingInfo {+ enabled: bool,+ server_url: Option<String>,}impl ChatCommand {/// Execute the chat commandpub async fn execute(&self) -> Result<()> {+ let language = Language::current();let client = Client::builder().timeout(Duration::from_secs(300)).build().map_err(|e| Error::Network(format!("Failed to create HTTP client: {}", e)))?;- let health = self.fetch_openviking_health(&client, None).await;- let auth = self.resolve_auth(health.as_ref().map(health_auth_mode))?;- self.warn_openviking_chat_auth(&client, health.as_ref(), &auth)+ let config = Config::load()?;+ let endpoint = self.resolve_endpoint_from_config(&config);+ let probe_auth = self.health_probe_auth_from_config(&config);+ let health = self+ .fetch_openviking_health(&client, &endpoint, Some(&probe_auth))+ .await;+ let openviking_info = openviking_info_from_health(&endpoint, health.as_ref());+ let gateway_token_required = health.as_ref().is_some_and(|health| {+ health.gateway.as_deref() == Some("vikingbot") && health.gateway_token_required+ });+ let auth = self.resolve_auth_from_config(+ config,+ health.as_ref().map(health_auth_mode),+ gateway_token_required,+ );+ let auth_warning = self+ .openviking_chat_auth_warning(&client, &endpoint, health.as_ref(), &auth).await;if let Some(message) = &self.message {+ if let Some(warning) = auth_warning {+ eprint!("{}", render_chat_warning(warning, language));+ }// Single message mode- self.send_message(&client, message, &auth).await+ self.send_message(&client, &endpoint, message, &auth).await} else {// Interactive mode- self.run_interactive(&client, &auth).await+ self.run_interactive(+ &client,+ &endpoint,+ &auth,+ auth_warning,+ &openviking_info,+ language,+ )+ .await}}- fn resolve_auth(&self, server_auth_mode: Option<&str>) -> Result<ChatAuth> {- let config = Config::load()?;- Ok(self.resolve_auth_from_config(config, server_auth_mode))+ fn resolve_endpoint_from_config(&self, config: &Config) -> String {+ if let Some(endpoint) = non_empty_string(self.endpoint.clone()) {+ return endpoint.trim_end_matches('/').to_string();+ }+ chat_endpoint_from_base_url(&config.url)}- fn resolve_auth_from_config(&self, config: Config, server_auth_mode: Option<&str>) -> ChatAuth {+ fn resolve_auth_from_config(+ &self,+ config: Config,+ server_auth_mode: Option<&str>,+ gateway_token_required: bool,+ ) -> ChatAuth {+ let gateway_token = config.effective_gateway_token();if server_auth_mode.map(|mode| mode.trim().eq_ignore_ascii_case("trusted")).unwrap_or(false)@@ -161,6 +231,11 @@ impl ChatCommand {.or_else(|| non_empty_string(config.account.clone())),user: non_empty_string(self.user.clone()).or_else(|| non_empty_string(config.user.clone())),+ actor_peer_id: non_empty_string(self.actor_peer_id.clone())+ .or_else(|| config.effective_actor_peer_id()),+ extra_headers: config.effective_extra_headers().unwrap_or_default(),+ gateway_token,+ gateway_token_required,};}@@ -173,8 +248,30 @@ impl ChatCommand {ChatAuth {api_key: auth.api_key,- account: auth.account,- user: auth.user,+ account: None,+ user: None,+ actor_peer_id: non_empty_string(self.actor_peer_id.clone())+ .or_else(|| config.effective_actor_peer_id()),+ extra_headers: config.effective_extra_headers().unwrap_or_default(),+ gateway_token,+ gateway_token_required,+ }+ }++ fn health_probe_auth_from_config(&self, config: &Config) -> ChatAuth {+ ChatAuth {+ api_key: non_empty_string(self.api_key.clone())+ .or_else(|| non_empty_string(config.root_api_key.clone()))+ .or_else(|| non_empty_string(config.api_key.clone())),+ account: non_empty_string(self.account.clone())+ .or_else(|| non_empty_string(config.account.clone())),+ user: non_empty_string(self.user.clone())+ .or_else(|| non_empty_string(config.user.clone())),+ actor_peer_id: non_empty_string(self.actor_peer_id.clone())+ .or_else(|| config.effective_actor_peer_id()),+ extra_headers: config.effective_extra_headers().unwrap_or_default(),+ gateway_token: config.effective_gateway_token(),+ gateway_token_required: false,}}@@ -192,11 +289,22 @@ impl ChatCommand {if let Some(user) = &auth.user {req_builder = req_builder.header("X-OpenViking-User", user);}+ if let Some(actor_peer_id) = &auth.actor_peer_id {+ req_builder = req_builder.header("X-OpenViking-Actor-Peer", actor_peer_id);+ }+ for (key, value) in &auth.extra_headers {+ req_builder = req_builder.header(key.as_str(), value);+ }+ if auth.gateway_token_required {+ if let Some(gateway_token) = &auth.gateway_token {+ req_builder = req_builder.header("X-Gateway-Token", gateway_token);+ }+ }req_builder}- fn openviking_health_url(&self) -> Option<String> {- let endpoint = self.endpoint.trim_end_matches('/');+ fn openviking_health_url(&self, endpoint: &str) -> Option<String> {+ let endpoint = endpoint.trim_end_matches('/');endpoint.strip_suffix("/bot/v1").map(|server_url| format!("{}/health", server_url.trim_end_matches('/')))@@ -205,31 +313,48 @@ impl ChatCommand {async fn fetch_openviking_health(&self,client: &Client,+ endpoint: &str,auth: Option<&ChatAuth>,) -> Option<OpenVikingHealth> {- let health_url = self.openviking_health_url()?;+ let health_url = self.openviking_health_url(endpoint)?;let mut req_builder = client.get(health_url).timeout(Duration::from_secs(5));if let Some(auth) = auth {req_builder = self.apply_auth_headers(req_builder, auth);}- let response = req_builder.send().await.ok()?;+ let retry = req_builder.try_clone();+ let mut response = req_builder.send().await.ok()?;+ let is_gateway_challenge = response.status() == reqwest::StatusCode::UNAUTHORIZED+ && response+ .headers()+ .get("X-VikingBot-Gateway")+ .and_then(|value| value.to_str().ok())+ .is_some_and(|value| value.eq_ignore_ascii_case("true"));+ if is_gateway_challenge {+ let gateway_token = auth.and_then(|auth| auth.gateway_token.as_deref())?;+ response = retry?+ .header("X-Gateway-Token", gateway_token)+ .send()+ .await+ .ok()?;+ }if !response.status().is_success() {return None;}response.json::<OpenVikingHealth>().await.ok()}- async fn warn_openviking_chat_auth(+ async fn openviking_chat_auth_warning(&self,client: &Client,+ endpoint: &str,health: Option<&OpenVikingHealth>,auth: &ChatAuth,- ) {+ ) -> Option<ChatAuthWarning> {let Some(health) = health else {- return;+ return None;};if health_auth_mode(health) != "api_key" {- return;+ return None;}if auth@@ -239,47 +364,41 @@ impl ChatCommand {.trim().is_empty(){- eprintln!(- "Warning: OpenViking server is in api_key mode, but ov chat is not configured \-with a User API key. OpenViking-backed VikingBot memory and file tools may not work correctly. \-Configure api_key in ovcli.conf with a User/Admin API key, or pass --api-key."- );- return;+ return Some(ChatAuthWarning::MissingUserKey);}- let Some(authenticated_health) = self.fetch_openviking_health(client, Some(auth)).await+ let Some(authenticated_health) = self+ .fetch_openviking_health(client, endpoint, Some(auth))+ .awaitelse {- eprintln!(- "Warning: OpenViking server is in api_key mode, but ov chat could not validate \-the configured API key. OpenViking-backed VikingBot memory and file tools may not work correctly."- );- return;+ return Some(ChatAuthWarning::CannotValidateKey);};if health_has_user_identity(&authenticated_health) {- return;+ return None;}if health_role(&authenticated_health) == "root" {- eprintln!(- "Warning: ov chat is using a ROOT API key, but OpenViking api_key mode requires \-a User/Admin API key for VikingBot memory and file tools. Configure api_key in ovcli.conf with \-a User/Admin API key, or pass --api-key."- );+ Some(ChatAuthWarning::RootKey)} else {- eprintln!(- "Warning: ov chat could not validate the configured API key as an OpenViking \-User/Admin API key. OpenViking-backed VikingBot memory and file tools may not work correctly."- );+ Some(ChatAuthWarning::InvalidUserKey)}}/// Send a single message and get response- async fn send_message(&self, client: &Client, message: &str, auth: &ChatAuth) -> Result<()> {+ async fn send_message(+ &self,+ client: &Client,+ endpoint: &str,+ message: &str,+ auth: &ChatAuth,+ ) -> Result<()> {if self.stream {- self.send_message_stream(client, message, auth).await+ self.send_message_stream(client, endpoint, message, auth)+ .await} else {- self.send_message_non_stream(client, message, auth).await+ self.send_message_non_stream(client, endpoint, message, auth)+ .await}}@@ -287,10 +406,11 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not woasync fn send_message_non_stream(&self,client: &Client,+ endpoint: &str,message: &str,auth: &ChatAuth,) -> Result<()> {- let url = format!("{}/chat", self.endpoint);+ let url = format!("{}/chat", endpoint);let request = ChatRequest {message: message.to_string(),@@ -331,10 +451,11 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not woasync fn send_message_stream(&self,client: &Client,+ endpoint: &str,message: &str,auth: &ChatAuth,) -> Result<()> {- let url = format!("{}/chat/stream", self.endpoint);+ let url = format!("{}/chat/stream", endpoint);let request = ChatRequest {message: message.to_string(),@@ -395,7 +516,7 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not woresponse_id = Some(rid.to_string());}if let Some(err) = obj.get("error").and_then(|e| e.as_str()) {- eprintln!("\x1b[1;31mError: {}\x1b[0m", err);+ print_chat_error(Language::current(), err);}}}@@ -405,7 +526,13 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not wo}if let Some(response_id) = response_id {- eprintln!("\x1b[2mResponse ID: {}\x1b[0m", response_id);+ eprintln!(+ "{}",+ chat_detail_line(+ copy(Language::current(), "Response ID", "响应 ID"),+ muted_value(&response_id),+ )+ );}// Print final response with markdown if we have it@@ -418,15 +545,26 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not wo}/// Run interactive chat mode with rustyline- async fn run_interactive(&self, client: &Client, auth: &ChatAuth) -> Result<()> {- println!("Vikingbot Chat - Interactive Mode");- println!("Endpoint: {}", self.endpoint);- if let Some(session) = &self.session {- println!("Session: {}", session);- }- println!("Sender: {}", self.sender);- println!("Type 'exit', 'quit', or press Ctrl+C to exit");- println!("----------------------------------------\n");+ async fn run_interactive(+ &self,+ client: &Client,+ endpoint: &str,+ auth: &ChatAuth,+ auth_warning: Option<ChatAuthWarning>,+ openviking_info: &ChatOpenVikingInfo,+ language: Language,+ ) -> Result<()> {+ print!(+ "{}",+ render_chat_banner(+ endpoint,+ self.session.as_deref(),+ &self.sender,+ auth_warning,+ openviking_info,+ language,+ )+ );// Initialize rustyline editorlet mut rl = DefaultEditor::new()@@ -446,8 +584,8 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not woloop {// Read input with rustyline- let prompt = "\x1b[1;32mYou:\x1b[0m ";- match rl.readline(prompt) {+ let prompt = format!("{} ", theme::prompt(copy(language, "You:", "你:")).bold());+ match rl.readline(&prompt) {Ok(line) => {let input: &str = line.trim();@@ -462,33 +600,39 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not wo// Check for exitif input.eq_ignore_ascii_case("exit") || input.eq_ignore_ascii_case("quit") {- println!("\nGoodbye!");+ println!("\n{}", theme::muted(copy(language, "Goodbye.", "已退出。")));break;}// Send messagematch self- .send_interactive_message(client, input, &mut session_id, auth)+ .send_interactive_message(client, endpoint, input, &mut session_id, auth).await{Ok(_) => {}Err(e) => {- eprintln!("\x1b[1;31mError: {}\x1b[0m", e);+ print_chat_error(language, &e.to_string());}}}Err(ReadlineError::Interrupted) => {// Ctrl+C- println!("\nGoodbye!");+ println!("\n{}", theme::muted(copy(language, "Goodbye.", "已退出。")));break;}Err(ReadlineError::Eof) => {// Ctrl+D- println!("\nGoodbye!");+ println!("\n{}", theme::muted(copy(language, "Goodbye.", "已退出。")));break;}Err(e) => {- eprintln!("\x1b[1;31mError reading input: {}\x1b[0m", e);+ print_chat_error(+ language,+ &format!(+ "{}: {e}",+ copy(language, "Failed to read input", "读取输入失败")+ ),+ );break;}}@@ -506,15 +650,16 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not woasync fn send_interactive_message(&self,client: &Client,+ endpoint: &str,input: &str,session_id: &mut Option<String>,auth: &ChatAuth,) -> Result<()> {if self.stream {- self.send_interactive_message_stream(client, input, session_id, auth)+ self.send_interactive_message_stream(client, endpoint, input, session_id, auth).await} else {- self.send_interactive_message_non_stream(client, input, session_id, auth)+ self.send_interactive_message_non_stream(client, endpoint, input, session_id, auth).await}}@@ -523,11 +668,12 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not woasync fn send_interactive_message_non_stream(&self,client: &Client,+ endpoint: &str,input: &str,session_id: &mut Option<String>,auth: &ChatAuth,) -> Result<()> {- let url = format!("{}/chat", self.endpoint);+ let url = format!("{}/chat", endpoint);let request = ChatRequest {message: input.to_string(),@@ -575,12 +721,16 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not woasync fn send_interactive_message_stream(&self,client: &Client,+ endpoint: &str,input: &str,session_id: &mut Option<String>,auth: &ChatAuth,) -> Result<()> {- let url = format!("{}/chat/stream", self.endpoint);- let request_session_id = session_id.clone().or_else(|| self.session.clone());+ let url = format!("{}/chat/stream", endpoint);+ let request_session_id = session_id+ .clone()+ .or_else(|| self.session.clone())+ .or_else(|| Some(Uuid::new_v4().to_string()));let request = ChatRequest {message: input.to_string(),@@ -603,13 +753,19 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not woreturn Err(Error::api(format!("Request failed ({}): {}", status, text)));}+ let response_session_id = response+ .headers()+ .get("X-VikingBot-Session-ID")+ .and_then(|value| value.to_str().ok())+ .and_then(non_empty_str)+ .map(ToString::to_string);let mut response = response;let mut buffer = String::new();let mut final_message = String::new();let mut response_id: Option<String> = None;if session_id.is_none() {- *session_id = request_session_id;+ *session_id = response_session_id.or(request_session_id);}while let Some(chunk) = response@@ -644,7 +800,7 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not woresponse_id = Some(rid.to_string());}if let Some(err) = obj.get("error").and_then(|e| e.as_str()) {- eprintln!("\x1b[1;31mError: {}\x1b[0m", err);+ print_chat_error(Language::current(), err);}}}@@ -654,7 +810,13 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not wo}if let Some(response_id) = response_id {- eprintln!("\x1b[2mResponse ID: {}\x1b[0m", response_id);+ eprintln!(+ "{}",+ chat_detail_line(+ copy(Language::current(), "Response ID", "响应 ID"),+ muted_value(&response_id),+ )+ );}// Print final response with markdown@@ -676,15 +838,12 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not womatch event.event.as_str() {"reasoning" => {if let Some(content) = event.data.as_str() {- println!(- " \x1b[2mThink: {}...\x1b[0m",- utils::truncate_utf8(content, 200)- );+ print_reasoning(content, Language::current());}}"tool_call" => {if let Some(content) = event.data.as_str() {- Self::print_tool_call(content);+ print_tool_call(content, Language::current());}}"tool_result" => {@@ -694,7 +853,7 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not wo} else {content.to_string()};- Self::print_tool_result(&truncated);+ print_tool_result(&truncated, Language::current());}}"iteration" => {@@ -707,31 +866,13 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not wo}}- /// Parse and print a tool_call with formatted styling- fn print_tool_call(content: &str) {- if let Some(paren_idx) = content.find('(') {- let tool_name = &content[..paren_idx];- let args = &content[paren_idx..];- print!(" \x1b[2m├─ Calling: \x1b[0m");- print!("\x1b[1m{}\x1b[0m", tool_name);- println!("\x1b[2m{}\x1b[0m", args);- } else {- // Fallback if format doesn't match- println!(" \x1b[2m├─ Calling: {}\x1b[0m", content);- }- }-- /// Print a tool_result with formatted styling- fn print_tool_result(content: &str) {- println!(" \x1b[2m└─ Result: {}\x1b[0m", content);- }-/// Print thinking/events (for non-streaming mode)fn print_events(&self, events: &Option<Vec<serde_json::Value>>) {if self.no_format {return;}+ let language = Language::current();if let Some(events) = events {for event in events {if let (Some(etype), Some(data)) = (@@ -741,14 +882,11 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not womatch etype {"reasoning" => {let content = data.as_str().unwrap_or("");- println!(- " \x1b[2mThink: {}...\x1b[0m",- utils::truncate_utf8(content, 200)- );+ print_reasoning(content, language);}"tool_call" => {let content = data.as_str().unwrap_or("");- Self::print_tool_call(content);+ print_tool_call(content, language);}"tool_result" => {let content = data.as_str().unwrap_or("");@@ -757,7 +895,7 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not wo} else {content.to_string()};- Self::print_tool_result(&truncated);+ print_tool_result(&truncated, language);}_ => {}}@@ -773,7 +911,10 @@ User/Admin API key. OpenViking-backed VikingBot memory and file tools may not woreturn;}- println!("\x1b[1;31mBot:\x1b[0m");+ println!(+ "{}",+ theme::heading(copy(Language::current(), "VikingBot", "VikingBot")).bold()+ );// Try to render markdown, fall back to plain textrender_markdown(message);@@ -792,6 +933,232 @@ impl ChatCommand {}}+fn render_chat_banner(+ endpoint: &str,+ session: Option<&str>,+ sender: &str,+ warning: Option<ChatAuthWarning>,+ openviking_info: &ChatOpenVikingInfo,+ language: Language,+) -> String {+ let mut lines = vec![chat_title(language)];++ if let Some(warning) = warning {+ lines.push(String::new());+ lines.push(chat_section_title(copy(language, "Warning", "警告")));+ lines.extend(chat_warning_lines(warning, language));+ }++ lines.push(String::new());+ lines.push(chat_section_title(copy(language, "Connection", "连接")));+ lines.push(chat_detail_line(+ copy(language, "Endpoint", "端点"),+ value_text(endpoint),+ ));+ lines.push(chat_detail_line(+ "OpenViking",+ enabled_value(openviking_info.enabled, language),+ ));+ lines.push(chat_detail_line(+ copy(language, "OV Server", "OV Server"),+ match openviking_info.server_url.as_deref() {+ Some(server_url) => value_text(server_url),+ None => muted_value(copy(language, "not configured", "未配置")),+ },+ ));+ lines.push(chat_detail_line(+ copy(language, "Session", "会话"),+ match session {+ Some(session) => value_text(session),+ None => muted_value(copy(language, "new session", "新会话")),+ },+ ));+ lines.push(chat_detail_line(+ copy(language, "Sender", "发送者"),+ plain_value(sender),+ ));++ lines.push(String::new());+ lines.push(chat_section_title(copy(language, "Controls", "操作")));+ lines.push(chat_action_line(+ "exit / quit",+ copy(language, "End the chat", "退出对话"),+ ));+ lines.push(chat_action_line(+ "Ctrl+C",+ copy(language, "End the chat", "退出对话"),+ ));++ format!("{}\n", lines.join("\n"))+}++fn render_chat_warning(warning: ChatAuthWarning, language: Language) -> String {+ let mut lines = vec![chat_section_title(copy(language, "Warning", "警告"))];+ lines.extend(chat_warning_lines(warning, language));+ format!("{}\n", lines.join("\n"))+}++fn chat_warning_lines(warning: ChatAuthWarning, language: Language) -> Vec<String> {+ let (issue, fix) = chat_warning_copy(warning, language);+ vec![+ chat_detail_line(copy(language, "Issue", "问题"), warning_value(issue)),+ chat_detail_line(copy(language, "Fix", "处理"), muted_value(fix)),+ ]+}++fn chat_warning_copy(warning: ChatAuthWarning, language: Language) -> (&'static str, &'static str) {+ match warning {+ ChatAuthWarning::MissingUserKey => (+ copy(+ language,+ "OpenViking server is in api_key mode and requires a User/Admin API key",+ "OpenViking server 是 api_key 模式,需使用 User/Admin API Key 访问",+ ),+ copy(+ language,+ "Set api_key in ovcli.conf, or pass --api-key.",+ "在 ovcli.conf 配置 api_key,或传 --api-key。",+ ),+ ),+ ChatAuthWarning::CannotValidateKey => (+ copy(+ language,+ "Configured API key could not be validated",+ "当前 API Key 无法验证",+ ),+ copy(+ language,+ "Memory and file tools may be unavailable; check the key.",+ "memory/file tools 可能不可用,请检查 API Key。",+ ),+ ),+ ChatAuthWarning::RootKey => (+ copy(+ language,+ "OpenViking server is in api_key mode and requires a User/Admin API key. The current request uses root_api_key, so VikingBot cannot use OpenViking features correctly.",+ "OpenViking server 是 api_key 模式,需使用 User/Admin API Key 访问。当前请求实际使用的是 root_api_key,bot 将无法正常使用 OpenViking 功能。",+ ),+ copy(+ language,+ "Set api_key in ovcli.conf to a User/Admin API key.",+ "请在 ovcli.conf 中配置 api_key 为 User/Admin API Key。",+ ),+ ),+ ChatAuthWarning::InvalidUserKey => (+ copy(+ language,+ "Configured key is not a usable User/Admin API key",+ "当前 API Key 不是可用的 User/Admin API Key",+ ),+ copy(+ language,+ "Update api_key in ovcli.conf, or pass --api-key.",+ "更新 ovcli.conf 的 api_key,或传 --api-key。",+ ),+ ),+ }+}++fn chat_title(language: Language) -> String {+ theme::brand_title(copy(language, "VIKINGBOT CHAT", "VIKINGBOT 对话"))+ .bold()+ .to_string()+}++fn chat_section_title(title: &str) -> String {+ theme::heading(title).bold().to_string()+}++fn chat_detail_line(label: &str, value: String) -> String {+ let label = theme::muted(pad_to_display_width(label, CHAT_LABEL_WIDTH));+ format!(" {label}{value}")+}++fn chat_action_line(command: &str, description: &str) -> String {+ let command = theme::command(pad_to_display_width(command, CHAT_ACTION_WIDTH)).bold();+ format!(" {command}{}", theme::muted(description))+}++fn value_text(value: &str) -> String {+ theme::value(value).to_string()+}++fn plain_value(value: &str) -> String {+ theme::body(value).to_string()+}++fn muted_value(value: &str) -> String {+ theme::muted(value).to_string()+}++fn warning_value(value: &str) -> String {+ theme::warning(value).bold().to_string()+}++fn enabled_value(enabled: bool, language: Language) -> String {+ if enabled {+ theme::success(copy(language, "Yes", "是"))+ .bold()+ .to_string()+ } else {+ theme::muted(copy(language, "No", "否")).to_string()+ }+}++fn pad_to_display_width(value: &str, width: usize) -> String {+ format!(+ "{}{}",+ value,+ " ".repeat(width.saturating_sub(UnicodeWidthStr::width(value)))+ )+}++fn print_chat_error(language: Language, message: &str) {+ eprintln!(+ "{} {}",+ theme::error(copy(language, "Error:", "错误:")).bold(),+ theme::body(message)+ );+}++fn print_reasoning(content: &str, language: Language) {+ println!(+ " {} {}",+ theme::muted(format!("{}:", copy(language, "Think", "思考"))),+ theme::muted(format!("{}...", utils::truncate_utf8(content, 200)))+ );+}++fn print_tool_call(content: &str, language: Language) {+ if let Some(paren_idx) = content.find('(') {+ let tool_name = &content[..paren_idx];+ let args = &content[paren_idx..];+ println!(+ " {} {} {}{}",+ theme::muted("├─"),+ theme::muted(format!("{}:", copy(language, "Calling", "调用"))),+ theme::command(tool_name).bold(),+ theme::muted(args)+ );+ } else {+ println!(+ " {} {} {}",+ theme::muted("├─"),+ theme::muted(format!("{}:", copy(language, "Calling", "调用"))),+ theme::body(content)+ );+ }+}++fn print_tool_result(content: &str, language: Language) {+ println!(+ " {} {} {}",+ theme::muted("└─"),+ theme::muted(format!("{}:", copy(language, "Result", "结果"))),+ theme::body(content)+ );+}+/// Render markdown to terminal using termimadfn render_markdown(text: &str) {let skin = MadSkin::default();@@ -813,6 +1180,64 @@ fn health_has_user_identity(health: &OpenVikingHealth) -> bool {matches!(role, "user" | "admin") && !account_id.is_empty() && !user_id.is_empty()}+fn openviking_info_from_health(+ endpoint: &str,+ health: Option<&OpenVikingHealth>,+) -> ChatOpenVikingInfo {+ let server_url_from_endpoint = openviking_server_url_from_endpoint(endpoint);+ let Some(health) = health else {+ return ChatOpenVikingInfo {+ enabled: false,+ server_url: None,+ };+ };++ if health_is_vikingbot_gateway(health) {+ let upstream_url = health+ .upstream_url+ .as_deref()+ .and_then(non_empty_str)+ .map(ToString::to_string);+ let upstream_configured = health+ .upstream_configured+ .unwrap_or_else(|| upstream_url.is_some());+ return ChatOpenVikingInfo {+ enabled: upstream_configured,+ server_url: upstream_configured.then_some(upstream_url).flatten(),+ };+ }++ ChatOpenVikingInfo {+ enabled: true,+ server_url: server_url_from_endpoint,+ }+}++fn health_is_vikingbot_gateway(health: &OpenVikingHealth) -> bool {+ health+ .gateway+ .as_deref()+ .map(|gateway| gateway.trim().eq_ignore_ascii_case("vikingbot"))+ .unwrap_or(false)+}++fn openviking_server_url_from_endpoint(endpoint: &str) -> Option<String> {+ endpoint+ .trim_end_matches('/')+ .strip_suffix("/bot/v1")+ .and_then(non_empty_str)+ .map(ToString::to_string)+}++fn chat_endpoint_from_base_url(url: &str) -> String {+ format!("{}/bot/v1", url.trim_end_matches('/'))+}++fn non_empty_str(value: &str) -> Option<&str> {+ let value = value.trim();+ if value.is_empty() { None } else { Some(value) }+}+fn non_empty_string(value: Option<String>) -> Option<String> {value.and_then(|text| {if text.trim().is_empty() {@@ -829,10 +1254,11 @@ mod tests {fn command_with_api_key(api_key: Option<&str>) -> ChatCommand {ChatCommand {- endpoint: DEFAULT_ENDPOINT.to_string(),+ endpoint: None,api_key: api_key.map(ToString::to_string),account: None,user: None,+ actor_peer_id: None,session: None,sender: "user".to_string(),message: None,@@ -850,7 +1276,7 @@ mod tests {..Config::default()};- let auth = command.resolve_auth_from_config(config, None);+ let auth = command.resolve_auth_from_config(config, None, false);assert_eq!(auth.api_key.as_deref(), Some("user-key"));}@@ -863,7 +1289,7 @@ mod tests {..Config::default()};- let auth = command.resolve_auth_from_config(config, None);+ let auth = command.resolve_auth_from_config(config, None, false);assert_eq!(auth.api_key.as_deref(), Some("override-key"));}@@ -879,7 +1305,7 @@ mod tests {..Config::default()};- let auth = command.resolve_auth_from_config(config, Some("trusted"));+ let auth = command.resolve_auth_from_config(config, Some("trusted"), false);assert_eq!(auth.api_key.as_deref(), Some("root-key"));assert_eq!(auth.account.as_deref(), Some("acme"));@@ -897,7 +1323,7 @@ mod tests {..Config::default()};- let auth = command.resolve_auth_from_config(config, Some("trusted"));+ let auth = command.resolve_auth_from_config(config, Some("trusted"), false);assert_eq!(auth.api_key.as_deref(), Some("override-root-key"));assert_eq!(auth.account.as_deref(), Some("acme"));@@ -915,7 +1341,7 @@ mod tests {..Config::default()};- let auth = command.resolve_auth_from_config(config, Some("api_key"));+ let auth = command.resolve_auth_from_config(config, Some("api_key"), false);assert_eq!(auth.api_key.as_deref(), Some("user-key"));assert!(auth.account.is_none());@@ -927,17 +1353,175 @@ mod tests {let command = command_with_api_key(None);assert_eq!(- command.openviking_health_url().as_deref(),+ command+ .openviking_health_url("http://localhost:1933/bot/v1")+ .as_deref(),Some("http://localhost:1933/health"));}#[test]fn openviking_health_url_ignores_non_bot_proxy_endpoint() {+ let command = command_with_api_key(None);++ assert_eq!(+ command.openviking_health_url("http://localhost:18790"),+ None+ );+ }++ #[test]+ fn chat_endpoint_is_derived_from_config_url_when_endpoint_is_not_explicit() {+ let command = command_with_api_key(None);+ let config = Config {+ url: "http://gateway.example:18790/".to_string(),+ ..Config::default()+ };++ assert_eq!(+ command.resolve_endpoint_from_config(&config),+ "http://gateway.example:18790/bot/v1"+ );+ }++ #[test]+ fn chat_endpoint_prefers_explicit_endpoint() {let mut command = command_with_api_key(None);- command.endpoint = "http://localhost:18790".to_string();+ command.endpoint = Some("http://custom.example/bot/v1/".to_string());++ assert_eq!(+ command.resolve_endpoint_from_config(&Config::default()),+ "http://custom.example/bot/v1"+ );+ }++ #[test]+ fn auth_keeps_gateway_token_separate_from_general_headers() {+ let command = command_with_api_key(None);+ let config = Config {+ api_key: Some("user-key".to_string()),+ actor_peer_id: Some("peer-a".to_string()),+ gateway_token: Some("gateway-secret".to_string()),+ ..Config::default()+ };++ let auth = command.resolve_auth_from_config(config, Some("api_key"), false);++ assert_eq!(auth.actor_peer_id.as_deref(), Some("peer-a"));+ assert_eq!(auth.gateway_token.as_deref(), Some("gateway-secret"));+ assert!(!auth.gateway_token_required);+ assert!(!auth.extra_headers.contains_key("X-Gateway-Token"));+ }++ #[test]+ fn chat_banner_renders_aligned_english_summary() {+ let openviking_info = ChatOpenVikingInfo {+ enabled: true,+ server_url: Some("http://localhost:18791".to_string()),+ };+ let rendered = render_chat_banner(+ "http://localhost:18791/bot/v1",+ Some("session-1"),+ "user",+ Some(ChatAuthWarning::RootKey),+ &openviking_info,+ Language::En,+ );+ let plain = strip_ansi(&rendered);++ assert!(plain.contains("VIKINGBOT CHAT"));+ assert!(plain.contains("Warning"));+ assert!(plain.contains("Issue OpenViking server is in api_key mode"));+ assert!(plain.contains("The current request uses root_api_key"));+ assert!(plain.contains("Fix Set api_key in ovcli.conf to a User/Admin API key."));+ assert!(plain.contains("Connection"));+ assert!(plain.contains("Endpoint http://localhost:18791/bot/v1"));+ assert!(plain.contains("OpenViking"));+ assert!(plain.contains("Yes"));+ assert!(plain.contains("OV Server http://localhost:18791"));+ assert!(plain.contains("Session session-1"));+ assert!(plain.contains("Controls"));+ assert!(plain.contains("exit / quit End the chat"));+ }++ #[test]+ fn chat_banner_renders_chinese_copy() {+ let openviking_info = ChatOpenVikingInfo {+ enabled: false,+ server_url: None,+ };+ let rendered = render_chat_banner(+ "http://localhost:18791/bot/v1",+ None,+ "user",+ Some(ChatAuthWarning::MissingUserKey),+ &openviking_info,+ Language::ZhCn,+ );+ let plain = strip_ansi(&rendered);++ assert!(plain.contains("VIKINGBOT 对话"));+ assert!(plain.contains("警告"));+ assert!(plain.contains("OpenViking server 是 api_key 模式"));+ assert!(plain.contains("连接"));+ assert!(plain.contains("端点"));+ assert!(plain.contains("OpenViking"));+ assert!(plain.contains("否"));+ assert!(plain.contains("OV Server 未配置"));+ assert!(plain.contains("新会话"));+ assert!(plain.contains("操作"));+ assert!(plain.contains("退出对话"));+ }- assert_eq!(command.openviking_health_url(), None);+ #[test]+ fn root_key_warning_tells_user_to_edit_ovcli_api_key_in_chinese() {+ let rendered = render_chat_warning(ChatAuthWarning::RootKey, Language::ZhCn);+ let plain = strip_ansi(&rendered);++ assert!(plain.contains("问题"));+ assert!(plain.contains("OpenViking server 是 api_key 模式"));+ assert!(plain.contains("当前请求实际使用的是 root_api_key"));+ assert!(plain.contains("bot 将无法正常使用 OpenViking 功能"));+ assert!(plain.contains("处理"));+ assert!(plain.contains("请在 ovcli.conf 中配置 api_key 为 User/Admin API Key。"));+ }++ #[test]+ fn openviking_info_uses_gateway_upstream() {+ let health = OpenVikingHealth {+ auth_mode: Some("api_key".to_string()),+ role: None,+ account_id: None,+ user_id: None,+ gateway: Some("vikingbot".to_string()),+ upstream_configured: Some(true),+ upstream_url: Some("http://ov.local:1935".to_string()),+ gateway_token_required: false,+ };++ let info = openviking_info_from_health("http://gateway.local:18791/bot/v1", Some(&health));++ assert!(info.enabled);+ assert_eq!(info.server_url.as_deref(), Some("http://ov.local:1935"));+ }++ #[test]+ fn openviking_info_marks_standalone_gateway_disabled() {+ let health = OpenVikingHealth {+ auth_mode: None,+ role: None,+ account_id: None,+ user_id: None,+ gateway: Some("vikingbot".to_string()),+ upstream_configured: Some(false),+ upstream_url: None,+ gateway_token_required: false,+ };++ let info = openviking_info_from_health("http://gateway.local:18791/bot/v1", Some(&health));++ assert!(!info.enabled);+ assert!(info.server_url.is_none());}#[test]@@ -947,24 +1531,28 @@ mod tests {role: Some("user".to_string()),account_id: Some("default".to_string()),user_id: Some("alice".to_string()),+ ..OpenVikingHealth::default()};let admin_health = OpenVikingHealth {auth_mode: Some("api_key".to_string()),role: Some("admin".to_string()),account_id: Some("default".to_string()),user_id: Some("alice".to_string()),+ ..OpenVikingHealth::default()};let root_health = OpenVikingHealth {auth_mode: Some("api_key".to_string()),role: Some("root".to_string()),account_id: Some("default".to_string()),user_id: Some("root".to_string()),+ ..OpenVikingHealth::default()};let missing_identity = OpenVikingHealth {auth_mode: Some("api_key".to_string()),role: Some("user".to_string()),account_id: None,user_id: Some("alice".to_string()),+ ..OpenVikingHealth::default()};assert!(health_has_user_identity(&user_health));@@ -972,4 +1560,24 @@ mod tests {assert!(!health_has_user_identity(&root_health));assert!(!health_has_user_identity(&missing_identity));}++ fn strip_ansi(input: &str) -> String {+ let mut output = String::with_capacity(input.len());+ let mut chars = input.chars().peekable();++ while let Some(ch) = chars.next() {+ if ch == '\u{1b}' && chars.peek() == Some(&'[') {+ chars.next();+ for next in chars.by_ref() {+ if next.is_ascii_alphabetic() {+ break;+ }+ }+ continue;+ }+ output.push(ch);+ }++ output+ }}diff --git a/crates/ov_cli/src/commands/mod.rs b/crates/ov_cli/src/commands/mod.rsindex fa7866f93..5fb3e488c 100644--- a/crates/ov_cli/src/commands/mod.rs+++ b/crates/ov_cli/src/commands/mod.rs@@ -12,7 +12,7 @@ pub mod resources;pub mod search;pub mod session;pub mod skills;-pub mod system;pub mod snapshot;+pub mod system;pub mod task;pub mod watch;diff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rsindex e57fd07c0..aa720dfaa 100644--- a/crates/ov_cli/src/commands/search.rs+++ b/crates/ov_cli/src/commands/search.rs@@ -85,7 +85,11 @@ impl SearchRenderContext {}}-pub(super) fn output_skills_list_results(result: &Value, output_format: OutputFormat, compact: bool) {+pub(super) fn output_skills_list_results(+ result: &Value,+ output_format: OutputFormat,+ compact: bool,+) {let context = SearchRenderContext::skills_list();if let Some(rendered) =render_search_output_for_table_with_context(result, output_format, Some(context))@@ -432,9 +436,7 @@ fn render_search_result_card(}}- if split_name_and_description- && render_skill_name_and_description(object, text_width, lines)- {+ if split_name_and_description && render_skill_name_and_description(object, text_width, lines) {return;}@@ -488,10 +490,7 @@ fn render_skill_name_and_description(let label = theme::heading("description:").bold().to_string();let wrapped = wrap_display_text(description, text_width, SEARCH_MAX_ABSTRACT_LINES);if let Some((first, rest)) = wrapped.split_first() {- lines.push(format!(- "{SEARCH_INDENT}{label} {}",- theme::body(first)- ));+ lines.push(format!("{SEARCH_INDENT}{label} {}", theme::body(first)));for line in rest {lines.push(format!("{SEARCH_INDENT}{}", theme::body(line)));}diff --git a/crates/ov_cli/src/commands/snapshot.rs b/crates/ov_cli/src/commands/snapshot.rsindex fbb55da37..cc60d9d0a 100644--- a/crates/ov_cli/src/commands/snapshot.rs+++ b/crates/ov_cli/src/commands/snapshot.rs@@ -1,12 +1,12 @@use std::io::Write;use std::path::PathBuf;-use serde_json::{json, Value};+use serde_json::{Value, json};+use crate::SnapshotCmd;use crate::client::{HttpClient, SnapshotCommitReq, SnapshotRestoreReq, SnapshotShowResult};use crate::error::Result;use crate::output::{OutputFormat, output_success};-use crate::SnapshotCmd;pub async fn dispatch(client: &HttpClient,@@ -89,10 +89,7 @@ pub async fn dispatch(/// Resolve `.ovgitignore` content: `--file` takes precedence over `--content`;/// if neither is given, the content is left empty (clears the rules).-fn resolve_ignore_content(- content: Option<&str>,- file: Option<&std::path::Path>,-) -> Result<String> {+fn resolve_ignore_content(content: Option<&str>, file: Option<&std::path::Path>) -> Result<String> {if let Some(path) = file {use std::io::Read;let mut buf = String::new();@@ -199,7 +196,12 @@ fn handle_show(Some(path) => {let mut f = std::fs::File::create(&path)?;f.write_all(&bytes)?;- eprintln!("Wrote {} bytes from {} to {}", size, &oid[..12.min(oid.len())], path.display());+ eprintln!(+ "Wrote {} bytes from {} to {}",+ size,+ &oid[..12.min(oid.len())],+ path.display()+ );}None => {let mut out = std::io::stdout().lock();diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rsindex 48c241ace..6b6b04425 100644--- a/crates/ov_cli/src/config.rs+++ b/crates/ov_cli/src/config.rs@@ -1,4 +1,5 @@use serde::{Deserialize, Serialize};+use std::collections::HashMap;use std::path::{Path, PathBuf};use crate::error::{Error, Result};@@ -6,6 +7,7 @@ use crate::error::{Error, Result};const OPENVIKING_CLI_CONFIG_ENV: &str = "OPENVIKING_CLI_CONFIG_FILE";pub const DEFAULT_CUSTOM_PORT: &str = "1933";pub const DEFAULT_CUSTOM_URL: &str = "http://127.0.0.1:1933";+pub const GATEWAY_TOKEN_HEADER: &str = "X-Gateway-Token";#[derive(Debug, Clone, Serialize, Deserialize)]pub struct UploadConfig {@@ -41,9 +43,9 @@ pub struct Config {pub api_key: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub root_api_key: Option<String>,- #[serde(skip_serializing_if = "Option::is_none", alias = "account_id")]+ #[serde(skip_serializing_if = "Option::is_none")]pub account: Option<String>,- #[serde(skip_serializing_if = "Option::is_none", alias = "user_id")]+ #[serde(skip_serializing_if = "Option::is_none")]pub user: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub actor_peer_id: Option<String>,@@ -83,7 +85,9 @@ pub struct Config {alias = "extra_header",skip_serializing_if = "Option::is_none")]- pub extra_headers: Option<std::collections::HashMap<String, String>>,+ pub extra_headers: Option<HashMap<String, String>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub gateway_token: Option<String>,}#[derive(Debug, Clone, PartialEq, Eq)]@@ -163,6 +167,7 @@ impl Default for Config {profile: false,upload: UploadConfig::default(),extra_headers: None,+ gateway_token: None,}}}@@ -266,6 +271,34 @@ impl Config {self.actor_peer_id.clone().or_else(|| self.agent_id.clone())}+ pub(crate) fn effective_gateway_token(&self) -> Option<String> {+ self.gateway_token+ .as_deref()+ .map(str::trim)+ .filter(|token| !token.is_empty())+ .map(ToString::to_string)+ .or_else(|| {+ self.extra_headers.as_ref().and_then(|headers| {+ headers+ .iter()+ .find(|(key, _)| key.eq_ignore_ascii_case(GATEWAY_TOKEN_HEADER))+ .map(|(_, value)| value.trim())+ .filter(|value| !value.is_empty())+ .map(ToString::to_string)+ })+ })+ }++ pub(crate) fn effective_extra_headers(&self) -> Option<HashMap<String, String>> {+ let mut headers = self.extra_headers.clone().unwrap_or_default();+ headers.retain(|key, _| !key.eq_ignore_ascii_case(GATEWAY_TOKEN_HEADER));+ if headers.is_empty() {+ None+ } else {+ Some(headers)+ }+ }+fn validate_identity_mode(&self) -> Result<()> {if self.actor_peer_id.is_some() && self.agent_id.is_some() {return Err(Error::Config(@@ -285,21 +318,17 @@ impl Config {let api_key = if sudo {self.root_api_key.clone()} else {- api_key_override.or_else(|| self.api_key.clone())+ api_key_override+ .or_else(|| self.api_key.clone())+ .or_else(|| self.root_api_key.clone())};let account = account_override.or_else(|| self.account.clone());let user = user_override.or_else(|| self.user.clone());- let send_identity = if sudo {- true- } else {- api_key.is_none() || api_key.as_deref() == self.root_api_key.as_deref()- };-EffectiveAuth {api_key,- account: send_identity.then_some(account).flatten(),- user: send_identity.then_some(user).flatten(),+ account,+ user,}}}@@ -376,7 +405,8 @@ mod tests {"api_key": "test-key","account": "acme","user": "alice",- "actor_peer_id": "peer-a"+ "actor_peer_id": "peer-a",+ "gateway_token": "gateway-secret"}"#,).expect("config should deserialize");@@ -384,6 +414,7 @@ mod tests {assert_eq!(config.account.as_deref(), Some("acme"));assert_eq!(config.user.as_deref(), Some("alice"));assert_eq!(config.actor_peer_id.as_deref(), Some("peer-a"));+ assert_eq!(config.gateway_token.as_deref(), Some("gateway-secret"));assert!(config.upload.ignore_dirs.is_none());assert!(config.upload.include.is_none());assert!(config.upload.exclude.is_none());@@ -443,7 +474,7 @@ mod tests {}#[test]- fn effective_auth_omits_stale_identity_for_regular_user_key() {+ fn effective_auth_forwards_explicit_identity_with_regular_user_key() {let config = Config {api_key: Some("user-key".to_string()),root_api_key: Some("root-key".to_string()),@@ -455,8 +486,8 @@ mod tests {let auth = config.effective_auth(false);assert_eq!(auth.api_key.as_deref(), Some("user-key"));- assert!(auth.account.is_none());- assert!(auth.user.is_none());+ assert_eq!(auth.account.as_deref(), Some("stale-account"));+ assert_eq!(auth.user.as_deref(), Some("stale-user"));}#[test]@@ -491,6 +522,54 @@ mod tests {assert_eq!(auth.user.as_deref(), Some("default"));}+ #[test]+ fn effective_auth_sends_explicit_identity_independently_of_gateway_token() {+ let config = Config {+ api_key: Some("trusted-root-key".to_string()),+ account: Some("acme".to_string()),+ user: Some("alice".to_string()),+ gateway_token: Some("gateway-secret".to_string()),+ ..Config::default()+ };++ let auth = config.effective_auth(false);++ assert_eq!(auth.api_key.as_deref(), Some("trusted-root-key"));+ assert_eq!(auth.account.as_deref(), Some("acme"));+ assert_eq!(auth.user.as_deref(), Some("alice"));+ }++ #[test]+ fn effective_auth_uses_root_key_for_trusted_identity_without_gateway_token() {+ let config = Config {+ root_api_key: Some("trusted-root-key".to_string()),+ account: Some("acme".to_string()),+ user: Some("alice".to_string()),+ ..Config::default()+ };++ let auth = config.effective_auth(false);++ assert_eq!(auth.api_key.as_deref(), Some("trusted-root-key"));+ assert_eq!(auth.account.as_deref(), Some("acme"));+ assert_eq!(auth.user.as_deref(), Some("alice"));+ }++ #[test]+ fn effective_auth_does_not_invent_missing_gateway_identity() {+ let config = Config {+ api_key: Some("trusted-root-key".to_string()),+ gateway_token: Some("gateway-secret".to_string()),+ ..Config::default()+ };++ let auth = config.effective_auth(false);++ assert_eq!(auth.api_key.as_deref(), Some("trusted-root-key"));+ assert_eq!(auth.account, None);+ assert_eq!(auth.user, None);+ }+#[test]fn effective_auth_uses_root_key_and_identity_for_sudo() {let config = Config {@@ -508,21 +587,6 @@ mod tests {assert_eq!(auth.user.as_deref(), Some("alice"));}- #[test]- fn config_deserializes_account_id_and_user_id_aliases() {- let config: Config = serde_json::from_str(- r#"{- "url": "http://127.0.0.1:1933",- "account_id": "acme",- "user_id": "alice"- }"#,- )- .expect("config should deserialize aliases");-- assert_eq!(config.account.as_deref(), Some("acme"));- assert_eq!(config.user.as_deref(), Some("alice"));- }-#[test]fn config_deserializes_upload_fields() {let config: Config = serde_json::from_str(@@ -668,4 +732,34 @@ mod tests {Some(&"Bearer token".to_string()));}++ #[test]+ fn gateway_token_is_kept_out_of_general_headers() {+ let config = Config {+ gateway_token: Some("gateway-secret".to_string()),+ ..Config::default()+ };++ assert_eq!(+ config.effective_gateway_token().as_deref(),+ Some("gateway-secret")+ );+ assert!(config.effective_extra_headers().is_none());+ }++ #[test]+ fn legacy_gateway_header_is_extracted_from_general_headers() {+ let mut extra_headers = std::collections::HashMap::new();+ extra_headers.insert("x-gateway-token".to_string(), "manual-secret".to_string());+ let config = Config {+ extra_headers: Some(extra_headers),+ ..Config::default()+ };++ assert_eq!(+ config.effective_gateway_token().as_deref(),+ Some("manual-secret")+ );+ assert!(config.effective_extra_headers().is_none());+ }}diff --git a/crates/ov_cli/src/config_agent.rs b/crates/ov_cli/src/config_agent.rsindex 97ebd52fb..4e83d1e7e 100644--- a/crates/ov_cli/src/config_agent.rs+++ b/crates/ov_cli/src/config_agent.rs@@ -1024,7 +1024,7 @@ mod tests {.expect("test server should bind");let addr = listener.local_addr().expect("test server should have addr");tokio::spawn(async move {- for _ in 0..6 {+ for _ in 0..12 {let Ok((mut stream, _)) = listener.accept().await else {return;};diff --git a/crates/ov_cli/src/config_wizard/store.rs b/crates/ov_cli/src/config_wizard/store.rsindex 01c2340ca..cbadbbf95 100644--- a/crates/ov_cli/src/config_wizard/store.rs+++ b/crates/ov_cli/src/config_wizard/store.rs@@ -581,8 +581,9 @@ pub(crate) async fn validate_candidate_config_with_role(config.actor_peer_id.clone(),timeout,config.profile,- config.extra_headers.clone(),- );+ config.effective_extra_headers(),+ )+ .with_gateway_token(config.effective_gateway_token());let value: Value = client.get("/health", &[]).await?;if value@@ -668,10 +669,15 @@ pub(crate) fn validation_error_copy(kind: ConfigKind, error: &Error) -> String {status: Some(401 | 403),..} => "API key was rejected. Check your API key.".to_string(),- Error::Api { status: Some(404), .. } => {+ Error::Api {+ status: Some(404), ..+ } => {"Server responded but the API endpoint was not found. Check the server URL.".to_string()}- Error::Api { status: Some(status), .. } => {+ Error::Api {+ status: Some(status),+ ..+ } => {format!("Server returned HTTP {status}. Check the server configuration.")}Error::Api { .. } => {@@ -698,23 +704,22 @@ pub(crate) fn validation_error_copy_zh(kind: ConfigKind, error: &Error) -> StrinConfigKind::OpenVikingService => {"无法连接 OpenViking 服务。请检查网络连接。".to_string()}- ConfigKind::Custom => {- "无法连接服务器。请检查 URL 和网络连接。".to_string()- }+ ConfigKind::Custom => "无法连接服务器。请检查 URL 和网络连接。".to_string(),},Error::Api {status: Some(401 | 403),..} => "API Key 被拒绝。请检查 API Key。".to_string(),- Error::Api { status: Some(404), .. } => {- "服务器响应了,但 API 端点未找到。请检查服务器 URL。".to_string()- }- Error::Api { status: Some(status), .. } => {+ Error::Api {+ status: Some(404), ..+ } => "服务器响应了,但 API 端点未找到。请检查服务器 URL。".to_string(),+ Error::Api {+ status: Some(status),+ ..+ } => {format!("服务器返回 HTTP {status}。请检查服务器配置。")}- Error::Api { .. } => {- "服务器验证时返回错误。请检查服务器日志。".to_string()- }+ Error::Api { .. } => "服务器验证时返回错误。请检查服务器日志。".to_string(),Error::Config(msg) => msg.clone(),_ => match kind {ConfigKind::OpenVikingService => "验证失败。请检查 API Key 后重试。".to_string(),diff --git a/crates/ov_cli/src/config_wizard/wizard.rs b/crates/ov_cli/src/config_wizard/wizard.rsindex 93499c7bf..0259f2094 100644--- a/crates/ov_cli/src/config_wizard/wizard.rs+++ b/crates/ov_cli/src/config_wizard/wizard.rs@@ -28,8 +28,7 @@ use super::store::{ApiKeyRole, ConfigDraft, ConfigEntry, ConfigKind, ConfigStore, IdentityField,OPENVIKING_SERVICE_URL, build_config, custom_allows_empty_api_key, normalize_custom_url,validate_candidate_config, validate_candidate_config_with_role, validate_config,- validate_config_name, validate_identity_value, validation_error_copy,- validation_error_copy_zh,+ validate_config_name, validate_identity_value, validation_error_copy, validation_error_copy_zh,};const OPENVIKING_SERVICE_API_KEY_URL: &str =@@ -925,8 +924,9 @@ async fn status_box_runtime(active: Option<&Config>) -> StatusBoxRuntime {config.actor_peer_id.clone(),STATUS_BOX_PROBE_TIMEOUT_SECS,config.profile,- config.extra_headers.clone(),- );+ config.effective_extra_headers(),+ )+ .with_gateway_token(config.effective_gateway_token());match client.get::<Value>("/api/v1/system/status", &[]).await {Ok(status) => {@@ -4604,8 +4604,9 @@ fn root_admin_client(config: &Config, root_api_key: &str) -> BaseClient {None,config.timeout.clamp(1.0, 60.0),config.profile,- config.extra_headers.clone(),+ config.effective_extra_headers(),)+ .with_gateway_token(config.effective_gateway_token())}async fn list_root_accounts(client: &BaseClient) -> Result<Vec<RootAccountSummary>> {diff --git a/crates/ov_cli/src/error_classifier.rs b/crates/ov_cli/src/error_classifier.rsindex 8f22880fc..b108a911f 100644--- a/crates/ov_cli/src/error_classifier.rs+++ b/crates/ov_cli/src/error_classifier.rs@@ -1,14 +1,66 @@+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct MissingTrustedIdentityFields {+ pub(crate) account: bool,+ pub(crate) user: bool,+}++pub(crate) fn missing_trusted_identity_fields(+ message: &str,+) -> Option<MissingTrustedIdentityFields> {+ let lower = message.to_ascii_lowercase();+ let describes_missing_value = lower.contains("must include")+ || lower.contains("requires")+ || lower.contains("required")+ || lower.contains("missing");+ let mentions_trusted_identity = lower.contains("trusted")+ && (lower.contains("x-openviking-account")+ || lower.contains("x-openviking-user")+ || lower.contains("account_id")+ || lower.contains("user_id"));+ if !describes_missing_value || !mentions_trusted_identity {+ return None;+ }++ let fields = MissingTrustedIdentityFields {+ account: lower.contains("x-openviking-account") || lower.contains("account_id"),+ user: lower.contains("x-openviking-user") || lower.contains("user_id"),+ };+ (fields.account || fields.user).then_some(fields)+}++pub(crate) fn looks_like_missing_api_key_error(message: &str) -> bool {+ let lower = message.to_ascii_lowercase();+ lower.contains("missing api key") || lower.contains("api key header required")+}+pub(crate) fn looks_like_auth_error(message: &str) -> bool {let lower = message.to_ascii_lowercase();lower.contains("api key")|| lower.contains("unauthorized")|| lower.contains("forbidden")|| lower.contains("authentication")+ || lower.contains("trusted openviking chat requires")+ || lower.contains("trusted mode requests must include")|| lower.split(|ch: char| !ch.is_ascii_alphanumeric()).any(|token| token == "auth")}+pub(crate) fn looks_like_gateway_dev_boundary_error(message: &str) -> bool {+ let lower = message.to_ascii_lowercase();+ lower.contains("dev auth can only be used when gateway and openviking server are localhost")+ || (lower.contains("auth_mode changed to dev")+ && lower.contains("gateway")+ && lower.contains("openviking server"))+}++pub(crate) fn looks_like_gateway_standalone_proxy_error(message: &str) -> bool {+ let lower = message.to_ascii_lowercase();+ lower.contains("openviking upstream is not configured")+ || (lower.contains("vikingbot gateway proxy")+ && lower.contains("no available openviking server"))+}+/// Detect the kernel's pydantic `extra="forbid"` rejection — e.g./// "body.tags: Extra inputs are not permitted" — and return the offending field/// name. This usually means the target OpenViking instance is on a different@@ -33,7 +85,11 @@ pub(crate) fn extra_forbidden_field(message: &str) -> Option<String> {#[cfg(test)]mod tests {- use super::{extra_forbidden_field, looks_like_auth_error};+ use super::{+ extra_forbidden_field, looks_like_auth_error, looks_like_gateway_dev_boundary_error,+ looks_like_gateway_standalone_proxy_error, looks_like_missing_api_key_error,+ missing_trusted_identity_fields,+ };#[test]fn extracts_extra_forbidden_field() {@@ -63,15 +119,77 @@ mod tests {"forbidden","authentication failed","auth failed",+ "Trusted OpenViking chat requires X-OpenViking-Account and X-OpenViking-User.",+ "Trusted mode requests must include X-OpenViking-Account.",] {assert!(looks_like_auth_error(message), "{message}");}}+ #[test]+ fn extracts_missing_trusted_identity_fields() {+ let both = missing_trusted_identity_fields(+ "Trusted mode requests must include X-OpenViking-Account or explicit account_id in the URL and X-OpenViking-User or explicit user_id in the URL.",+ )+ .expect("trusted identity fields");+ assert!(both.account);+ assert!(both.user);++ let user =+ missing_trusted_identity_fields("Trusted OpenViking chat requires X-OpenViking-User.")+ .expect("trusted user field");+ assert!(!user.account);+ assert!(user.user);++ let wrapped = missing_trusted_identity_fields(+ "Request failed (401 Unauthorized): {\"detail\":\"Trusted request is missing account_id and user_id\"}",+ )+ .expect("wrapped trusted identity fields");+ assert!(wrapped.account);+ assert!(wrapped.user);++ assert!(missing_trusted_identity_fields("API key is invalid").is_none());+ }++ #[test]+ fn detects_missing_api_key_without_matching_invalid_keys() {+ for message in [+ "Missing API Key when resolving identity.",+ "Missing API Key in trusted mode with Root API Key enabled.",+ "OpenViking API key header required",+ ] {+ assert!(looks_like_missing_api_key_error(message), "{message}");+ }+ assert!(!looks_like_missing_api_key_error("API key is invalid"));+ }+#[test]fn avoids_auth_substring_false_positives() {for message in ["author not found", "authority unavailable"] {assert!(!looks_like_auth_error(message), "{message}");}}++ #[test]+ fn detects_gateway_dev_boundary_errors() {+ for message in [+ "Request failed (403 Forbidden): {\"detail\":\"OpenViking dev auth can only be used when gateway and OpenViking server are localhost\"}",+ "Request failed (403 Forbidden): {\"detail\":\"OpenViking server auth_mode changed to dev, but dev auth can only be used when gateway and OpenViking server are localhost\"}",+ ] {+ assert!(looks_like_gateway_dev_boundary_error(message), "{message}");+ }+ }++ #[test]+ fn detects_gateway_standalone_proxy_errors() {+ for message in [+ "OpenViking upstream is not configured",+ "VikingBot gateway proxy is active, but no available OpenViking server is configured",+ ] {+ assert!(+ looks_like_gateway_standalone_proxy_error(message),+ "{message}"+ );+ }+ }}diff --git a/crates/ov_cli/src/error_ui.rs b/crates/ov_cli/src/error_ui.rsindex eb187211e..44a65cf85 100644--- a/crates/ov_cli/src/error_ui.rs+++ b/crates/ov_cli/src/error_ui.rs@@ -5,7 +5,11 @@ use unicode_width::UnicodeWidthStr;use crate::{error::Error,- error_classifier::{extra_forbidden_field, looks_like_auth_error},+ error_classifier::{+ MissingTrustedIdentityFields, extra_forbidden_field, looks_like_auth_error,+ looks_like_gateway_dev_boundary_error, looks_like_gateway_standalone_proxy_error,+ looks_like_missing_api_key_error, missing_trusted_identity_fields,+ },i18n::{Language, copy},terminal_ui::{fit_to_display_width, truncate_to_display_width},theme,@@ -241,6 +245,118 @@ pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &ErrorErrorAction::new("ov health", copy(language, "Run a quick server health check", "快速检查服务器健康状态")),ErrorAction::new("ov config switch", copy(language, "Switch to another config", "切换到其他配置")),]),+ Error::Api { message, .. } if looks_like_gateway_dev_boundary_error(message) => {+ ErrorReport::new(+ copy(language, "Gateway Safety Check", "Gateway 安全校验失败"),+ copy(+ language,+ "OpenViking is in dev mode. VikingBot gateway and OpenViking server must both listen on localhost.",+ "OpenViking 当前是 dev 模式,VikingBot gateway 和 OpenViking server 必须都监听 localhost。",+ ),+ )+ .with_command(command)+ .with_detail(message)+ .with_actions(vec![+ ErrorAction::new(+ "ov config",+ copy(+ language,+ "Set bot.gateway.host to 127.0.0.1, or configure server.root_api_key",+ "将 bot.gateway.host 改为 127.0.0.1,或配置 server.root_api_key",+ ),+ ),+ ErrorAction::new(+ "ov health",+ copy(language, "Check the active endpoint", "检查当前端点"),+ ),+ ])+ }+ Error::Api { message, .. } if looks_like_gateway_standalone_proxy_error(message) => {+ ErrorReport::new(+ copy(language, "VikingBot Gateway Proxy", "VikingBot Gateway Proxy 不可用"),+ copy(+ language,+ "The active config is using VikingBot gateway proxy, but the gateway has no available OpenViking server. Standalone gateway mode can only serve ov chat.",+ "当前配置正在使用 VikingBot gateway proxy,但 gateway 没有可用的 OpenViking server。standalone gateway 模式只能使用 ov chat,其他 ov CLI 请求无法转发。",+ ),+ )+ .with_command(command)+ .with_detail(message)+ .with_actions(vec![+ ErrorAction::new(+ "ov chat",+ copy(language, "Chat with standalone VikingBot", "使用 standalone VikingBot 对话"),+ ),+ ErrorAction::new(+ "ov config",+ copy(+ language,+ "Point url to OpenViking server or fix bot.ov_server",+ "将 url 指向 OpenViking server,或修复 bot.ov_server",+ ),+ ),+ ErrorAction::new(+ "ov health",+ copy(language, "Check the active endpoint", "检查当前端点"),+ ),+ ])+ }+ Error::Api { message, .. } if missing_trusted_identity_fields(message).is_some() => {+ let fields = missing_trusted_identity_fields(message).expect("matched above");+ let names = trusted_identity_field_names(fields, language);+ ErrorReport::new(+ copy(+ language,+ "OpenViking Identity Missing",+ "OpenViking 身份配置缺失",+ ),+ trusted_identity_error_message(fields, language),+ )+ .with_command(command)+ .with_detail(message)+ .with_actions(vec![+ ErrorAction::new(+ "ov config",+ match language {+ Language::En => format!("Configure {names} in ovcli.conf"),+ Language::ZhCn => format!("在 ovcli.conf 中配置 {names}"),+ },+ ),+ ErrorAction::new(+ "ov config show",+ copy(language, "Show the active config", "查看当前配置"),+ ),+ ])+ }+ Error::Api { message, .. } if looks_like_missing_api_key_error(message) => {+ let trusted = message+ .to_ascii_lowercase()+ .contains("trusted mode");+ ErrorReport::new(+ copy(+ language,+ "OpenViking API Key Missing",+ "OpenViking API Key 未配置",+ ),+ missing_api_key_error_message(language, trusted),+ )+ .with_command(command)+ .with_detail(message)+ .with_actions(vec![+ ErrorAction::new(+ "ov config",+ copy(+ language,+ "Configure api_key in ovcli.conf",+ "在 ovcli.conf 中配置 api_key",+ ),+ ),+ ErrorAction::new(+ "ov config show",+ copy(language, "Show the active config", "查看当前配置"),+ ),+ ])+ }Error::Api { message, status } if is_client_auth_error(*status, message) => ErrorReport::new(copy(language, "Authentication Error", "认证错误"),copy(language, "OpenViking rejected the API key for the active config.", "OpenViking 拒绝了当前配置的 API Key。"),@@ -317,6 +433,50 @@ pub(crate) fn report_for_runtime_error(command: impl Into<String>, error: &Error}}+fn trusted_identity_field_names(+ fields: MissingTrustedIdentityFields,+ language: Language,+) -> &'static str {+ match (fields.account, fields.user) {+ (true, true) => copy(language, "account and user", "account 和 user"),+ (true, false) => "account",+ (false, true) => "user",+ (false, false) => unreachable!("at least one identity field is required"),+ }+}++fn trusted_identity_error_message(+ fields: MissingTrustedIdentityFields,+ language: Language,+) -> String {+ let names = trusted_identity_field_names(fields, language);+ match language {+ Language::En => format!(+ "OpenViking server is using trusted mode. The active ovcli.conf is missing {names}, so the request identity cannot be determined. Configure {names} in ovcli.conf."+ ),+ Language::ZhCn => format!(+ "OpenViking server 使用 trusted 模式。当前 ovcli.conf 缺少 {names},无法确定请求身份。请在 ovcli.conf 中配置 {names}。"+ ),+ }+}++fn missing_api_key_error_message(language: Language, trusted: bool) -> &'static str {+ match (language, trusted) {+ (Language::En, true) => {+ "OpenViking server is using trusted mode with a Root API Key. The active ovcli.conf did not provide that key. Configure api_key with the server's Root API Key."+ }+ (Language::ZhCn, true) => {+ "OpenViking server 使用 trusted 模式,并启用了 Root API Key。当前 ovcli.conf 未提供该 key。请将 api_key 配置为该 server 的 Root API Key。"+ }+ (Language::En, false) => {+ "The current request did not provide an OpenViking API Key. Configure api_key in ovcli.conf: use a User/Admin API Key for api_key mode, or a Root API Key for trusted mode."+ }+ (Language::ZhCn, false) => {+ "当前请求未提供 OpenViking API Key。请在 ovcli.conf 中配置 api_key:api_key 模式使用 User/Admin API Key,trusted 模式使用 Root API Key。"+ }+ }+}+fn config_error_actions(message: &str, language: Language) -> Vec<ErrorAction> {if is_config_file_load_error(message) {return vec![ErrorAction::new(@@ -1008,10 +1168,11 @@ fn help_command_from_usage(usage: &str) -> Option<String> {#[cfg(test)]mod tests {use super::{- CARD_WIDTH, ErrorAction, ErrorReport, render_report, render_report_with_width,- report_for_clap_error, report_for_runtime_error,+ CARD_WIDTH, ErrorAction, ErrorReport, missing_api_key_error_message, render_report,+ render_report_with_width, report_for_clap_error, report_for_runtime_error,+ trusted_identity_error_message,};- use crate::error::Error;+ use crate::{error::Error, error_classifier::MissingTrustedIdentityFields, i18n::Language};use std::ffi::OsString;use unicode_width::UnicodeWidthStr;@@ -1150,6 +1311,73 @@ Usage: ov config [OPTIONS] [COMMAND]assert!(verbose.contains("Request ID"));}+ #[test]+ fn trusted_identity_error_names_missing_ovcli_fields() {+ let error = Error::api(+ "[INVALID_ARGUMENT] Trusted mode requests must include X-OpenViking-Account or explicit account_id in the URL and X-OpenViking-User or explicit user_id in the URL."+ .to_string(),+ );+ let report = report_for_runtime_error("ov ls viking://", &error);+ let normal = strip_ansi(&render_report(&report, false));++ assert!(normal.contains("OpenViking Identity Missing"));+ assert!(normal.contains("trusted mode"));+ assert!(normal.contains("ovcli.conf"));+ assert!(normal.contains("account and user"));+ assert!(!normal.contains("rejected the API key"));+ }++ #[test]+ fn missing_api_key_error_is_not_reported_as_rejected_key() {+ let error = Error::api(+ "[UNAUTHENTICATED] Missing API Key in trusted mode with Root API Key enabled."+ .to_string(),+ );+ let report = report_for_runtime_error("ov ls viking://", &error);+ let normal = strip_ansi(&render_report(&report, false));++ assert!(normal.contains("OpenViking API Key Missing"));+ assert!(normal.contains("trusted mode"));+ assert!(normal.contains("Root API Key"));+ assert!(normal.contains("ovcli.conf"));+ assert!(!normal.contains("rejected the API key"));+ }++ #[test]+ fn trusted_identity_and_missing_key_have_chinese_guidance() {+ let identity = trusted_identity_error_message(+ MissingTrustedIdentityFields {+ account: true,+ user: true,+ },+ Language::ZhCn,+ );+ assert!(identity.contains("OpenViking server 使用 trusted 模式"));+ assert!(identity.contains("ovcli.conf 缺少 account 和 user"));+ assert!(identity.contains("配置 account 和 user"));++ let api_key = missing_api_key_error_message(Language::ZhCn, true);+ assert!(api_key.contains("trusted 模式"));+ assert!(api_key.contains("Root API Key"));+ assert!(api_key.contains("ovcli.conf"));+ assert!(api_key.contains("api_key"));+ }++ #[test]+ fn gateway_dev_boundary_error_is_not_reported_as_api_key_rejection() {+ let error = Error::api(+ "Request failed (403 Forbidden): {\"detail\":\"OpenViking server auth_mode changed to dev, but dev auth can only be used when gateway and OpenViking server are localhost\"}"+ .to_string(),+ );+ let report = report_for_runtime_error("ov ls viking://", &error);+ let normal = strip_ansi(&render_report(&report, false));++ assert!(normal.contains("Gateway Safety Check"));+ assert!(normal.contains("OpenViking is in dev mode"));+ assert!(normal.contains("bot.gateway.host"));+ assert!(!normal.contains("OpenViking rejected the API key"));+ }+#[test]fn remote_resource_auth_failure_wrapped_as_5xx_is_not_api_key_error() {let error = Error::api_with_status(@@ -1157,7 +1385,8 @@ Usage: ov config [OPTIONS] [COMMAND].to_string(),500,);- let report = report_for_runtime_error("ov add-resource https://example.com/private", &error);+ let report =+ report_for_runtime_error("ov add-resource https://example.com/private", &error);let normal = strip_ansi(&render_report(&report, false));assert!(normal.contains("OpenViking API Error"));@@ -1165,6 +1394,23 @@ Usage: ov config [OPTIONS] [COMMAND]assert!(!normal.contains("OpenViking rejected the API key"));}+ #[test]+ fn gateway_standalone_proxy_error_explains_missing_openviking_server() {+ let error = Error::api(+ "VikingBot gateway proxy is active, but no available OpenViking server is configured"+ .to_string(),+ );+ let report = report_for_runtime_error("ov ls viking://", &error);+ let normal = strip_ansi(&render_report(&report, false));++ assert!(normal.contains("VikingBot Gateway Proxy"));+ assert!(normal.contains("no available") || normal.contains("没有可用"));+ assert!(normal.contains("OpenViking server"));+ assert!(normal.contains("serve ov chat") || normal.contains("只能使用 ov chat"));+ assert!(normal.contains("ov chat"));+ assert!(!normal.contains("OpenViking rejected the API key"));+ }+#[test]fn server_401_is_still_api_key_error() {let error = Error::api_with_status("API key invalid".to_string(), 401);diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 8633e789b..0114122da 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -89,8 +89,9 @@ pub async fn handle_add_resource(ctx.config.effective_actor_peer_id(),effective_timeout,ctx.profile.unwrap_or(ctx.config.profile),- ctx.config.extra_headers.clone(),- );+ ctx.config.effective_extra_headers(),+ )+ .with_gateway_token(ctx.config.effective_gateway_token());commands::resources::add_resource(&client,&path,diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 6f5bb3433..4090b1331 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -102,8 +102,9 @@ impl CliContext {self.config.effective_actor_peer_id(),timeout_secs.unwrap_or(self.config.timeout),self.profile.unwrap_or(self.config.profile),- self.config.extra_headers.clone(),+ self.config.effective_extra_headers(),)+ .with_gateway_token(self.config.effective_gateway_token())}}@@ -367,7 +368,12 @@ enum Commands {#[arg(long, value_name = "seconds", help_heading = "Common options")]timeout: Option<f64>,/// Parent skill root URI (e.g. viking://agent/skills); defaults to user-private skills- #[arg(short = 'p', long = "parent-auto-create", value_name = "uri", help_heading = "Skill options")]+ #[arg(+ short = 'p',+ long = "parent-auto-create",+ value_name = "uri",+ help_heading = "Skill options"+ )]parent: Option<String>,#[command(flatten)]upload_options: UploadCliOptions,@@ -3028,11 +3034,11 @@ async fn main() {} => {let session_id = session.or_else(|| config::get_or_create_machine_id().ok());let endpoint = if let Ok(env_endpoint) = std::env::var("VIKINGBOT_ENDPOINT") {- env_endpoint+ Some(env_endpoint)} else if let Ok(config_url) = std::env::var("OPENVIKING_URL") {- format!("{}/bot/v1", config_url)+ Some(format!("{}/bot/v1", config_url))} else {- format!("{}/bot/v1", ctx.config.url)+ None};let api_key = std::env::var("VIKINGBOT_API_KEY").ok();let cmd = commands::chat::ChatCommand {@@ -3040,6 +3046,7 @@ async fn main() {api_key,account: ctx.config.account.clone(),user: ctx.config.user.clone(),+ actor_peer_id: ctx.config.effective_actor_peer_id(),session: session_id,sender,message,@@ -3905,9 +3912,10 @@ mod tests {.expect("skills remove --yes should parse");match remove.command {Commands::Skills {- action: SkillCommands::Remove {- skills, yes, all, ..- },+ action:+ SkillCommands::Remove {+ skills, yes, all, ..+ },} => {assert_eq!(skills, vec!["foo", "bar"]);assert!(yes);@@ -4320,6 +4328,7 @@ mod tests {upload: Default::default(),extra_headers: None,profile: false,+ gateway_token: None,};let ctx = CliContext::from_config(@@ -4359,6 +4368,7 @@ mod tests {upload: Default::default(),extra_headers: None,profile: false,+ gateway_token: None,};let ctx = CliContext::from_config(@@ -4396,6 +4406,7 @@ mod tests {profile: false,upload: Default::default(),extra_headers: None,+ gateway_token: None,};// Without sudo: use api_keydiff --git a/docs/images/vikingbot-gateway-routing.png b/docs/images/vikingbot-gateway-routing.pngnew file mode 100644index 000000000..002ffc7a9Binary files /dev/null and b/docs/images/vikingbot-gateway-routing.png differdiff --git a/examples/ov.conf.example b/examples/ov.conf.exampleindex c381bedb6..1e9b1365e 100644--- a/examples/ov.conf.example+++ b/examples/ov.conf.example@@ -176,6 +176,18 @@"openclaw": {"enabled": false, "mode": "both", "user_field": "sender"},},},+ "bot": {+ "gateway": {+ "host": "127.0.0.1",+ "port": 18790,+ "token": null,+ },+ "ov_server": {+ "server_url": null,+ "api_key_type": "user",+ "api_key": null,+ },+ },"log": {"level": "INFO","format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",diff --git a/examples/ovcli.conf.example b/examples/ovcli.conf.exampleindex 49e3cef05..4dbc37870 100644--- a/examples/ovcli.conf.example+++ b/examples/ovcli.conf.example@@ -2,6 +2,7 @@"url": "http://localhost:1933","api_key": null,"root_api_key": null,+ "gateway_token": null,"account": null,"user": null,"timeout": 60.0,diff --git a/openviking/server/bootstrap.py b/openviking/server/bootstrap.pyindex 7fa0228e2..e9168da57 100644--- a/openviking/server/bootstrap.py+++ b/openviking/server/bootstrap.py@@ -17,7 +17,7 @@ from typing import Optionalimport uvicornfrom openviking.server.app import create_app-from openviking.server.config import load_server_config+from openviking.server.config import get_server_url_from_server_data, load_server_configfrom openviking_cli.utils.config import OPENVIKING_CONFIG_ENVfrom openviking_cli.utils.config.config_loader import resolve_config_pathfrom openviking_cli.utils.config.consts import (@@ -264,7 +264,14 @@ def main():bot_log_dir,bot_port,config_path=args.config,+ managed_server_url=get_server_url_from_server_data(config),)+ if bot_process is None:+ print(+ "Error: --with-bot was requested, but VikingBot could not be started.",+ file=sys.stderr,+ )+ sys.exit(1)# Create and run server appapp = create_app(config)@@ -318,6 +325,7 @@ def _start_vikingbot_gateway(log_dir: str,port: int = VIKINGBOT_DEFAULT_PORT,config_path: Optional[str] = None,+ managed_server_url: Optional[str] = None,) -> Optional[BotProcess]:"""Start vikingbot gateway as a subprocess."""print("Starting vikingbot gateway...")@@ -331,7 +339,7 @@ def _start_vikingbot_gateway(python_cmd = sys.executabletry:result = subprocess.run(- [python_cmd, "-m", "vikingbot", "--help"], capture_output=True, timeout=5+ [python_cmd, "-m", "vikingbot", "--help"], capture_output=True, timeout=15)if result.returncode == 0:vikingbot_cmd = [python_cmd, "-m", "vikingbot", "gateway"]@@ -375,6 +383,9 @@ def _start_vikingbot_gateway(cli_config_path = _resolve_cli_config_for_bot(config_path)if cli_config_path is not None:env[OPENVIKING_CLI_CONFIG_ENV] = cli_config_path+ env["VIKINGBOT_WITH_OPENVIKING_SERVER"] = "1"+ if managed_server_url:+ env["VIKINGBOT_MANAGED_OV_SERVER_URL"] = managed_server_urlprocess = subprocess.Popen(vikingbot_cmd,diff --git a/openviking/server/routers/bot.py b/openviking/server/routers/bot.pyindex d0672ebba..4eda08dad 100644--- a/openviking/server/routers/bot.py+++ b/openviking/server/routers/bot.py@@ -146,8 +146,10 @@ async def health_check(request: Request):try:async with _create_bot_proxy_client() as client:# Forward to Vikingbot OpenAPIChannel health endpoint+ headers = {"X-Gateway-Token": BOT_API_KEY} if BOT_API_KEY else Noneresponse = await client.get(f"{bot_url}/bot/v1/health",+ headers=headers,timeout=5.0,)response.raise_for_status()@@ -246,7 +248,7 @@ async def feedback(response = await client.post(f"{bot_url}/bot/v1/feedback",- json=body,+ json=_attach_openviking_connection(body, request, _ctx),headers=headers,timeout=30.0,)diff --git a/openviking_cli/client/_http_compat.py b/openviking_cli/client/_http_compat.pyindex 0a9e6b305..bb8703092 100644--- a/openviking_cli/client/_http_compat.py+++ b/openviking_cli/client/_http_compat.py@@ -4,6 +4,9 @@from __future__ import annotations+import json+import os+from pathlib import Pathfrom typing import Any, Dictimport httpx@@ -56,6 +59,23 @@ ERROR_CODE_TO_EXCEPTION = {}+def _timeout_configured_outside_call() -> bool:+ if os.getenv("OPENVIKING_TIMEOUT"):+ return True+ config_path = os.getenv("OPENVIKING_CLI_CONFIG_FILE")+ if config_path:+ path = Path(config_path).expanduser()+ else:+ path = Path.home() / ".openviking" / "ovcli.conf"+ if not path.exists():+ return False+ try:+ raw = json.loads(path.read_text())+ except (OSError, ValueError):+ return False+ return isinstance(raw, dict) and "timeout" in raw++def _raise_legacy_exception(error: Dict[str, Any]) -> None:code = error.get("code", "UNKNOWN")message = error.get("message", "Unknown error")@@ -91,8 +111,8 @@ class AsyncHTTPClient(import_openviking_sdk().AsyncHTTPClient):def __init__(self, *args, **kwargs):# Heavy local benchmark runs can keep OpenViking search requests queued# behind embedding/vector work. Use a larger default read timeout than- # the upstream SDK's 60s while still respecting explicit caller values,- # including the SDK default when callers pass no timeout argument.+ # the upstream SDK's 60s while still respecting explicit caller values+ # and timeouts configured via environment or ovcli.conf.if "timeout" not in kwargs:try:import inspect@@ -108,7 +128,7 @@ class AsyncHTTPClient(import_openviking_sdk().AsyncHTTPClient):timeout_index = params.index("timeout")except Exception:timeout_index = 7- if len(args) <= timeout_index:+ if len(args) <= timeout_index and not _timeout_configured_outside_call():kwargs["timeout"] = 180.0super().__init__(*args, **kwargs)diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.pyindex b0b57206b..98d016cd5 100644--- a/openviking_cli/client/http.py+++ b/openviking_cli/client/http.py@@ -2,6 +2,8 @@# SPDX-License-Identifier: AGPL-3.0"""Compatibility shim for the legacy HTTP client import path."""+import httpx+from openviking_cli.client._http_compat import ERROR_CODE_TO_EXCEPTION, AsyncHTTPClient-__all__ = ["AsyncHTTPClient", "ERROR_CODE_TO_EXCEPTION"]+__all__ = ["AsyncHTTPClient", "ERROR_CODE_TO_EXCEPTION", "httpx"]diff --git a/openviking_cli/utils/config/ovcli_config.py b/openviking_cli/utils/config/ovcli_config.pyindex 52a7f9edb..6f01f89d1 100644--- a/openviking_cli/utils/config/ovcli_config.py+++ b/openviking_cli/utils/config/ovcli_config.py@@ -37,6 +37,7 @@ class OVCLIConfig(BaseModel):echo_command: Optional[bool] = Noneupload: Optional[OVCLIUploadConfig] = Noneextra_headers: Optional[Dict[str, str]] = None+ gateway_token: Optional[str] = Nonemodel_config = {"extra": "forbid"}diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex af5066493..946e68e85 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -7,6 +7,7 @@ import osimport tempfileimport uuidimport zipfile+from enum import Enumfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Unionfrom urllib.parse import quote@@ -61,6 +62,9 @@ ERROR_CODE_TO_EXCEPTION = {"UNKNOWN": OpenVikingError,}+GATEWAY_MARKER_HEADER = "X-VikingBot-Gateway"+GATEWAY_TOKEN_HEADER = "X-Gateway-Token"+def _image_mime_type(file_name: str = "") -> str:mime_type, _ = mimetypes.guess_type(file_name or "")@@ -266,6 +270,7 @@ class AsyncHTTPClient:self._account = config.accountself._user_id = config.userself._actor_peer_id = config.actor_peer_id+ self._gateway_token = config.gateway_tokenself._timeout = config.timeoutself._extra_headers = config.extra_headersself._profile_enabled = config.profile_enabled@@ -293,6 +298,77 @@ class AsyncHTTPClient:)self._observer = _HTTPObserver(self)+ @staticmethod+ def _has_header(headers: Dict[str, str], name: str) -> bool:+ return any(key.lower() == name.lower() for key in headers)++ @staticmethod+ def _is_gateway_token_challenge(response: httpx.Response) -> bool:+ return (+ getattr(response, "status_code", None) == httpx.codes.UNAUTHORIZED+ and getattr(response, "headers", {}).get(GATEWAY_MARKER_HEADER, "").lower() == "true"+ )++ def _has_explicit_gateway_header(self, headers: Dict[str, str]) -> bool:+ return self._has_header(self._extra_headers, GATEWAY_TOKEN_HEADER) or self._has_header(+ headers, GATEWAY_TOKEN_HEADER+ )++ async def _gateway_token_required(self) -> bool:+ if self._http is None:+ raise RuntimeError("Client is not initialized")+ response = await self._http.get("/health")+ return self._is_gateway_token_challenge(response)++ async def _send_http_request(+ self,+ method: str,+ url: str,+ headers: Dict[str, str],+ request_kwargs: Dict[str, Any],+ ) -> httpx.Response:+ if self._http is None:+ raise RuntimeError("Client is not initialized")+ call_kwargs = dict(request_kwargs)+ if headers:+ call_kwargs["headers"] = headers+ request_method = getattr(self._http, "request", None)+ if callable(request_method):+ return await request_method(method, url, **call_kwargs)+ verb_method = getattr(self._http, method.lower())+ return await verb_method(url, **call_kwargs)++ async def _request(self, method: str, url: str, **kwargs: Any) -> httpx.Response:+ if self._http is None:+ raise RuntimeError("Client is not initialized")++ request_kwargs = dict(kwargs)+ headers = dict(request_kwargs.pop("headers", {}) or {})+ has_explicit_gateway_header = self._has_explicit_gateway_header(headers)++ # Multipart streams cannot be replayed safely after the first request. Probe the+ # endpoint before sending them so a Gateway token is attached only when challenged.+ if (+ request_kwargs.get("files") is not None+ and self._gateway_token+ and not has_explicit_gateway_header+ and await self._gateway_token_required()+ ):+ headers[GATEWAY_TOKEN_HEADER] = self._gateway_token++ response = await self._send_http_request(method, url, headers, request_kwargs)+ if (+ not self._is_gateway_token_challenge(response)+ or not self._gateway_token+ or has_explicit_gateway_header+ or request_kwargs.get("files") is not None+ ):+ return response++ retry_headers = dict(headers)+ retry_headers[GATEWAY_TOKEN_HEADER] = self._gateway_token+ return await self._send_http_request(method, url, retry_headers, request_kwargs)+async def close(self) -> None:if self._http:try:@@ -339,6 +415,16 @@ class AsyncHTTPClient:compacted[key] = valuereturn compacted+ @staticmethod+ def _normalize_context_type(context_type: Optional[Any]) -> Optional[Any]:+ if context_type is None:+ return None+ if isinstance(context_type, list):+ return [item.value if isinstance(item, Enum) else item for item in context_type]+ if isinstance(context_type, Enum):+ return context_type.value+ return context_type+def _handle_response_data(self, response: httpx.Response) -> Dict[str, Any]:try:data = response.json()@@ -415,7 +501,8 @@ class AsyncHTTPClient:with open(file_path, "rb") as f:files = {"file": (Path(file_path).name, f, "application/octet-stream")}data = {"upload_mode": self._upload_mode} if self._upload_mode else None- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/resources/temp_upload",files=files,data=data,@@ -492,7 +579,7 @@ class AsyncHTTPClient:request_data["path"] = pathrequest_data = self._compact_request_body(request_data)- response = await self._http.post("/api/v1/resources", json=request_data)+ response = await self._request("POST", "/api/v1/resources", json=request_data)return self._handle_response_data(response).get("result", {})async def batch_add_messages(@@ -505,7 +592,8 @@ class AsyncHTTPClient:payload: Dict[str, Any] = {"messages": messages}if telemetry is not False:payload["telemetry"] = telemetry- response = await self._http.post(+ response = await self._request(+ "POST",f"/api/v1/sessions/{session_path}/messages/batch",json=payload,)@@ -539,7 +627,7 @@ class AsyncHTTPClient:request_data["data"] = dataelse:request_data["data"] = data- response = await self._http.post("/api/v1/skills", json=request_data)+ response = await self._request("POST", "/api/v1/skills", json=request_data)return self._handle_response_data(response).get("result", {})async def list_skills(@@ -550,7 +638,7 @@ class AsyncHTTPClient:params: Dict[str, Any] = {"node_limit": node_limit}if target_uri is not None:params["target_uri"] = target_uri- response = await self._http.get("/api/v1/skills", params=params)+ response = await self._request("GET", "/api/v1/skills", params=params)return self._handle_response(response)async def find_skills(@@ -571,7 +659,7 @@ class AsyncHTTPClient:}if target_uri is not None:payload["target_uri"] = target_uri- response = await self._http.post("/api/v1/skills/find", json=payload)+ response = await self._request("POST", "/api/v1/skills/find", json=payload)return self._handle_response_data(response).get("result", {})async def validate_skill(@@ -589,7 +677,7 @@ class AsyncHTTPClient:payload["skill_dir_name"] = skill_dir_nameif target_uri is not None:payload["target_uri"] = target_uri- response = await self._http.post("/api/v1/skills/validate", json=payload)+ response = await self._request("POST", "/api/v1/skills/validate", json=payload)return self._handle_response(response)async def get_skill(@@ -611,7 +699,7 @@ class AsyncHTTPClient:params["level"] = levelif target_uri is not None:params["target_uri"] = target_uri- response = await self._http.get(f"/api/v1/skills/{skill_name}", params=params)+ response = await self._request("GET", f"/api/v1/skills/{skill_name}", params=params)return self._handle_response(response)async def update_skill(@@ -649,7 +737,7 @@ class AsyncHTTPClient:request_data["data"] = dataelse:request_data["data"] = data- response = await self._http.put(f"/api/v1/skills/{skill_name}", json=request_data)+ response = await self._request("PUT", f"/api/v1/skills/{skill_name}", json=request_data)return self._handle_response_data(response).get("result", {})async def delete_skill(@@ -660,7 +748,7 @@ class AsyncHTTPClient:params: Dict[str, Any] = {}if target_uri is not None:params["target_uri"] = target_uri- response = await self._http.delete(f"/api/v1/skills/{skill_name}", params=params)+ response = await self._request("DELETE", f"/api/v1/skills/{skill_name}", params=params)return self._handle_response(response)async def list_watches(@@ -671,7 +759,7 @@ class AsyncHTTPClient:params: Dict[str, Any] = {"active_only": active_only}if to_uri is not None:params["to_uri"] = VikingURI.normalize(to_uri)- response = await self._http.get("/api/v1/watches", params=params)+ response = await self._request("GET", "/api/v1/watches", params=params)return self._handle_response(response)async def get_watch(@@ -682,7 +770,7 @@ class AsyncHTTPClient:params = {}if to_uri is not None:params["to_uri"] = VikingURI.normalize(to_uri)- response = await self._http.get(f"/api/v1/watches/{task_id}", params=params)+ response = await self._request("GET", f"/api/v1/watches/{task_id}", params=params)return self._handle_response(response)async def update_watch(@@ -710,11 +798,12 @@ class AsyncHTTPClient:params = {}if to_uri is not None:params["to_uri"] = VikingURI.normalize(to_uri)- response = await self._http.patch(- f"/api/v1/watches/{task_id}", params=params, json=payload+ response = await self._request(+ "PATCH", f"/api/v1/watches/{task_id}", params=params, json=payload)else:- response = await self._http.patch(+ response = await self._request(+ "PATCH","/api/v1/watches",params={"to_uri": VikingURI.normalize(to_uri)},json=payload,@@ -730,10 +819,10 @@ class AsyncHTTPClient:params = {}if to_uri is not None:params["to_uri"] = VikingURI.normalize(to_uri)- response = await self._http.delete(f"/api/v1/watches/{task_id}", params=params)+ response = await self._request("DELETE", f"/api/v1/watches/{task_id}", params=params)else:- response = await self._http.delete(- "/api/v1/watches", params={"to_uri": VikingURI.normalize(to_uri)}+ response = await self._request(+ "DELETE", "/api/v1/watches", params={"to_uri": VikingURI.normalize(to_uri)})return self._handle_response(response)@@ -746,16 +835,19 @@ class AsyncHTTPClient:params = {}if to_uri is not None:params["to_uri"] = VikingURI.normalize(to_uri)- response = await self._http.post(f"/api/v1/watches/{task_id}/trigger", params=params)+ response = await self._request(+ "POST", f"/api/v1/watches/{task_id}/trigger", params=params+ )else:- response = await self._http.post(- "/api/v1/watches/trigger", params={"to_uri": VikingURI.normalize(to_uri)}+ response = await self._request(+ "POST", "/api/v1/watches/trigger", params={"to_uri": VikingURI.normalize(to_uri)})return self._handle_response(response)async def wait_processed(self, timeout: Optional[float] = None) -> Dict[str, Any]:http_timeout = timeout if timeout else 600.0- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/system/wait",json={"timeout": timeout},timeout=http_timeout,@@ -772,7 +864,8 @@ class AsyncHTTPClient:show_all_hidden: bool = False,node_limit: int = 1000,) -> List[Any]:- response = await self._http.get(+ response = await self._request(+ "GET","/api/v1/fs/ls",params={"uri": VikingURI.normalize(uri),@@ -794,7 +887,8 @@ class AsyncHTTPClient:show_all_hidden: bool = False,node_limit: int = 1000,) -> List[Dict[str, Any]]:- response = await self._http.get(+ response = await self._request(+ "GET","/api/v1/fs/tree",params={"uri": VikingURI.normalize(uri),@@ -807,12 +901,14 @@ class AsyncHTTPClient:return self._handle_response(response)async def stat(self, uri: str) -> Dict[str, Any]:- response = await self._http.get("/api/v1/fs/stat", params={"uri": VikingURI.normalize(uri)})+ response = await self._request(+ "GET", "/api/v1/fs/stat", params={"uri": VikingURI.normalize(uri)}+ )return self._handle_response(response)async def attrs(self, uri: str) -> Dict[str, Any]:- response = await self._http.get(- "/api/v1/fs/attrs", params={"uri": VikingURI.normalize(uri)}+ response = await self._request(+ "GET", "/api/v1/fs/attrs", params={"uri": VikingURI.normalize(uri)})return self._handle_response(response)@@ -820,7 +916,7 @@ class AsyncHTTPClient:payload = {"uri": VikingURI.normalize(uri)}if description is not None:payload["description"] = description- response = await self._http.post("/api/v1/fs/mkdir", json=payload)+ response = await self._request("POST", "/api/v1/fs/mkdir", json=payload)self._handle_response(response)async def rm(@@ -833,32 +929,34 @@ class AsyncHTTPClient:params = {"uri": VikingURI.normalize(uri), "recursive": recursive, "wait": wait}if timeout is not None:params["timeout"] = timeout- response = await self._http.request("DELETE", "/api/v1/fs", params=params)+ response = await self._request("DELETE", "/api/v1/fs", params=params)self._handle_response(response)async def mv(self, from_uri: str, to_uri: str) -> None:- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/fs/mv",json={"from_uri": VikingURI.normalize(from_uri), "to_uri": VikingURI.normalize(to_uri)},)self._handle_response(response)async def read(self, uri: str, offset: int = 0, limit: int = -1) -> str:- response = await self._http.get(+ response = await self._request(+ "GET","/api/v1/content/read",params={"uri": VikingURI.normalize(uri), "offset": offset, "limit": limit},)return self._handle_response(response)async def abstract(self, uri: str) -> str:- response = await self._http.get(- "/api/v1/content/abstract", params={"uri": VikingURI.normalize(uri)}+ response = await self._request(+ "GET", "/api/v1/content/abstract", params={"uri": VikingURI.normalize(uri)})return self._handle_response(response)async def overview(self, uri: str) -> str:- response = await self._http.get(- "/api/v1/content/overview", params={"uri": VikingURI.normalize(uri)}+ response = await self._request(+ "GET", "/api/v1/content/overview", params={"uri": VikingURI.normalize(uri)})return self._handle_response(response)@@ -871,7 +969,8 @@ class AsyncHTTPClient:timeout: Optional[float] = None,telemetry: Any = False,) -> Dict[str, Any]:- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/content/write",json={"uri": VikingURI.normalize(uri),@@ -892,7 +991,8 @@ class AsyncHTTPClient:recursive: bool = False,telemetry: Any = False,) -> Dict[str, Any]:- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/fs/attrs/set_tags",json={"uri": VikingURI.normalize(uri),@@ -925,12 +1025,12 @@ class AsyncHTTPClient:"limit": actual_limit,"score_threshold": score_threshold,"filter": filter,- "context_type": context_type,+ "context_type": self._normalize_context_type(context_type),"tags": tags,"telemetry": telemetry,}payload = self._compact_request_body(payload)- response = await self._http.post("/api/v1/search/find", json=payload)+ response = await self._request("POST", "/api/v1/search/find", json=payload)return self._handle_response_data(response).get("result", {})async def search(@@ -958,12 +1058,12 @@ class AsyncHTTPClient:"limit": actual_limit,"score_threshold": score_threshold,"filter": filter,- "context_type": context_type,+ "context_type": self._normalize_context_type(context_type),"tags": tags,"telemetry": telemetry,}payload = self._compact_request_body(payload)- response = await self._http.post("/api/v1/search/search", json=payload)+ response = await self._request("POST", "/api/v1/search/search", json=payload)return self._handle_response_data(response).get("result", {})async def grep(@@ -982,7 +1082,7 @@ class AsyncHTTPClient:}if exclude_uri is not None:request_json["exclude_uri"] = VikingURI.normalize(exclude_uri)- response = await self._http.post("/api/v1/search/grep", json=request_json)+ response = await self._request("POST", "/api/v1/search/grep", json=request_json)return self._handle_response(response)async def glob(@@ -991,7 +1091,8 @@ class AsyncHTTPClient:uri: str = "viking://",node_limit: int = 256,) -> Dict[str, Any]:- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/search/glob",json={"pattern": pattern,@@ -1002,8 +1103,8 @@ class AsyncHTTPClient:return self._handle_response(response)async def relations(self, uri: str) -> List[Any]:- response = await self._http.get(- "/api/v1/relations", params={"uri": VikingURI.normalize(uri)}+ response = await self._request(+ "GET", "/api/v1/relations", params={"uri": VikingURI.normalize(uri)})return self._handle_response(response)@@ -1012,7 +1113,8 @@ class AsyncHTTPClient:to_uris = VikingURI.normalize(to_uris)else:to_uris = [VikingURI.normalize(u) for u in to_uris]- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/relations/link",json={"from_uri": VikingURI.normalize(from_uri),@@ -1023,7 +1125,7 @@ class AsyncHTTPClient:self._handle_response(response)async def unlink(self, from_uri: str, to_uri: str) -> None:- response = await self._http.request(+ response = await self._request("DELETE","/api/v1/relations/link",json={@@ -1046,24 +1148,25 @@ class AsyncHTTPClient:json_body["memory_policy"] = memory_policyif telemetry is not False:json_body["telemetry"] = telemetry- response = await self._http.post("/api/v1/sessions", json=json_body)+ response = await self._request("POST", "/api/v1/sessions", json=json_body)return self._handle_response_data(response).get("result", {})async def list_sessions(self) -> List[Any]:- response = await self._http.get("/api/v1/sessions")+ response = await self._request("GET", "/api/v1/sessions")return self._handle_response(response)async def get_session(self, session_id: str, *, auto_create: bool = False) -> Dict[str, Any]:params = {"auto_create": "true"} if auto_create else {}session_path = self._path_segment(session_id)- response = await self._http.get(f"/api/v1/sessions/{session_path}", params=params)+ response = await self._request("GET", f"/api/v1/sessions/{session_path}", params=params)return self._handle_response(response)async def get_session_context(self, session_id: str, token_budget: int = 128_000) -> Dict[str, Any]:session_path = self._path_segment(session_id)- response = await self._http.get(+ response = await self._request(+ "GET",f"/api/v1/sessions/{session_path}/context",params={"token_budget": token_budget},)@@ -1072,16 +1175,18 @@ class AsyncHTTPClient:async def get_session_archive(self, session_id: str, archive_id: str) -> Dict[str, Any]:session_path = self._path_segment(session_id)archive_path = self._path_segment(archive_id)- response = await self._http.get(f"/api/v1/sessions/{session_path}/archives/{archive_path}")+ response = await self._request(+ "GET", f"/api/v1/sessions/{session_path}/archives/{archive_path}"+ )return self._handle_response(response)async def delete_session(self, session_id: str) -> None:session_path = self._path_segment(session_id)- response = await self._http.delete(f"/api/v1/sessions/{session_path}")+ response = await self._request("DELETE", f"/api/v1/sessions/{session_path}")self._handle_response(response)async def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:- response = await self._http.get(f"/api/v1/tasks/{task_id}")+ response = await self._request("GET", f"/api/v1/tasks/{task_id}")if response.status_code == 404:return Nonereturn self._handle_response(response)@@ -1100,7 +1205,7 @@ class AsyncHTTPClient:params["status"] = statusif resource_id is not None:params["resource_id"] = resource_id- response = await self._http.get("/api/v1/tasks", params=params)+ response = await self._request("GET", "/api/v1/tasks", params=params)return self._handle_response(response)async def commit_session(@@ -1111,7 +1216,8 @@ class AsyncHTTPClient:keep_recent_count: int = 0,) -> Dict[str, Any]:session_path = self._path_segment(session_id)- response = await self._http.post(+ response = await self._request(+ "POST",f"/api/v1/sessions/{session_path}/commit",json={"keep_recent_count": keep_recent_count, "telemetry": telemetry},)@@ -1141,7 +1247,9 @@ class AsyncHTTPClient:if telemetry is not False:payload["telemetry"] = telemetrysession_path = self._path_segment(session_id)- response = await self._http.post(f"/api/v1/sessions/{session_path}/messages", json=payload)+ response = await self._request(+ "POST", f"/api/v1/sessions/{session_path}/messages", json=payload+ )return self._handle_response_data(response).get("result", {})async def export_ovpack(@@ -1158,7 +1266,8 @@ class AsyncHTTPClient:elif not str(to_path).endswith(".ovpack"):to_path = Path(str(to_path) + ".ovpack")to_path.parent.mkdir(parents=True, exist_ok=True)- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/pack/export",json={"uri": uri, "include_vectors": include_vectors},)@@ -1175,8 +1284,8 @@ class AsyncHTTPClient:elif not str(to_path).endswith(".ovpack"):to_path = Path(str(to_path) + ".ovpack")to_path.parent.mkdir(parents=True, exist_ok=True)- response = await self._http.post(- "/api/v1/pack/backup", json={"include_vectors": include_vectors}+ response = await self._request(+ "POST", "/api/v1/pack/backup", json={"include_vectors": include_vectors})if not response.is_success:self._handle_response(response)@@ -1202,7 +1311,7 @@ class AsyncHTTPClient:if not file_path_obj.is_file():raise ValueError(f"Path {file_path} is not a file")request_data["temp_file_id"] = await self._upload_temp_file(file_path)- response = await self._http.post("/api/v1/pack/import", json=request_data)+ response = await self._request("POST", "/api/v1/pack/import", json=request_data)result = self._handle_response(response)return result.get("uri", "")@@ -1223,12 +1332,13 @@ class AsyncHTTPClient:if not file_path_obj.is_file():raise ValueError(f"Path {file_path} is not a file")request_data["temp_file_id"] = await self._upload_temp_file(file_path)- response = await self._http.post("/api/v1/pack/restore", json=request_data)+ response = await self._request("POST", "/api/v1/pack/restore", json=request_data)result = self._handle_response(response)return result.get("uri", "")async def check_consistency(self, uri: str) -> Dict[str, Any]:- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/system/consistency",json={"uri": VikingURI.normalize(uri)},)@@ -1236,7 +1346,7 @@ class AsyncHTTPClient:async def health(self) -> bool:try:- response = await self._http.get("/health")+ response = await self._request("GET", "/health")data = response.json()return data.get("status") == "ok"except Exception:@@ -1248,26 +1358,27 @@ class AsyncHTTPClient:mode: str = "vectors_only",wait: bool = True,) -> Dict[str, Any]:- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/content/reindex",json={"uri": uri, "mode": mode, "wait": wait},)return self._handle_response(response)async def _get_queue_status(self) -> Dict[str, Any]:- response = await self._http.get("/api/v1/observer/queue")+ response = await self._request("GET", "/api/v1/observer/queue")return self._handle_response(response)async def _get_vikingdb_status(self) -> Dict[str, Any]:- response = await self._http.get("/api/v1/observer/vikingdb")+ response = await self._request("GET", "/api/v1/observer/vikingdb")return self._handle_response(response)async def _get_models_status(self) -> Dict[str, Any]:- response = await self._http.get("/api/v1/observer/models")+ response = await self._request("GET", "/api/v1/observer/models")return self._handle_response(response)async def _get_system_status(self) -> Dict[str, Any]:- response = await self._http.get("/api/v1/observer/system")+ response = await self._request("GET", "/api/v1/observer/system")return self._handle_response(response)async def admin_create_account(@@ -1282,18 +1393,19 @@ class AsyncHTTPClient:payload["seed"] = seedif user_config is not None:payload["user_config"] = user_config- response = await self._http.post(+ response = await self._request(+ "POST","/api/v1/admin/accounts",json=payload,)return self._handle_response(response)async def admin_list_accounts(self) -> List[Any]:- response = await self._http.get("/api/v1/admin/accounts")+ response = await self._request("GET", "/api/v1/admin/accounts")return self._handle_response(response)async def admin_delete_account(self, account_id: str) -> Dict[str, Any]:- response = await self._http.delete(f"/api/v1/admin/accounts/{account_id}")+ response = await self._request("DELETE", f"/api/v1/admin/accounts/{account_id}")return self._handle_response(response)async def admin_register_user(@@ -1309,22 +1421,26 @@ class AsyncHTTPClient:payload["seed"] = seedif user_config is not None:payload["user_config"] = user_config- response = await self._http.post(+ response = await self._request(+ "POST",f"/api/v1/admin/accounts/{account_id}/users",json=payload,)return self._handle_response(response)async def admin_list_users(self, account_id: str) -> List[Any]:- response = await self._http.get(f"/api/v1/admin/accounts/{account_id}/users")+ response = await self._request("GET", f"/api/v1/admin/accounts/{account_id}/users")return self._handle_response(response)async def admin_remove_user(self, account_id: str, user_id: str) -> Dict[str, Any]:- response = await self._http.delete(f"/api/v1/admin/accounts/{account_id}/users/{user_id}")+ response = await self._request(+ "DELETE", f"/api/v1/admin/accounts/{account_id}/users/{user_id}"+ )return self._handle_response(response)async def admin_set_role(self, account_id: str, user_id: str, role: str) -> Dict[str, Any]:- response = await self._http.put(+ response = await self._request(+ "PUT",f"/api/v1/admin/accounts/{account_id}/users/{user_id}/role",json={"role": role},)@@ -1336,14 +1452,15 @@ class AsyncHTTPClient:payload: Dict[str, Any] = {}if seed is not None:payload["seed"] = seed- response = await self._http.post(+ response = await self._request(+ "POST",f"/api/v1/admin/accounts/{account_id}/users/{user_id}/key",json=payload,)return self._handle_response(response)async def admin_migrate(self, cleanup: bool = False) -> Dict[str, Any]:- response = await self._http.post("/api/v1/admin/migrate", json={"cleanup": cleanup})+ response = await self._request("POST", "/api/v1/admin/migrate", json={"cleanup": cleanup})return self._handle_response(response)def get_status(self) -> Dict[str, Any]:@@ -1377,7 +1494,7 @@ class AsyncHTTPClient:body["author_name"] = author_nameif author_email is not None:body["author_email"] = author_email- response = await self._http.post("/api/v1/snapshot/commit", json=body)+ response = await self._request("POST", "/api/v1/snapshot/commit", json=body)return self._handle_response(response)async def git_restore(@@ -1405,7 +1522,7 @@ class AsyncHTTPClient:body["author_name"] = author_nameif author_email is not None:body["author_email"] = author_email- response = await self._http.post("/api/v1/snapshot/restore", json=body)+ response = await self._request("POST", "/api/v1/snapshot/restore", json=body)return self._handle_response(response)async def git_show(@@ -1418,7 +1535,7 @@ class AsyncHTTPClient:params: Dict[str, Any] = {"target_ref": target_ref}if path is not None:params["path"] = path- response = await self._http.get("/api/v1/snapshot/show", params=params)+ response = await self._request("GET", "/api/v1/snapshot/show", params=params)if path is None:return self._handle_response(response)@@ -1441,7 +1558,8 @@ class AsyncHTTPClient:limit: int = 20,) -> List[Dict[str, Any]]:"""Walk commit history newest-first."""- response = await self._http.get(+ response = await self._request(+ "GET","/api/v1/snapshot/log",params={"branch": branch, "limit": limit},)@@ -1449,13 +1567,14 @@ class AsyncHTTPClient:async def git_get_ignore(self) -> str:"""Return the account ``.ovgitignore`` content (empty string if absent)."""- response = await self._http.get("/api/v1/snapshot/ignore")+ response = await self._request("GET", "/api/v1/snapshot/ignore")result = self._handle_response(response)return result if isinstance(result, str) else ""async def git_set_ignore(self, *, content: str) -> None:"""Write the account ``.ovgitignore`` control file."""- response = await self._http.put(+ response = await self._request(+ "PUT","/api/v1/snapshot/ignore",json={"content": content},)@@ -1463,7 +1582,7 @@ class AsyncHTTPClient:async def git_delete_ignore(self) -> None:"""Delete the account ``.ovgitignore`` control file (missing is success)."""- response = await self._http.delete("/api/v1/snapshot/ignore")+ response = await self._request("DELETE", "/api/v1/snapshot/ignore")self._handle_response(response)@propertydiff --git a/sdk/python/openviking_sdk/config.py b/sdk/python/openviking_sdk/config.pyindex e874ef313..1fcc2f66a 100644--- a/sdk/python/openviking_sdk/config.py+++ b/sdk/python/openviking_sdk/config.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport jsonimport osfrom dataclasses import dataclass+from difflib import get_close_matchesfrom pathlib import Pathfrom typing import Optional@@ -20,6 +21,7 @@ class ClientConfig:timeout: floatprofile_enabled: boolextra_headers: dict[str, str]+ gateway_token: Optional[str]upload_mode: Optional[str]@@ -34,6 +36,7 @@ class OVCLIConfig:timeout: floatprofile: boolextra_headers: dict[str, str]+ gateway_token: Optional[str]upload_mode: Optional[str]output: Optional[str]@@ -93,6 +96,14 @@ def _parse_extra_headers(value: object, *, path: str) -> dict[str, str]:return parsed+def _unknown_field_error(path: str, key: str, allowed_keys: set[str]) -> ValueError:+ message = f"Unknown field '{path}.{key}'"+ matches = get_close_matches(key, sorted(allowed_keys), n=1, cutoff=0.6)+ if matches:+ message = f"{message}. Did you mean '{path}.{matches[0]}'?"+ return ValueError(message)++def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfig]:path = Path(config_path).expanduser() if config_path else _resolve_ovcli_config_path()if path is None or not path.exists():@@ -120,10 +131,11 @@ def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfig"extra_header","output","root_api_key",+ "gateway_token",}unknown_keys = sorted(set(data) - allowed_keys)if unknown_keys:- raise ValueError(f"Unknown field 'ovcli.{unknown_keys[0]}'")+ raise _unknown_field_error("ovcli", unknown_keys[0], allowed_keys)extra_header_alias = data.get("extra_header")extra_headers_value = data.get("extra_headers", extra_header_alias)@@ -135,7 +147,11 @@ def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfigallowed_upload_keys = {"mode", "ignore_dirs", "include", "exclude"}unknown_upload_keys = sorted(set(upload) - allowed_upload_keys)if unknown_upload_keys:- raise ValueError(f"Unknown field 'ovcli.upload.{unknown_upload_keys[0]}'")+ raise _unknown_field_error(+ "ovcli.upload",+ unknown_upload_keys[0],+ allowed_upload_keys,+ )upload_mode = _optional_string(upload.get("mode"), path="ovcli.upload.mode")actor_peer_id = _optional_string(data.get("actor_peer_id"), path="ovcli.actor_peer_id")@@ -145,7 +161,6 @@ def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfigtimeout = _optional_float(data.get("timeout"), path="ovcli.timeout")profile = _optional_bool(data.get("profile"), path="ovcli.profile")-return OVCLIConfig(url=_optional_string(data.get("url"), path="ovcli.url"),api_key=_optional_string(data.get("api_key"), path="ovcli.api_key"),@@ -156,6 +171,7 @@ def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfigtimeout=60.0 if timeout is None else timeout,profile=False if profile is None else profile,extra_headers=_parse_extra_headers(extra_headers_value, path="ovcli.extra_headers"),+ gateway_token=_optional_string(data.get("gateway_token"), path="ovcli.gateway_token"),upload_mode=upload_mode,output=_optional_string(data.get("output"), path="ovcli.output"),)@@ -210,6 +226,14 @@ def resolve_client_config(resolved_extra_headers = dict(extra_headers) if extra_headers is not None else {}if extra_headers is None and cli_config is not None:resolved_extra_headers = dict(cli_config.extra_headers)+ resolved_gateway_token = None+ if (+ cli_config is not None+ and cli_config.url+ and resolved_url+ and cli_config.url.rstrip("/") == resolved_url.rstrip("/")+ ):+ resolved_gateway_token = cli_config.gateway_tokenresolved_upload_mode = upload_modeif resolved_upload_mode is None and cli_config is not None:@@ -229,5 +253,6 @@ def resolve_client_config(timeout=resolved_timeout,profile_enabled=resolved_profile_enabled,extra_headers=resolved_extra_headers,+ gateway_token=resolved_gateway_token,upload_mode=resolved_upload_mode,)diff --git a/sdk/python/tests/test_ovcli_config_compat.py b/sdk/python/tests/test_ovcli_config_compat.pyindex ab7616f26..a923dae43 100644--- a/sdk/python/tests/test_ovcli_config_compat.py+++ b/sdk/python/tests/test_ovcli_config_compat.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport json+import httpximport pytestfrom openviking_sdk import AsyncHTTPClient@@ -13,6 +14,7 @@ def test_async_http_client_loads_connection_fields_from_ovcli_config(tmp_path, m{"url": "http://config-host:1933","api_key": "config-key",+ "gateway_token": "gateway-secret","account": "config-account","user": "config-user","timeout": 12.5,@@ -27,6 +29,8 @@ def test_async_http_client_loads_connection_fields_from_ovcli_config(tmp_path, massert client._url == "http://config-host:1933"assert client._api_key == "config-key"+ assert client._gateway_token == "gateway-secret"+ assert "X-Gateway-Token" not in client._extra_headersassert client._account == "config-account"assert client._user_id == "config-user"assert client._timeout == 12.5@@ -67,6 +71,7 @@ def test_async_http_client_explicit_arguments_override_ovcli_config(tmp_path, mo{"url": "http://config-host:1933","api_key": "config-key",+ "gateway_token": "gateway-secret","account": "config-account","user": "config-user","timeout": 12.5,@@ -88,6 +93,7 @@ def test_async_http_client_explicit_arguments_override_ovcli_config(tmp_path, mo)assert client._url == "http://explicit-host:1933"+ assert client._gateway_token is Noneassert client._api_key == "explicit-key"assert client._account == "explicit-account"assert client._user_id == "explicit-user"@@ -106,6 +112,69 @@ def test_async_http_client_reports_invalid_ovcli_config(tmp_path, monkeypatch):AsyncHTTPClient()+def test_async_http_client_does_not_override_explicit_gateway_header(tmp_path, monkeypatch):+ config_path = tmp_path / "ovcli.conf"+ config_path.write_text(+ json.dumps(+ {+ "url": "http://config-host:1933",+ "gateway_token": "gateway-secret",+ "extra_headers": {"x-gateway-token": "manual-secret"},+ }+ )+ )+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(config_path))+ monkeypatch.delenv("OPENVIKING_URL", raising=False)++ client = AsyncHTTPClient()++ assert client._extra_headers["x-gateway-token"] == "manual-secret"+ assert "X-Gateway-Token" not in client._extra_headers+++async def test_async_http_client_retries_gateway_token_only_after_marked_challenge(+ tmp_path, monkeypatch+):+ config_path = tmp_path / "ovcli.conf"+ config_path.write_text(+ json.dumps(+ {+ "url": "http://gateway.example",+ "gateway_token": "gateway-secret",+ }+ )+ )+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(config_path))+ requests = []++ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ if len(requests) == 1:+ return httpx.Response(+ 401,+ headers={"X-VikingBot-Gateway": "true"},+ json={"detail": "X-Gateway-Token header required"},+ )+ return httpx.Response(200, json={"status": "ok"})++ client = AsyncHTTPClient()+ await client.initialize()+ await client._http.aclose()+ client._http = httpx.AsyncClient(+ base_url=client._url,+ transport=httpx.MockTransport(handler),+ )+ try:+ assert await client.health() is True+ finally:+ await client.close()++ assert len(requests) == 2+ assert "X-Gateway-Token" not in requests[0].headers+ assert requests[1].headers["X-Gateway-Token"] == "gateway-secret"++def test_async_http_client_inherits_profile_enabled_from_ovcli_config(tmp_path, monkeypatch):config_path = tmp_path / "ovcli.conf"config_path.write_text(diff --git a/tests/client/test_http_client_config.py b/tests/client/test_http_client_config.pyindex ff0f32850..ee1c4ed86 100644--- a/tests/client/test_http_client_config.py+++ b/tests/client/test_http_client_config.py@@ -38,6 +38,7 @@ def test_async_http_client_loads_missing_fields_from_ovcli_config(tmp_path, monk{"url": "http://config-host:1933","api_key": "config-key",+ "gateway_token": "gateway-secret","account": "config-account","user": "config-user","actor_peer_id": "config-actor",@@ -52,6 +53,8 @@ def test_async_http_client_loads_missing_fields_from_ovcli_config(tmp_path, monkassert client._url == "http://explicit-host:1933"assert client._api_key == "config-key"+ assert client._gateway_token == "gateway-secret"+ assert client._extra_headers["X-Gateway-Token"] == "gateway-secret"assert client._account == "config-account"assert client._user_id == "config-user"assert client._actor_peer_id == "config-actor"@@ -386,9 +389,6 @@ async def test_async_http_client_find_does_not_send_peer_id(tmp_path, monkeypatc"query": "invoice","target_uri": "viking://user/memories","limit": 10,- "score_threshold": None,- "filter": None,- "context_type": None,"telemetry": False,},)@@ -442,9 +442,6 @@ async def test_async_http_client_search_does_not_send_peer_id(tmp_path, monkeypa"target_uri": "viking://user/memories","session_id": "session-1","limit": 10,- "score_threshold": None,- "filter": None,- "context_type": None,"telemetry": False,},)@@ -532,8 +529,6 @@ async def test_async_http_client_find_sends_context_type(tmp_path, monkeypatch):"query": "invoice","target_uri": "","limit": 10,- "score_threshold": None,- "filter": None,"context_type": ["memory", "resource"],"telemetry": False,},@@ -562,10 +557,7 @@ async def test_async_http_client_search_sends_context_type(tmp_path, monkeypatch{"query": "invoice","target_uri": "",- "session_id": None,"limit": 10,- "score_threshold": None,- "filter": None,"context_type": "skill","telemetry": False,},diff --git a/tests/unit/test_server_bootstrap_bot_gateway.py b/tests/unit/test_server_bootstrap_bot_gateway.pyindex 6eaa2b3bc..cc972f867 100644--- a/tests/unit/test_server_bootstrap_bot_gateway.py+++ b/tests/unit/test_server_bootstrap_bot_gateway.py@@ -120,3 +120,52 @@ def test_start_vikingbot_gateway_preserves_explicit_cli_config_env(monkeypatch,assert process is not Noneassert captured["env"][OPENVIKING_CLI_CONFIG_ENV] == str(explicit_cli_config)+++def test_start_vikingbot_gateway_passes_managed_server_runtime(monkeypatch):+ captured = {}++ monkeypatch.setattr(bootstrap.shutil, "which", lambda name: "/usr/bin/vikingbot")++ def _fake_popen(cmd, stdout=None, stderr=None, text=None, env=None):+ captured["env"] = env+ return _FakeProcess()++ monkeypatch.setattr(bootstrap.subprocess, "Popen", _fake_popen)+ monkeypatch.setattr(bootstrap.time, "sleep", lambda _: None)++ process = bootstrap._start_vikingbot_gateway(+ enable_logging=False,+ log_dir="/tmp/logs",+ managed_server_url="http://127.0.0.1:1940",+ )++ assert process is not None+ assert captured["env"]["VIKINGBOT_WITH_OPENVIKING_SERVER"] == "1"+ assert captured["env"]["VIKINGBOT_MANAGED_OV_SERVER_URL"] == "http://127.0.0.1:1940"+++def test_start_vikingbot_gateway_allows_slow_module_probe(monkeypatch):+ captured = {}++ monkeypatch.setattr(bootstrap.shutil, "which", lambda name: None)++ def _fake_run(cmd, capture_output=None, timeout=None):+ captured["probe_cmd"] = cmd+ captured["probe_timeout"] = timeout+ return type("Result", (), {"returncode": 0})()++ def _fake_popen(cmd, stdout=None, stderr=None, text=None, env=None):+ captured["cmd"] = cmd+ return _FakeProcess()++ monkeypatch.setattr(bootstrap.subprocess, "run", _fake_run)+ monkeypatch.setattr(bootstrap.subprocess, "Popen", _fake_popen)+ monkeypatch.setattr(bootstrap.time, "sleep", lambda _: None)++ process = bootstrap._start_vikingbot_gateway(enable_logging=False, log_dir="/tmp/logs")++ assert process is not None+ assert captured["probe_cmd"][1:] == ["-m", "vikingbot", "--help"]+ assert captured["probe_timeout"] == 15+ assert captured["cmd"][1:4] == ["-m", "vikingbot", "gateway"]