Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(vikingbot): honor SDK, exec, and cron options (#4530)

DuTao6bbf84027f2c
diff --git a/bot/tests/test_cron_datetime_parsing.py b/bot/tests/test_cron_datetime_parsing.py
index 823f22038..933404fc6 100644
--- a/bot/tests/test_cron_datetime_parsing.py
+++ b/bot/tests/test_cron_datetime_parsing.py
@@ -3,6 +3,7 @@
"""Regression tests for cron ISO datetime parsing."""
import sys
+from datetime import datetime, timezone
from pathlib import Path
from types import SimpleNamespace
@@ -14,7 +15,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from vikingbot.agent.tools.cron import CronTool # noqa: E402
from vikingbot.cli.commands import cron_add # noqa: E402
from vikingbot.config.schema import SessionKey # noqa: E402
-from vikingbot.cron.service import CronService # noqa: E402
+from vikingbot.cron.service import CronService, _compute_next_run # noqa: E402
+from vikingbot.cron.types import CronSchedule # noqa: E402
def test_cron_cli_accepts_z_datetime(tmp_path, monkeypatch):
@@ -27,6 +29,7 @@ def test_cron_cli_accepts_z_datetime(tmp_path, monkeypatch):
cron_expr=None,
at="2099-08-17T10:00:00Z",
deliver=False,
+ timezone=None,
)
jobs = CronService(tmp_path / "cron" / "jobs.json").list_jobs()
@@ -45,6 +48,7 @@ def test_cron_cli_reports_invalid_datetime(tmp_path, monkeypatch):
cron_expr=None,
at="not-a-date",
deliver=False,
+ timezone=None,
)
@@ -86,3 +90,71 @@ async def test_cron_tool_reports_invalid_datetime(tmp_path):
)
assert result.startswith("Error: invalid at datetime:")
+
+
+def test_cron_schedule_uses_explicit_timezone():
+ now_ms = int(datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp() * 1000)
+
+ shanghai = _compute_next_run(
+ CronSchedule(kind="cron", expr="0 9 * * *", tz="Asia/Shanghai"),
+ now_ms,
+ )
+ los_angeles = _compute_next_run(
+ CronSchedule(kind="cron", expr="0 9 * * *", tz="America/Los_Angeles"),
+ now_ms,
+ )
+
+ assert shanghai == int(datetime(2026, 1, 1, 1, tzinfo=timezone.utc).timestamp() * 1000)
+ assert los_angeles == int(datetime(2026, 1, 1, 17, tzinfo=timezone.utc).timestamp() * 1000)
+
+
+async def test_cron_tool_persists_timezone(tmp_path):
+ service = CronService(tmp_path / "jobs.json")
+ tool = CronTool(service)
+ context = SimpleNamespace(
+ session_key=SessionKey(type="cli", channel_id="default", chat_id="default"),
+ channel_metadata=None,
+ )
+
+ result = await tool.execute(
+ context,
+ action="add",
+ name="morning",
+ message="good morning",
+ cron_expr="0 9 * * *",
+ timezone="Asia/Shanghai",
+ )
+
+ assert result.startswith("Created job")
+ persisted = CronService(tmp_path / "jobs.json").list_jobs()
+ assert persisted[0].schedule.tz == "Asia/Shanghai"
+
+
+def test_cron_service_rejects_invalid_timezone(tmp_path):
+ service = CronService(tmp_path / "jobs.json")
+
+ with pytest.raises(ValueError, match="Invalid cron timezone: Mars/Olympus"):
+ service.add_job(
+ name="invalid timezone",
+ schedule=CronSchedule(kind="cron", expr="0 9 * * *", tz="Mars/Olympus"),
+ message="hello",
+ session_key=SessionKey(type="cli", channel_id="default", chat_id="default"),
+ )
+
+
+def test_cron_cli_persists_timezone(tmp_path, monkeypatch):
+ monkeypatch.setattr("vikingbot.config.loader.get_data_dir", lambda: tmp_path)
+
+ cron_add(
+ name="morning",
+ message="good morning",
+ every=None,
+ cron_expr="0 9 * * *",
+ at=None,
+ deliver=False,
+ timezone="Asia/Shanghai",
+ )
+
+ jobs = CronService(tmp_path / "cron" / "jobs.json").list_jobs()
+ assert jobs[0].schedule.tz == "Asia/Shanghai"
diff --git a/bot/tests/test_exec_tool.py b/bot/tests/test_exec_tool.py
new file mode 100644
index 000000000..ba6408c10
--- /dev/null
+++ b/bot/tests/test_exec_tool.py
@@ -0,0 +1,89 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Regression tests for the exec tool working directory."""
+
+from types import SimpleNamespace
+
+import pytest
+from vikingbot.agent.tools.shell import ExecTool
+from vikingbot.config.schema import SessionKey
+from vikingbot.sandbox.backends.direct import DirectBackend
+
+
+class _SandboxManager:
+ def __init__(self, sandbox):
+ self.sandbox = sandbox
+
+ async def get_sandbox(self, _session_key):
+ return self.sandbox
+
+
+async def test_exec_tool_applies_working_dir_for_all_sandbox_backends():
+ calls = []
+
+ class Sandbox:
+ sandbox_cwd = "/workspace"
+
+ async def execute(self, command, timeout):
+ calls.append((command, timeout))
+ return "ok"
+
+ context = SimpleNamespace(
+ sandbox_manager=_SandboxManager(Sandbox()),
+ session_key="session",
+ )
+
+ result = await ExecTool(timeout=7).execute(
+ context,
+ command="pwd",
+ working_dir="directory with spaces",
+ )
+
+ assert result == "ok"
+ assert calls == [("cd 'directory with spaces' && pwd", 7)]
+
+
+async def test_exec_tool_pwd_without_working_dir_uses_sandbox_root():
+ class Sandbox:
+ sandbox_cwd = "/workspace"
+
+ async def execute(self, command, timeout):
+ raise AssertionError((command, timeout))
+
+ context = SimpleNamespace(
+ sandbox_manager=_SandboxManager(Sandbox()),
+ session_key="session",
+ )
+
+ result = await ExecTool().execute(context, command="pwd")
+
+ assert result == "/workspace"
+
+
+async def test_exec_tool_working_dir_changes_real_command_cwd(tmp_path):
+ class Config:
+ restrict_workspaces = True
+
+ workspace = tmp_path / "workspace"
+ working_dir = workspace / "directory with spaces"
+ working_dir.mkdir(parents=True)
+ session_key = SessionKey(type="cli", channel_id="default", chat_id="exec-test")
+ sandbox = DirectBackend(Config(), session_key, workspace)
+ await sandbox.start()
+ try:
+ context = SimpleNamespace(
+ sandbox_manager=_SandboxManager(sandbox),
+ session_key=session_key,
+ )
+ result = await ExecTool().execute(
+ context,
+ command="pwd",
+ working_dir="directory with spaces",
+ )
+ finally:
+ await sandbox.stop()
+
+ assert result.strip() == str(working_dir)
diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.py
index 3d51a3c26..d9fb0c7b8 100644
--- a/bot/tests/test_openviking_api_key_type.py
+++ b/bot/tests/test_openviking_api_key_type.py
@@ -1922,7 +1922,52 @@ async def test_viking_client_ensure_session_creates_after_legacy_not_found(monke
)
assert result == {"session_id": "session-1", "memory_policy": {"strategy": "compact"}}
- assert created == [("session-1", {"memory_policy": {"strategy": "compact"}})]
+ assert created == [
+ ("session-1", {"memory_policy": {"strategy": "compact"}}),
+ ]
+
+
+async def test_viking_client_find_forwards_advanced_fields_via_sdk_options(monkeypatch):
+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))
+ client = VikingClient(workspace_id="workspace")
+ calls = []
+
+ async def _find(query="", target_uri="", limit=10, image=None, options=None):
+ calls.append(
+ {
+ "query": query,
+ "target_uri": target_uri,
+ "limit": limit,
+ "image": image,
+ "options": options,
+ }
+ )
+ return {"memories": []}
+
+ monkeypatch.setattr(client.client, "find", _find)
+
+ result = await client.find(
+ "hello",
+ target_uri="viking://~/memories/",
+ context_type="memory",
+ filter={"tags": ["important"]},
+ limit=3,
+ )
+
+ assert result == {"memories": []}
+ assert calls == [
+ {
+ "query": "hello",
+ "target_uri": "viking://~/memories/",
+ "limit": 3,
+ "image": None,
+ "options": {
+ "context_type": "memory",
+ "filter": {"tags": ["important"]},
+ },
+ }
+ ]
@pytest.mark.asyncio
diff --git a/bot/vikingbot/agent/tools/cron.py b/bot/vikingbot/agent/tools/cron.py
index 70f09546f..b288ea718 100644
--- a/bot/vikingbot/agent/tools/cron.py
+++ b/bot/vikingbot/agent/tools/cron.py
@@ -48,6 +48,12 @@ class CronTool(Tool):
"type": "string",
"description": "Cron expression like '0 9 * * *' (for scheduled tasks)",
},
+ "timezone": {
+ "type": "string",
+ "description": (
+ "IANA timezone for cron expressions, for example Asia/Shanghai"
+ ),
+ },
"at": {
"type": "string",
"description": "ISO datetime for one-time execution (e.g. '2026-02-12T10:30:00')",
@@ -65,6 +71,7 @@ class CronTool(Tool):
message: str = "",
every_seconds: int | None = None,
cron_expr: str | None = None,
+ timezone: str | None = None,
at: str | None = None,
job_id: str | None = None,
**kwargs: Any,
@@ -75,6 +82,7 @@ class CronTool(Tool):
message,
every_seconds,
cron_expr,
+ timezone,
at,
tool_context.session_key,
self._delivery_metadata(getattr(tool_context, "channel_metadata", None)),
@@ -91,19 +99,22 @@ class CronTool(Tool):
message: str,
every_seconds: int | None,
cron_expr: str | None,
+ timezone: 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"
+ if timezone and not cron_expr:
+ return "Error: timezone is only supported with cron_expr"
# Build schedule
delete_after = False
if every_seconds:
schedule = CronSchedule(kind="every", every_ms=every_seconds * 1000)
elif cron_expr:
- schedule = CronSchedule(kind="cron", expr=cron_expr)
+ schedule = CronSchedule(kind="cron", expr=cron_expr, tz=timezone)
elif at:
try:
dt = parse_iso_datetime(at)
diff --git a/bot/vikingbot/agent/tools/shell.py b/bot/vikingbot/agent/tools/shell.py
index d2b513382..ac7c69ae7 100644
--- a/bot/vikingbot/agent/tools/shell.py
+++ b/bot/vikingbot/agent/tools/shell.py
@@ -1,5 +1,6 @@
"""Shell execution tool."""
+import shlex
from typing import TYPE_CHECKING, Any
from vikingbot.agent.tools.base import Tool
@@ -30,7 +31,10 @@ class ExecTool(Tool):
"command": {"type": "string", "description": "The shell command to execute"},
"working_dir": {
"type": "string",
- "description": "Optional working directory for the command",
+ "description": (
+ "Optional working directory for the command, relative to the sandbox "
+ "root or an absolute path inside the sandbox"
+ ),
},
},
"required": ["command"],
@@ -47,7 +51,9 @@ class ExecTool(Tool):
try:
sandbox = await tool_context.sandbox_manager.get_sandbox(tool_context.session_key)
- if command.strip() == "pwd":
+ if working_dir:
+ command = f"cd {shlex.quote(working_dir)} && {command}"
+ elif command.strip() == "pwd":
return sandbox.sandbox_cwd
return await sandbox.execute(command, timeout=self.timeout)
diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.py
index a80807442..6d38e4f02 100644
--- a/bot/vikingbot/cli/commands.py
+++ b/bot/vikingbot/cli/commands.py
@@ -1123,6 +1123,12 @@ def cron_add(
cron_expr: str = typer.Option(None, "--cron", "-c", help="Cron expression (e.g. '0 9 * * *')"),
at: str = typer.Option(None, "--at", help="Run once at time (ISO format)"),
deliver: bool = typer.Option(False, "--deliver", "-d", help="Deliver response to channel"),
+ timezone: str = typer.Option(
+ None,
+ "--timezone",
+ "--tz",
+ help="IANA timezone for --cron (e.g. Asia/Shanghai)",
+ ),
):
"""Add a scheduled job."""
from vikingbot.config.loader import get_data_dir
@@ -1130,10 +1136,13 @@ def cron_add(
from vikingbot.cron.types import CronSchedule
# Determine schedule type
+ if timezone and not cron_expr:
+ console.print("[red]Error: --timezone requires --cron[/red]")
+ raise typer.Exit(1)
if every:
schedule = CronSchedule(kind="every", every_ms=every * 1000)
elif cron_expr:
- schedule = CronSchedule(kind="cron", expr=cron_expr)
+ schedule = CronSchedule(kind="cron", expr=cron_expr, tz=timezone)
elif at:
try:
dt = parse_iso_datetime(at)
diff --git a/bot/vikingbot/cron/service.py b/bot/vikingbot/cron/service.py
index 6d5248e38..dcd6e8ccf 100644
--- a/bot/vikingbot/cron/service.py
+++ b/bot/vikingbot/cron/service.py
@@ -4,8 +4,10 @@ import asyncio
import json
import time
import uuid
+from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Coroutine
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from loguru import logger
@@ -21,6 +23,15 @@ def _dict_or_empty(value: Any) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
+def _validate_schedule_timezone(schedule: CronSchedule) -> None:
+ if schedule.kind != "cron" or not schedule.tz:
+ return
+ try:
+ ZoneInfo(schedule.tz)
+ except ZoneInfoNotFoundError as exc:
+ raise ValueError(f"Invalid cron timezone: {schedule.tz}") from exc
+
+
def _compute_next_run(schedule: CronSchedule, now_ms: int) -> int | None:
"""Compute next run time in ms."""
if schedule.kind == "at":
@@ -36,9 +47,16 @@ def _compute_next_run(schedule: CronSchedule, now_ms: int) -> int | None:
try:
from croniter import croniter
- cron = croniter(schedule.expr, time.time())
- next_time = cron.get_next()
- return int(next_time * 1000)
+ if schedule.tz:
+ cron_timezone = ZoneInfo(schedule.tz)
+ base_time = datetime.fromtimestamp(now_ms / 1000, tz=cron_timezone)
+ else:
+ base_time = datetime.fromtimestamp(now_ms / 1000).astimezone()
+ cron = croniter(schedule.expr, base_time)
+ next_time = cron.get_next(datetime)
+ return int(next_time.timestamp() * 1000)
+ except ZoneInfoNotFoundError:
+ return None
except Exception:
return None
@@ -278,6 +296,7 @@ class CronService:
delete_after_run: bool = False,
) -> CronJob:
"""Add a new job."""
+ _validate_schedule_timezone(schedule)
now = _now_ms()
next_run_at_ms = _compute_next_run(schedule, now)
if next_run_at_ms is None:
@@ -330,6 +349,7 @@ class CronService:
if job.id == job_id:
next_run_at_ms = None
if enabled:
+ _validate_schedule_timezone(job.schedule)
next_run_at_ms = _compute_next_run(job.schedule, _now_ms())
if next_run_at_ms is None:
raise ValueError("Schedule does not have a future run time")
diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.py
index 6aa9a113c..028053e30 100644
--- a/bot/vikingbot/openviking_mount/ov_server.py
+++ b/bot/vikingbot/openviking_mount/ov_server.py
@@ -562,10 +562,13 @@ class VikingClient:
):
"""搜索资源"""
kwargs: Dict[str, Any] = {"limit": limit}
+ options: Dict[str, Any] = {}
if context_type is not None:
- kwargs["context_type"] = context_type
+ options["context_type"] = context_type
if filter is not None:
- kwargs["filter"] = filter
+ options["filter"] = filter
+ if options:
+ kwargs["options"] = options
if target_uri:
return await self.client.find(query, target_uri=target_uri, **kwargs)
return await self.client.find(query, **kwargs)
@@ -1189,7 +1192,7 @@ class VikingClient:
return await client.create_session(
session_id=session_id,
- options={"memory_policy": memory_policy} if memory_policy else None,
+ options={"memory_policy": memory_policy} if memory_policy is not None else None,
)
@staticmethod