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
调整定时任务 (#5106)
DuTao32b99a12d0d0
diff --git a/bot/README.md b/bot/README.mdindex 009b090ea..9f19f0f84 100644--- a/bot/README.md+++ b/bot/README.md@@ -411,6 +411,28 @@ For the complete loading order, file responsibilities, and customization boundar`readonly` mode does not register `openviking_add_resource`. When a channel sets `ov_tools_enable: false`, it does not expose OpenViking tools or inject Profiles, Memories, and Experiences.+### Scheduled Task Configuration++Scheduled tasks are disabled by default. Set `bot.tools.cron.enabled` to `true` in `ov.conf` to enable them:++```json+{+ "bot": {+ "tools": {+ "cron": {+ "enabled": true+ }+ }+ }+}+```++This switch controls both `cron` tool registration and the scheduler in Gateway and local Chat modes. When set to `false` or omitted, the tool is not registered and the scheduler does not start. Existing jobs remain on disk but do not run automatically.++Restart the Bot after changing this setting. Existing deployments must explicitly set `enabled: true` after upgrading to continue running scheduled jobs automatically. Subagents and `--eval` mode still do not provide scheduled task capabilities.++The `vikingbot cron` commands remain available for manual job management; this switch does not restrict CLI management operations.+### MCP ToolsConfigure third-party MCP Servers under `bot.tools.mcp_servers`:diff --git a/bot/README_CN.md b/bot/README_CN.mdindex 3714bdaf5..35fdb37e0 100644--- a/bot/README_CN.md+++ b/bot/README_CN.md@@ -408,6 +408,28 @@ Agent 实际使用的活动目录还取决于 `bot.sandbox.mode`:`readonly` 模式不会注册 `openviking_add_resource`。渠道设置 `ov_tools_enable: false` 时,该渠道不显示 OpenViking 工具,也不注入 Profile、Memory 和 Experience。+### 定时任务配置++定时任务默认关闭。在 `ov.conf` 中设置 `bot.tools.cron.enabled` 为 `true`,即可开启:++```json+{+ "bot": {+ "tools": {+ "cron": {+ "enabled": true+ }+ }+ }+}+```++此开关同时控制 `cron` 工具注册和定时调度服务,适用于 Gateway 和本地 Chat。设为 `false` 或省略此配置时,不注册 `cron` 工具,也不启动调度服务;已有任务保留在磁盘上,但不会自动执行。++修改后需要重启 Bot。已有部署升级后,如需继续自动执行定时任务,必须显式设置 `enabled: true`。子 Agent 和 `--eval` 模式仍不提供定时任务能力。++`vikingbot cron` 命令仍可手动管理任务,此开关不限制 CLI 管理操作。+### MCP 工具第三方 MCP Server 配置在 `bot.tools.mcp_servers`:diff --git a/bot/docs/en/concepts/02-agent-capabilities.md b/bot/docs/en/concepts/02-agent-capabilities.mdindex 926b7a389..eea314ef9 100644--- a/bot/docs/en/concepts/02-agent-capabilities.md+++ b/bot/docs/en/concepts/02-agent-capabilities.md@@ -40,7 +40,7 @@ A Skill may orchestrate several tools, but it does not receive additional permis| OpenViking | `openviking_list/search/grep/glob/multi_read` | Browse, retrieve, and read context || OpenViking | `openviking_add_resource`, `openviking_memory_commit` | Add resources and commit memory || Delivery | `message`, `generate_image` | Send messages proactively or generate images |-| Automation | `cron` | Manage scheduled Agent tasks |+| Automation | `cron` | Manage scheduled Agent tasks; disabled by default || Parallel work | `spawn` | Start a background subagent |ToolRegistry handles registration, argument validation, execution, and Hooks. ToolContext gives each call the current SessionKey, sender identity, channel metadata, sandbox, and authenticated OpenViking connection.@@ -158,7 +158,23 @@ Both proactive execution mechanisms ultimately call AgentLoop:| Cron | `at`, `every`, or a cron expression | Timed reminders and recurring jobs || Heartbeat | Periodically reads `HEARTBEAT.md` from the workspace | Continuously check a changing set of tasks |-Cron jobs are persisted in `cron/jobs.json` and retain the original SessionKey and channel metadata. When `deliver=true`, the result is sent back to the originating channel.+The `cron` tool lets the Agent add, list, and remove scheduled tasks. For example, a user can say “Remind me to check the daily report at 9 AM every day,” and the Agent can create a job that the scheduler invokes the Agent to execute when due. It supports one-time execution, fixed intervals, and cron expressions.++**Scheduled tasks are disabled by default.** Add the following configuration to `ov.conf` and restart the Bot to enable both the `cron` tool and scheduler in Gateway and local Chat modes:++```json+{+ "bot": {+ "tools": {+ "cron": {+ "enabled": true+ }+ }+ }+}+```++When set to `false` or omitted, the tool is not registered and the scheduler does not start. Jobs are persisted in `cron/jobs.json`; disabling Cron preserves them but stops automatic execution. Jobs retain the original SessionKey and channel metadata. When `deliver=true`, the result is sent back to the originating channel.Heartbeat skips empty files, Sessions that explicitly disable heartbeat, and long-inactive Sessions. The Agent returns `HEARTBEAT_OK` when no work is required.diff --git a/bot/docs/zh/concepts/02-agent-capabilities.md b/bot/docs/zh/concepts/02-agent-capabilities.mdindex 0950ae7e7..4c19adc83 100644--- a/bot/docs/zh/concepts/02-agent-capabilities.md+++ b/bot/docs/zh/concepts/02-agent-capabilities.md@@ -40,7 +40,7 @@ Skill 可以编排多个工具,但不会自动获得额外权限。工具是| OpenViking | `openviking_list/search/grep/glob/multi_read` | 浏览、检索和读取上下文 || OpenViking | `openviking_add_resource`、`openviking_memory_commit` | 添加资源和提交记忆 || 对外操作 | `message`、`generate_image` | 主动发送消息或生成图片 |-| 自动化 | `cron` | 管理定时 Agent 任务 |+| 自动化 | `cron` | 管理定时 Agent 任务,默认关闭 || 并行任务 | `spawn` | 启动后台子 Agent |ToolRegistry 负责注册、参数校验、执行和 Hook。ToolContext 为每次调用提供当前 SessionKey、发送者身份、渠道 metadata、沙箱和已认证的 OpenViking 连接。@@ -158,7 +158,23 @@ VikingBot 支持三类多模态能力:| Cron | `at`、`every` 或 cron 表达式 | 指定时间提醒、固定周期任务 || Heartbeat | 周期读取工作区 `HEARTBEAT.md` | 持续检查一组可能变化的事项 |-Cron 任务持久化在 `cron/jobs.json`,保存原 SessionKey 和渠道 metadata;`deliver=true` 时将执行结果发回原渠道。+Cron 通过 `cron` 工具提供新增、查看和删除定时任务的能力。例如,用户说“每天上午 9 点提醒我看日报”,Agent 可以创建相应任务,由调度服务到期后调用 Agent 执行。支持指定时间执行一次、固定间隔执行和 cron 表达式调度。++**定时任务默认关闭**。在 `ov.conf` 中配置以下内容并重启 Bot,即可开启 `cron` 工具和调度服务,适用于 Gateway 和本地 Chat:++```json+{+ "bot": {+ "tools": {+ "cron": {+ "enabled": true+ }+ }+ }+}+```++设为 `false` 或省略此配置时,不注册 `cron` 工具,也不启动调度服务。Cron 任务持久化在 `cron/jobs.json`,关闭后仍保留,但不会自动执行。任务保存原 SessionKey 和渠道 metadata;`deliver=true` 时将执行结果发回原渠道。Heartbeat 跳过空文件、明确禁用心跳的 Session 和长期不活跃 Session。Agent 无需处理任务时返回 `HEARTBEAT_OK`。diff --git a/bot/tests/test_cron_config.py b/bot/tests/test_cron_config.pynew file mode 100644index 000000000..230202794--- /dev/null+++ b/bot/tests/test_cron_config.py@@ -0,0 +1,122 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Cron is opt-in for both tool registration and scheduler startup."""++import json+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest+from vikingbot.agent.tools.factory import register_default_tools, register_subagent_tools+from vikingbot.agent.tools.registry import ToolRegistry+from vikingbot.bus.queue import MessageBus+from vikingbot.cli import commands+from vikingbot.config import loader+from vikingbot.config.schema import Config, SessionKey+from vikingbot.cron.service import CronService+from vikingbot.cron.types import CronSchedule++[email protected]("enabled", [None, False, True])+def test_cron_config_load_and_save(tmp_path, monkeypatch, enabled):+ path = tmp_path / "ov.conf"+ tools = {} if enabled is None else {"cron": {"enabled": enabled}}+ path.write_text(json.dumps({"bot": {"tools": tools}}))+ monkeypatch.setattr(loader, "CONFIG_PATH", path)++ config = loader.load_config()+ assert config.tools.cron.enabled is (enabled is True)+ loader.save_config(config, path)+ assert loader.load_config().tools.cron.enabled is (enabled is True)++[email protected]("enabled", [False, True])+def test_cron_tool_registration(tmp_path, enabled):+ config = Config(tools={"cron": {"enabled": enabled}})+ registry = ToolRegistry(config=config)+ service = CronService(tmp_path / "jobs.json")+ register_default_tools(registry, config, cron_service=service)+ assert registry.has("cron") is enabled+ assert registry.has("exec")+ assert registry.has("read_file")+ names = {tool["function"]["name"] for tool in registry.get_definitions()}+ assert ("cron" in names) is enabled++ subagent = ToolRegistry(config=config)+ register_subagent_tools(subagent, config)+ assert not subagent.has("cron")++ without_service = ToolRegistry(config=config)+ register_default_tools(without_service, config)+ assert not without_service.has("cron")+++def test_disabled_cron_preserves_existing_jobs(tmp_path, monkeypatch):+ monkeypatch.setattr(commands, "get_data_dir", lambda: tmp_path)+ path = tmp_path / "cron" / "jobs.json"+ service = CronService(path)+ service.add_job(+ "reminder",+ CronSchedule(kind="every", every_ms=60_000),+ "hello",+ SessionKey(type="cli", channel_id="test", chat_id="test"),+ )+ before = path.read_bytes()+ constructor = Mock(side_effect=AssertionError("Disabled cron must not be constructed"))+ monkeypatch.setattr(commands, "CronService", constructor)++ assert commands.prepare_cron(Config(), MessageBus()) is None+ constructor.assert_not_called()+ assert path.read_bytes() == before++[email protected]("enabled", [False, True])[email protected]("mode", ["gateway", "interactive", "single_turn", "eval"])+def test_startup_respects_cron_config(tmp_path, monkeypatch, enabled, mode):+ config = Config(storage_workspace=str(tmp_path), tools={"cron": {"enabled": enabled}})+ agent = SimpleNamespace(run=AsyncMock(), close_mcp=AsyncMock())+ channels = SimpleNamespace(start_all=AsyncMock())+ cron = SimpleNamespace(start=AsyncMock(), status=lambda: {"jobs": 0})+ constructor = Mock(return_value=cron)+ prepare_agent = Mock(return_value=agent)+ monkeypatch.setattr(commands, "ensure_config", lambda _: config)+ monkeypatch.setattr(commands, "validate_openviking_auth", lambda _: None)+ monkeypatch.setattr(commands, "_init_bot_data", lambda _: None)+ monkeypatch.setattr(commands, "_abort_if_port_in_use", lambda *_: None)+ monkeypatch.setattr(commands, "_redirect_openviking_logs_to_stderr", lambda: None)+ monkeypatch.setattr(commands, "get_data_dir", lambda: tmp_path)+ monkeypatch.setattr(commands, "logger", Mock())+ monkeypatch.setattr(commands, "CronService", constructor)+ monkeypatch.setattr(commands, "prepare_agent_loop", prepare_agent)+ monkeypatch.setattr(commands, "prepare_channel", lambda *_, **__: channels)+ monkeypatch.setattr(commands, "prepare_agent_channel", lambda *_, **__: channels)+ monkeypatch.setattr(+ commands, "prepare_heartbeat", lambda *_: SimpleNamespace(start=AsyncMock())+ )+ monkeypatch.setattr(+ "vikingbot.compile.service.BotCompileService",+ lambda **_: SimpleNamespace(start=AsyncMock()),+ )+ monkeypatch.setattr("uvicorn.Server", lambda _: SimpleNamespace(serve=AsyncMock()))+ monkeypatch.setenv("VIKINGBOT_LOG_FILE", str(tmp_path / "bot.log"))++ if mode == "gateway":+ commands.gateway(port=None, host="127.0.0.1", verbose=False, config_path=None)+ else:+ commands.chat(+ message=None if mode == "interactive" else "hello",+ session_id="test",+ markdown=False,+ logs=False,+ eval=mode == "eval",+ config_path=None,+ sender=None,+ memory_peer=None,+ memory_user=None,+ )++ should_start = enabled and mode != "eval"+ assert constructor.call_count == int(should_start)+ assert cron.start.await_count == int(should_start)+ assert prepare_agent.call_args.args[3] is (cron if should_start else None)+ agent.close_mcp.assert_awaited_once()diff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.pyindex 8d161cb56..13db88e9c 100644--- a/bot/vikingbot/agent/context.py+++ b/bot/vikingbot/agent/context.py@@ -286,7 +286,7 @@ The following local and remote Skills extend your capabilities.user_ids=memory_owner_user_ids if memory_owner_user_ids else None,openviking_connection=self._openviking_connection,)- logger.info(f"viking_memory={viking_memory}")+ logger.info(f"viking_memory={viking_memory[:200] if viking_memory else 'None'}")cost = round(_time.time() - start, 2)logger.info(f"[READ_USER_MEMORY]: cost {cost}s, "diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex 1c860c70a..24842a15e 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -1674,7 +1674,7 @@ class AgentLoop:result_text if isinstance(result, MultimodalToolResult) else result)args_str = json.dumps(tool_call.arguments, ensure_ascii=False)- logger.info(f"[RESULT]: {result_text[:600]}")+ logger.info(f"[RESULT]: {result_text[:200]}")if publish_events:await self.bus.publish_outbound(diff --git a/bot/vikingbot/agent/tools/factory.py b/bot/vikingbot/agent/tools/factory.pyindex b5f7ac4ed..6337d5efa 100644--- a/bot/vikingbot/agent/tools/factory.py+++ b/bot/vikingbot/agent/tools/factory.py@@ -128,7 +128,7 @@ def register_default_tools(registry.register(spawn_tool)# Cron tool- if include_cron_tool and cron_service:+ if include_cron_tool and cron_service and config.tools.cron.enabled:registry.register(CronTool(cron_service))diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.pyindex 8e66c8e0c..0c30b99dc 100644--- a/bot/vikingbot/cli/commands.py+++ b/bot/vikingbot/cli/commands.py@@ -33,7 +33,7 @@ from vikingbot.config.loader import (load_config,validate_openviking_auth,)-from vikingbot.config.schema import SessionKey, requires_gateway_token+from vikingbot.config.schema import Config, SessionKey, requires_gateway_tokenfrom vikingbot.cron.service import CronServicefrom vikingbot.cron.types import CronJobfrom vikingbot.heartbeat.service import HeartbeatService@@ -493,7 +493,7 @@ def gateway(version="1.0.0",)- cron = prepare_cron(bus)+ cron = prepare_cron(config, bus)agent_loop = prepare_agent_loop(config, bus, session_manager, cron)from vikingbot.compile.service import BotCompileService@@ -521,13 +521,14 @@ def gateway(server = uvicorn.Server(config_uvicorn)tasks = [- cron.start(),heartbeat.start(),compile_service.start(),channels.start_all(),agent_loop.run(),server.serve(),]+ if cron is not None:+ tasks.append(cron.start())try:await asyncio.gather(*tasks)finally:@@ -591,7 +592,12 @@ def prepare_agent_loop(config, bus, session_manager, cron, quiet: bool = False,return agent-def prepare_cron(bus, quiet: bool = False) -> CronService:+def prepare_cron(config: Config, bus, quiet: bool = False) -> CronService | None:+ if not config.tools.cron.enabled:+ if not quiet:+ logger.info("Cron: disabled")+ return None+# Create cron service first (callback set after agent creation)cron_store_path = get_data_dir() / "cron" / "jobs.json"cron = CronService(cron_store_path)@@ -858,7 +864,7 @@ def chat(# Use unified default session IDif session_id is None:session_id = get_or_create_machine_id()- cron = None if eval else prepare_cron(bus, quiet=is_single_turn)+ cron = None if eval else prepare_cron(config, bus, quiet=is_single_turn)channels = prepare_agent_channel(config,bus,diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.pyindex f8a86b4cf..189f28232 100644--- a/bot/vikingbot/config/schema.py+++ b/bot/vikingbot/config/schema.py@@ -686,6 +686,12 @@ class WebToolsConfig(BaseModel):search: WebSearchConfig = Field(default_factory=WebSearchConfig)+class CronConfig(BaseModel):+ """Scheduled task tool and scheduler configuration."""++ enabled: bool = False++class ExecToolConfig(BaseModel):"""Shell exec tool configuration."""@@ -714,6 +720,7 @@ class ToolsConfig(BaseModel):"""Tools configuration."""web: WebToolsConfig = Field(default_factory=WebToolsConfig)+ cron: CronConfig = Field(default_factory=CronConfig)exec: ExecToolConfig = Field(default_factory=ExecToolConfig)mcp_servers: dict[str, MCPServerConfig] = Field(default_factory=dict)