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
修复bot 主动发消息、CORN消息、image消息,属性异常的问题 (#2924)
DuTao360795ba2933
diff --git a/bot/tests/test_channel_delivery_metadata.py b/bot/tests/test_channel_delivery_metadata.pynew file mode 100644index 000000000..2facc37d1--- /dev/null+++ b/bot/tests/test_channel_delivery_metadata.py@@ -0,0 +1,117 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Regression tests for preserving channel delivery metadata."""++import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from vikingbot.agent.tools.cron import CronTool # noqa: E402+from vikingbot.agent.tools.message import MessageTool # noqa: E402+from vikingbot.bus.events import OutboundMessage # noqa: E402+from vikingbot.bus.queue import MessageBus # noqa: E402+from vikingbot.channels.feishu import FeishuChannel # noqa: E402+from vikingbot.config.schema import FeishuChannelConfig, SessionKey # noqa: E402+from vikingbot.cron.service import CronService # noqa: E402+from vikingbot.cron.types import CronSchedule # noqa: E402+++async def test_message_tool_preserves_channel_metadata():+ sent = []+ metadata = {"reply_to": "oc_chat", "chat_type": "group", "message_id": "om_old"}++ async def send_callback(msg: OutboundMessage) -> None:+ sent.append(msg)++ tool = MessageTool(send_callback=send_callback)+ context = SimpleNamespace(+ session_key=SessionKey(type="feishu", channel_id="cli_app", chat_id="oc_chat"),+ channel_metadata=metadata,+ )++ result = await tool.execute(context, content="hello")++ assert result.startswith("Message sent")+ assert sent[0].metadata == metadata+ assert sent[0].metadata is not metadata+++async def test_cron_tool_persists_only_delivery_metadata(tmp_path):+ service = CronService(tmp_path / "jobs.json")+ tool = CronTool(service)+ context = SimpleNamespace(+ session_key=SessionKey(type="feishu", channel_id="cli_app", chat_id="oc_chat"),+ channel_metadata={+ "reply_to": "oc_chat",+ "chat_type": "group",+ "chat_mode": "thread",+ "root_id": "om_root",+ "sender_id": "ou_sender",+ "message_id": "om_should_not_be_persisted",+ },+ )++ result = await tool.execute(+ context,+ action="add",+ name="standup",+ message="time for standup",+ every_seconds=3600,+ )++ assert result.startswith("Created job")+ loaded = CronService(tmp_path / "jobs.json").list_jobs()+ assert len(loaded) == 1+ assert loaded[0].payload.channel_metadata == {+ "reply_to": "oc_chat",+ "chat_type": "group",+ "chat_mode": "thread",+ "root_id": "om_root",+ "sender_id": "ou_sender",+ }+++def test_cron_service_accepts_missing_channel_metadata(tmp_path):+ service = CronService(tmp_path / "jobs.json")+ job = service.add_job(+ name="cli-job",+ schedule=CronSchedule(kind="every", every_ms=3600),+ message="hello",+ session_key=SessionKey(type="cli", channel_id="default", chat_id="default"),+ deliver=True,+ )++ assert job.payload.channel_metadata == {}+++def test_feishu_uses_thread_root_for_scheduled_delivery():+ assert (+ FeishuChannel._reply_to_message_id_from_metadata(+ {+ "reply_to": "oc_chat",+ "chat_type": "group",+ "chat_mode": "thread",+ "root_id": "om_root",+ }+ )+ == "om_root"+ )+++async def test_feishu_send_skips_normal_message_without_reply_to():+ channel = FeishuChannel(FeishuChannelConfig(app_id="cli_app"), MessageBus())+ channel._client = object()++ await channel.send(+ OutboundMessage(+ session_key=SessionKey(type="feishu", channel_id="cli_app", chat_id="oc_chat"),+ content="hello",+ )+ )diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex 7d9cbebfb..94f51d188 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -657,6 +657,7 @@ class AgentLoop:memory_owner_user_ids: list[str] | None = None,disabled_tools: list[str] | None = None,openviking_connection: dict[str, Any] | None = None,+ channel_metadata: dict[str, Any] | None = None,) -> tuple[str | None, str | None, list[dict], dict[str, int], int]:"""Run the core agent loop: call LLM, execute tools, repeat until done.@@ -671,6 +672,7 @@ class AgentLoop:trusted-mode owner-user memory lookupdisabled_tools: Tool names to hide from the model for this requestopenviking_connection: Request-scoped OpenViking identity for tools+ channel_metadata: Channel-specific metadata for tools that publish outbound messagesReturns:tuple of (final_content, final_reasoning_content, tools_used, token_usage, iteration)@@ -799,6 +801,7 @@ class AgentLoop:memory_peer_ids=memory_peer_ids,memory_owner_user_ids=memory_owner_user_ids,openviking_connection=openviking_connection,+ channel_metadata=channel_metadata,)tool_execute_duration = (time.time() - tool_execute_start_time) * 1000return idx, tool_call, result, tool_execute_duration@@ -1177,6 +1180,7 @@ class AgentLoop:memory_owner_user_ids=memory_owner_user_ids,disabled_tools=disabled_tools,openviking_connection=openviking_connection,+ channel_metadata=msg.metadata,)if auto_memory_tool:@@ -1439,6 +1443,7 @@ class AgentLoop:publish_events=False,ov_tools_enable=ov_tools_enable,memory_peer_ids=None,+ channel_metadata=msg.metadata,)if final_content is None or (isinstance(final_content, str) and not final_content.strip()):diff --git a/bot/vikingbot/agent/tools/base.py b/bot/vikingbot/agent/tools/base.pyindex 533407995..1ee3ed4f6 100644--- a/bot/vikingbot/agent/tools/base.py+++ b/bot/vikingbot/agent/tools/base.py@@ -31,6 +31,8 @@ class ToolContext:openviking_connection: Optional request-scoped OpenViking identity. Studiorequests use this so tools call OpenViking with the same connectionselected in the browser.+ channel_metadata: Channel-specific metadata from the inbound message. Tools+ that publish outbound messages can reuse this to preserve delivery context.Example:>>> context = ToolContext(@@ -48,12 +50,15 @@ class ToolContext:memory_owner_user_ids: list[str] | None = Nonememory_user_ids: list[str] | None = None # Deprecated alias for memory_owner_user_ids.openviking_connection: dict[str, Any] | None = None+ channel_metadata: dict[str, Any] | None = Nonedef __post_init__(self) -> None:if self.memory_owner_user_ids is None and self.memory_user_ids is not None:self.memory_owner_user_ids = self.memory_user_idselif self.memory_user_ids is None and self.memory_owner_user_ids is not None:self.memory_user_ids = self.memory_owner_user_ids+ if self.channel_metadata is None:+ self.channel_metadata = {}class Tool(ABC):diff --git a/bot/vikingbot/agent/tools/cron.py b/bot/vikingbot/agent/tools/cron.pyindex ff8b96492..80c630b53 100644--- a/bot/vikingbot/agent/tools/cron.py+++ b/bot/vikingbot/agent/tools/cron.py@@ -1,15 +1,21 @@"""Cron tool for scheduling reminders and tasks."""-from typing import Any+from typing import TYPE_CHECKING, Anyfrom vikingbot.agent.tools.base import Toolfrom vikingbot.cron.service import CronServicefrom vikingbot.cron.types import CronSchedule+if TYPE_CHECKING:+ from vikingbot.agent.tools.base import ToolContext+ from vikingbot.config.schema import SessionKey+class CronTool(Tool):"""Tool to schedule reminders and recurring tasks."""+ DELIVERY_METADATA_KEYS = ("reply_to", "chat_type", "chat_mode", "root_id", "sender_id")+def __init__(self, cron_service: CronService):self._cron = cron_service@@ -64,7 +70,13 @@ class CronTool(Tool):) -> str:if action == "add":return self._add_job(- name, message, every_seconds, cron_expr, at, tool_context.session_key+ name,+ message,+ every_seconds,+ cron_expr,+ at,+ tool_context.session_key,+ self._delivery_metadata(getattr(tool_context, "channel_metadata", None)),)elif action == "list":return self._list_jobs()@@ -80,6 +92,7 @@ class CronTool(Tool):cron_expr: str | None,at: str | None,session_key: "SessionKey",+ channel_metadata: dict[str, Any] | None = None,) -> str:if not message:return "Error: message is required for add"@@ -106,10 +119,20 @@ class CronTool(Tool):message=message,deliver=True,session_key=session_key,+ channel_metadata=channel_metadata,delete_after_run=delete_after,)return f"Created job '{job.name}' (id: {job.id})"+ def _delivery_metadata(self, metadata: dict[str, Any] | None) -> dict[str, Any]:+ if not metadata:+ return {}+ return {+ key: metadata[key]+ for key in self.DELIVERY_METADATA_KEYS+ if isinstance(metadata.get(key), str) and metadata[key]+ }+def _list_jobs(self) -> str:jobs = self._cron.list_jobs()if not jobs:diff --git a/bot/vikingbot/agent/tools/image.py b/bot/vikingbot/agent/tools/image.pyindex c3d35b208..1757810d4 100644--- a/bot/vikingbot/agent/tools/image.py+++ b/bot/vikingbot/agent/tools/image.py@@ -298,7 +298,11 @@ class ImageGenerationTool(Tool):if send_to_user and self._send_callback:try:msg_content = "\n".join([f"send://{f}" for f in saved_filenames])- msg = OutboundMessage(session_key=tool_context.session_key, content=msg_content)+ msg = OutboundMessage(+ session_key=tool_context.session_key,+ content=msg_content,+ metadata=dict(getattr(tool_context, "channel_metadata", None) or {}),+ )await self._send_callback(msg)sent_to_user = Trueexcept Exception as e:diff --git a/bot/vikingbot/agent/tools/message.py b/bot/vikingbot/agent/tools/message.pyindex 9a6db75b2..ff0117ecb 100644--- a/bot/vikingbot/agent/tools/message.py+++ b/bot/vikingbot/agent/tools/message.py@@ -1,10 +1,12 @@"""Message tool for sending messages to users."""-from typing import Any, Callable, Awaitable+from typing import TYPE_CHECKING, Any, Awaitable, Callablefrom vikingbot.agent.tools.base import Toolfrom vikingbot.bus.events import OutboundMessage-from vikingbot.config.schema import SessionKey++if TYPE_CHECKING:+ from vikingbot.agent.tools.base import ToolContextclass MessageTool(Tool):@@ -39,14 +41,16 @@ class MessageTool(Tool):}async def execute(self, tool_context: "ToolContext", **kwargs: Any) -> str:- from loguru import logger-content = kwargs.get("content")if not self._send_callback:return "Error: Message sending not configured"- msg = OutboundMessage(session_key=tool_context.session_key, content=content)+ msg = OutboundMessage(+ session_key=tool_context.session_key,+ content=content,+ metadata=dict(getattr(tool_context, "channel_metadata", None) or {}),+ )try:await self._send_callback(msg)diff --git a/bot/vikingbot/agent/tools/registry.py b/bot/vikingbot/agent/tools/registry.pyindex 93a6fbbeb..5a1088310 100644--- a/bot/vikingbot/agent/tools/registry.py+++ b/bot/vikingbot/agent/tools/registry.py@@ -144,6 +144,7 @@ class ToolRegistry:memory_owner_user_ids: list[str] | None = None,memory_user_ids: list[str] | None = None,openviking_connection: dict[str, Any] | None = None,+ channel_metadata: dict[str, Any] | None = None,) -> str:"""Execute a tool by name with given parameters.@@ -159,6 +160,7 @@ class ToolRegistry:trusted-mode owner-user memory lookup.memory_user_ids: Deprecated alias for memory_owner_user_ids.openviking_connection: Request-scoped OpenViking identity.+ channel_metadata: Channel-specific metadata from the inbound message.Returns:Tool execution result as string.@@ -178,6 +180,7 @@ class ToolRegistry:memory_owner_user_ids=memory_owner_user_ids,memory_user_ids=memory_user_ids,openviking_connection=openviking_connection,+ channel_metadata=dict(channel_metadata or {}),)# Langfuse tool call tracing - automatic for all toolsdiff --git a/bot/vikingbot/channels/feishu.py b/bot/vikingbot/channels/feishu.pyindex 22ed24305..231e629f6 100644--- a/bot/vikingbot/channels/feishu.py+++ b/bot/vikingbot/channels/feishu.py@@ -555,6 +555,11 @@ class FeishuChannel(BaseChannel):# Determine receive_id_type based on chat_id format# open_id starts with "ou_", chat_id starts with "oc_"reply_to = msg.metadata.get("reply_to")+ if not isinstance(reply_to, str) or not reply_to:+ logger.warning(+ f"Skipping Feishu message without reply_to metadata: session={msg.session_key}"+ )+ returnif reply_to.startswith("oc_"):receive_id_type = "chat_id"else:@@ -566,13 +571,10 @@ class FeishuChannel(BaseChannel):content_with_mentions = cleaned_content# --- Build interactive card with markdown rendering ---- reply_to_message_id = Noneoriginal_sender_id = Nonechat_type = "group"+ reply_to_message_id = self._reply_to_message_id_from_metadata(msg.metadata)if msg.metadata:- reply_to_message_id = msg.metadata.get("reply_to_message_id") or msg.metadata.get(- "message_id"- )original_sender_id = msg.metadata.get("sender_id")chat_type = msg.metadata.get("chat_type", "group")@@ -665,6 +667,23 @@ class FeishuChannel(BaseChannel):except Exception as e:logger.exception(f"Error sending Feishu message: {e}")+ @staticmethod+ def _reply_to_message_id_from_metadata(metadata: dict[str, Any] | None) -> str | None:+ """Resolve the Feishu message id to reply to, including scheduled thread delivery."""+ if not metadata:+ return None++ for key in ("reply_to_message_id", "message_id"):+ value = metadata.get(key)+ if isinstance(value, str) and value:+ return value++ root_id = metadata.get("root_id")+ if metadata.get("chat_mode") == "thread" and isinstance(root_id, str) and root_id:+ return root_id++ return None+@staticmethoddef _should_reply_in_thread(metadata: dict[str, Any] | None,diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.pyindex 65c075fbd..2b6568fac 100644--- a/bot/vikingbot/cli/commands.py+++ b/bot/vikingbot/cli/commands.py@@ -482,6 +482,7 @@ def prepare_cron(bus, quiet: bool = False) -> CronService:"""Execute a cron job through the agent."""session_key = SessionKey(**json.loads(job.payload.session_key_str))message = job.payload.message+ channel_metadata = dict(job.payload.channel_metadata or {})if agent_holder["agent"] is None:raise RuntimeError("Agent not initialized yet")@@ -504,6 +505,7 @@ Reminder message to deliver:response = await agent_holder["agent"].process_direct(cron_instruction,session_key=session_key,+ metadata=channel_metadata,)if job.payload.deliver:from vikingbot.bus.events import OutboundMessage@@ -512,6 +514,7 @@ Reminder message to deliver:OutboundMessage(session_key=session_key,content=response or "",+ metadata=channel_metadata,))return responsediff --git a/bot/vikingbot/cron/service.py b/bot/vikingbot/cron/service.pyindex 20ed25c03..7a390a24b 100644--- a/bot/vikingbot/cron/service.py+++ b/bot/vikingbot/cron/service.py@@ -17,6 +17,10 @@ def _now_ms() -> int:return int(time.time() * 1000)+def _dict_or_empty(value: Any) -> dict[str, Any]:+ return value if isinstance(value, dict) else {}++def _compute_next_run(schedule: CronSchedule, now_ms: int) -> int | None:"""Compute next run time in ms."""if schedule.kind == "at":@@ -82,6 +86,9 @@ class CronService:message=j["payload"].get("message", ""),deliver=j["payload"].get("deliver", False),session_key_str=j["payload"].get("session_key_str"),+ channel_metadata=_dict_or_empty(+ j["payload"].get("channel_metadata")+ ),),state=CronJobState(next_run_at_ms=j.get("state", {}).get("nextRunAtMs"),@@ -129,6 +136,7 @@ class CronService:"message": j.payload.message,"deliver": j.payload.deliver,"session_key_str": j.payload.session_key_str,+ "channel_metadata": j.payload.channel_metadata,},"state": {"nextRunAtMs": j.state.next_run_at_ms,@@ -225,9 +233,8 @@ class CronService:logger.info(f"Cron: executing job '{job.name}' ({job.id})")try:- response = Noneif self.on_job:- response = await self.on_job(job)+ await self.on_job(job)job.state.last_status = "ok"job.state.last_error = None@@ -267,6 +274,7 @@ class CronService:message: str,session_key: SessionKey,deliver: bool = False,+ channel_metadata: dict[str, Any] | None = None,delete_after_run: bool = False,) -> CronJob:"""Add a new job."""@@ -283,6 +291,7 @@ class CronService:message=message,deliver=deliver,session_key_str=session_key.model_dump_json(),+ channel_metadata=dict(_dict_or_empty(channel_metadata)),),state=CronJobState(next_run_at_ms=_compute_next_run(schedule, now)),created_at_ms=now,diff --git a/bot/vikingbot/cron/types.py b/bot/vikingbot/cron/types.pyindex 3e7a7d721..e6f71f47e 100644--- a/bot/vikingbot/cron/types.py+++ b/bot/vikingbot/cron/types.py@@ -1,9 +1,7 @@"""Cron types."""from dataclasses import dataclass, field-from typing import Literal--from vikingbot.config.schema import SessionKey+from typing import Any, Literal@dataclass@@ -30,6 +28,7 @@ class CronPayload:# Deliver response to channeldeliver: bool = Falsesession_key_str: str | None = None # e.g. "whatsapp"+ channel_metadata: dict[str, Any] = field(default_factory=dict)@dataclass