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):Improve VikingBot subagent delivery and configuration (#2988)
DuTao60957e1ce3f9
diff --git a/bot/README.md b/bot/README.mdindex 7874e6c87..7634f19dc 100644--- a/bot/README.md+++ b/bot/README.md@@ -176,6 +176,7 @@ All configurations are under the `bot` field in `ov.conf`, with default values f- `extra_headers`: Optional extra HTTP headers passed to the model provider.- `max_tool_iterations`: Maximum number of cycles for a single round of conversation tasks, returns results directly if exceeded- `memory_window`: Upper limit of conversation rounds for automatically submitting sessions to OpenViking+ - `subagent_enabled`: Enable the `spawn` tool so the main agent can start background subagents. Defaults to `true`; set to `false` to disable subagents.- `gen_image_model`: Model for generating images- `gateway`: Gateway configuration- `host`: Gateway listening address, default value is `0.0.0.0`@@ -215,7 +216,8 @@ All configurations are under the `bot` field in `ov.conf`, with default values f"thinking": true,"timeout": 60.0,"max_tool_iterations": 50,- "memory_window": 50+ "memory_window": 50,+ "subagent_enabled": true},"gateway": {"host": "0.0.0.0",diff --git a/bot/README_CN.md b/bot/README_CN.mdindex 05eb2ad43..adc16922b 100644--- a/bot/README_CN.md+++ b/bot/README_CN.md@@ -178,6 +178,7 @@ bot 将连接到远程 OpenViking Server,使用前请先启动 OpenViking Serv- `extra_headers`:可选,透传给模型 provider 的额外 HTTP 请求头。- `max_tool_iterations`:单轮对话任务最大循环次数,超过则直接返回结果。- `memory_window`:自动提交 session 到 OpenViking 的对话轮次上限。+ - `subagent_enabled`:是否启用 `spawn` 工具,让主 Agent 可以启动后台子 Agent。默认 `true`;设为 `false` 可禁用子 Agent。- `gen_image_model`:生成图片使用的模型。- `gateway`:Gateway 配置- host:Gateway 监听地址,默认值为 `0.0.0.0`@@ -217,7 +218,8 @@ bot 将连接到远程 OpenViking Server,使用前请先启动 OpenViking Serv"thinking": true,"timeout": 60.0,"max_tool_iterations": 50,- "memory_window": 50+ "memory_window": 50,+ "subagent_enabled": true},"gateway": {"host": "0.0.0.0",diff --git a/bot/tests/test_agent_loop_outcome.py b/bot/tests/test_agent_loop_outcome.pyindex a45d35d25..153af3b3c 100644--- a/bot/tests/test_agent_loop_outcome.py+++ b/bot/tests/test_agent_loop_outcome.py@@ -1,9 +1,14 @@import json+import sysfrom datetime import datetimefrom pathlib import Pathimport pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from vikingbot.agent import loop as loop_module+from vikingbot.agent.context import ContextBuilderfrom vikingbot.agent.loop import AgentLoopfrom vikingbot.bus.events import InboundMessage, OutboundEventTypefrom vikingbot.bus.queue import MessageBus@@ -95,6 +100,41 @@ def test_agents_config_temperature_schema_caps_at_two():assert temperature["maximum"] == 2.0+def test_agents_config_enables_subagents_by_default():+ assert AgentsConfig().subagent_enabled is True+++def test_agent_loop_omits_spawn_tool_when_subagents_disabled(temp_dir: Path, monkeypatch):+ monkeypatch.setattr(AgentLoop, "_register_builtin_hooks", lambda self: None)+ monkeypatch.setattr("vikingbot.agent.loop.SubagentManager", _FakeSubagentManager)++ bus = 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,+ provider=provider,+ workspace=temp_dir / "workspace",+ model=config.agents.model,+ temperature=config.agents.temperature,+ config=config,+ )++ assert "spawn" not in loop.tools.tool_names+++async def test_context_prompt_omits_subagent_capability_when_disabled(temp_dir: Path):+ context = ContextBuilder(workspace=temp_dir / "workspace", enable_subagents=False)+ session_key = SessionKey(type="cli", channel_id="default", chat_id="session-1")++ prompt = await context._get_identity(session_key)++ assert "Spawn subagents" not in prompt++@pytest.mark.asyncioasync def test_agent_loop_passes_configured_temperature_to_provider(temp_dir: Path, monkeypatch):monkeypatch.setattr(AgentLoop, "_register_builtin_hooks", lambda self: None)diff --git a/bot/tests/test_channel_delivery_metadata.py b/bot/tests/test_channel_delivery_metadata.pyindex 5d643564f..c2f723932 100644--- a/bot/tests/test_channel_delivery_metadata.py+++ b/bot/tests/test_channel_delivery_metadata.py@@ -10,12 +10,15 @@ import pytestsys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from vikingbot.agent.loop import AgentLoop # noqa: E402+from vikingbot.agent.subagent import SubagentManager # noqa: E402from vikingbot.agent.tools.cron import CronTool # noqa: E402from vikingbot.agent.tools.message import MessageTool # noqa: E402-from vikingbot.bus.events import OutboundMessage # noqa: E402+from vikingbot.agent.tools.spawn import SpawnTool # noqa: E402+from vikingbot.bus.events import InboundMessage, OutboundMessage # noqa: E402from vikingbot.bus.queue import MessageBus # noqa: E402from vikingbot.channels.feishu import FeishuChannel # noqa: E402-from vikingbot.config.schema import FeishuChannelConfig, SessionKey # noqa: E402+from vikingbot.config.schema import Config, FeishuChannelConfig, SessionKey # noqa: E402from vikingbot.cron.service import CronService # noqa: E402from vikingbot.cron.types import CronSchedule # noqa: E402@@ -41,6 +44,100 @@ async def test_message_tool_preserves_channel_metadata():assert sent[0].metadata is not metadata+async def test_spawn_tool_preserves_channel_metadata():+ metadata = {"reply_to": "oc_chat", "chat_type": "group", "message_id": "om_old"}+ calls = []++ class FakeSubagentManager:+ async def spawn(self, **kwargs):+ calls.append(kwargs)+ return "started"++ tool = SpawnTool(manager=FakeSubagentManager())+ context = SimpleNamespace(+ session_key=SessionKey(type="feishu", channel_id="cli_app", chat_id="oc_chat"),+ channel_metadata=metadata,+ )++ result = await tool.execute(context, task="read files", label="read")++ assert result == "started"+ assert calls[0]["channel_metadata"] == metadata+++async def test_subagent_announcement_preserves_channel_metadata(tmp_path):+ bus = MessageBus()+ metadata = {"reply_to": "oc_chat", "chat_type": "group", "message_id": "om_old"}+ session_key = SessionKey(type="feishu", channel_id="cli_app", chat_id="oc_chat")+ manager = SubagentManager(+ provider=SimpleNamespace(get_default_model=lambda: "fake-model"),+ workspace=tmp_path,+ bus=bus,+ config=SimpleNamespace(),+ )++ await manager._announce_result(+ "task-id",+ "read",+ "read files",+ "done",+ session_key,+ "ok",+ metadata,+ )++ inbound = await bus.consume_inbound()+ assert inbound.metadata == metadata+ assert inbound.metadata is not metadata+++async def test_system_message_response_preserves_channel_metadata(tmp_path, monkeypatch):+ monkeypatch.setattr(AgentLoop, "_register_builtin_hooks", lambda self: None)+ monkeypatch.setattr(AgentLoop, "_register_default_tools", lambda self: None)+ monkeypatch.setattr("vikingbot.agent.loop.SubagentManager", lambda **kwargs: SimpleNamespace())++ metadata = {"reply_to": "oc_chat", "chat_type": "group", "message_id": "om_old"}+ session_key = SessionKey(type="feishu", channel_id="cli_app", chat_id="oc_chat")+ config = Config(storage_workspace=str(tmp_path / "data"))+ loop = AgentLoop(+ bus=MessageBus(),+ provider=SimpleNamespace(get_default_model=lambda: "fake-model"),+ workspace=tmp_path / "workspace",+ model=config.agents.model,+ temperature=config.agents.temperature,+ config=config,+ )++ async def fake_build_prompt_history(*args, **kwargs):+ return []++ async def fake_build_messages(**kwargs):+ return [{"role": "user", "content": kwargs["current_message"]}]++ async def fake_run_agent_loop(**kwargs):+ return "summary", None, [], {}, 1++ loop._build_prompt_history = fake_build_prompt_history+ loop.context = SimpleNamespace(build_messages=fake_build_messages)+ loop._run_agent_loop = fake_run_agent_loop++ outbound = await loop._process_system_message(+ InboundMessage(+ sender_id="subagent",+ session_key=session_key,+ content="subagent done",+ metadata=metadata,+ )+ )++ assert outbound.content == "summary"+ assert outbound.metadata == metadata+ assert outbound.metadata is not metadata++@pytest.mark.asyncioasync def test_cron_tool_persists_only_delivery_metadata(tmp_path):service = CronService(tmp_path / "jobs.json")diff --git a/bot/tests/test_subagent_skills_context.py b/bot/tests/test_subagent_skills_context.pynew file mode 100644index 000000000..7062739a1--- /dev/null+++ b/bot/tests/test_subagent_skills_context.py@@ -0,0 +1,124 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Regression tests for subagent prompt skill loading."""++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.subagent import SubagentManager # noqa: E402+from vikingbot.bus.queue import MessageBus # noqa: E402+++def _write_skill(workspace: Path, name: str, content: str) -> None:+ skill_dir = workspace / "skills" / name+ skill_dir.mkdir(parents=True)+ (skill_dir / "SKILL.md").write_text(content, encoding="utf-8")+++def test_subagent_prompt_loads_local_skills(tmp_path):+ _write_skill(+ tmp_path,+ "always-skill",+ """---+description: Always active instructions+always: true+---+# Always Skill++Always-loaded instruction.+""",+ )+ _write_skill(+ tmp_path,+ "normal-skill",+ """---+description: Normal on-demand instructions+---+# Normal Skill++Read this only when needed.+""",+ )++ manager = SubagentManager(+ provider=SimpleNamespace(get_default_model=lambda: "fake-model"),+ workspace=tmp_path,+ bus=MessageBus(),+ config=SimpleNamespace(),+ )++ prompt = manager._build_subagent_prompt("inspect local files")++ assert "# Active Skills" in prompt+ assert "### Skill: always-skill" in prompt+ assert "Always-loaded instruction." in prompt+ assert "description: Always active instructions" not in prompt+ assert "# Skills" in prompt+ assert "<name>normal-skill</name>" in prompt+ assert "<description>Normal on-demand instructions</description>" in prompt+ assert "<location>skills/normal-skill/SKILL.md</location>" in prompt+++async def test_subagent_prompt_loads_skills_from_session_workspace(tmp_path):+ source_workspace = tmp_path / "source"+ session_workspace = tmp_path / "sandboxes" / "session"+ _write_skill(+ source_workspace,+ "global-skill",+ """---+description: Global instructions+always: true+---+# Global Skill++Global-loaded instruction.+""",+ )+ _write_skill(+ session_workspace,+ "session-skill",+ """---+description: Session instructions+always: true+---+# Session Skill++Session-loaded instruction.+""",+ )++ class FakeSandboxManager:+ def __init__(self):+ self.created_for = []++ async def get_sandbox(self, session_key):+ self.created_for.append(session_key)+ return SimpleNamespace()++ def get_workspace_path(self, session_key):+ return session_workspace++ sandbox_manager = FakeSandboxManager()+ manager = SubagentManager(+ provider=SimpleNamespace(get_default_model=lambda: "fake-model"),+ workspace=source_workspace,+ bus=MessageBus(),+ config=SimpleNamespace(),+ sandbox_manager=sandbox_manager,+ )+ session_key = SimpleNamespace()++ prompt_workspace = await manager._get_session_workspace(session_key)+ prompt = manager._build_subagent_prompt("inspect local files", workspace=prompt_workspace)++ assert sandbox_manager.created_for == [session_key]+ assert f"Your workspace is at: {session_workspace}" in prompt+ assert "### Skill: session-skill" in prompt+ assert "Session-loaded instruction." in prompt+ assert "Global-loaded instruction." not in promptdiff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.pyindex 735c7e565..3d4a1b086 100644--- a/bot/vikingbot/agent/context.py+++ b/bot/vikingbot/agent/context.py@@ -37,6 +37,7 @@ class ContextBuilder:is_group_chat: bool = False,eval: bool = False,openviking_connection: dict[str, Any] | None = None,+ enable_subagents: bool = True,):self.workspace = workspaceself._templates_ensured = False@@ -48,6 +49,7 @@ class ContextBuilder:self._is_group_chat = is_group_chatself._eval = evalself._openviking_connection = openviking_connection+ self._enable_subagents = enable_subagentsself.latest_relevant_memories: str | None = None@property@@ -288,17 +290,23 @@ Skills with available="false" need dependencies installed first - you can try inelse:workspace_display = workspace_path+ capabilities = [+ "- Read, search, and grep OpenViking files",+ "- Read, write, and edit local files",+ "- Execute shell commands",+ "- Search the web and fetch web pages",+ "- Send messages to users on chat channels",+ ]+ if self._enable_subagents:+ capabilities.append("- Spawn subagents for complex background tasks")+ capabilities_text = "\n".join(capabilities)+return f"""# vikingbot 🐈You are VikingBot, an AI assistant built based on the OpenViking context database.When acquiring information, data, and knowledge, you **prioritize using openviking tools to read and search OpenViking (a context database) above all other sources**.You have access to tools that allow you to:-- Read, search, and grep OpenViking files-- Read, write, and edit local files-- Execute shell commands-- Search the web and fetch web pages-- Send messages to users on chat channels-- Spawn subagents for complex background tasks+{capabilities_text}## Runtime{runtime}diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex 64d0ddcaa..7616715ab 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -171,7 +171,11 @@ class AgentLoop:self.sandbox_manager = sandbox_managerself.config = config- self.context = ContextBuilder(workspace, sandbox_manager=sandbox_manager)+ self.context = ContextBuilder(+ workspace,+ sandbox_manager=sandbox_manager,+ enable_subagents=self._subagents_enabled(),+ )self._register_builtin_hooks()self.sessions = session_manager or SessionManager(@@ -371,8 +375,13 @@ class AgentLoop:send_callback=self.bus.publish_outbound,subagent_manager=self.subagents,cron_service=self.cron_service,+ include_spawn_tool=self._subagents_enabled(),)+ def _subagents_enabled(self) -> bool:+ agents_config = getattr(self.config, "agents", None)+ return bool(getattr(agents_config, "subagent_enabled", True))+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))@@ -1231,6 +1240,7 @@ class AgentLoop:is_group_chat=is_group_chat,eval=self._eval,openviking_connection=openviking_connection,+ enable_subagents=self._subagents_enabled(),)# Build initial messages (use OpenViking session context when enabled)@@ -1588,7 +1598,11 @@ class AgentLoop:)await self.sessions.save(session)- return OutboundMessage(session_key=msg.session_key, content=final_content)+ return OutboundMessage(+ session_key=msg.session_key,+ content=final_content,+ metadata=dict(msg.metadata or {}),+ )async def _consolidate_memory(self, session, archive_all: bool = False) -> None:"""Consolidate old messages into MEMORY.md + HISTORY.md. Works on a cloned session."""diff --git a/bot/vikingbot/agent/subagent.py b/bot/vikingbot/agent/subagent.pyindex ca08aa13e..6101eed3a 100644--- a/bot/vikingbot/agent/subagent.py+++ b/bot/vikingbot/agent/subagent.py@@ -52,6 +52,7 @@ class SubagentManager:task: str,session_key: SessionKey,label: str | None = None,+ channel_metadata: dict[str, Any] | None = None,) -> str:"""Spawn a subagent to execute a task in the background.@@ -69,7 +70,15 @@ class SubagentManager:display_label = label or task[:30] + ("..." if len(task) > 30 else "")# Create background task- bg_task = asyncio.create_task(self._run_subagent(task_id, task, display_label, session_key))+ bg_task = asyncio.create_task(+ self._run_subagent(+ task_id,+ task,+ display_label,+ session_key,+ dict(channel_metadata or {}),+ )+ )self._running_tasks[task_id] = bg_task# Cleanup when done@@ -79,7 +88,12 @@ class SubagentManager:return f"Subagent [{display_label}] started (id: {task_id}). I'll notify you when it completes."async def _run_subagent(- self, task_id: str, task: str, label: str, session_key: SessionKey+ self,+ task_id: str,+ task: str,+ label: str,+ session_key: SessionKey,+ channel_metadata: dict[str, Any] | None = None,) -> None:"""Execute the subagent task and announce the result."""logger.info(f"Subagent [{task_id}] starting task: {label}")@@ -113,7 +127,8 @@ class SubagentManager:logger.warning(f"Subagent [{task_id}] failed to load experience memory: {e}")# Build messages with subagent-specific prompt- system_prompt = self._build_subagent_prompt(task)+ prompt_workspace = await self._get_session_workspace(session_key)+ system_prompt = self._build_subagent_prompt(task, workspace=prompt_workspace)messages: list[dict[str, Any]] = [{"role": "system", "content": system_prompt},{"role": "user", "content": task_content},@@ -183,12 +198,16 @@ class SubagentManager:final_result = "Task completed but no final response was generated."logger.info(f"Subagent [{task_id}] completed successfully")- await self._announce_result(task_id, label, task, final_result, session_key, "ok")+ await self._announce_result(+ task_id, label, task, final_result, session_key, "ok", channel_metadata+ )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")+ await self._announce_result(+ task_id, label, task, error_msg, session_key, "error", channel_metadata+ )async def _announce_result(self,@@ -198,6 +217,7 @@ class SubagentManager:result: str,session_key: SessionKey,status: str,+ channel_metadata: 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"@@ -216,20 +236,31 @@ Summarize this naturally for the user. Keep it brief (1-2 sentences). Do not mensender_id="subagent",session_key=session_key,content=announce_content,+ metadata=dict(channel_metadata or {}),)await self.bus.publish_inbound(msg)logger.debug(f"Subagent [{task_id}] announced result to {session_key}")- def _build_subagent_prompt(self, task: str) -> str:+ async def _get_session_workspace(self, session_key: SessionKey) -> Path:+ """Return the workspace path used by tools for this subagent session."""+ if not self.sandbox_manager:+ return self.workspace++ await self.sandbox_manager.get_sandbox(session_key)+ return self.sandbox_manager.get_workspace_path(session_key)++ def _build_subagent_prompt(self, task: str, workspace: Path | None = None) -> str:"""Build a focused system prompt for the subagent."""from datetime import datetimeimport time as _time+ workspace = workspace or self.workspacenow = datetime.now().strftime("%Y-%m-%d %H:%M (%A)")tz = _time.strftime("%Z") or "UTC"+ skills_context = self._build_subagent_skills_context(workspace)- return f"""# Subagent+ prompt = f"""# Subagent## Current Time{now} ({tz})@@ -254,10 +285,54 @@ You are a subagent spawned by the main agent to complete a specific task.- Access the main agent's conversation history## Workspace-Your workspace is at: {self.workspace}-Skills are available at: {self.workspace}/skills/ (read SKILL.md files as needed)+Your workspace is at: {workspace}+Skills are available at: {workspace}/skills/ (read SKILL.md files as needed)When you have completed the task, provide a clear summary of your findings or actions."""+ if skills_context:+ prompt = f"{prompt}\n\n{skills_context}"+ return prompt++ def _build_subagent_skills_context(self, workspace: Path | None = None) -> str:+ """Build the same local skills context format used by the main agent."""+ try:+ from vikingbot.agent.skills import SkillsLoader++ workspace = workspace or self.workspace+ skills = SkillsLoader(workspace)+ parts: list[str] = []++ always_skills = skills.get_always_skills()+ if always_skills:+ always_content = skills.load_skills_for_context(always_skills)+ if always_content:+ parts.append(f"# Active Skills\n\n{always_content}")++ skills_summary = skills.build_skills_summary()+ if skills_summary:+ required_skill_note = ""+ required_skill_candidates = [+ "skills/experience_loader/SKILL.md",+ "skills/task_case_experience/SKILL.md",+ ]+ for skill_path in required_skill_candidates:+ if (workspace / skill_path).exists():+ required_skill_note = (+ "\nRequired skill: before taking any task action, you MUST read "+ f"`{skill_path}` and apply its instructions.\n"+ )+ break+ parts.append(f"""# Skills++The following skills extend your capabilities. To use a skill, read its SKILL.md file using the read_file tool.+Skills with available="false" need dependencies installed first - you can try installing them with apt/brew.+{required_skill_note}+{skills_summary}""")++ return "\n\n".join(parts)+ except Exception as e:+ logger.warning(f"Failed to build subagent skills context: {e}")+ return ""def get_running_count(self) -> int:"""Return the number of currently running subagents."""diff --git a/bot/vikingbot/agent/tools/spawn.py b/bot/vikingbot/agent/tools/spawn.pyindex da4dded71..42cec5cef 100644--- a/bot/vikingbot/agent/tools/spawn.py+++ b/bot/vikingbot/agent/tools/spawn.py@@ -56,4 +56,5 @@ class SpawnTool(Tool):task=task,label=label,session_key=tool_context.session_key,+ channel_metadata=tool_context.channel_metadata,)diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.pyindex a610879e4..405bca4f4 100644--- a/bot/vikingbot/config/schema.py+++ b/bot/vikingbot/config/schema.py@@ -456,6 +456,10 @@ class AgentsConfig(BaseModel):)max_tool_iterations: int = 50memory_window: int = 50+ subagent_enabled: bool = Field(+ default=True,+ description="Enable the spawn tool so the main agent can start background subagents.",+ )session_context_enabled: bool = Falsesession_context_token_budget: int = 3000commit_token_threshold: int = 200000