增加主人身份识别和网络搜索工具调用

This commit is contained in:
2026-03-14 00:19:45 +08:00
parent 2d2992d66d
commit 74cd7353f5
23 changed files with 1329 additions and 6 deletions
+72 -1
View File
@@ -19,6 +19,8 @@ VoidBot is a Python agent runtime built around three ideas:
- Let the gateway receive HTTP, Feishu, and QQ traffic
- Store sessions, messages, and session metadata in SQLite
- Configure multiple providers and switch models per session
- Support canonical identity binding, with local CLI always treated as the owner
- Let owner-bound direct messages share context with the local `main` session
## Installation
@@ -119,7 +121,51 @@ voidbot --message "Summarize this repository"
voidbot gateway
```
8. Inspect SQLite data
8. Inspect the current identity inside a channel conversation
First, send this to VoidBot from Feishu or QQ:
```text
/whoami
```
It returns the identity resolved for the current incoming message, including:
- `identity_status`
- `actor_user_id`
- `actor_external_id`
- `actor_is_owner`
- `session_id`
The most important field here is `actor_external_id`, because you will use it for binding.
9. Bind that channel identity to the owner locally
For Feishu:
```bash
voidbot identity bind-owner --channel feishu --external-id YOUR_FEISHU_OPEN_ID
```
For QQ:
```bash
voidbot identity bind-owner --channel qq --external-id YOUR_QQ_EXTERNAL_ID
```
After this, the system layer treats that external identity as the owner. The model does not decide this on its own.
10. Continue chatting from the channel DM or the local CLI
Current routing rules:
- Local `cli` is always treated as the owner and always enters `main`
- Direct messages bound to the owner also enter `main`
- Unbound identities or group messages do not merge into `main`
So once you bind a Feishu or QQ direct-message identity to the owner, the local CLI and that direct-message thread share the same context.
11. Inspect SQLite data
```bash
voidbot data dump
@@ -194,12 +240,37 @@ Inside a conversation:
```text
/models
/use 2
/whoami
```
- `/models` lists configured models
- `/use <id>` switches only the current session
- `/whoami` shows the identity resolution result for the current message
- The selected provider id is stored in SQLite session metadata
## Identity Binding
If you want one Feishu or QQ direct-message conversation to share the owner's context with the local CLI, use this flow:
1. Send `/whoami` in that direct-message conversation
2. Copy the returned `actor_external_id`
3. Run `voidbot identity bind-owner --channel <channel> --external-id <id>` locally
4. Later direct messages from that bound identity are routed into the owner `main` session
Available commands:
```bash
voidbot identity bind-owner --channel feishu --external-id YOUR_FEISHU_OPEN_ID
voidbot identity bind-owner --channel qq --external-id YOUR_QQ_EXTERNAL_ID
voidbot identity list
```
Notes:
- `bind-owner` is a local CLI management command used to bind one external identity to the owner
- `identity list` prints canonical users and stored external identity bindings
- Binding direct-message identities is recommended before binding any group-side identities
## User Home
The default user-level data directory is `~/.voidbot`:
+72 -1
View File
@@ -17,6 +17,8 @@ VoidBot 是一个 Python 智能体
- gateway 可同时接收 HTTP、飞书、QQ
- 使用 SQLite 存储 session、消息和 session 元数据
- 支持配置多个 provider,并按 session 动态切换模型
- 支持渠道身份归一,本地 CLI 固定视为主人
- 已绑定到主人的直聊消息可与本地 `main` 会话共享上下文
## 安装
@@ -117,7 +119,51 @@ voidbot --message "Summarize this repository"
voidbot gateway
```
8. 查看 SQLite 数据
8. 在渠道对话里查看当前身份
先在飞书或 QQ 里给 VoidBot 发:
```text
/whoami
```
它会直接回显当前这条消息解析到的:
- `identity_status`
- `actor_user_id`
- `actor_external_id`
- `actor_is_owner`
- `session_id`
其中最重要的是 `actor_external_id`,后面绑定主人时会用到。
9. 在本地把这个渠道身份绑定给主人
例如飞书:
```bash
voidbot identity bind-owner --channel feishu --external-id YOUR_FEISHU_OPEN_ID
```
例如 QQ:
```bash
voidbot identity bind-owner --channel qq --external-id YOUR_QQ_EXTERNAL_ID
```
执行后,这个渠道身份就会被系统层认定为主人,不依赖大模型自己推断。
10. 绑定后继续在渠道私聊或本地 CLI 中对话
当前规则是:
- 本地 `cli` 永远视为主人,固定进入 `main`
- 已绑定到主人的直聊消息也会进入 `main`
- 未绑定身份或群聊消息不会自动并入 `main`
所以当您把飞书或 QQ 的私聊身份绑定给主人后,本地和该渠道私聊会共享同一段上下文。
11. 查看 SQLite 数据
```bash
voidbot data dump
@@ -192,12 +238,37 @@ voidbot data dump --session-id main
```text
/models
/use 2
/whoami
```
- `/models` 查看所有可用模型
- `/use <id>` 只切换当前 session
- `/whoami` 查看当前这条消息对应的身份解析结果
- 当前选择会写入 SQLite 的 session 元数据
## 身份绑定
如果您希望某个飞书或 QQ 直聊和本地 CLI 共享主人上下文,推荐流程如下:
1. 在该渠道私聊里发送 `/whoami`
2. 记下返回里的 `actor_external_id`
3. 在本地执行 `voidbot identity bind-owner --channel <channel> --external-id <id>`
4. 之后该渠道直聊会被路由到主会话 `main`
可用命令:
```bash
voidbot identity bind-owner --channel feishu --external-id YOUR_FEISHU_OPEN_ID
voidbot identity bind-owner --channel qq --external-id YOUR_QQ_EXTERNAL_ID
voidbot identity list
```
说明:
- `bind-owner` 只能通过本地 CLI 执行,用来把某个外部身份绑定给主人
- `identity list` 用于查看当前数据库里的规范用户与外部身份绑定
- 目前更建议绑定私聊身份,不建议先绑定群聊身份
## 用户目录
默认用户级数据目录为 `~/.voidbot`:
+1
View File
@@ -30,6 +30,7 @@
"max_iterations": 8,
"history_limit": 24,
"system_prompt": "You are VoidBot, a concise coding agent. Use tools when needed, cite tool results plainly, and finish once the task is complete.",
"jina_api_key": "YOUR_JINA_API_KEY",
"gateway_host": "127.0.0.1",
"gateway_port": 8787,
"gateway_url": "http://127.0.0.1:8787",
+51
View File
@@ -229,9 +229,14 @@ class AgentRuntime:
"python_executable": inbound.python_executable,
"runtime_mode": execution.runtime_mode,
"install_mode": execution.install_mode,
"actor_identity_status": inbound.actor_identity_status,
"actor_user_id": inbound.actor_user_id,
"actor_role": inbound.actor_role,
"actor_external_id": inbound.actor_external_id,
}.items():
if value:
metadata[key] = value
metadata["actor_is_owner"] = inbound.actor_is_owner
if inbound.capabilities:
metadata["channel_capabilities"] = list(inbound.capabilities)
return metadata
@@ -539,6 +544,23 @@ class AgentRuntime:
model_name=provider_description["model"],
)
if text == "/whoami":
description = self._format_actor_identity(inbound)
provider_description = self.providers.describe(session_state.provider_id)
self._record_control_command(
inbound,
command_text=text,
reply_text=description,
provider_id=provider_description["id"],
)
return RunTurnResult(
reply=description,
iterations=0,
provider_id=provider_description["id"],
provider_label=provider_description["label"],
model_name=provider_description["model"],
)
if text.startswith("/use "):
provider_id = text.removeprefix("/use ").strip()
if not provider_id:
@@ -624,6 +646,35 @@ class AgentRuntime:
lines.append(t("agent.models.switch_hint"))
return "\n".join(lines)
@staticmethod
def _format_actor_identity(inbound: InboundMessageContext) -> str:
lines = [t("agent.identity.title")]
lines.append(
t("agent.identity.status", value=inbound.actor_identity_status or "unknown")
)
lines.append(t("agent.identity.role", value=inbound.actor_role or "unknown"))
lines.append(
t(
"agent.identity.user_id",
value=inbound.actor_user_id or "(unresolved)",
)
)
lines.append(
t(
"agent.identity.external_id",
value=inbound.actor_external_id or "(unknown)",
)
)
lines.append(
t(
"agent.identity.is_owner",
value="true" if inbound.actor_is_owner else "false",
)
)
lines.append(t("agent.identity.channel", value=inbound.channel or "unknown"))
lines.append(t("agent.identity.session", value=inbound.session_id))
return "\n".join(lines)
def _format_runtime(self, inbound: InboundMessageContext) -> str:
execution = detect_runtime_execution(
entrypoint_path=inbound.entrypoint_path,
+5 -1
View File
@@ -26,7 +26,11 @@ def build_app(config: AppConfig) -> VoidBotApp:
config=config,
providers=ProviderManager(config),
session=SessionStore(config.storage_path),
tools=build_default_tool_registry(config.workspace),
tools=build_default_tool_registry(
config.workspace,
jina_api_key=config.jina_api_key,
request_timeout=config.request_timeout,
),
context_builder=ContextBuilder(config),
)
return VoidBotApp(config=config, runtime=runtime)
+3
View File
@@ -32,9 +32,12 @@ class InboundChannelMessage:
message_id: str = field(default_factory=_new_id)
received_at: str = field(default_factory=_now_utc)
metadata: dict[str, Any] = field(default_factory=dict)
resolved_session_id: str | None = None
@property
def session_id(self) -> str:
if self.resolved_session_id:
return self.resolved_session_id
return f"{self.channel}:{self.chat_id}"
+52
View File
@@ -13,6 +13,12 @@ from voidbot.channels.typing import create_reply_indicator_callbacks
from voidbot.config import ChannelsConfig
from voidbot.gateway.messages import InboundMessageContext
from voidbot.gateway.run_queue import InMemoryRunQueue
from voidbot.identity import (
build_bound_identity,
build_unknown_identity,
is_direct_channel_message,
resolve_session_id_for_channel,
)
LOGGER = logging.getLogger(__name__)
@@ -69,6 +75,14 @@ class ChannelManager:
LOGGER.warning("Received message for unknown channel: %s", message.channel)
return
actor = self._resolve_actor_identity(message)
message.resolved_session_id = resolve_session_id_for_channel(
actor=actor,
channel=message.channel,
chat_id=message.chat_id,
is_direct=is_direct_channel_message(message),
)
inbound = InboundMessageContext(
session_id=message.session_id,
raw_body=message.raw_body or message.body,
@@ -79,6 +93,11 @@ class ChannelManager:
source_mode="channel",
channel=message.channel,
capabilities=channel.capabilities,
actor_identity_status=actor.identity_status,
actor_user_id=actor.canonical_user_id,
actor_role=actor.role,
actor_external_id=actor.external_id,
actor_is_owner=actor.is_owner,
)
self._update_runtime_metadata(inbound)
reply_indicator = create_reply_indicator_callbacks(
@@ -193,9 +212,42 @@ class ChannelManager:
metadata["channel"] = inbound.channel
if inbound.capabilities:
metadata["channel_capabilities"] = list(inbound.capabilities)
metadata["actor_identity_status"] = inbound.actor_identity_status
metadata["actor_role"] = inbound.actor_role
metadata["actor_is_owner"] = inbound.actor_is_owner
if inbound.actor_user_id:
metadata["actor_user_id"] = inbound.actor_user_id
if inbound.actor_external_id:
metadata["actor_external_id"] = inbound.actor_external_id
if metadata:
updater(inbound.session_id, metadata=metadata)
def _resolve_actor_identity(self, message: InboundChannelMessage):
session_store = getattr(self.runtime, "session", None)
if session_store is None:
return build_unknown_identity(
channel=message.channel,
external_id=message.sender_id,
)
binding = getattr(session_store, "get_identity_binding", None)
if binding is None:
return build_unknown_identity(
channel=message.channel,
external_id=message.sender_id,
)
resolved = binding(channel=message.channel, external_id=message.sender_id)
if resolved is None:
return build_unknown_identity(
channel=message.channel,
external_id=message.sender_id,
)
return build_bound_identity(
channel=resolved.channel,
external_id=resolved.external_id,
canonical_user_id=resolved.user_id,
role=resolved.user_role,
)
def start_background(self) -> None:
"""Start channel listeners on a dedicated asyncio loop thread."""
if not self.channels:
+5
View File
@@ -191,6 +191,7 @@ def build_example_config() -> dict[str, Any]:
"Use tools when needed, cite tool results plainly, "
"and finish once the task is complete."
),
"jina_api_key": "YOUR_JINA_API_KEY",
"gateway_host": "127.0.0.1",
"gateway_port": 8787,
"gateway_url": "http://127.0.0.1:8787",
@@ -335,6 +336,7 @@ class AppConfig:
context_safety_margin_tokens: int = 1024
context_compaction_max_rounds: int = 3
system_prompt: str | None = None
jina_api_key: str = ""
request_timeout: int = 120
gateway_host: str = "127.0.0.1"
gateway_port: int = 8787
@@ -399,6 +401,7 @@ class AppConfig:
system_prompt=str(data["system_prompt"])
if data.get("system_prompt")
else None,
jina_api_key=str(data.get("jina_api_key") or ""),
request_timeout=int(data.get("request_timeout") or 120),
gateway_host=str(data.get("gateway_host") or "127.0.0.1"),
gateway_port=int(data.get("gateway_port") or 8787),
@@ -544,6 +547,8 @@ def load_config(
"VOIDBOT_CONTEXT_COMPACTION_MAX_ROUNDS"
),
"system_prompt": os.getenv("VOIDBOT_SYSTEM_PROMPT"),
"jina_api_key": os.getenv("VOIDBOT_JINA_API_KEY")
or os.getenv("JINA_API_KEY"),
"request_timeout": os.getenv("VOIDBOT_REQUEST_TIMEOUT"),
"gateway_host": os.getenv("VOIDBOT_GATEWAY_HOST"),
"gateway_port": os.getenv("VOIDBOT_GATEWAY_PORT"),
+12
View File
@@ -122,6 +122,11 @@ class ContextBuilder:
", ".join(inbound.capabilities) if inbound.capabilities else "none"
)
source_mode = inbound.source_mode or "unknown"
actor_user_id = inbound.actor_user_id or "(unresolved)"
actor_external_id = inbound.actor_external_id or "(unknown)"
actor_role = inbound.actor_role or "unknown"
actor_status = inbound.actor_identity_status or "unknown"
actor_owner = "true" if inbound.actor_is_owner else "false"
return (
"## Runtime Environment\n"
f"Time: {now}\n"
@@ -144,6 +149,13 @@ class ContextBuilder:
f"Received At: {inbound.received_at}\n"
f"Provider: {provider_summary}\n"
"\n"
"## Actor Identity\n"
f"Identity Status: {actor_status}\n"
f"Actor Role: {actor_role}\n"
f"Actor User ID: {actor_user_id}\n"
f"Actor External ID: {actor_external_id}\n"
f"Is Owner: {actor_owner}\n"
"\n"
"## Available Tools\n"
f"{tool_text}\n\n"
"## Workspace Instructions\n"
+91
View File
@@ -27,6 +27,7 @@ from voidbot.gateway.messages import InboundMessageContext
from voidbot.gateway.run_queue import InMemoryRunQueue
from voidbot.gateway.server import GatewayApplication, run_gateway_server
from voidbot.gateway.ui import render_single_turn, run_terminal_loop
from voidbot.identity import OWNER_USER_ID
from voidbot.i18n import t
from voidbot.providers.registry import get_provider_spec, list_provider_specs
from voidbot.runtime_env import (
@@ -159,6 +160,43 @@ def build_parser() -> argparse.ArgumentParser:
help=t("cli.help.data.limit"),
)
identity_parser = subparsers.add_parser(
"identity",
help=t("cli.help.identity"),
)
identity_subparsers = identity_parser.add_subparsers(
dest="identity_command",
required=True,
)
bind_owner_parser = identity_subparsers.add_parser(
"bind-owner",
help=t("cli.help.identity.bind_owner"),
)
bind_owner_parser.add_argument(
"--config",
type=Path,
help=_config_help_text(),
)
bind_owner_parser.add_argument(
"--channel",
required=True,
help=t("cli.help.identity.channel"),
)
bind_owner_parser.add_argument(
"--external-id",
required=True,
help=t("cli.help.identity.external_id"),
)
list_parser = identity_subparsers.add_parser(
"list",
help=t("cli.help.identity.list"),
)
list_parser.add_argument(
"--config",
type=Path,
help=_config_help_text(),
)
return parser
@@ -211,6 +249,17 @@ def main() -> None:
session_id=args.session_id,
limit=args.limit,
)
return
if args.command == "identity":
if args.identity_command == "bind-owner":
run_identity_bind_owner_command(
config_path=args.config,
channel=args.channel,
external_id=args.external_id,
)
return
if args.identity_command == "list":
run_identity_list_command(config_path=args.config)
def _config_help_text() -> str:
@@ -443,6 +492,43 @@ def run_data_dump_command(
print(json.dumps(payload, ensure_ascii=False, indent=2))
def run_identity_bind_owner_command(
*,
config_path: Path | None,
channel: str,
external_id: str,
) -> None:
"""Bind one external identity to the local owner."""
config = load_config(config_path, require_api_key=False)
store = SessionStore(config.storage_path)
binding = store.bind_identity(
channel=channel,
external_id=external_id,
user_id=OWNER_USER_ID,
role="owner",
)
print(
t(
"identity.bind_owner.saved",
channel=binding.channel,
external_id=binding.external_id,
user_id=binding.user_id,
)
)
def run_identity_list_command(*, config_path: Path | None) -> None:
"""Print stored canonical users and external identity bindings."""
config = load_config(config_path, require_api_key=False)
store = SessionStore(config.storage_path)
payload = {
"database_path": str(config.storage_path),
"users": store.list_users(),
"identities": store.list_identities(),
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
def _open_path(path: Path) -> None:
"""Open a path with the platform default application."""
if os.name == "nt":
@@ -551,6 +637,11 @@ def _run_one_turn(
launch_cwd=resolve_launch_cwd(),
entrypoint_path=resolve_entrypoint_path(),
python_executable=resolve_python_executable(),
actor_identity_status="owner",
actor_user_id=OWNER_USER_ID,
actor_role="owner",
actor_external_id=OWNER_USER_ID,
actor_is_owner=True,
)
if via == "local":
return _run_local(inbound, config)
+5
View File
@@ -36,6 +36,11 @@ class GatewayClient:
"launch_cwd": inbound.launch_cwd,
"entrypoint_path": inbound.entrypoint_path,
"python_executable": inbound.python_executable,
"actor_identity_status": inbound.actor_identity_status,
"actor_user_id": inbound.actor_user_id,
"actor_role": inbound.actor_role,
"actor_external_id": inbound.actor_external_id,
"actor_is_owner": inbound.actor_is_owner,
}
return self._request("POST", "/v1/agent/run", payload)
+28
View File
@@ -6,6 +6,8 @@ from dataclasses import dataclass, field
from datetime import datetime, timezone
import uuid
from voidbot.identity import OWNER_USER_ID
def _new_id() -> str:
return uuid.uuid4().hex
@@ -31,6 +33,11 @@ class InboundMessageContext:
entrypoint_path: str | None = None
python_executable: str | None = None
capabilities: tuple[str, ...] = field(default_factory=tuple)
actor_identity_status: str = "unknown"
actor_user_id: str | None = None
actor_role: str = "unknown"
actor_external_id: str | None = None
actor_is_owner: bool = False
def __post_init__(self) -> None:
if not self.run_id:
@@ -41,3 +48,24 @@ class InboundMessageContext:
self.received_at = _now_utc()
if not isinstance(self.capabilities, tuple):
self.capabilities = tuple(str(item) for item in self.capabilities)
self.actor_identity_status = str(
self.actor_identity_status or "unknown"
).strip() or "unknown"
self.actor_role = str(self.actor_role or "unknown").strip() or "unknown"
if self.actor_user_id is not None:
self.actor_user_id = str(self.actor_user_id).strip() or None
if self.actor_external_id is not None:
self.actor_external_id = str(self.actor_external_id).strip() or None
self.actor_is_owner = bool(self.actor_is_owner)
if (
(self.channel or "").strip().lower() == "cli"
and self.actor_identity_status == "unknown"
and self.actor_user_id is None
and self.actor_external_id is None
and not self.actor_is_owner
):
self.actor_identity_status = "owner"
self.actor_user_id = OWNER_USER_ID
self.actor_role = "owner"
self.actor_external_id = OWNER_USER_ID
self.actor_is_owner = True
+9
View File
@@ -72,6 +72,15 @@ class GatewayApplication:
python_executable=str(payload["python_executable"])
if payload.get("python_executable")
else None,
actor_identity_status=str(payload.get("actor_identity_status") or "unknown"),
actor_user_id=str(payload["actor_user_id"])
if payload.get("actor_user_id")
else None,
actor_role=str(payload.get("actor_role") or "unknown"),
actor_external_id=str(payload["actor_external_id"])
if payload.get("actor_external_id")
else None,
actor_is_owner=bool(payload.get("actor_is_owner", False)),
)
result = self.run_queue.enqueue(
inbound.session_id,
+34 -2
View File
@@ -14,6 +14,11 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"cli.help.gateway": "Run the gateway server",
"cli.help.config": "Manage the user-level VoidBot config in ~/.voidbot",
"cli.help.data": "Inspect the SQLite-backed stored sessions and messages",
"cli.help.identity": "Manage canonical users and external identity bindings",
"cli.help.identity.bind_owner": "Bind one channel identity to the local owner",
"cli.help.identity.list": "Print canonical users and bound external identities",
"cli.help.identity.channel": "Channel name, for example qq or feishu",
"cli.help.identity.external_id": "Channel-specific sender id such as open_id",
"cli.help.config.sync": (
"Create or incrementally update ~/.voidbot/config.json from the example template"
),
@@ -73,6 +78,9 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"config.add_model.provider_item": (
" - {id}. {label} [preset={preset}, model={model}]"
),
"identity.bind_owner.saved": (
"Bound {channel}:{external_id} to owner user {user_id}"
),
"gateway.listening": "VoidBot gateway listening on http://{host}:{port}",
"ui.title": "terminal agent",
"ui.session": "Session",
@@ -82,7 +90,7 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"ui.model": "model={value}",
"ui.gateway": "gateway={value}",
"ui.welcome": "Enter submit, Esc+Enter newline, Ctrl+L clear screen",
"ui.model_help": "/use <id> switch model, /models list models, /runtime show runtime",
"ui.model_help": "/use <id> switch model, /models list models, /runtime show runtime, /whoami show identity",
"ui.prompt.input": "Message",
"ui.user": "User",
"ui.assistant": "Assistant",
@@ -95,6 +103,14 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"agent.models.title": "Available models:",
"agent.models.switch_hint": "Use `/use <id>` to switch the current session model.",
"agent.runtime.title": "Current runtime:",
"agent.identity.title": "Current identity:",
"agent.identity.status": "identity_status: {value}",
"agent.identity.role": "actor_role: {value}",
"agent.identity.user_id": "actor_user_id: {value}",
"agent.identity.external_id": "actor_external_id: {value}",
"agent.identity.is_owner": "actor_is_owner: {value}",
"agent.identity.channel": "channel: {value}",
"agent.identity.session": "session_id: {value}",
"agent.use.switched": "Switched to model {id}: {label} / {model}",
"agent.provider.unknown": "unknown provider id '{provider_id}', expected one of: {available}",
"agent.local_requires_config": "local mode requires a config with provider credentials",
@@ -114,6 +130,11 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"cli.help.gateway": "启动 gateway 服务",
"cli.help.config": "管理位于 ~/.voidbot 的用户级 VoidBot 配置",
"cli.help.data": "查看使用 SQLite 持久化的会话与消息数据",
"cli.help.identity": "管理规范用户与外部身份绑定",
"cli.help.identity.bind_owner": "将一个渠道身份绑定到本地主人",
"cli.help.identity.list": "输出规范用户与已绑定的外部身份",
"cli.help.identity.channel": "渠道名,例如 qq 或 feishu",
"cli.help.identity.external_id": "渠道侧发送者 ID,例如 open_id",
"cli.help.config.sync": "根据示例模板创建或增量更新 ~/.voidbot/config.json",
"cli.help.config.path": "输出默认用户级配置文件路径",
"cli.help.config.open": "用系统默认程序打开配置文件",
@@ -171,6 +192,9 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"config.add_model.provider_item": (
" - {id}. {label} [preset={preset}, model={model}]"
),
"identity.bind_owner.saved": (
"已将 {channel}:{external_id} 绑定到主人用户 {user_id}"
),
"gateway.listening": "VoidBot gateway 正在监听 http://{host}:{port}",
"ui.title": "终端智能体",
"ui.session": "会话",
@@ -180,7 +204,7 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"ui.model": "模型={value}",
"ui.gateway": "gateway={value}",
"ui.welcome": "Enter 提交,Esc+Enter 换行,Ctrl+L 清屏",
"ui.model_help": "/use <id> 切换模型,/models 查看模型列表,/runtime 查看运行环境",
"ui.model_help": "/use <id> 切换模型,/models 查看模型列表,/runtime 查看运行环境,/whoami 查看身份",
"ui.prompt.input": "输入消息",
"ui.user": "主人",
"ui.assistant": "小月",
@@ -193,6 +217,14 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"agent.models.title": "可用模型列表:",
"agent.models.switch_hint": "使用 `/use <id>` 可切换当前会话的模型。",
"agent.runtime.title": "当前运行环境:",
"agent.identity.title": "当前身份:",
"agent.identity.status": "identity_status: {value}",
"agent.identity.role": "actor_role: {value}",
"agent.identity.user_id": "actor_user_id: {value}",
"agent.identity.external_id": "actor_external_id: {value}",
"agent.identity.is_owner": "actor_is_owner: {value}",
"agent.identity.channel": "channel: {value}",
"agent.identity.session": "session_id: {value}",
"agent.use.switched": "已切换到模型 {id}:{label} / {model}",
"agent.provider.unknown": "未知模型编号 '{provider_id}',可选值有:{available}",
"agent.local_requires_config": "本地模式需要带有模型凭据的配置",
+91
View File
@@ -0,0 +1,91 @@
"""Runtime identity resolution helpers."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
OWNER_SESSION_ID = "main"
OWNER_USER_ID = "owner"
@dataclass(frozen=True, slots=True)
class ActorIdentity:
"""Resolved actor identity for one inbound turn."""
identity_status: str
canonical_user_id: str | None = None
role: str = "unknown"
is_owner: bool = False
channel: str | None = None
external_id: str | None = None
def build_local_owner_identity() -> ActorIdentity:
"""Return the fixed owner identity used by local CLI turns."""
return ActorIdentity(
identity_status="owner",
canonical_user_id=OWNER_USER_ID,
role="owner",
is_owner=True,
channel="cli",
external_id=OWNER_USER_ID,
)
def build_unknown_identity(*, channel: str | None, external_id: str | None) -> ActorIdentity:
"""Return an unverified actor identity."""
return ActorIdentity(
identity_status="unknown",
canonical_user_id=None,
role="unknown",
is_owner=False,
channel=channel,
external_id=external_id,
)
def build_bound_identity(
*,
channel: str,
external_id: str,
canonical_user_id: str,
role: str,
) -> ActorIdentity:
"""Return one bound actor identity."""
normalized_role = role.strip().lower() or "user"
return ActorIdentity(
identity_status="owner" if normalized_role == "owner" else "known_user",
canonical_user_id=canonical_user_id.strip() or None,
role=normalized_role,
is_owner=normalized_role == "owner",
channel=channel,
external_id=external_id,
)
def is_direct_channel_message(message: Any) -> bool:
"""Best-effort detection for direct messages across supported channels."""
metadata = getattr(message, "metadata", {}) or {}
chat_type = str(metadata.get("chat_type") or "").strip().lower()
if chat_type:
return chat_type not in {"group", "channel"}
if "is_group" in metadata:
return not bool(metadata.get("is_group"))
reply_target_type = str(getattr(message, "reply_target_type", "") or "").strip().lower()
return reply_target_type not in {"group", "chat_id"}
def resolve_session_id_for_channel(
*,
actor: ActorIdentity,
channel: str,
chat_id: str,
is_direct: bool,
) -> str:
"""Resolve the runtime session id for one channel message."""
if is_direct and actor.is_owner:
return OWNER_SESSION_ID
if is_direct and actor.canonical_user_id:
return f"user:{actor.canonical_user_id}"
return f"{channel}:{chat_id}"
+306
View File
@@ -43,6 +43,31 @@ class SessionCompaction:
created_at: str | None = None
@dataclass(slots=True)
class UserRecord:
"""Stored canonical user."""
user_id: str
role: str
metadata: dict[str, Any] = field(default_factory=dict)
created_at: str | None = None
updated_at: str | None = None
@dataclass(slots=True)
class UserIdentityBinding:
"""Stored external identity binding."""
id: int
channel: str
external_id: str
user_id: str
user_role: str
metadata: dict[str, Any] = field(default_factory=dict)
created_at: str | None = None
updated_at: str | None = None
@dataclass(slots=True)
class SessionStore:
"""SQLite-backed chat history and session metadata."""
@@ -75,6 +100,31 @@ class SessionStore:
"""
)
connection.commit()
connection.execute(
"""
CREATE TABLE IF NOT EXISTS users (
user_id TEXT PRIMARY KEY,
role TEXT NOT NULL,
metadata_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
"""
)
connection.execute(
"""
CREATE TABLE IF NOT EXISTS user_identities (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel TEXT NOT NULL,
external_id TEXT NOT NULL,
user_id TEXT NOT NULL,
metadata_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(channel, external_id)
)
"""
)
connection.execute(
"""
CREATE TABLE IF NOT EXISTS messages (
@@ -103,6 +153,12 @@ class SessionStore:
)
"""
)
connection.execute(
"""
CREATE INDEX IF NOT EXISTS idx_user_identities_user_id
ON user_identities (user_id, id)
"""
)
connection.execute(
"""
CREATE INDEX IF NOT EXISTS idx_messages_session_id_id
@@ -235,6 +291,192 @@ class SessionStore:
metadata["channel"] = channel
return self.update_session_state(session_id, metadata=metadata)
def ensure_user(
self,
user_id: str,
*,
role: str = "user",
metadata: dict[str, Any] | None = None,
) -> UserRecord:
"""Ensure one canonical user exists."""
normalized_user_id = user_id.strip()
if not normalized_user_id:
raise ValueError("user_id is required")
normalized_role = role.strip().lower() or "user"
now = _utc_now()
current = self.get_user(normalized_user_id)
merged_metadata = dict(current.metadata if current else {})
if metadata:
merged_metadata.update(metadata)
resolved_role = normalized_role or (current.role if current else "user")
with self._lock:
with closing(self._connect()) as connection:
connection.execute(
"""
INSERT INTO users (user_id, role, metadata_json, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
role = excluded.role,
metadata_json = excluded.metadata_json,
updated_at = excluded.updated_at
""",
(
normalized_user_id,
resolved_role,
json.dumps(merged_metadata, ensure_ascii=False),
current.created_at if current and current.created_at else now,
now,
),
)
connection.commit()
return self.get_user(normalized_user_id) or UserRecord(
user_id=normalized_user_id,
role=resolved_role,
metadata=merged_metadata,
created_at=now,
updated_at=now,
)
def get_user(self, user_id: str) -> UserRecord | None:
"""Load one canonical user."""
normalized_user_id = user_id.strip()
if not normalized_user_id:
return None
with self._lock:
with closing(self._connect()) as connection:
row = connection.execute(
"""
SELECT user_id, role, metadata_json, created_at, updated_at
FROM users
WHERE user_id = ?
""",
(normalized_user_id,),
).fetchone()
if row is None:
return None
metadata = json.loads(row["metadata_json"] or "{}")
if not isinstance(metadata, dict):
metadata = {}
return UserRecord(
user_id=str(row["user_id"]),
role=str(row["role"] or "user"),
metadata=metadata,
created_at=str(row["created_at"]),
updated_at=str(row["updated_at"]),
)
def bind_identity(
self,
*,
channel: str,
external_id: str,
user_id: str,
role: str = "user",
metadata: dict[str, Any] | None = None,
) -> UserIdentityBinding:
"""Bind one external identity to a canonical user."""
normalized_channel = channel.strip().lower()
normalized_external_id = external_id.strip()
normalized_user_id = user_id.strip()
if not normalized_channel:
raise ValueError("channel is required")
if not normalized_external_id:
raise ValueError("external_id is required")
if not normalized_user_id:
raise ValueError("user_id is required")
user = self.ensure_user(normalized_user_id, role=role)
now = _utc_now()
current = self.get_identity_binding(
channel=normalized_channel,
external_id=normalized_external_id,
)
merged_metadata = dict(current.metadata if current else {})
if metadata:
merged_metadata.update(metadata)
with self._lock:
with closing(self._connect()) as connection:
connection.execute(
"""
INSERT INTO user_identities (
channel,
external_id,
user_id,
metadata_json,
created_at,
updated_at
)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(channel, external_id) DO UPDATE SET
user_id = excluded.user_id,
metadata_json = excluded.metadata_json,
updated_at = excluded.updated_at
""",
(
normalized_channel,
normalized_external_id,
user.user_id,
json.dumps(merged_metadata, ensure_ascii=False),
current.created_at if current and current.created_at else now,
now,
),
)
connection.commit()
binding = self.get_identity_binding(
channel=normalized_channel,
external_id=normalized_external_id,
)
if binding is None:
raise RuntimeError("identity binding was not persisted")
return binding
def get_identity_binding(
self,
*,
channel: str,
external_id: str,
) -> UserIdentityBinding | None:
"""Resolve one identity binding."""
normalized_channel = channel.strip().lower()
normalized_external_id = external_id.strip()
if not normalized_channel or not normalized_external_id:
return None
with self._lock:
with closing(self._connect()) as connection:
row = connection.execute(
"""
SELECT
i.id,
i.channel,
i.external_id,
i.user_id,
i.metadata_json,
i.created_at,
i.updated_at,
u.role AS user_role
FROM user_identities AS i
JOIN users AS u ON u.user_id = i.user_id
WHERE i.channel = ? AND i.external_id = ?
""",
(normalized_channel, normalized_external_id),
).fetchone()
if row is None:
return None
metadata = json.loads(row["metadata_json"] or "{}")
if not isinstance(metadata, dict):
metadata = {}
return UserIdentityBinding(
id=int(row["id"]),
channel=str(row["channel"]),
external_id=str(row["external_id"]),
user_id=str(row["user_id"]),
user_role=str(row["user_role"] or "user"),
metadata=metadata,
created_at=str(row["created_at"]),
updated_at=str(row["updated_at"]),
)
def append(self, message: dict[str, Any], *, session_id: str = "main") -> None:
"""Append one raw message payload."""
self.ensure_session(session_id)
@@ -542,6 +784,68 @@ class SessionStore:
)
return sessions
def list_users(self) -> list[dict[str, Any]]:
"""Return all canonical users."""
with self._lock:
with closing(self._connect()) as connection:
rows = connection.execute(
"""
SELECT user_id, role, metadata_json, created_at, updated_at
FROM users
ORDER BY user_id ASC
"""
).fetchall()
users: list[dict[str, Any]] = []
for row in rows:
metadata = json.loads(row["metadata_json"] or "{}")
users.append(
{
"user_id": str(row["user_id"]),
"role": str(row["role"] or "user"),
"metadata": metadata if isinstance(metadata, dict) else {},
"created_at": str(row["created_at"]),
"updated_at": str(row["updated_at"]),
}
)
return users
def list_identities(self) -> list[dict[str, Any]]:
"""Return all stored external identity bindings."""
with self._lock:
with closing(self._connect()) as connection:
rows = connection.execute(
"""
SELECT
i.id,
i.channel,
i.external_id,
i.user_id,
i.metadata_json,
i.created_at,
i.updated_at,
u.role AS user_role
FROM user_identities AS i
JOIN users AS u ON u.user_id = i.user_id
ORDER BY i.channel ASC, i.external_id ASC
"""
).fetchall()
identities: list[dict[str, Any]] = []
for row in rows:
metadata = json.loads(row["metadata_json"] or "{}")
identities.append(
{
"id": int(row["id"]),
"channel": str(row["channel"]),
"external_id": str(row["external_id"]),
"user_id": str(row["user_id"]),
"user_role": str(row["user_role"] or "user"),
"metadata": metadata if isinstance(metadata, dict) else {},
"created_at": str(row["created_at"]),
"updated_at": str(row["updated_at"]),
}
)
return identities
def list_messages(
self,
*,
@@ -597,6 +901,8 @@ class SessionStore:
return {
"database_path": str(self.path),
"sessions": sessions,
"users": self.list_users(),
"identities": self.list_identities(),
"messages": self.list_messages(session_id=session_id, limit=limit),
"compactions": self.list_compactions(session_id=session_id),
}
+9 -1
View File
@@ -5,13 +5,21 @@ from pathlib import Path
from voidbot.tools.base import ToolRegistry
from voidbot.tools.filesystem import ListDirTool, ReadFileTool, WriteFileTool
from voidbot.tools.shell import RunCommandTool
from voidbot.tools.web import ReadUrlTool, SearchWebTool
def build_default_tool_registry(workspace: Path) -> ToolRegistry:
def build_default_tool_registry(
workspace: Path,
*,
jina_api_key: str = "",
request_timeout: int = 120,
) -> ToolRegistry:
"""Create the default tool registry."""
registry = ToolRegistry()
registry.register(ListDirTool(workspace))
registry.register(ReadFileTool(workspace))
registry.register(WriteFileTool(workspace))
registry.register(RunCommandTool(workspace))
registry.register(ReadUrlTool(api_key=jina_api_key, timeout=request_timeout))
registry.register(SearchWebTool(api_key=jina_api_key, timeout=request_timeout))
return registry
+243
View File
@@ -0,0 +1,243 @@
"""Built-in web tools backed by Jina Reader/Search."""
from __future__ import annotations
import urllib.error
import urllib.parse
import urllib.request
from typing import Any
from voidbot.tools.base import Tool, paginate_text
class ReadUrlTool(Tool):
"""Read webpage contents through Jina Reader."""
name = "read_url"
description = (
"Read webpage content through Jina Reader with paginated text output. "
"This tool works without a Jina key, but adding 'jina_api_key' in config.json "
"or setting JINA_API_KEY is recommended for reliable access."
)
parameters = {
"type": "object",
"additionalProperties": False,
"properties": {
"url": {
"type": "string",
"description": "HTTP or HTTPS URL to fetch.",
"minLength": 1,
},
"page": {
"type": "integer",
"description": "1-based result page.",
"minimum": 1,
},
"page_size": {
"type": "integer",
"description": "Number of characters per page.",
"minimum": 256,
"maximum": 12000,
},
},
"required": ["url"],
}
def __init__(self, *, api_key: str = "", timeout: int = 120):
self.api_key = api_key.strip()
self.timeout = timeout
def execute(self, arguments: dict[str, Any]):
target_url = _normalize_url(str(arguments["url"]))
endpoint = (
"https://r.jina.ai/"
+ urllib.parse.quote(target_url, safe=":/?&=#%+-_.~")
)
response = _request_jina_text(
endpoint=endpoint,
api_key=self.api_key,
timeout=self.timeout,
)
if not response["ok"]:
return self.failure(
response["error"]["code"],
response["error"]["message"],
data=response.get("data"),
meta=response.get("meta"),
)
try:
content, pagination = paginate_text(
str(response["text"]),
page=int(arguments.get("page") or 1),
page_size=int(arguments.get("page_size") or 4000),
)
except ValueError as exc:
return self.failure("page_out_of_range", str(exc))
return self.success(
data={
"url": target_url,
"content": content,
},
meta={
"provider": "jina",
"mode": "reader",
"pagination": pagination,
**response["meta"],
},
)
class SearchWebTool(Tool):
"""Search the web through Jina Search."""
name = "search_web"
description = (
"Search the web through Jina Search with paginated text output. "
"Requires 'jina_api_key' in config.json or the JINA_API_KEY environment variable. "
"If the key is missing, stop and ask the user to update the config."
)
parameters = {
"type": "object",
"additionalProperties": False,
"properties": {
"query": {
"type": "string",
"description": "Search query.",
"minLength": 1,
},
"page": {
"type": "integer",
"description": "1-based result page.",
"minimum": 1,
},
"page_size": {
"type": "integer",
"description": "Number of characters per page.",
"minimum": 256,
"maximum": 12000,
},
},
"required": ["query"],
}
def __init__(self, *, api_key: str = "", timeout: int = 120):
self.api_key = api_key.strip()
self.timeout = timeout
def execute(self, arguments: dict[str, Any]):
if not self.api_key:
return self.failure(
"config_required",
(
"Jina search is not configured. Ask the user to set "
"'jina_api_key' in config.json or export JINA_API_KEY "
"before using search_web."
),
meta={
"config_path": "config.json",
"config_field": "jina_api_key",
"env_var": "JINA_API_KEY",
},
)
query = str(arguments["query"]).strip()
endpoint = "https://s.jina.ai/" + urllib.parse.quote(query, safe="")
response = _request_jina_text(
endpoint=endpoint,
api_key=self.api_key,
timeout=self.timeout,
)
if not response["ok"]:
return self.failure(
response["error"]["code"],
response["error"]["message"],
data=response.get("data"),
meta=response.get("meta"),
)
try:
content, pagination = paginate_text(
str(response["text"]),
page=int(arguments.get("page") or 1),
page_size=int(arguments.get("page_size") or 4000),
)
except ValueError as exc:
return self.failure("page_out_of_range", str(exc))
return self.success(
data={
"query": query,
"content": content,
},
meta={
"provider": "jina",
"mode": "search",
"pagination": pagination,
**response["meta"],
},
)
def _normalize_url(raw_url: str) -> str:
candidate = raw_url.strip()
if "://" not in candidate:
candidate = "https://" + candidate
parsed = urllib.parse.urlparse(candidate)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError("url must be a valid http or https URL")
return urllib.parse.urlunparse(parsed)
def _request_jina_text(
*,
endpoint: str,
api_key: str,
timeout: int,
) -> dict[str, Any]:
headers = {
"Accept": "text/plain; charset=utf-8",
"User-Agent": "VoidBot/0.1.0",
}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
request = urllib.request.Request(endpoint, headers=headers, method="GET")
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return {
"ok": True,
"text": response.read().decode("utf-8", errors="replace"),
"meta": {
"endpoint": endpoint,
"status_code": int(getattr(response, "status", 200)),
"content_type": str(response.headers.get("Content-Type") or ""),
"final_url": response.geturl(),
},
}
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
return {
"ok": False,
"error": {
"code": "http_error",
"message": f"Jina request failed with HTTP {exc.code}",
},
"data": {
"body": body[:4000],
},
"meta": {
"endpoint": endpoint,
"status_code": int(exc.code),
},
}
except urllib.error.URLError as exc:
return {
"ok": False,
"error": {
"code": "network_error",
"message": f"Network error: {exc.reason}",
},
"meta": {
"endpoint": endpoint,
},
}
+26
View File
@@ -253,6 +253,11 @@ class AgentRuntimeTests(unittest.TestCase):
self.assertIn("Channel: cli", system_prompt)
self.assertIn("Capabilities: slash_commands, model_switch", system_prompt)
self.assertIn("Source Mode: cli_local", system_prompt)
self.assertIn("## Actor Identity", system_prompt)
self.assertIn("Identity Status: owner", system_prompt)
self.assertIn("Actor Role: owner", system_prompt)
self.assertIn("Actor User ID: owner", system_prompt)
self.assertIn("Is Owner: true", system_prompt)
self.assertIn("## Available Tools", system_prompt)
self.assertEqual(
runtime.providers.last_messages[1]["content"],
@@ -297,6 +302,9 @@ class AgentRuntimeTests(unittest.TestCase):
self.assertEqual(state.metadata["runtime_mode"], "installed")
self.assertEqual(state.metadata["install_mode"], "editable")
self.assertEqual(state.metadata["channel_capabilities"], ["reply_status"])
self.assertEqual(state.metadata["actor_identity_status"], "unknown")
self.assertEqual(state.metadata["actor_role"], "unknown")
self.assertFalse(state.metadata["actor_is_owner"])
def test_session_history_is_isolated_by_session_id(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
@@ -383,6 +391,24 @@ class AgentRuntimeTests(unittest.TestCase):
self.assertIn("source_mode: cli_local", result.reply)
self.assertIn("entrypoint_path: /usr/local/bin/voidbot", result.reply)
def test_whoami_command_reports_current_identity(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
runtime = self._make_runtime(Path(temp_dir))
inbound = InboundMessageContext(
session_id="main",
raw_body="/whoami",
body_for_agent="/whoami",
source_mode="cli_local",
channel="cli",
)
result = runtime.run_turn(inbound)
self.assertIn("Current identity:", result.reply)
self.assertIn("identity_status: owner", result.reply)
self.assertIn("actor_user_id: owner", result.reply)
self.assertIn("actor_is_owner: true", result.reply)
def test_use_command_switches_provider_for_session(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
runtime = self._make_runtime(Path(temp_dir))
+62
View File
@@ -168,6 +168,68 @@ class ChannelManagerTests(unittest.TestCase):
self.assertEqual(status["feishu"]["replying_count"], 0)
self.assertEqual(status["feishu"]["replying_sessions"], [])
def test_bound_owner_direct_message_routes_to_main_session(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
config = AppConfig.from_mapping(
{
"default_provider": "1",
"providers": [
{
"id": "1",
"preset": "openai_chatgpt",
"api_key": "test-key",
}
],
"workspace": temp_dir,
"database_path": str(Path(temp_dir) / ".voidbot/voidbot.db"),
"channels": {
"feishu": {
"enabled": True,
"app_id": "app-id",
"app_secret": "secret",
}
},
}
)
runtime = FakeRuntime(config=config)
runtime.session.bind_identity(
channel="feishu",
external_id="ou_owner",
user_id="owner",
role="owner",
)
manager = ChannelManager(
runtime,
config.channels,
channel_factories={"feishu": FakeChannel},
)
message = InboundChannelMessage(
channel="feishu",
chat_id="oc_direct_chat",
sender_id="ou_owner",
body="hello owner",
reply_target="ou_owner",
reply_target_type="open_id",
message_id="msg-owner-1",
metadata={"chat_type": "p2p"},
)
asyncio.run(manager.handle_inbound(message))
state = runtime.session.get_session_state("main")
self.assertEqual(runtime.calls, ["main"])
channel = manager.channels["feishu"]
self.assertEqual(
channel.indicator_events,
[("start", "main"), ("stop", "main")],
)
self.assertIsNotNone(state)
self.assertEqual(state.metadata["actor_identity_status"], "owner")
self.assertEqual(state.metadata["actor_role"], "owner")
self.assertEqual(state.metadata["actor_user_id"], "owner")
self.assertTrue(state.metadata["actor_is_owner"])
class _FakeFeishuMessageReactionAPI:
def __init__(self) -> None:
+28
View File
@@ -201,6 +201,34 @@ class ConfigLoadingTests(unittest.TestCase):
self.assertEqual(siliconflow["api_base"], "https://api.siliconflow.cn/v1")
self.assertEqual(siliconflow["model"], "deepseek-ai/DeepSeek-V3")
def test_example_config_includes_jina_api_key_placeholder(self) -> None:
example = build_example_config()
self.assertEqual(example["jina_api_key"], "YOUR_JINA_API_KEY")
def test_load_config_reads_jina_api_key_from_environment(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
config_path = Path(temp_dir) / "config.json"
config_path.write_text(
json.dumps(
{
"default_provider": "1",
"providers": [
{
"id": "1",
"preset": "openai_chatgpt",
"api_key": "test-key",
}
],
}
),
encoding="utf-8",
)
with patch.dict(os.environ, {"JINA_API_KEY": "jina-env-key"}, clear=False):
config = load_config(config_path)
self.assertEqual(config.jina_api_key, "jina-env-key")
if __name__ == "__main__":
unittest.main()
+18
View File
@@ -13,6 +13,7 @@ from voidbot.config import AppConfig
from voidbot.gateway.cli import (
_run_one_turn,
build_parser,
run_identity_bind_owner_command,
run_config_add_model_command,
run_config_open_command,
run_config_path_command,
@@ -72,6 +73,9 @@ class GatewayTests(unittest.TestCase):
self.assertEqual(runtime.last_inbound.launch_cwd, "/tmp/demo-launch")
self.assertEqual(runtime.last_inbound.entrypoint_path, "/usr/local/bin/voidbot")
self.assertEqual(runtime.last_inbound.python_executable, "/usr/bin/python3.12")
self.assertEqual(runtime.last_inbound.actor_identity_status, "owner")
self.assertEqual(runtime.last_inbound.actor_user_id, "owner")
self.assertTrue(runtime.last_inbound.actor_is_owner)
self.assertIn("queue", application.health())
application.shutdown()
@@ -177,6 +181,9 @@ class GatewayTests(unittest.TestCase):
self.assertIsNotNone(inbound.launch_cwd)
self.assertIsNotNone(inbound.entrypoint_path)
self.assertIsNotNone(inbound.python_executable)
self.assertEqual(inbound.actor_identity_status, "owner")
self.assertEqual(inbound.actor_user_id, "owner")
self.assertTrue(inbound.actor_is_owner)
def test_auto_mode_falls_back_to_local(self) -> None:
config = AppConfig(api_key="test-key")
@@ -252,12 +259,16 @@ class GatewayTests(unittest.TestCase):
]
)
dump_args = parser.parse_args(["data", "dump"])
identity_args = parser.parse_args(
["identity", "bind-owner", "--channel", "qq", "--external-id", "user-1"]
)
self.assertEqual(sync_args.config_command, "sync")
self.assertEqual(path_args.config_command, "path")
self.assertEqual(open_args.config_command, "open")
self.assertEqual(add_model_args.config_command, "add-model")
self.assertEqual(dump_args.data_command, "dump")
self.assertEqual(identity_args.identity_command, "bind-owner")
def test_config_sync_command_prints_added_fields(self) -> None:
buffer = io.StringIO()
@@ -387,6 +398,11 @@ class GatewayTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as temp_dir:
config = AppConfig(database_path=Path(temp_dir) / "voidbot.db")
with patch("voidbot.gateway.cli.load_config", return_value=config):
run_identity_bind_owner_command(
config_path=None,
channel="qq",
external_id="openid-1",
)
buffer = io.StringIO()
with patch("sys.stdout", buffer):
run_data_dump_command(
@@ -398,6 +414,8 @@ class GatewayTests(unittest.TestCase):
payload = json.loads(buffer.getvalue())
self.assertIn("database_path", payload)
self.assertIn("sessions", payload)
self.assertIn("users", payload)
self.assertIn("identities", payload)
self.assertIn("messages", payload)
+106
View File
@@ -4,10 +4,31 @@ import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from voidbot.tools import build_default_tool_registry
class FakeHTTPResponse:
def __init__(self, body: str, *, url: str, status: int = 200) -> None:
self._body = body
self._url = url
self.status = status
self.headers = {"Content-Type": "text/plain; charset=utf-8"}
def read(self) -> bytes:
return self._body.encode("utf-8")
def geturl(self) -> str:
return self._url
def __enter__(self) -> "FakeHTTPResponse":
return self
def __exit__(self, exc_type, exc, tb) -> None:
return None
class ToolRegistryTests(unittest.TestCase):
def test_validation_rejects_unexpected_fields(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
@@ -77,6 +98,91 @@ class ToolRegistryTests(unittest.TestCase):
self.assertEqual(len(second.data["content"]), 1999)
self.assertNotEqual(first.data["content"], second.data["content"])
def test_read_url_fetches_paginated_web_content(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
registry = build_default_tool_registry(workspace)
captured_request = {}
def fake_urlopen(request, timeout=0):
captured_request["url"] = request.full_url
captured_request["timeout"] = timeout
return FakeHTTPResponse(
"A" * 5000,
url=request.full_url,
)
with patch("urllib.request.urlopen", side_effect=fake_urlopen):
result = registry.execute(
"read_url",
{"url": "example.com/post", "page": 2, "page_size": 2000},
)
self.assertTrue(result.ok)
self.assertEqual(result.data["url"], "https://example.com/post")
self.assertEqual(len(result.data["content"]), 2000)
self.assertEqual(result.meta["pagination"]["page"], 2)
self.assertEqual(result.meta["pagination"]["total_pages"], 3)
self.assertEqual(
captured_request["url"],
"https://r.jina.ai/https://example.com/post",
)
def test_search_web_is_registered_without_key_and_returns_config_guidance(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
registry = build_default_tool_registry(workspace)
schema_names = {
item["function"]["name"]
for item in registry.schemas()
}
result = registry.execute(
"search_web",
{"query": "voidbot project", "page_size": 4000},
)
self.assertIn("search_web", schema_names)
self.assertFalse(result.ok)
self.assertEqual(result.error["code"], "config_required")
self.assertIn("jina_api_key", result.error["message"])
self.assertEqual(result.meta["config_path"], "config.json")
self.assertEqual(result.meta["env_var"], "JINA_API_KEY")
def test_search_web_uses_jina_authorization_when_key_is_configured(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
registry = build_default_tool_registry(workspace, jina_api_key="jina-key")
schema_names = {
item["function"]["name"]
for item in registry.schemas()
}
captured_request = {}
def fake_urlopen(request, timeout=0):
captured_request["url"] = request.full_url
captured_request["authorization"] = request.headers.get("Authorization")
captured_request["timeout"] = timeout
return FakeHTTPResponse(
"Search result body",
url=request.full_url,
)
with patch("urllib.request.urlopen", side_effect=fake_urlopen):
result = registry.execute(
"search_web",
{"query": "voidbot project", "page_size": 4000},
)
self.assertIn("search_web", schema_names)
self.assertTrue(result.ok)
self.assertEqual(result.data["query"], "voidbot project")
self.assertEqual(
captured_request["url"],
"https://s.jina.ai/voidbot%20project",
)
self.assertEqual(captured_request["authorization"], "Bearer jina-key")
if __name__ == "__main__":
unittest.main()