Skip to content

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

fix(bot): harden scheduling, sessions, sandbox, and packaging (#3549)

Hao Zhe4237c66031a5
diff --git a/Cargo.lock b/Cargo.lock
index 5f45a69ec..b1f5ee370 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3923,6 +3923,7 @@ dependencies = [
"toml",
"tracing",
"uuid",
+ "windows-sys 0.61.2",
]
[[package]]
diff --git a/bot/docs/en/concepts/03-channels-and-gateway.md b/bot/docs/en/concepts/03-channels-and-gateway.md
index 60089c68f..c43a4178c 100644
--- a/bot/docs/en/concepts/03-channels-and-gateway.md
+++ b/bot/docs/en/concepts/03-channels-and-gateway.md
@@ -65,7 +65,7 @@ The Bot API is available under `/bot/v1`:
| GET/POST | `/bot/v1/sessions` | List or create API Sessions |
| GET/DELETE | `/bot/v1/sessions/{id}` | Retrieve or delete an API Session |
-ChatRequest supports a session ID, additional context, reply control, request-level disabled tools, and a channel ID. ChatResponse returns a response ID, final text, intermediate events, relevant memories, and token usage.
+ChatRequest supports a session ID, reply control, request-level disabled tools, and a channel ID. The `context` field does not accept non-empty messages; omit it or send an empty list, otherwise the API returns HTTP 422. Only one request may be in flight for a session at a time. A concurrent request with the same session ID returns HTTP 409, so clients should serialize same-session requests and retry after the active request completes. ChatResponse returns a response ID, final text, intermediate events, relevant memories, and token usage.
SSE emits reasoning, content delta, tool call, tool result, iteration, and final response events.
diff --git a/bot/docs/en/concepts/05-channel.md b/bot/docs/en/concepts/05-channel.md
index 8209bc198..852781246 100644
--- a/bot/docs/en/concepts/05-channel.md
+++ b/bot/docs/en/concepts/05-channel.md
@@ -14,6 +14,8 @@ Talk to your vikingbot through Telegram, Discord, WhatsApp, Feishu, Mochat, Ding
| **Email** | Medium (IMAP/SMTP credentials) |
| **QQ** | Easy (app credentials) |
+Channel configuration lives at `bot.channels` in `~/.openviking/ov.conf`. The complete Telegram example below shows the wrapper; later snippets show the `channels` field to merge into the same `bot` object.
+
<details>
<summary><b>Telegram</b> (recommended)</summary>
@@ -27,14 +29,16 @@ Talk to your vikingbot through Telegram, Discord, WhatsApp, Feishu, Mochat, Ding
```json
{
- "channels": [
- {
- "type": "telegram",
- "enabled": true,
- "token": "YOUR_BOT_TOKEN",
- "allowFrom": ["YOUR_USER_ID"]
- }
- ]
+ "bot": {
+ "channels": [
+ {
+ "type": "telegram",
+ "enabled": true,
+ "token": "YOUR_BOT_TOKEN",
+ "allowFrom": ["YOUR_USER_ID"]
+ }
+ ]
+ }
}
```
@@ -62,7 +66,7 @@ Send the following message to vikingbot, replacing `xxx@xxx` with your actual em
Read https://raw.githubusercontent.com/HKUDS/MoChat/refs/heads/main/skills/vikingbot/skill.md and register on MoChat. My Email account is xxx@xxx Bind me as your owner and DM me on MoChat.
```
-vikingbot automatically registers, updates `~/.vikingbot/config.json`, and connects to Mochat.
+After registration, add the returned channel settings to `bot.channels` in `~/.openviking/ov.conf` and connect to Mochat.
**2. Restart the gateway**
@@ -77,7 +81,7 @@ That is all—vikingbot handles the rest.
<details>
<summary>Manual configuration (advanced)</summary>
-If you prefer to configure Mochat manually, add the following to `~/.vikingbot/config.json`:
+If you prefer to configure Mochat manually, merge the following `channels` field into the `bot` object in `~/.openviking/ov.conf`:
> Keep `claw_token` secret. It should only be sent to your Mochat API endpoint in the `X-Claw-Token` header.
diff --git a/bot/docs/zh/concepts/03-channels-and-gateway.md b/bot/docs/zh/concepts/03-channels-and-gateway.md
index 92ddd4cf1..441501f20 100644
--- a/bot/docs/zh/concepts/03-channels-and-gateway.md
+++ b/bot/docs/zh/concepts/03-channels-and-gateway.md
@@ -65,7 +65,7 @@ Bot API 位于 `/bot/v1`:
| GET/POST | `/bot/v1/sessions` | 列出或创建 API Session |
| GET/DELETE | `/bot/v1/sessions/{id}` | 查询或删除 API Session |
-ChatRequest 支持 session ID、额外上下文、是否回复、请求级禁用工具和渠道 ID。ChatResponse 返回 response ID、最终文本、中间事件、相关记忆和 token usage。
+ChatRequest 支持 session ID、是否回复、请求级禁用工具和渠道 ID。`context` 字段不接受非空消息;请省略该字段或传入空列表,否则 API 返回 HTTP 422。同一个 session 同时只能有一个进行中的请求;使用相同 session ID 的并发请求会返回 HTTP 409,因此客户端应串行发送同 session 请求,并在当前请求完成后重试。ChatResponse 返回 response ID、最终文本、中间事件、相关记忆和 token usage。
SSE 会发送 reasoning、content delta、tool call、tool result、iteration 和最终 response 等事件。
diff --git a/bot/docs/zh/concepts/05-channel.md b/bot/docs/zh/concepts/05-channel.md
index 96e1d964a..a2790cf0c 100644
--- a/bot/docs/zh/concepts/05-channel.md
+++ b/bot/docs/zh/concepts/05-channel.md
@@ -14,6 +14,8 @@
| **邮件** | 中等(IMAP/SMTP 凭证) |
| **QQ** | 简单(应用凭证) |
+渠道配置位于 `~/.openviking/ov.conf` 的 `bot.channels`。下面的 Telegram 示例展示完整外层结构;后续片段中的 `channels` 字段都应合并到同一个 `bot` 对象中。
+
<details>
<summary><b>Telegram</b>(推荐)</summary>
@@ -26,14 +28,16 @@
```json
{
- "channels": [
- {
- "type": "telegram",
- "enabled": true,
- "token": "YOUR_BOT_TOKEN",
- "allowFrom": ["YOUR_USER_ID"]
- }
- ]
+ "bot": {
+ "channels": [
+ {
+ "type": "telegram",
+ "enabled": true,
+ "token": "YOUR_BOT_TOKEN",
+ "allowFrom": ["YOUR_USER_ID"]
+ }
+ ]
+ }
}
```
@@ -62,7 +66,7 @@ vikingbot gateway
Read https://raw.githubusercontent.com/HKUDS/MoChat/refs/heads/main/skills/vikingbot/skill.md and register on MoChat. My Email account is xxx@xxx Bind me as your owner and DM me on MoChat.
```
-vikingbot 将自动注册、配置 `~/.vikingbot/config.json` 并连接到 Mochat。
+注册后,请将返回的渠道设置添加到 `~/.openviking/ov.conf` 的 `bot.channels`,然后连接 Mochat。
**2. 重启网关**
@@ -77,7 +81,7 @@ vikingbot gateway
<details>
<summary>手动配置(高级)</summary>
-如果您更喜欢手动配置,请将以下内容添加到 `~/.vikingbot/config.json`:
+如果您更喜欢手动配置,请将下面的 `channels` 字段合并到 `~/.openviking/ov.conf` 的 `bot` 对象:
> 请保密 `claw_token`。它只应在 `X-Claw-Token` 头中发送到您的 Mochat API 端点。
@@ -415,4 +419,4 @@ vikingbot gateway
vikingbot gateway
```
-</details>
\ No newline at end of file
+</details>
diff --git a/bot/package-lock.json b/bot/package-lock.json
index f0e456324..3c89beef7 100644
--- a/bot/package-lock.json
+++ b/bot/package-lock.json
@@ -7,7 +7,7 @@
"": {
"name": "bot",
"version": "1.0.0",
- "license": "ISC",
+ "license": "AGPL-3.0",
"dependencies": {
"@anthropic-ai/sandbox-runtime": "^0.0.37"
}
diff --git a/bot/package.json b/bot/package.json
index e74861d28..2e5f99292 100644
--- a/bot/package.json
+++ b/bot/package.json
@@ -11,7 +11,7 @@
},
"keywords": [],
"author": "",
- "license": "ISC",
+ "license": "AGPL-3.0",
"type": "commonjs",
"dependencies": {
"@anthropic-ai/sandbox-runtime": "^0.0.37"
diff --git a/bot/tests/test_channel_delivery_metadata.py b/bot/tests/test_channel_delivery_metadata.py
index 9f148cf16..c9e3cfdaa 100644
--- a/bot/tests/test_channel_delivery_metadata.py
+++ b/bot/tests/test_channel_delivery_metadata.py
@@ -205,6 +205,89 @@ def test_cron_service_accepts_missing_channel_metadata(tmp_path):
assert job.payload.channel_metadata == {}
+ "schedule",
+ [
+ CronSchedule(kind="every", every_ms=0),
+ CronSchedule(kind="at", at_ms=1),
+ CronSchedule(kind="cron", expr="not a cron expression"),
+ ],
+)
+def test_cron_service_rejects_unschedulable_jobs(tmp_path, schedule):
+ path = tmp_path / "jobs.json"
+ key = SessionKey(type="cli", channel_id="default", chat_id="default")
+ with pytest.raises(ValueError, match="future run time"):
+ CronService(path).add_job("invalid", schedule, "hello", key)
+ assert not path.exists()
+
+
+def test_cron_service_rejects_reenabling_expired_one_shot(tmp_path, monkeypatch):
+ path = tmp_path / "jobs.json"
+ key = SessionKey(type="cli", channel_id="default", chat_id="default")
+ monkeypatch.setattr("vikingbot.cron.service._now_ms", lambda: 1_000)
+ service = CronService(path)
+ job = service.add_job("one-shot", CronSchedule(kind="at", at_ms=2_000), "hello", key)
+ service.enable_job(job.id, enabled=False)
+ original = path.read_bytes()
+
+ monkeypatch.setattr("vikingbot.cron.service._now_ms", lambda: 3_000)
+ with pytest.raises(ValueError, match="future run time"):
+ service.enable_job(job.id)
+
+ assert path.read_bytes() == original
+ assert not job.enabled
+ assert job.state.next_run_at_ms is None
+
+
+async def test_cron_service_without_callback_preserves_one_shot(tmp_path):
+ path = tmp_path / "jobs.json"
+ service = CronService(path)
+ job = service.add_job(
+ "one-shot",
+ CronSchedule(kind="at", at_ms=9999999999999),
+ "hello",
+ SessionKey(type="cli", channel_id="default", chat_id="default"),
+ delete_after_run=True,
+ )
+ original = path.read_bytes()
+
+ with pytest.raises(RuntimeError, match="no job execution callback"):
+ await service.run_job(job.id)
+ assert path.read_bytes() == original
+
+
+async def test_cron_service_without_callback_rearms_recurring_timer(tmp_path, monkeypatch):
+ path = tmp_path / "jobs.json"
+ now_ms = 1_000
+ monkeypatch.setattr("vikingbot.cron.service._now_ms", lambda: now_ms)
+ service = CronService(path)
+ job = service.add_job(
+ "recurring",
+ CronSchedule(kind="every", every_ms=100),
+ "hello",
+ SessionKey(type="cli", channel_id="default", chat_id="default"),
+ )
+ service._running = True
+ rearmed_at = []
+ monkeypatch.setattr(
+ service, "_arm_timer", lambda: rearmed_at.append(service._get_next_wake_ms())
+ )
+ now_ms = 1_100
+
+ await service._on_timer()
+
+ assert job.state.last_status == "error"
+ assert job.state.last_error == "Cron service has no job execution callback"
+ assert job.state.last_run_at_ms == now_ms
+ assert job.state.next_run_at_ms == 1_200
+ assert rearmed_at == [1_200]
+ persisted = CronService(path).list_jobs()
+ assert persisted[0].state.last_status == "error"
+ assert persisted[0].state.next_run_at_ms == 1_200
+
+
def test_feishu_uses_thread_root_for_scheduled_delivery():
assert (
FeishuChannel._reply_to_message_id_from_metadata(
diff --git a/bot/tests/test_openapi_auth.py b/bot/tests/test_openapi_auth.py
index 07fe69e76..56ee767a9 100644
--- a/bot/tests/test_openapi_auth.py
+++ b/bot/tests/test_openapi_auth.py
@@ -15,9 +15,10 @@ from fastapi.testclient import TestClient
from vikingbot.bus.events import OutboundEventType, OutboundMessage
from vikingbot.bus.queue import MessageBus
from vikingbot.channels.openapi import OpenAPIChannel, OpenAPIChannelConfig, PendingResponse
-from vikingbot.channels.openapi_models import ChatResponse
+from vikingbot.channels.openapi_models import ChatRequest, ChatResponse
from vikingbot.compile.models import CompileAccepted
from vikingbot.config.schema import BotChannelConfig, SessionKey
+from vikingbot.session.manager import Session
@pytest.fixture
@@ -174,6 +175,84 @@ class TestOpenAPIAuth:
assert service.connection is None
assert runtime_probes == [{}, {}]
+ def test_chat_request_rejects_unsupported_context(self):
+ with pytest.raises(ValueError, match="context is not supported"):
+ ChatRequest(message="hello", context=[{"role": "user", "content": "prior"}])
+ assert ChatRequest(message="hello", context=[]).context == []
+ description = ChatRequest.model_json_schema()["properties"]["context"]["description"]
+ assert "not supported" in description
+
+ def test_chat_returns_422_for_unsupported_context(self, message_bus, temp_workspace):
+ channel = OpenAPIChannel(OpenAPIChannelConfig(), message_bus, temp_workspace)
+
+ response = _make_client(channel).post(
+ "/bot/v1/chat",
+ json={
+ "message": "hello",
+ "context": [{"role": "user", "content": "prior"}],
+ },
+ )
+
+ assert response.status_code == 422
+ assert message_bus.inbound_size == 0
+
+ def test_chat_rejects_second_in_flight_request(self, message_bus, temp_workspace):
+ channel = OpenAPIChannel(OpenAPIChannelConfig(), message_bus, temp_workspace)
+ scope = channel._principal_scope("standalone")
+ storage_key = channel._scoped_session_id(scope, "same-session")
+ channel._pending[storage_key] = PendingResponse()
+
+ response = _make_client(channel).post(
+ "/bot/v1/chat", json={"message": "hello", "session_id": "same-session"}
+ )
+
+ assert response.status_code == 409
+ assert message_bus.inbound_size == 0
+
+ def test_delete_rotation_survives_restart_and_session_id_reuse(
+ self, message_bus, temp_workspace
+ ):
+ channel = OpenAPIChannel(OpenAPIChannelConfig(), message_bus, temp_workspace)
+ client = _make_client(channel)
+ session_id = client.post("/bot/v1/sessions", json={}).json()["session_id"]
+ scope = channel._principal_scope("standalone")
+ storage_key = channel._scoped_session_id(scope, session_id)
+ key = SessionKey(type="cli", channel_id="default", chat_id=storage_key)
+ old_session = Session(key=key)
+ old_session.add_message("user", "deleted history")
+ channel._session_manager._save_unlocked(old_session)
+
+ response = client.delete(f"/bot/v1/sessions/{session_id}")
+
+ assert response.status_code == 200
+ assert not channel._session_manager.has_persisted(key)
+ reused_storage_key = channel._scoped_session_id(scope, session_id)
+ assert reused_storage_key != storage_key
+
+ reused_key = SessionKey(type="cli", channel_id="default", chat_id=reused_storage_key)
+ reused_session = Session(key=reused_key)
+ reused_session.add_message("user", "new history")
+ channel._session_manager._save_unlocked(reused_session)
+
+ restarted = OpenAPIChannel(OpenAPIChannelConfig(), message_bus, temp_workspace)
+ assert restarted._scoped_session_id(scope, session_id) == reused_storage_key
+ assert restarted._session_manager.get_or_create(reused_key).messages[0]["content"] == (
+ "new history"
+ )
+
+ restarted._sessions[reused_storage_key] = {
+ "session_id": session_id,
+ "principal_scope": scope,
+ }
+ restart_client = _make_client(restarted)
+ assert restart_client.delete(f"/bot/v1/sessions/{session_id}").status_code == 200
+
+ next_storage_key = restarted._scoped_session_id(scope, session_id)
+ assert next_storage_key not in {storage_key, reused_storage_key}
+ assert not restarted._session_manager.has_persisted(reused_key)
+ next_key = SessionKey(type="cli", channel_id="default", chat_id=next_storage_key)
+ assert restarted._session_manager.get_or_create(next_key).messages == []
+
def test_health_remains_available_without_api_key(self, message_bus, temp_workspace):
channel = OpenAPIChannel(
OpenAPIChannelConfig(),
diff --git a/bot/tests/test_sandbox_startup.py b/bot/tests/test_sandbox_startup.py
new file mode 100644
index 000000000..c4c4cbbbd
--- /dev/null
+++ b/bot/tests/test_sandbox_startup.py
@@ -0,0 +1,54 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Regression tests for sandbox construction and startup failures."""
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from vikingbot.config.schema import Config, SessionKey # noqa: E402
+from vikingbot.sandbox.backends.srt import SrtBackend # noqa: E402
+from vikingbot.sandbox.manager import SandboxManager # noqa: E402
+
+
+def test_srt_backend_uses_workspace_id_and_nested_config(tmp_path):
+ config = Config().sandbox
+ config.backends.srt.network.allowed_domains = ["example.com"]
+
+ backend = SrtBackend(config, "shared", tmp_path / "shared")
+
+ assert backend._settings_path.name == "shared-srt-settings.json"
+ settings = json.loads(backend._settings_path.read_text())
+ assert settings["network"]["allowedDomains"] == ["example.com"]
+ assert settings["filesystem"]["allowWrite"][0] == str((tmp_path / "shared").resolve())
+
+
+async def test_startup_failure_is_not_cached_and_can_retry(tmp_path):
+ class FailingBackend:
+ instances = []
+
+ def __init__(self, config, workspace_id, workspace):
+ self.stopped = False
+ self.instances.append(self)
+
+ async def start(self):
+ raise RuntimeError("startup failed")
+
+ async def stop(self):
+ self.stopped = True
+
+ manager = SandboxManager(Config(), tmp_path / "sandboxes", tmp_path / "source")
+ manager._backend_cls = FailingBackend
+ session_key = SessionKey(type="cli", channel_id="default", chat_id="test")
+
+ for expected_attempts in (1, 2):
+ with pytest.raises(RuntimeError, match="startup failed"):
+ await manager.get_sandbox(session_key)
+ assert manager._sandboxes == {}
+ assert len(FailingBackend.instances) == expected_attempts
+ assert FailingBackend.instances[-1].stopped
diff --git a/bot/vikingbot/agent/skills.py b/bot/vikingbot/agent/skills.py
index c537301d9..ca46baf4a 100644
--- a/bot/vikingbot/agent/skills.py
+++ b/bot/vikingbot/agent/skills.py
@@ -7,10 +7,11 @@ import shutil
from pathlib import Path
import yaml
-from loguru import logger
+
+from vikingbot.utils.helpers import get_source_workspace_path
# Default builtin skills directory (relative to this file)
-BUILTIN_SKILLS_DIR = Path(__file__).parent.parent.parent / "workspace" / "skills"
+BUILTIN_SKILLS_DIR = get_source_workspace_path() / "skills"
class SkillsLoader:
@@ -136,7 +137,7 @@ class SkillsLoader:
if missing:
lines.append(f" <requires>{escape_xml(missing)}</requires>")
- lines.append(f" </skill>")
+ lines.append(" </skill>")
lines.append("</skills>")
return "\n".join(lines)
diff --git a/bot/vikingbot/agent/tools/cron.py b/bot/vikingbot/agent/tools/cron.py
index 80c630b53..b74c97421 100644
--- a/bot/vikingbot/agent/tools/cron.py
+++ b/bot/vikingbot/agent/tools/cron.py
@@ -113,15 +113,18 @@ class CronTool(Tool):
else:
return "Error: either every_seconds, cron_expr, or at is required"
- job = self._cron.add_job(
- name=name,
- schedule=schedule,
- message=message,
- deliver=True,
- session_key=session_key,
- channel_metadata=channel_metadata,
- delete_after_run=delete_after,
- )
+ try:
+ job = self._cron.add_job(
+ name=name,
+ schedule=schedule,
+ message=message,
+ deliver=True,
+ session_key=session_key,
+ channel_metadata=channel_metadata,
+ delete_after_run=delete_after,
+ )
+ except ValueError as e:
+ return f"Error: {e}"
return f"Created job '{job.name}' (id: {job.id})"
def _delivery_metadata(self, metadata: dict[str, Any] | None) -> dict[str, Any]:
diff --git a/bot/vikingbot/channels/openapi.py b/bot/vikingbot/channels/openapi.py
index 553a86be7..eeaffe2bb 100644
--- a/bot/vikingbot/channels/openapi.py
+++ b/bot/vikingbot/channels/openapi.py
@@ -516,6 +516,14 @@ class OpenAPIChannel(BaseChannel):
if storage_key not in channel._sessions:
raise HTTPException(status_code=404, detail="Session not found")
+ channel._ensure_no_pending(channel._pending, storage_key)
+ session_key = SessionKey(
+ type="cli",
+ channel_id=channel.config.channel_id(),
+ chat_id=storage_key,
+ )
+ channel._advance_session_generation(scope, session_id)
+ channel._session_manager.delete(session_key)
del channel._sessions[storage_key]
return {"deleted": True}
@@ -1102,9 +1110,43 @@ class OpenAPIChannel(BaseChannel):
)
return self._principal_scope(f"openviking:{account_id}:{user_id}")
+ def _scoped_session_id(self, principal_scope: str, session_id: str) -> str:
+ """Resolve the durable storage key for one public session ID."""
+ base = f"{principal_scope}:{session_id}"
+ generation_path = self._session_generation_path(base)
+ try:
+ raw_generation = generation_path.read_text(encoding="utf-8").strip()
+ except FileNotFoundError:
+ return base
+ try:
+ generation = uuid.UUID(raw_generation).hex
+ except ValueError as exc:
+ raise RuntimeError(
+ f"Invalid OpenAPI session generation marker: {generation_path}"
+ ) from exc
+ return f"{base}:{generation}"
+
+ def _advance_session_generation(self, principal_scope: str, session_id: str) -> None:
+ """Atomically rotate storage before deleting the current session history."""
+ base = f"{principal_scope}:{session_id}"
+ generation_path = self._session_generation_path(base)
+ generation_path.parent.mkdir(parents=True, exist_ok=True)
+ generation = uuid.uuid4().hex
+ temp_path = generation_path.with_name(f".{generation_path.name}.{generation}.tmp")
+ try:
+ temp_path.write_text(generation, encoding="utf-8")
+ temp_path.replace(generation_path)
+ finally:
+ temp_path.unlink(missing_ok=True)
+
+ def _session_generation_path(self, base: str) -> Path:
+ digest = hashlib.sha256(base.encode("utf-8")).hexdigest()
+ return self._session_manager.sessions_dir / ".openapi-session-generations" / f"{digest}.txt"
+
@staticmethod
- def _scoped_session_id(principal_scope: str, session_id: str) -> str:
- return f"{principal_scope}:{session_id}"
+ def _ensure_no_pending(pending: Dict[str, PendingResponse], storage_key: str) -> None:
+ if storage_key in pending:
+ raise HTTPException(status_code=409, detail="Session already has a request in progress")
async def _gateway_health(self, request: Request) -> dict[str, Any]:
from vikingbot import __version__
@@ -1275,6 +1317,7 @@ class OpenAPIChannel(BaseChannel):
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)
+ self._ensure_no_pending(self._pending, storage_key)
# Create session if new
if storage_key not in self._sessions:
@@ -1304,11 +1347,7 @@ class OpenAPIChannel(BaseChannel):
chat_id=storage_key,
)
- # Build content with context if provided
content = self._request_content(request)
- if request.context:
- # Context is handled separately by session manager
- pass
# Create and publish inbound message
msg = InboundMessage(
@@ -1355,6 +1394,7 @@ class OpenAPIChannel(BaseChannel):
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)
+ self._ensure_no_pending(self._pending, storage_key)
# Create session if new
if storage_key not in self._sessions:
@@ -1428,6 +1468,7 @@ class OpenAPIChannel(BaseChannel):
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)
+ self._ensure_no_pending(self._bot_pending[channel_id], storage_key)
# Ensure channel has session storage
if channel_id not in self._bot_sessions:
@@ -1461,11 +1502,7 @@ class OpenAPIChannel(BaseChannel):
chat_id=storage_key,
)
- # Build content with context if provided
content = self._request_content(request)
- if request.context:
- # Context is handled separately by session manager
- pass
# Create and publish inbound message
msg = InboundMessage(
@@ -1516,6 +1553,7 @@ class OpenAPIChannel(BaseChannel):
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)
+ self._ensure_no_pending(self._bot_pending[channel_id], storage_key)
# Ensure channel has session storage
if channel_id not in self._bot_sessions:
diff --git a/bot/vikingbot/channels/openapi_models.py b/bot/vikingbot/channels/openapi_models.py
index 1ac16855a..9b1e77d6e 100644
--- a/bot/vikingbot/channels/openapi_models.py
+++ b/bot/vikingbot/channels/openapi_models.py
@@ -176,7 +176,8 @@ class ChatRequest(BaseModel):
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(
- default=None, description="Additional context messages"
+ default=None,
+ description="Non-empty context messages are not supported and are rejected",
)
need_reply: bool = True
channel_id: Optional[str] = Field(
@@ -192,9 +193,11 @@ class ChatRequest(BaseModel):
)
@model_validator(mode="after")
- def validate_message_or_images(self) -> "ChatRequest":
+ def validate_request(self) -> "ChatRequest":
if not self.message.strip() and not self.images:
raise ValueError("message or at least one image is required")
+ if self.context:
+ raise ValueError("context is not supported")
return self
diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.py
index 1a227ccd0..15ee6bfa0 100644
--- a/bot/vikingbot/cli/commands.py
+++ b/bot/vikingbot/cli/commands.py
@@ -1142,13 +1142,17 @@ def cron_add(
session_key = SessionKey(type="cli", channel_id="default", chat_id="default")
- job = service.add_job(
- name=name,
- schedule=schedule,
- message=message,
- deliver=deliver,
- session_key=session_key,
- )
+ try:
+ job = service.add_job(
+ name=name,
+ schedule=schedule,
+ message=message,
+ deliver=deliver,
+ session_key=session_key,
+ )
+ except ValueError as e:
+ console.print(f"[red]Error: {e}[/red]")
+ raise typer.Exit(1) from e
console.print(f"[green]✓[/green] Added job '{job.name}' ({job.id})")
@@ -1182,7 +1186,11 @@ def cron_enable(
store_path = get_data_dir() / "cron" / "jobs.json"
service = CronService(store_path)
- job = service.enable_job(job_id, enabled=not disable)
+ try:
+ job = service.enable_job(job_id, enabled=not disable)
+ except ValueError as e:
+ console.print(f"[red]Error: {e}[/red]")
+ raise typer.Exit(1) from e
if job:
status = "disabled" if disable else "enabled"
console.print(f"[green]✓[/green] Job '{job.name}' {status}")
@@ -1205,10 +1213,16 @@ def cron_run(
async def run():
return await service.run_job(job_id, force=force)
- if asyncio.run(run()):
- console.print("[green]✓[/green] Job executed")
- else:
+ try:
+ executed = asyncio.run(run())
+ except RuntimeError as e:
+ console.print(f"[red]Error: {e}[/red]")
+ raise typer.Exit(1) from e
+
+ if not executed:
console.print(f"[red]Failed to run job {job_id}[/red]")
+ raise typer.Exit(1)
+ console.print("[green]✓[/green] Job executed")
# ============================================================================
diff --git a/bot/vikingbot/cron/service.py b/bot/vikingbot/cron/service.py
index f143bba01..6d5248e38 100644
--- a/bot/vikingbot/cron/service.py
+++ b/bot/vikingbot/cron/service.py
@@ -103,9 +103,7 @@ class CronService:
)
self._store = CronStore(jobs=jobs)
except Exception as e:
- raise RuntimeError(
- f"Failed to load cron store from {self.store_path}: {e}"
- ) from e
+ raise RuntimeError(f"Failed to load cron store from {self.store_path}: {e}") from e
else:
self._store = CronStore()
@@ -234,8 +232,9 @@ class CronService:
logger.info(f"Cron: executing job '{job.name}' ({job.id})")
try:
- if self.on_job:
- await self.on_job(job)
+ if self.on_job is None:
+ raise RuntimeError("Cron service has no job execution callback")
+ await self.on_job(job)
job.state.last_status = "ok"
job.state.last_error = None
@@ -279,8 +278,11 @@ class CronService:
delete_after_run: bool = False,
) -> CronJob:
"""Add a new job."""
- store = self._load_store()
now = _now_ms()
+ next_run_at_ms = _compute_next_run(schedule, now)
+ if next_run_at_ms is None:
+ raise ValueError("Schedule does not have a future run time")
+ store = self._load_store()
job = CronJob(
id=str(uuid.uuid4())[:8],
@@ -294,7 +296,7 @@ class CronService:
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)),
+ state=CronJobState(next_run_at_ms=next_run_at_ms),
created_at_ms=now,
updated_at_ms=now,
delete_after_run=delete_after_run,
@@ -326,12 +328,14 @@ class CronService:
store = self._load_store()
for job in store.jobs:
if job.id == job_id:
+ next_run_at_ms = None
+ if enabled:
+ 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")
job.enabled = enabled
job.updated_at_ms = _now_ms()
- if enabled:
- job.state.next_run_at_ms = _compute_next_run(job.schedule, _now_ms())
- else:
- job.state.next_run_at_ms = None
+ job.state.next_run_at_ms = next_run_at_ms
self._save_store()
self._arm_timer()
return job
@@ -344,6 +348,8 @@ class CronService:
if job.id == job_id:
if not force and not job.enabled:
return False
+ if self.on_job is None:
+ raise RuntimeError("Cron service has no job execution callback")
await self._execute_job(job)
self._save_store()
self._arm_timer()
diff --git a/bot/vikingbot/sandbox/backends/srt.py b/bot/vikingbot/sandbox/backends/srt.py
index 4f09f6081..1a16e1efa 100644
--- a/bot/vikingbot/sandbox/backends/srt.py
+++ b/bot/vikingbot/sandbox/backends/srt.py
@@ -4,25 +4,24 @@ import asyncio
import json
import os
from pathlib import Path
-from typing import TYPE_CHECKING, Any
+from typing import Any
+
from loguru import logger
-from vikingbot.sandbox.base import SandboxBackend, SandboxNotStartedError
+from vikingbot.config.schema import SandboxConfig
from vikingbot.sandbox.backends import register_backend
-
-
-from vikingbot.config.schema import SandboxConfig, SessionKey
+from vikingbot.sandbox.base import SandboxBackend, SandboxNotStartedError
@register_backend("srt")
class SrtBackend(SandboxBackend):
"""SRT backend using @anthropic-ai/sandbox-runtime."""
- def __init__(self, config, session_key: SessionKey, workspace: Path):
+ def __init__(self, config: SandboxConfig, workspace_id: str, workspace: Path):
# SRT has built-in isolation, restrict_to_workspace is not needed
super().__init__()
self.config = config
- self.session_key = session_key
+ self.workspace_id = workspace_id
self._workspace = workspace
self._process = None
self._settings_path = self._generate_settings()
@@ -42,9 +41,7 @@ class SrtBackend(SandboxBackend):
srt_config = self._load_config()
# Place settings file in workspace/sandboxes/ directory
- settings_path = (
- self._workspace / "sandboxes" / f"{self.session_key.safe_name()}-srt-settings.json"
- )
+ settings_path = self._workspace / "sandboxes" / f"{self.workspace_id}-srt-settings.json"
settings_path.parent.mkdir(parents=True, exist_ok=True)
with open(settings_path, "w") as f:
@@ -224,6 +221,7 @@ class SrtBackend(SandboxBackend):
def _load_config(self) -> dict[str, Any]:
sandbox_workspace_str = str(self._workspace.resolve())
allow_write = [sandbox_workspace_str]
+ srt_config = self.config.backends.srt
tmp_dir = "/tmp"
if tmp_dir not in allow_write:
@@ -231,14 +229,14 @@ class SrtBackend(SandboxBackend):
return {
"network": {
- "allowedDomains": self.config.network.allowed_domains,
- "deniedDomains": self.config.network.denied_domains,
- "allowLocalBinding": self.config.network.allow_local_binding,
+ "allowedDomains": srt_config.network.allowed_domains,
+ "deniedDomains": srt_config.network.denied_domains,
+ "allowLocalBinding": srt_config.network.allow_local_binding,
},
"filesystem": {
- "denyRead": self.config.filesystem.deny_read,
+ "denyRead": srt_config.filesystem.deny_read,
"allowWrite": allow_write,
- "denyWrite": self.config.filesystem.deny_write,
+ "denyWrite": srt_config.filesystem.deny_write,
},
}
diff --git a/bot/vikingbot/sandbox/manager.py b/bot/vikingbot/sandbox/manager.py
index 595fd6bcf..20774b7c7 100644
--- a/bot/vikingbot/sandbox/manager.py
+++ b/bot/vikingbot/sandbox/manager.py
@@ -1,15 +1,11 @@
"""Sandbox manager for creating and managing sandbox instances."""
-import asyncio
from pathlib import Path
-from typing import TYPE_CHECKING
from openviking.async_client import logger
-from vikingbot.sandbox.base import SandboxBackend, SandboxDisabledError, UnsupportedBackendError
+from vikingbot.config.schema import Config, SessionKey
from vikingbot.sandbox.backends import get_backend
-
-
-from vikingbot.config.schema import SandboxConfig, SessionKey, Config
+from vikingbot.sandbox.base import SandboxBackend, UnsupportedBackendError
class SandboxManager:
@@ -44,20 +40,23 @@ class SandboxManager:
instance = self._backend_cls(self.config.sandbox, workspace_id, workspace)
try:
await instance.start()
- except Exception as e:
- import traceback
-
- traceback.print_exc()
- if not workspace.exists():
- await self._copy_bootstrap_files(workspace)
+ if not workspace.exists():
+ await self._copy_bootstrap_files(workspace)
+ except Exception:
+ logger.exception(f"Failed to start sandbox for workspace {workspace_id}")
+ try:
+ await instance.stop()
+ except Exception:
+ logger.exception(f"Failed to clean up sandbox for workspace {workspace_id}")
+ raise
return instance
async def _copy_bootstrap_files(self, sandbox_workspace: Path) -> None:
"""Copy bootstrap files from source workspace to sandbox workspace."""
- from vikingbot.agent.context import ContextBuilder
- from vikingbot.agent.skills import BUILTIN_SKILLS_DIR
import shutil
+ from vikingbot.agent.context import ContextBuilder
+
# Copy from source workspace init directory (if exists)
init_dir = self.source_workspace / ContextBuilder.INIT_DIR
if init_dir.exists() and init_dir.is_dir():
diff --git a/bot/vikingbot/utils/helpers.py b/bot/vikingbot/utils/helpers.py
index 17fb7681c..909c7c119 100644
--- a/bot/vikingbot/utils/helpers.py
+++ b/bot/vikingbot/utils/helpers.py
@@ -1,7 +1,8 @@
"""Utility functions for vikingbot."""
-from pathlib import Path
from datetime import datetime
+from pathlib import Path
+
from loguru import logger
@@ -97,6 +98,9 @@ def get_mounts_path() -> Path:
def get_source_workspace_path() -> Path:
"""Get the source workspace path from the codebase."""
+ package_workspace = Path(__file__).parent.parent / "workspace"
+ if package_workspace.is_dir():
+ return package_workspace
return Path(__file__).parent.parent.parent / "workspace"
@@ -106,6 +110,7 @@ def get_workspace_path() -> Path:
def ensure_workspace_templates(workspace: Path) -> None:
import shutil
+
from vikingbot.agent.skills import BUILTIN_SKILLS_DIR
# Ensure workspace directory exists first
@@ -117,7 +122,7 @@ def ensure_workspace_templates(workspace: Path) -> None:
if not has_any_file:
# Workspace is empty, copy templates from source
- source_dir = Path(__file__).parent.parent.parent / "workspace"
+ source_dir = get_source_workspace_path()
if not source_dir.exists():
# Fallback: create minimal templates
diff --git a/crates/ragfs/Cargo.toml b/crates/ragfs/Cargo.toml
index 3dad1781c..082fb13b1 100644
--- a/crates/ragfs/Cargo.toml
+++ b/crates/ragfs/Cargo.toml
@@ -100,6 +100,9 @@ grep-matcher = "0.1.8"
grep-regex = "0.1.14"
grep-searcher = "0.1.16"
+[target.'cfg(windows)'.dependencies]
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }
+
# Development dependencies
[dev-dependencies]
tempfile = "3.12"
diff --git a/crates/ragfs/src/plugins/localfs/mod.rs b/crates/ragfs/src/plugins/localfs/mod.rs
index bb71063d2..162b5efd2 100644
--- a/crates/ragfs/src/plugins/localfs/mod.rs
+++ b/crates/ragfs/src/plugins/localfs/mod.rs
@@ -93,38 +93,69 @@ impl LocalFileSystem {
}
}
- /// Return whether an open file still identifies the file currently stored at `path`.
- fn open_file_matches_path(file: &fs::File, path: &Path) -> Result<bool> {
- let open_metadata = file
- .metadata()
- .map_err(|e| Error::plugin(format!("failed to stat open CAS file: {}", e)))?;
- let path_metadata = match fs::metadata(path) {
- Ok(metadata) => metadata,
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
- Err(e) => {
- return Err(Error::plugin(format!(
- "failed to stat CAS path '{}': {}",
- path.display(),
- e
- )));
- }
+ #[cfg(windows)]
+ fn windows_file_identity(file: &fs::File) -> Result<(u32, u64)> {
+ use std::os::windows::io::AsRawHandle;
+ use windows_sys::Win32::Storage::FileSystem::{
+ GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
};
+ let mut info = BY_HANDLE_FILE_INFORMATION::default();
+ // SAFETY: `file` owns a live OS handle and `info` points to valid,
+ // writable storage for the duration of this call.
+ let succeeded =
+ unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info as *mut _) };
+ if succeeded == 0 {
+ return Err(Error::plugin(format!(
+ "failed to inspect open CAS file: {}",
+ std::io::Error::last_os_error()
+ )));
+ }
+
+ let file_index = (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow);
+ Ok((info.dwVolumeSerialNumber, file_index))
+ }
+
+ /// Return whether an open file still identifies the file currently stored at `path`.
+ fn open_file_matches_path(file: &fs::File, path: &Path) -> Result<bool> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
+ let open_metadata = file
+ .metadata()
+ .map_err(|e| Error::plugin(format!("failed to stat open CAS file: {}", e)))?;
+ let path_metadata = match fs::metadata(path) {
+ Ok(metadata) => metadata,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(e) => {
+ return Err(Error::plugin(format!(
+ "failed to stat CAS path '{}': {}",
+ path.display(),
+ e
+ )));
+ }
+ };
Ok(open_metadata.dev() == path_metadata.dev()
&& open_metadata.ino() == path_metadata.ino())
}
#[cfg(windows)]
{
- use std::os::windows::fs::MetadataExt;
- Ok(open_metadata.volume_serial_number() == path_metadata.volume_serial_number()
- && open_metadata.file_index() == path_metadata.file_index())
+ let path_file = match fs::File::open(path) {
+ Ok(path_file) => path_file,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(e) => {
+ return Err(Error::plugin(format!(
+ "failed to open CAS path '{}': {}",
+ path.display(),
+ e
+ )));
+ }
+ };
+ Ok(Self::windows_file_identity(file)? == Self::windows_file_identity(&path_file)?)
}
#[cfg(not(any(unix, windows)))]
{
- let _ = (open_metadata, path_metadata);
+ let _ = (file, path);
Err(Error::invalid_operation(
"CAS file identity checks are unsupported on this platform",
))
@@ -1372,6 +1403,28 @@ mod tests {
std::fs::write(path, content).unwrap();
}
+ #[test]
+ fn test_open_file_identity_matches_only_the_current_path_entry() {
+ let dir = TempDir::new().unwrap();
+ write_file(dir.path(), "first.txt", "same content");
+ write_file(dir.path(), "second.txt", "same content");
+
+ let first_path = dir.path().join("first.txt");
+ let first_file = std::fs::File::open(&first_path).unwrap();
+
+ assert!(LocalFileSystem::open_file_matches_path(&first_file, &first_path).unwrap());
+ assert!(!LocalFileSystem::open_file_matches_path(
+ &first_file,
+ &dir.path().join("second.txt")
+ )
+ .unwrap());
+ assert!(!LocalFileSystem::open_file_matches_path(
+ &first_file,
+ &dir.path().join("missing.txt")
+ )
+ .unwrap());
+ }
+
#[tokio::test]
async fn test_localfs_rejects_parent_path_components() {
let dir = TempDir::new().unwrap();
diff --git a/pyproject.toml b/pyproject.toml
index b6645691f..2deda373a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -235,6 +235,7 @@ vikingbot = [
"**/*.mjs",
"skills/**/*.md",
"skills/**/*.sh",
+ "workspace/**/*",
"bridge/**/*",
]
diff --git a/setup.py b/setup.py
index ea09762c4..0f06758a8 100644
--- a/setup.py
+++ b/setup.py
@@ -512,6 +512,23 @@ class OpenVikingBuildPy(build_py):
def run(self):
_build_web_studio()
super().run()
+ package_root = Path(self.build_lib) / "vikingbot"
+ for asset_name in ("workspace", "bridge"):
+ source = SETUP_DIR / "bot" / asset_name
+ if not source.is_dir():
+ raise FileNotFoundError(
+ f"required VikingBot asset directory not found: {source}"
+ )
+ destination = package_root / asset_name
+ if destination.exists():
+ shutil.rmtree(destination)
+ shutil.copytree(
+ source,
+ destination,
+ ignore=shutil.ignore_patterns(
+ "node_modules", "dist", "__pycache__", "*.pyc"
+ ),
+ )
if bdist_wheel is not None:
@@ -552,6 +569,10 @@ setup(
"storage/vectordb/engine/*.abi3.so",
"storage/vectordb/engine/*.pyd",
],
+ "vikingbot": [
+ "workspace/**/*",
+ "bridge/**/*",
+ ],
},
include_package_data=True,
)