增加国际化
This commit is contained in:
+147
@@ -0,0 +1,147 @@
|
||||
# VoidBot English Docs
|
||||
|
||||
[Back to Index](README.md) | [中文文档](README.zh-CN.md) | [Architecture](docs/architecture.en.md)
|
||||
|
||||
## Overview
|
||||
|
||||
VoidBot is a Python agent runtime built around three ideas:
|
||||
|
||||
- Borrow the lightweight execution loop and persistence style from `nanobot`
|
||||
- Borrow the provider compatibility and gateway/runtime separation from `openclaw`
|
||||
- Keep the first version runnable while supporting CLI, gateway, SQLite persistence, multi-provider config, and per-session model switching
|
||||
|
||||
## Current Capabilities
|
||||
|
||||
- Build runtime context from workspace data, system prompt, tools, and session history
|
||||
- Call an OpenAI-compatible `/chat/completions` endpoint
|
||||
- Execute tools and feed tool results back into the model loop
|
||||
- Run directly as a CLI or as a standalone gateway
|
||||
- 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
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
uv tool install --editable .
|
||||
```
|
||||
|
||||
After installation:
|
||||
|
||||
```bash
|
||||
voidbot --help
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. Sync the default config into `~/.voidbot/config.json`
|
||||
|
||||
```bash
|
||||
voidbot config sync
|
||||
```
|
||||
|
||||
2. Check or open the config file
|
||||
|
||||
```bash
|
||||
voidbot config path
|
||||
voidbot config open
|
||||
```
|
||||
|
||||
3. Fill in your real API keys and provider settings
|
||||
|
||||
4. Start the CLI
|
||||
|
||||
```bash
|
||||
voidbot
|
||||
```
|
||||
|
||||
5. Run one message
|
||||
|
||||
```bash
|
||||
voidbot --message "Summarize this repository"
|
||||
```
|
||||
|
||||
6. Start the gateway
|
||||
|
||||
```bash
|
||||
voidbot gateway
|
||||
```
|
||||
|
||||
7. Inspect SQLite data
|
||||
|
||||
```bash
|
||||
voidbot data dump
|
||||
voidbot data dump --session-id main
|
||||
```
|
||||
|
||||
## Config Shape
|
||||
|
||||
Key fields:
|
||||
|
||||
- `default_provider`: default provider id for new sessions
|
||||
- `providers`: list of configured model endpoints
|
||||
- `providers[].id`: stable id used by `/use <id>`
|
||||
- `providers[].preset`: provider preset name
|
||||
- `providers[].api_key`: provider API key
|
||||
- `providers[].api_base`: optional compatible base URL
|
||||
- `providers[].model`: model name
|
||||
- `providers[].label`: display label
|
||||
- `workspace`: workspace used by tools and context
|
||||
- `database_path`: SQLite database path
|
||||
- `cli_via`: `local` / `gateway` / `auto`
|
||||
|
||||
Channel fields:
|
||||
|
||||
- `channels.feishu.enabled`
|
||||
- `channels.feishu.app_id`
|
||||
- `channels.feishu.app_secret`
|
||||
- `channels.feishu.group_policy`
|
||||
- `channels.qq.enabled`
|
||||
- `channels.qq.app_id`
|
||||
- `channels.qq.secret`
|
||||
|
||||
## Dynamic Model Switching
|
||||
|
||||
Each provider has a unique id, for example:
|
||||
|
||||
```json
|
||||
{
|
||||
"default_provider": "1",
|
||||
"providers": [
|
||||
{ "id": "1", "preset": "zhipu_coding_plan", "api_key": "...", "model": "glm-4.7" },
|
||||
{ "id": "2", "preset": "openai_chatgpt", "api_key": "...", "model": "gpt-4.1-mini" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Inside a conversation:
|
||||
|
||||
```text
|
||||
/models
|
||||
/use 2
|
||||
```
|
||||
|
||||
- `/models` lists configured models
|
||||
- `/use <id>` switches only the current session
|
||||
- The selected provider id is stored in SQLite session metadata
|
||||
|
||||
## User Home
|
||||
|
||||
The default user-level data directory is `~/.voidbot`:
|
||||
|
||||
- `~/.voidbot/config.json`
|
||||
- `~/.voidbot/voidbot.db`
|
||||
- `~/.voidbot/cli_history`
|
||||
|
||||
Without `--config`, config lookup order is:
|
||||
|
||||
1. `./config.json`
|
||||
2. `~/.voidbot/config.json`
|
||||
|
||||
## Notes
|
||||
|
||||
- The model layer currently focuses on OpenAI-compatible APIs first
|
||||
- Built-in tools are `list_dir`, `read_file`, `write_file`, and `run_command`
|
||||
- `voidbot` starts the interactive CLI by default
|
||||
- `voidbot gateway` starts HTTP and any enabled channel listeners
|
||||
|
||||
@@ -1,252 +1,18 @@
|
||||
# VoidBot
|
||||
# VoidBot Docs
|
||||
|
||||
VoidBot is a minimal Python agent runtime designed around three ideas:
|
||||
- [中文文档](README.zh-CN.md)
|
||||
- [English Docs](README.en.md)
|
||||
|
||||
- Borrow the lightweight execution loop and session persistence style from `nanobot`.
|
||||
- Borrow the provider compatibility and gateway/runtime separation from `openclaw`.
|
||||
- Keep the first version small: direct CLI or standalone gateway, provider compatibility, tool loop, and persistent session state.
|
||||
## 中文
|
||||
|
||||
## Architecture
|
||||
这是 VoidBot 的双语文档入口页。
|
||||
|
||||
```text
|
||||
CLI Agent
|
||||
-> AgentRuntime
|
||||
-> ContextBuilder
|
||||
-> SQLite SessionStore
|
||||
-> ToolRegistry
|
||||
-> ProviderManager
|
||||
-> OpenAI Compatible Provider
|
||||
- 项目总览与使用说明:[`README.zh-CN.md`](README.zh-CN.md)
|
||||
- 架构说明:[`docs/architecture.zh-CN.md`](docs/architecture.zh-CN.md)
|
||||
|
||||
Gateway Server
|
||||
-> GatewayApplication
|
||||
-> AgentRuntime
|
||||
-> ChannelManager
|
||||
-> Feishu
|
||||
-> QQ
|
||||
```
|
||||
## English
|
||||
|
||||
See [docs/architecture.md](docs/architecture.md) for the layer breakdown and message flow.
|
||||
This is the bilingual documentation index for VoidBot.
|
||||
|
||||
## Initial Capabilities
|
||||
|
||||
- Build runtime context from workspace metadata, system prompt, tool list, and session history
|
||||
- Call an OpenAI-compatible chat completions endpoint
|
||||
- Execute tools and feed tool results back into the model loop
|
||||
- Run as a direct CLI agent or through a standalone gateway process
|
||||
- Let the standalone gateway listen on HTTP, Feishu, and QQ at the same time
|
||||
- Persist sessions, messages, and session metadata in SQLite
|
||||
- Isolate transcript history by `session_id`, so each chat keeps its own context
|
||||
- Support multiple configured model endpoints and switch per session
|
||||
- Support provider presets for:
|
||||
- `openai_chatgpt`
|
||||
- `zhipu_coding_plan`
|
||||
- `custom_openai_compatible`
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. Install the command into your user environment:
|
||||
|
||||
```bash
|
||||
uv tool install --editable .
|
||||
```
|
||||
|
||||
After that, you can run `voidbot` directly.
|
||||
|
||||
2. Create a config file:
|
||||
|
||||
```json
|
||||
{
|
||||
"provider": "zhipu_coding_plan",
|
||||
"api_key": "YOUR_API_KEY",
|
||||
"model": "glm-4.7",
|
||||
"workspace": ".",
|
||||
"max_iterations": 8
|
||||
}
|
||||
```
|
||||
|
||||
You can also start from [config.example.json](config.example.json).
|
||||
|
||||
3. Sync the default user config into `~/.voidbot/config.json`:
|
||||
|
||||
```bash
|
||||
uv run voidbot config sync
|
||||
```
|
||||
|
||||
This command is incremental:
|
||||
|
||||
- it creates `~/.voidbot/config.json` if it does not exist
|
||||
- it adds new fields from the latest example template
|
||||
- it does not delete your custom fields
|
||||
- it does not overwrite values you already filled in
|
||||
|
||||
4. Check or open the config path when needed:
|
||||
|
||||
```bash
|
||||
uv run voidbot config path
|
||||
uv run voidbot config open
|
||||
```
|
||||
|
||||
5. Edit `~/.voidbot/config.json` with your real values.
|
||||
|
||||
6. Start the CLI directly:
|
||||
|
||||
```bash
|
||||
voidbot
|
||||
```
|
||||
|
||||
7. Run one turn locally:
|
||||
|
||||
```bash
|
||||
voidbot --message "Summarize this repository"
|
||||
```
|
||||
|
||||
8. Start the standalone gateway:
|
||||
|
||||
```bash
|
||||
voidbot gateway
|
||||
```
|
||||
|
||||
9. Call the agent through the HTTP gateway:
|
||||
|
||||
```bash
|
||||
voidbot --via gateway --message "Summarize this repository"
|
||||
```
|
||||
|
||||
10. Run interactive mode with automatic fallback:
|
||||
|
||||
```bash
|
||||
voidbot --via auto
|
||||
```
|
||||
|
||||
11. Inspect stored SQLite data:
|
||||
|
||||
```bash
|
||||
voidbot data dump
|
||||
```
|
||||
|
||||
## Config Fields
|
||||
|
||||
- `default_provider`: default provider id for new sessions
|
||||
- `providers`: a list of configured model endpoints
|
||||
- `providers[].id`: stable numeric or string id used for switching
|
||||
- `providers[].preset`: provider preset name
|
||||
- `providers[].api_key`: provider API key
|
||||
- `providers[].api_base`: optional base URL override
|
||||
- `providers[].model`: optional model override
|
||||
- `providers[].label`: optional display name
|
||||
- `workspace`: workspace path used by tools and context
|
||||
- `database_path`: optional SQLite database path
|
||||
- `max_iterations`: max tool-call rounds in one turn
|
||||
- `history_limit`: number of previous messages to include
|
||||
- `system_prompt`: optional custom system prompt
|
||||
- `gateway_host`: default gateway bind host
|
||||
- `gateway_port`: default gateway bind port
|
||||
- `gateway_url`: optional default gateway URL for CLI client mode
|
||||
- `cli_via`: default CLI behavior, one of `local`, `gateway`, or `auto`
|
||||
- `channels.feishu.enabled`: enable Feishu long-connection listener
|
||||
- `channels.feishu.app_id`: Feishu app ID
|
||||
- `channels.feishu.app_secret`: Feishu app secret
|
||||
- `channels.feishu.group_policy`: `mention` or `open`
|
||||
- `channels.qq.enabled`: enable QQ bot listener
|
||||
- `channels.qq.app_id`: QQ bot app ID
|
||||
- `channels.qq.secret`: QQ bot secret
|
||||
|
||||
## Channel Gateway
|
||||
|
||||
The `voidbot gateway` process can expose the same runtime in three ways at once:
|
||||
|
||||
- HTTP requests on `/v1/agent/run`
|
||||
- Feishu events through `lark-oapi` WebSocket long connection
|
||||
- QQ bot events through `qq-botpy`
|
||||
|
||||
Example channel config:
|
||||
|
||||
```json
|
||||
{
|
||||
"provider": "openai_chatgpt",
|
||||
"api_key": "YOUR_API_KEY",
|
||||
"workspace": ".",
|
||||
"channels": {
|
||||
"feishu": {
|
||||
"enabled": true,
|
||||
"app_id": "cli_xxx",
|
||||
"app_secret": "xxx",
|
||||
"group_policy": "mention"
|
||||
},
|
||||
"qq": {
|
||||
"enabled": true,
|
||||
"app_id": "1024xxxx",
|
||||
"secret": "xxx"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Platform notes:
|
||||
|
||||
- Feishu: enable bot capability and subscribe to `im.message.receive_v1`.
|
||||
- QQ: enable C2C messages and group `@bot` messages for the app.
|
||||
- Every Feishu or QQ chat is mapped to its own `session_id`, so contexts do not leak across chats.
|
||||
- Model switching is stored per session, so each chat can stay on its own provider.
|
||||
|
||||
## Model Switching
|
||||
|
||||
Each configured provider has an `id`, for example:
|
||||
|
||||
```json
|
||||
{
|
||||
"default_provider": "1",
|
||||
"providers": [
|
||||
{ "id": "1", "preset": "zhipu_coding_plan", "api_key": "...", "model": "glm-4.7" },
|
||||
{ "id": "2", "preset": "openai_chatgpt", "api_key": "...", "model": "gpt-4.1-mini" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Inside a conversation, you can switch the current session model dynamically:
|
||||
|
||||
```text
|
||||
/models
|
||||
/use 2
|
||||
```
|
||||
|
||||
- `/models` lists all configured providers
|
||||
- `/use <id>` switches only the current session
|
||||
- The selected provider id is stored in SQLite session metadata
|
||||
|
||||
## User Home Layout
|
||||
|
||||
VoidBot now keeps user-level state under `~/.voidbot` by default.
|
||||
|
||||
- `~/.voidbot/config.json`: default config file
|
||||
- `~/.voidbot/voidbot.db`: SQLite database for sessions, metadata, and messages
|
||||
- `~/.voidbot/cli_history`: interactive CLI input history
|
||||
|
||||
Config lookup order without `--config`:
|
||||
|
||||
1. `./config.json`
|
||||
2. `~/.voidbot/config.json`
|
||||
|
||||
Useful command:
|
||||
|
||||
```bash
|
||||
voidbot config sync
|
||||
```
|
||||
|
||||
This command analyzes the existing JSON structure and only adds missing fields from the latest example config.
|
||||
|
||||
Useful data command:
|
||||
|
||||
```bash
|
||||
voidbot data dump
|
||||
voidbot data dump --session-id main
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- The model layer is deliberately OpenAI-compatible first, so adding more gateways later is straightforward.
|
||||
- The current built-in tools are `list_dir`, `read_file`, `write_file`, and `run_command`.
|
||||
- Every inbound request gets `session_id`, `run_id`, and `message_id` before entering the runtime.
|
||||
- `voidbot agent --via auto` tries the gateway first, then falls back to local execution.
|
||||
- `voidbot` without a subcommand starts the interactive CLI.
|
||||
- `voidbot gateway` starts the HTTP listener and any enabled channel listeners.
|
||||
- Project overview and usage guide: [`README.en.md`](README.en.md)
|
||||
- Architecture guide: [`docs/architecture.en.md`](docs/architecture.en.md)
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
# VoidBot 中文文档
|
||||
|
||||
[返回文档入口](README.md) | [English Version](README.en.md) | [架构文档](docs/architecture.zh-CN.md)
|
||||
|
||||
## 项目简介
|
||||
|
||||
VoidBot 是一个 Python 智能体运行时,设计重点有三点:
|
||||
|
||||
- 借鉴 `nanobot` 的轻量执行循环与会话持久化思路
|
||||
- 借鉴 `openclaw` 的 provider 兼容层与 gateway/runtime 分层
|
||||
- 保持首版可运行,同时支持 CLI、gateway、SQLite 持久化、多模型配置与会话级切换
|
||||
|
||||
## 当前能力
|
||||
|
||||
- 根据工作区信息、系统提示词、工具列表与会话历史构建上下文
|
||||
- 调用 OpenAI 兼容的 `/chat/completions` 接口
|
||||
- 执行工具并将结果回填给模型
|
||||
- 既可以直接作为 CLI 运行,也可以作为独立 gateway 运行
|
||||
- gateway 可同时接收 HTTP、飞书、QQ
|
||||
- 使用 SQLite 存储 session、消息和 session 元数据
|
||||
- 支持配置多个 provider,并按 session 动态切换模型
|
||||
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
uv tool install --editable .
|
||||
```
|
||||
|
||||
安装完成后,可以直接使用:
|
||||
|
||||
```bash
|
||||
voidbot --help
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
1. 同步默认配置到 `~/.voidbot/config.json`
|
||||
|
||||
```bash
|
||||
voidbot config sync
|
||||
```
|
||||
|
||||
2. 查看或打开配置文件
|
||||
|
||||
```bash
|
||||
voidbot config path
|
||||
voidbot config open
|
||||
```
|
||||
|
||||
3. 填写真实的 API Key 与模型配置
|
||||
|
||||
4. 启动 CLI
|
||||
|
||||
```bash
|
||||
voidbot
|
||||
```
|
||||
|
||||
5. 单次执行
|
||||
|
||||
```bash
|
||||
voidbot --message "Summarize this repository"
|
||||
```
|
||||
|
||||
6. 启动 gateway
|
||||
|
||||
```bash
|
||||
voidbot gateway
|
||||
```
|
||||
|
||||
7. 查看 SQLite 数据
|
||||
|
||||
```bash
|
||||
voidbot data dump
|
||||
voidbot data dump --session-id main
|
||||
```
|
||||
|
||||
## 配置结构
|
||||
|
||||
核心配置字段:
|
||||
|
||||
- `default_provider`:新 session 默认使用的 provider 编号
|
||||
- `providers`:模型配置列表
|
||||
- `providers[].id`:稳定编号,用于 `/use <id>` 切换
|
||||
- `providers[].preset`:provider 预设名
|
||||
- `providers[].api_key`:模型 API Key
|
||||
- `providers[].api_base`:可选的兼容接口地址
|
||||
- `providers[].model`:模型名
|
||||
- `providers[].label`:显示名称
|
||||
- `workspace`:工具执行与上下文读取的工作区
|
||||
- `database_path`:SQLite 数据库路径
|
||||
- `cli_via`:`local` / `gateway` / `auto`
|
||||
|
||||
渠道相关字段:
|
||||
|
||||
- `channels.feishu.enabled`
|
||||
- `channels.feishu.app_id`
|
||||
- `channels.feishu.app_secret`
|
||||
- `channels.feishu.group_policy`
|
||||
- `channels.qq.enabled`
|
||||
- `channels.qq.app_id`
|
||||
- `channels.qq.secret`
|
||||
|
||||
## 动态切换模型
|
||||
|
||||
每个 provider 都有唯一编号,例如:
|
||||
|
||||
```json
|
||||
{
|
||||
"default_provider": "1",
|
||||
"providers": [
|
||||
{ "id": "1", "preset": "zhipu_coding_plan", "api_key": "...", "model": "glm-4.7" },
|
||||
{ "id": "2", "preset": "openai_chatgpt", "api_key": "...", "model": "gpt-4.1-mini" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
在对话中可使用:
|
||||
|
||||
```text
|
||||
/models
|
||||
/use 2
|
||||
```
|
||||
|
||||
- `/models` 查看所有可用模型
|
||||
- `/use <id>` 只切换当前 session
|
||||
- 当前选择会写入 SQLite 的 session 元数据
|
||||
|
||||
## 用户目录
|
||||
|
||||
默认用户级数据目录为 `~/.voidbot`:
|
||||
|
||||
- `~/.voidbot/config.json`
|
||||
- `~/.voidbot/voidbot.db`
|
||||
- `~/.voidbot/cli_history`
|
||||
|
||||
不带 `--config` 时,配置查找顺序是:
|
||||
|
||||
1. `./config.json`
|
||||
2. `~/.voidbot/config.json`
|
||||
|
||||
## 说明
|
||||
|
||||
- 模型调用层目前优先支持 OpenAI 兼容接口
|
||||
- 内置工具有 `list_dir`、`read_file`、`write_file`、`run_command`
|
||||
- `voidbot` 默认启动交互式 CLI
|
||||
- `voidbot gateway` 启动 HTTP 与已启用渠道监听
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# VoidBot Architecture
|
||||
|
||||
[Back to Index](../README.md) | [Project Overview](../README.en.md) | [中文版本](architecture.zh-CN.md)
|
||||
|
||||
## Design Goals
|
||||
|
||||
- Keep the first version small and runnable
|
||||
- Separate gateway, runtime, and provider adapter from the start
|
||||
- Normalize tool-calling so more providers can be added later
|
||||
|
||||
## Layers
|
||||
|
||||
### 1. Gateway
|
||||
|
||||
Files:
|
||||
|
||||
- `src/voidbot/gateway/cli.py`
|
||||
- `src/voidbot/gateway/client.py`
|
||||
- `src/voidbot/gateway/messages.py`
|
||||
- `src/voidbot/gateway/server.py`
|
||||
- `src/voidbot/channels/*`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Parse CLI input
|
||||
- Normalize `InboundMessageContext`
|
||||
- Generate `session_id`, `run_id`, and `message_id`
|
||||
- Decide between local runtime and standalone gateway
|
||||
- Receive HTTP / Feishu / QQ traffic
|
||||
- Manage config, data export, and CLI history under `~/.voidbot`
|
||||
|
||||
### 2. Runtime
|
||||
|
||||
Files:
|
||||
|
||||
- `src/voidbot/agent.py`
|
||||
- `src/voidbot/context.py`
|
||||
- `src/voidbot/session.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Load history from SQLite
|
||||
- Manage session metadata such as the active `provider_id`
|
||||
- Build model context
|
||||
- Execute the model/tool loop
|
||||
- Handle built-in commands like `/models` and `/use <id>`
|
||||
|
||||
### 3. Provider Compatibility
|
||||
|
||||
Files:
|
||||
|
||||
- `src/voidbot/providers/base.py`
|
||||
- `src/voidbot/providers/manager.py`
|
||||
- `src/voidbot/providers/registry.py`
|
||||
- `src/voidbot/providers/compat.py`
|
||||
- `src/voidbot/providers/openai_compatible.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Resolve provider presets
|
||||
- Resolve configured provider ids
|
||||
- Normalize request payloads
|
||||
- Hide provider-specific differences
|
||||
|
||||
### 4. Tools
|
||||
|
||||
Files:
|
||||
|
||||
- `src/voidbot/tools/base.py`
|
||||
- `src/voidbot/tools/filesystem.py`
|
||||
- `src/voidbot/tools/shell.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Define tool schemas
|
||||
- Execute real capabilities
|
||||
- Return plain-text results
|
||||
|
||||
## Message Flow
|
||||
|
||||
```text
|
||||
CLI / channel message
|
||||
-> InboundMessageContext
|
||||
-> SessionStore(load session metadata)
|
||||
-> ProviderManager(resolve current provider)
|
||||
-> AgentRuntime.run_turn()
|
||||
-> Provider.chat()
|
||||
-> ToolRegistry.execute()
|
||||
-> SQLite persistence
|
||||
```
|
||||
|
||||
```text
|
||||
voidbot config sync
|
||||
-> built-in example config
|
||||
-> merge missing fields
|
||||
-> preserve user-defined fields
|
||||
```
|
||||
|
||||
```text
|
||||
voidbot data dump
|
||||
-> read SQLite
|
||||
-> print session and message data
|
||||
```
|
||||
|
||||
## Why This Shape
|
||||
|
||||
- `nanobot` informs the lightweight loop and normalized message handling
|
||||
- `openclaw` informs the gateway/runtime/provider separation
|
||||
- SQLite plus session metadata keeps model switching and multi-channel context stable
|
||||
|
||||
+3
-151
@@ -1,152 +1,4 @@
|
||||
# VoidBot Architecture
|
||||
# Architecture Docs
|
||||
|
||||
## Design Goals
|
||||
|
||||
- Keep the first version small and runnable.
|
||||
- Separate gateway, runtime, and model adapter from the start.
|
||||
- Normalize tool calling so more providers can be added later without rewriting the agent loop.
|
||||
|
||||
## Layers
|
||||
|
||||
### 1. Gateway
|
||||
|
||||
Files:
|
||||
|
||||
- `src/voidbot/gateway/cli.py`
|
||||
- `src/voidbot/gateway/client.py`
|
||||
- `src/voidbot/gateway/messages.py`
|
||||
- `src/voidbot/gateway/server.py`
|
||||
- `src/voidbot/channels/base.py`
|
||||
- `src/voidbot/channels/manager.py`
|
||||
- `src/voidbot/channels/feishu.py`
|
||||
- `src/voidbot/channels/qq.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Parse CLI input
|
||||
- Normalize inbound text into `InboundMessageContext`
|
||||
- Generate `session_id`, `run_id`, and `message_id`
|
||||
- Either call the local runtime directly or send the request to a standalone gateway server
|
||||
- Accept HTTP requests and forward them to the same runtime implementation
|
||||
- Accept Feishu and QQ messages and route them through the same runtime
|
||||
- Send the final agent reply back to the originating channel
|
||||
- Manage the user-level `~/.voidbot` home, including config sync, config open/path helpers, data dump, and CLI history
|
||||
|
||||
### 2. Runtime
|
||||
|
||||
Files:
|
||||
|
||||
- `src/voidbot/agent.py`
|
||||
- `src/voidbot/context.py`
|
||||
- `src/voidbot/session.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Load aligned history from SQLite
|
||||
- Keep a separate logical session per `session_id`
|
||||
- Store per-session metadata such as the selected provider id
|
||||
- Build a stable system prompt and a volatile runtime block
|
||||
- Execute the loop:
|
||||
- call model
|
||||
- inspect tool calls
|
||||
- execute tools
|
||||
- inject tool results
|
||||
- continue until final answer or iteration limit
|
||||
- Intercept built-in commands like `/models` and `/use <id>`
|
||||
|
||||
### 3. Model Compatibility Layer
|
||||
|
||||
Files:
|
||||
|
||||
- `src/voidbot/providers/base.py`
|
||||
- `src/voidbot/providers/manager.py`
|
||||
- `src/voidbot/providers/registry.py`
|
||||
- `src/voidbot/providers/compat.py`
|
||||
- `src/voidbot/providers/openai_compatible.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Resolve provider presets
|
||||
- Resolve configured provider ids from the user config
|
||||
- Normalize request payload shape
|
||||
- Hide provider-specific API details behind one `chat()` method
|
||||
- Keep compatibility rules out of the runtime loop
|
||||
|
||||
### 4. Tools
|
||||
|
||||
Files:
|
||||
|
||||
- `src/voidbot/tools/base.py`
|
||||
- `src/voidbot/tools/filesystem.py`
|
||||
- `src/voidbot/tools/shell.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Provide OpenAI-style JSON schema definitions
|
||||
- Execute real capabilities inside the workspace
|
||||
- Return plain text results that can be injected back into the transcript
|
||||
|
||||
## Current Message Flow
|
||||
|
||||
```text
|
||||
CLI input
|
||||
-> InboundMessageContext
|
||||
-> SessionStore(session metadata lookup)
|
||||
-> local AgentRuntime.run_turn()
|
||||
-> ContextBuilder.build_messages()
|
||||
-> ProviderManager.resolve(session provider)
|
||||
-> Provider.chat()
|
||||
-> LLMResponse
|
||||
-> ToolRegistry.execute() if tool calls exist
|
||||
-> tool result messages appended
|
||||
-> Provider.chat() again
|
||||
-> final assistant reply
|
||||
-> SQLite session persistence
|
||||
```
|
||||
|
||||
```text
|
||||
CLI input
|
||||
-> GatewayClient
|
||||
-> Gateway HTTP server
|
||||
-> GatewayApplication
|
||||
-> AgentRuntime.run_turn()
|
||||
-> final JSON response
|
||||
```
|
||||
|
||||
```text
|
||||
Feishu / QQ message
|
||||
-> ChannelManager
|
||||
-> InboundMessageContext(session_id=<channel>:<chat>)
|
||||
-> AgentRuntime.run_turn()
|
||||
-> channel.send_text()
|
||||
```
|
||||
|
||||
```text
|
||||
voidbot config sync
|
||||
-> built-in example config
|
||||
-> merge missing fields into ~/.voidbot/config.json
|
||||
-> preserve unknown/custom user fields
|
||||
```
|
||||
|
||||
```text
|
||||
voidbot data dump
|
||||
-> load configured SQLite database path
|
||||
-> read sessions table
|
||||
-> read messages table
|
||||
-> print JSON
|
||||
```
|
||||
|
||||
## Why This Matches openclaw + nanobot
|
||||
|
||||
- From `nanobot`: the loop is kept simple and centered on normalized `LLMResponse`, tool schemas, and append-only history.
|
||||
- From `openclaw`: gateway context is explicit, direct and gateway modes coexist, provider presets are registry-driven, and compatibility logic is separated from the loop.
|
||||
- From both: channel ingress is outside the core runtime, so CLI, HTTP, Feishu, and QQ all converge on one `AgentRuntime`.
|
||||
- The added provider catalog and SQLite session metadata keep model selection stable across turns and channels.
|
||||
|
||||
## Planned Next Extensions
|
||||
|
||||
- Streaming output adapter
|
||||
- WebSocket gateway and event streaming in addition to the current HTTP gateway
|
||||
- More providers and provider-specific compat patches
|
||||
- Safer command execution policies and approval hooks
|
||||
- Richer channel payloads such as attachments, cards, and structured replies
|
||||
- [中文架构文档](architecture.zh-CN.md)
|
||||
- [English Architecture Docs](architecture.en.md)
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# VoidBot 架构文档
|
||||
|
||||
[返回入口](../README.md) | [中文总览](../README.zh-CN.md) | [English Version](architecture.en.md)
|
||||
|
||||
## 设计目标
|
||||
|
||||
- 首版保持小而可运行
|
||||
- 从一开始就分离 gateway、runtime、provider adapter
|
||||
- 统一工具调用结构,方便后续增加 provider
|
||||
|
||||
## 分层
|
||||
|
||||
### 1. Gateway
|
||||
|
||||
涉及文件:
|
||||
|
||||
- `src/voidbot/gateway/cli.py`
|
||||
- `src/voidbot/gateway/client.py`
|
||||
- `src/voidbot/gateway/messages.py`
|
||||
- `src/voidbot/gateway/server.py`
|
||||
- `src/voidbot/channels/*`
|
||||
|
||||
职责:
|
||||
|
||||
- 解析 CLI 输入
|
||||
- 规范化 `InboundMessageContext`
|
||||
- 生成 `session_id`、`run_id`、`message_id`
|
||||
- 决定走本地 runtime 还是独立 gateway
|
||||
- 接收 HTTP / 飞书 / QQ 消息
|
||||
- 管理 `~/.voidbot` 下的配置、数据导出和历史输入
|
||||
|
||||
### 2. Runtime
|
||||
|
||||
涉及文件:
|
||||
|
||||
- `src/voidbot/agent.py`
|
||||
- `src/voidbot/context.py`
|
||||
- `src/voidbot/session.py`
|
||||
|
||||
职责:
|
||||
|
||||
- 从 SQLite 读取历史
|
||||
- 管理 session 元数据,例如当前 `provider_id`
|
||||
- 构建模型上下文
|
||||
- 执行模型调用与工具循环
|
||||
- 处理 `/models`、`/use <id>` 这类内建命令
|
||||
|
||||
### 3. Provider Compatibility
|
||||
|
||||
涉及文件:
|
||||
|
||||
- `src/voidbot/providers/base.py`
|
||||
- `src/voidbot/providers/manager.py`
|
||||
- `src/voidbot/providers/registry.py`
|
||||
- `src/voidbot/providers/compat.py`
|
||||
- `src/voidbot/providers/openai_compatible.py`
|
||||
|
||||
职责:
|
||||
|
||||
- 解析 provider 预设
|
||||
- 解析配置中的 provider 编号
|
||||
- 统一请求 payload
|
||||
- 隐藏 provider 差异
|
||||
|
||||
### 4. Tools
|
||||
|
||||
涉及文件:
|
||||
|
||||
- `src/voidbot/tools/base.py`
|
||||
- `src/voidbot/tools/filesystem.py`
|
||||
- `src/voidbot/tools/shell.py`
|
||||
|
||||
职责:
|
||||
|
||||
- 定义工具 schema
|
||||
- 执行真实能力
|
||||
- 以纯文本形式返回结果
|
||||
|
||||
## 消息流
|
||||
|
||||
```text
|
||||
CLI / 渠道消息
|
||||
-> InboundMessageContext
|
||||
-> SessionStore(读取 session 元数据)
|
||||
-> ProviderManager(解析当前 provider)
|
||||
-> AgentRuntime.run_turn()
|
||||
-> Provider.chat()
|
||||
-> ToolRegistry.execute()
|
||||
-> SQLite 持久化
|
||||
```
|
||||
|
||||
```text
|
||||
voidbot config sync
|
||||
-> 内置示例配置
|
||||
-> 合并缺失字段
|
||||
-> 保留用户已有字段
|
||||
```
|
||||
|
||||
```text
|
||||
voidbot data dump
|
||||
-> 读取 SQLite
|
||||
-> 输出 session 与 message 数据
|
||||
```
|
||||
|
||||
## 为什么这样设计
|
||||
|
||||
- `nanobot` 给了轻量循环和消息归一化的思路
|
||||
- `openclaw` 给了 gateway/runtime/provider 分层的方向
|
||||
- SQLite + session 元数据让模型切换与多渠道上下文更稳定
|
||||
|
||||
@@ -7,6 +7,7 @@ from dataclasses import dataclass
|
||||
from voidbot.config import AppConfig
|
||||
from voidbot.context import ContextBuilder
|
||||
from voidbot.gateway.messages import InboundMessageContext
|
||||
from voidbot.i18n import t
|
||||
from voidbot.models import RunTurnResult
|
||||
from voidbot.providers.manager import ProviderManager
|
||||
from voidbot.session import SessionState, SessionStore
|
||||
@@ -173,9 +174,11 @@ class AgentRuntime:
|
||||
inbound.session_id,
|
||||
provider_id=profile.id,
|
||||
)
|
||||
reply = (
|
||||
f"已切换到模型 {profile.id}: "
|
||||
f"{profile.label or profile.preset} / {profile.model or '(default)'}"
|
||||
reply = t(
|
||||
"agent.use.switched",
|
||||
id=profile.id,
|
||||
label=profile.label or profile.preset,
|
||||
model=profile.model or "(default)",
|
||||
)
|
||||
self._record_control_command(
|
||||
inbound,
|
||||
@@ -225,7 +228,7 @@ class AgentRuntime:
|
||||
|
||||
def _format_models(self, active_provider_id: str | None) -> str:
|
||||
current_id = active_provider_id or self.config.default_provider
|
||||
lines = ["可用模型列表:"]
|
||||
lines = [t("agent.models.title")]
|
||||
for profile in self.providers.list_profiles():
|
||||
description = self.providers.describe(profile.id)
|
||||
marker = "*" if description["id"] == current_id else " "
|
||||
@@ -234,5 +237,5 @@ class AgentRuntime:
|
||||
f"{description['label']} "
|
||||
f"[preset={description['preset']}, model={description['model']}]"
|
||||
)
|
||||
lines.append("使用 `/use <id>` 可切换当前会话的模型。")
|
||||
lines.append(t("agent.models.switch_hint"))
|
||||
return "\n".join(lines)
|
||||
|
||||
+31
-35
@@ -22,6 +22,7 @@ from voidbot.gateway.client import GatewayClient
|
||||
from voidbot.gateway.messages import InboundMessageContext
|
||||
from voidbot.gateway.server import GatewayApplication, run_gateway_server
|
||||
from voidbot.gateway.ui import render_single_turn, run_terminal_loop
|
||||
from voidbot.i18n import t
|
||||
from voidbot.session import SessionStore
|
||||
|
||||
|
||||
@@ -29,35 +30,35 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
"""Build CLI parser."""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="voidbot",
|
||||
description="VoidBot CLI, gateway, config, and data tools",
|
||||
description=t("cli.description"),
|
||||
)
|
||||
_add_agent_arguments(parser)
|
||||
subparsers = parser.add_subparsers(dest="command", required=False)
|
||||
|
||||
agent_parser = subparsers.add_parser(
|
||||
"agent",
|
||||
help="Run the agent locally or via gateway",
|
||||
help=t("cli.help.agent"),
|
||||
)
|
||||
_add_agent_arguments(agent_parser)
|
||||
|
||||
chat_parser = subparsers.add_parser(
|
||||
"chat",
|
||||
help="Backward-compatible alias of agent",
|
||||
help=t("cli.help.chat"),
|
||||
)
|
||||
_add_agent_arguments(chat_parser)
|
||||
|
||||
gateway_parser = subparsers.add_parser("gateway", help="Run the gateway server")
|
||||
gateway_parser = subparsers.add_parser("gateway", help=t("cli.help.gateway"))
|
||||
gateway_parser.add_argument(
|
||||
"--config",
|
||||
type=Path,
|
||||
help=_config_help_text(),
|
||||
help=t("cli.help.gateway_config"),
|
||||
)
|
||||
gateway_parser.add_argument("--host", help="Gateway bind host")
|
||||
gateway_parser.add_argument("--port", type=int, help="Gateway bind port")
|
||||
gateway_parser.add_argument("--host", help=t("cli.help.gateway_host"))
|
||||
gateway_parser.add_argument("--port", type=int, help=t("cli.help.gateway_port"))
|
||||
|
||||
config_parser = subparsers.add_parser(
|
||||
"config",
|
||||
help="Manage the user-level VoidBot config in ~/.voidbot",
|
||||
help=t("cli.help.config"),
|
||||
)
|
||||
config_subparsers = config_parser.add_subparsers(
|
||||
dest="config_command",
|
||||
@@ -65,25 +66,25 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
)
|
||||
sync_parser = config_subparsers.add_parser(
|
||||
"sync",
|
||||
help="Create or incrementally update ~/.voidbot/config.json from the example template",
|
||||
help=t("cli.help.config.sync"),
|
||||
)
|
||||
sync_parser.add_argument(
|
||||
"--path",
|
||||
action="store_true",
|
||||
help="Print the target config path after syncing",
|
||||
help=t("cli.help.config.path_flag"),
|
||||
)
|
||||
config_subparsers.add_parser(
|
||||
"path",
|
||||
help="Print the default user-level config path",
|
||||
help=t("cli.help.config.path"),
|
||||
)
|
||||
config_subparsers.add_parser(
|
||||
"open",
|
||||
help="Open the default config file with the system default application",
|
||||
help=t("cli.help.config.open"),
|
||||
)
|
||||
|
||||
data_parser = subparsers.add_parser(
|
||||
"data",
|
||||
help="Inspect the SQLite-backed stored sessions and messages",
|
||||
help=t("cli.help.data"),
|
||||
)
|
||||
data_subparsers = data_parser.add_subparsers(
|
||||
dest="data_command",
|
||||
@@ -91,7 +92,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
)
|
||||
dump_parser = data_subparsers.add_parser(
|
||||
"dump",
|
||||
help="Print stored sessions and messages from the SQLite database",
|
||||
help=t("cli.help.data.dump"),
|
||||
)
|
||||
dump_parser.add_argument(
|
||||
"--config",
|
||||
@@ -100,12 +101,12 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
)
|
||||
dump_parser.add_argument(
|
||||
"--session-id",
|
||||
help="Optional session id filter",
|
||||
help=t("cli.help.data.session_id"),
|
||||
)
|
||||
dump_parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
help="Limit the number of returned messages",
|
||||
help=t("cli.help.data.limit"),
|
||||
)
|
||||
|
||||
return parser
|
||||
@@ -151,10 +152,7 @@ def main() -> None:
|
||||
|
||||
|
||||
def _config_help_text() -> str:
|
||||
return (
|
||||
"Path to a JSON config file. "
|
||||
f"Default lookup: ./config.json, then {get_default_config_path()}"
|
||||
)
|
||||
return t("cli.help.config_path", path=get_default_config_path())
|
||||
|
||||
|
||||
def _add_agent_arguments(parser: argparse.ArgumentParser) -> None:
|
||||
@@ -163,19 +161,19 @@ def _add_agent_arguments(parser: argparse.ArgumentParser) -> None:
|
||||
type=Path,
|
||||
help=_config_help_text(),
|
||||
)
|
||||
parser.add_argument("--message", "-m", help="Send one message and exit")
|
||||
parser.add_argument("--message", "-m", help=t("cli.help.message"))
|
||||
parser.add_argument(
|
||||
"--via",
|
||||
choices=("local", "gateway", "auto"),
|
||||
default=None,
|
||||
help="Choose how the CLI reaches the agent runtime.",
|
||||
help=t("cli.help.via"),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--gateway-url",
|
||||
help="Gateway base URL, e.g. http://127.0.0.1:8787",
|
||||
help=t("cli.help.gateway_url"),
|
||||
)
|
||||
parser.add_argument("--gateway-host", help="Gateway host override")
|
||||
parser.add_argument("--gateway-port", type=int, help="Gateway port override")
|
||||
parser.add_argument("--gateway-host", help=t("cli.help.gateway_host"))
|
||||
parser.add_argument("--gateway-port", type=int, help=t("cli.help.gateway_port"))
|
||||
|
||||
|
||||
def run_agent_command(
|
||||
@@ -250,15 +248,15 @@ def run_config_sync_command(*, show_path: bool) -> None:
|
||||
"""Create or incrementally update the default user-level config."""
|
||||
config_path, created, added_paths = sync_default_config()
|
||||
verb = "created" if created else "updated"
|
||||
print(f"VoidBot config {verb}: {config_path}")
|
||||
print(t(f"config.sync.{verb}", path=config_path))
|
||||
if added_paths:
|
||||
print("Added missing fields:")
|
||||
print(t("config.sync.added_fields"))
|
||||
for path in added_paths:
|
||||
print(f" - {path}")
|
||||
else:
|
||||
print("No missing fields were added.")
|
||||
print(t("config.sync.no_changes"))
|
||||
if show_path:
|
||||
print(f"VoidBot home: {get_voidbot_home()}")
|
||||
print(t("config.sync.home", path=get_voidbot_home()))
|
||||
|
||||
|
||||
def run_config_path_command() -> None:
|
||||
@@ -270,7 +268,7 @@ def run_config_open_command() -> None:
|
||||
"""Open the default config file."""
|
||||
config_path, _, _ = sync_default_config()
|
||||
_open_path(config_path)
|
||||
print(f"Opened {config_path}")
|
||||
print(t("config.opened", path=config_path))
|
||||
|
||||
|
||||
def run_data_dump_command(
|
||||
@@ -317,9 +315,7 @@ def _run_one_turn(
|
||||
return _run_via_gateway(inbound, gateway_url)
|
||||
except Exception as exc:
|
||||
if config is None:
|
||||
raise RuntimeError(
|
||||
f"gateway call failed and no local config is available for fallback: {exc}"
|
||||
) from exc
|
||||
raise RuntimeError(t("agent.auto_no_fallback", error=exc)) from exc
|
||||
result = _run_local(inbound, config)
|
||||
result["meta"] = {"fallback": "local", "gateway_error": str(exc)}
|
||||
return result
|
||||
@@ -327,7 +323,7 @@ def _run_one_turn(
|
||||
|
||||
def _run_local(inbound: InboundMessageContext, config: AppConfig | None) -> dict:
|
||||
if config is None:
|
||||
raise ValueError("local mode requires a config with provider credentials")
|
||||
raise ValueError(t("agent.local_requires_config"))
|
||||
app = build_app(config)
|
||||
result = app.runtime.run_turn(inbound)
|
||||
return {
|
||||
@@ -347,7 +343,7 @@ def _run_local(inbound: InboundMessageContext, config: AppConfig | None) -> dict
|
||||
|
||||
def _run_via_gateway(inbound: InboundMessageContext, gateway_url: str | None) -> dict:
|
||||
if not gateway_url:
|
||||
raise ValueError("gateway mode requires --gateway-url or gateway config")
|
||||
raise ValueError(t("agent.gateway_requires_url"))
|
||||
client = GatewayClient(gateway_url)
|
||||
response = client.run_agent(inbound)
|
||||
response["mode"] = "gateway"
|
||||
|
||||
@@ -10,6 +10,7 @@ from typing import Any
|
||||
from voidbot.agent import AgentRuntime
|
||||
from voidbot.channels.manager import ChannelManager
|
||||
from voidbot.gateway.messages import InboundMessageContext
|
||||
from voidbot.i18n import t
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -129,7 +130,7 @@ def run_gateway_server(
|
||||
if application.channel_manager:
|
||||
application.channel_manager.start_background()
|
||||
server = ThreadingHTTPServer((host, port), create_gateway_handler(application))
|
||||
print(f"VoidBot gateway listening on http://{host}:{port}")
|
||||
print(t("gateway.listening", host=host, port=port))
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
|
||||
+36
-30
@@ -20,6 +20,7 @@ from rich.table import Table
|
||||
from rich.text import Text
|
||||
|
||||
from voidbot.config import AppConfig, get_cli_history_path
|
||||
from voidbot.i18n import t
|
||||
|
||||
|
||||
PROMPT_STYLE = Style.from_dict(
|
||||
@@ -89,26 +90,28 @@ class TerminalUI:
|
||||
Rule(
|
||||
title=(
|
||||
"[bold #7aa2f7]VoidBot[/bold #7aa2f7] "
|
||||
"[#9aa5ce]terminal agent[/#9aa5ce]"
|
||||
f"[#9aa5ce]{t('ui.title')}[/#9aa5ce]"
|
||||
),
|
||||
style="#414868",
|
||||
)
|
||||
)
|
||||
details = [
|
||||
f"mode={self.via}",
|
||||
f"provider={self.active_provider_id} {self.active_provider_label}"
|
||||
t("ui.mode", value=self.via),
|
||||
t(
|
||||
"ui.provider",
|
||||
id=self.active_provider_id,
|
||||
label=self.active_provider_label,
|
||||
)
|
||||
if self.config
|
||||
else "provider=(gateway-only)",
|
||||
f"model={self.active_model_name}",
|
||||
else t("ui.provider_gateway"),
|
||||
t("ui.model", value=self.active_model_name),
|
||||
]
|
||||
if self.gateway_url:
|
||||
details.append(f"gateway={self.gateway_url}")
|
||||
details.append(t("ui.gateway", value=self.gateway_url))
|
||||
self.console.print(
|
||||
Panel.fit(
|
||||
"\n".join(details)
|
||||
+ "\nEnter submit, Esc+Enter newline, Ctrl+L clear screen"
|
||||
+ "\n/use <id> 切换模型, /models 查看可用模型",
|
||||
title="[bold #c0caf5]Session[/bold #c0caf5]",
|
||||
"\n".join(details) + f"\n{t('ui.welcome')}" + f"\n{t('ui.model_help')}",
|
||||
title=f"[bold #c0caf5]{t('ui.session')}[/bold #c0caf5]",
|
||||
border_style="#7aa2f7",
|
||||
padding=(0, 1),
|
||||
)
|
||||
@@ -119,8 +122,8 @@ class TerminalUI:
|
||||
return self.session.prompt(
|
||||
HTML(
|
||||
"<prompt.border>┃</prompt.border> "
|
||||
"<prompt.label>主人</prompt.label> "
|
||||
"<prompt>输入消息</prompt>\n"
|
||||
f"<prompt.label>{t('ui.user')}</prompt.label> "
|
||||
f"<prompt>{t('ui.prompt.input')}</prompt>\n"
|
||||
"<prompt.border>╰─➤ </prompt.border>"
|
||||
),
|
||||
bottom_toolbar=self._bottom_toolbar,
|
||||
@@ -132,11 +135,7 @@ class TerminalUI:
|
||||
def busy(self) -> Status:
|
||||
"""Create the transient busy indicator."""
|
||||
spinner = "dots" if self.via != "gateway" else "line"
|
||||
label = (
|
||||
"VoidBot 正在思考与调用工具"
|
||||
if self.via != "gateway"
|
||||
else "VoidBot 正在等待 gateway 返回"
|
||||
)
|
||||
label = t("ui.busy.local") if self.via != "gateway" else t("ui.busy.gateway")
|
||||
return self.console.status(f"[#9ece6a]{label}[/#9ece6a]", spinner=spinner)
|
||||
|
||||
def render_turn(self, user_message: str, result: dict) -> None:
|
||||
@@ -146,7 +145,7 @@ class TerminalUI:
|
||||
self.console.print(
|
||||
Panel(
|
||||
Text(user_message.strip() or "(empty)", style="#c0caf5"),
|
||||
title="[bold #f7768e]主人[/bold #f7768e]",
|
||||
title=f"[bold #f7768e]{t('ui.user')}[/bold #f7768e]",
|
||||
border_style="#414868",
|
||||
padding=(0, 1),
|
||||
)
|
||||
@@ -159,7 +158,7 @@ class TerminalUI:
|
||||
self.console.print(
|
||||
Panel(
|
||||
Markdown(reply_text or "(no reply)"),
|
||||
title="[bold #7aa2f7]小月[/bold #7aa2f7]",
|
||||
title=f"[bold #7aa2f7]{t('ui.assistant')}[/bold #7aa2f7]",
|
||||
subtitle=_build_reply_subtitle(result),
|
||||
subtitle_align="right",
|
||||
border_style="#7aa2f7",
|
||||
@@ -171,7 +170,7 @@ class TerminalUI:
|
||||
if meta.get("fallback") == "local":
|
||||
self.console.print(
|
||||
Text(
|
||||
f"gateway 不可用,已回退本地执行: {meta.get('gateway_error')}",
|
||||
t("ui.fallback", error=meta.get("gateway_error")),
|
||||
style="#e0af68",
|
||||
)
|
||||
)
|
||||
@@ -180,12 +179,16 @@ class TerminalUI:
|
||||
gateway = self.gateway_url or "-"
|
||||
return HTML(
|
||||
"<bottom>"
|
||||
f" via {self.via} "
|
||||
f"• provider {self.active_provider_id}:{self.active_provider_label} "
|
||||
f"• model {self.active_model_name} "
|
||||
f"• gateway {gateway} "
|
||||
"• exit quit/exit "
|
||||
"</bottom>"
|
||||
+ t(
|
||||
"ui.toolbar",
|
||||
via=self.via,
|
||||
provider_id=self.active_provider_id,
|
||||
provider_label=self.active_provider_label,
|
||||
model=self.active_model_name,
|
||||
gateway=gateway,
|
||||
)
|
||||
+ t("ui.exit_hint")
|
||||
+ "</bottom>"
|
||||
)
|
||||
|
||||
def _apply_result_state(self, result: dict) -> None:
|
||||
@@ -217,7 +220,7 @@ def run_terminal_loop(
|
||||
ui.console.print()
|
||||
break
|
||||
except KeyboardInterrupt:
|
||||
ui.console.print(Text("输入已取消", style="#e0af68"))
|
||||
ui.console.print(Text(t("ui.input_cancelled"), style="#e0af68"))
|
||||
continue
|
||||
if not user_message:
|
||||
continue
|
||||
@@ -281,7 +284,10 @@ def _build_reply_subtitle(result: dict) -> str:
|
||||
provider = result.get("provider_id") or "?"
|
||||
model = result.get("model_name") or "(unknown)"
|
||||
return (
|
||||
f"mode={result.get('mode')} · iter={result.get('iterations')} · "
|
||||
f"tools={tool_count} · provider={provider} · model={model} · "
|
||||
f"run={result.get('run_id')}"
|
||||
f"{t('reply.mode', value=result.get('mode'))} · "
|
||||
f"{t('reply.iter', value=result.get('iterations'))} · "
|
||||
f"{t('reply.tools', value=tool_count)} · "
|
||||
f"{t('reply.provider', value=provider)} · "
|
||||
f"{t('reply.model', value=model)} · "
|
||||
f"{t('reply.run', value=result.get('run_id'))}"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Lightweight runtime internationalization."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import locale
|
||||
import os
|
||||
|
||||
|
||||
TRANSLATIONS: dict[str, dict[str, str]] = {
|
||||
"en": {
|
||||
"cli.description": "VoidBot CLI, gateway, config, and data tools",
|
||||
"cli.help.agent": "Run the agent locally or via gateway",
|
||||
"cli.help.chat": "Backward-compatible alias of agent",
|
||||
"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.config.sync": (
|
||||
"Create or incrementally update ~/.voidbot/config.json from the example template"
|
||||
),
|
||||
"cli.help.config.path": "Print the default user-level config path",
|
||||
"cli.help.config.open": "Open the default config file with the system default application",
|
||||
"cli.help.config.path_flag": "Print the target config path after syncing",
|
||||
"cli.help.data.dump": "Print stored sessions and messages from the SQLite database",
|
||||
"cli.help.data.session_id": "Optional session id filter",
|
||||
"cli.help.data.limit": "Limit the number of returned messages",
|
||||
"cli.help.config_path": "Path to a JSON config file. Default lookup: ./config.json, then {path}",
|
||||
"cli.help.message": "Send one message and exit",
|
||||
"cli.help.via": "Choose how the CLI reaches the agent runtime.",
|
||||
"cli.help.gateway_url": "Gateway base URL, e.g. http://127.0.0.1:8787",
|
||||
"cli.help.gateway_host": "Gateway host override",
|
||||
"cli.help.gateway_port": "Gateway port override",
|
||||
"cli.help.gateway_config": "Path to a JSON config file",
|
||||
"config.sync.created": "VoidBot config created: {path}",
|
||||
"config.sync.updated": "VoidBot config updated: {path}",
|
||||
"config.sync.added_fields": "Added missing fields:",
|
||||
"config.sync.no_changes": "No missing fields were added.",
|
||||
"config.sync.home": "VoidBot home: {path}",
|
||||
"config.opened": "Opened {path}",
|
||||
"gateway.listening": "VoidBot gateway listening on http://{host}:{port}",
|
||||
"ui.title": "terminal agent",
|
||||
"ui.session": "Session",
|
||||
"ui.mode": "mode={value}",
|
||||
"ui.provider": "provider={id} {label}",
|
||||
"ui.provider_gateway": "provider=(gateway-only)",
|
||||
"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",
|
||||
"ui.prompt.input": "Message",
|
||||
"ui.user": "User",
|
||||
"ui.assistant": "Assistant",
|
||||
"ui.busy.local": "VoidBot is thinking and using tools",
|
||||
"ui.busy.gateway": "VoidBot is waiting for the gateway response",
|
||||
"ui.input_cancelled": "Input cancelled",
|
||||
"ui.fallback": "gateway unavailable, fell back to local mode: {error}",
|
||||
"ui.exit_hint": "• exit quit/exit ",
|
||||
"ui.toolbar": " via {via} • provider {provider_id}:{provider_label} • model {model} • gateway {gateway} ",
|
||||
"agent.models.title": "Available models:",
|
||||
"agent.models.switch_hint": "Use `/use <id>` to switch the current session model.",
|
||||
"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",
|
||||
"agent.gateway_requires_url": "gateway mode requires --gateway-url or gateway config",
|
||||
"agent.auto_no_fallback": "gateway call failed and no local config is available for fallback: {error}",
|
||||
"reply.mode": "mode={value}",
|
||||
"reply.iter": "iter={value}",
|
||||
"reply.tools": "tools={value}",
|
||||
"reply.provider": "provider={value}",
|
||||
"reply.model": "model={value}",
|
||||
"reply.run": "run={value}",
|
||||
},
|
||||
"zh-CN": {
|
||||
"cli.description": "VoidBot 命令行、网关、配置与数据工具",
|
||||
"cli.help.agent": "本地或通过 gateway 运行智能体",
|
||||
"cli.help.chat": "兼容旧用法的 agent 别名",
|
||||
"cli.help.gateway": "启动 gateway 服务",
|
||||
"cli.help.config": "管理位于 ~/.voidbot 的用户级 VoidBot 配置",
|
||||
"cli.help.data": "查看使用 SQLite 持久化的会话与消息数据",
|
||||
"cli.help.config.sync": "根据示例模板创建或增量更新 ~/.voidbot/config.json",
|
||||
"cli.help.config.path": "输出默认用户级配置文件路径",
|
||||
"cli.help.config.open": "用系统默认程序打开配置文件",
|
||||
"cli.help.config.path_flag": "同步后额外输出目标配置路径",
|
||||
"cli.help.data.dump": "输出 SQLite 数据库中的会话与消息",
|
||||
"cli.help.data.session_id": "可选的 session_id 过滤条件",
|
||||
"cli.help.data.limit": "限制返回的消息数量",
|
||||
"cli.help.config_path": "JSON 配置文件路径。默认查找顺序:./config.json,然后 {path}",
|
||||
"cli.help.message": "发送一条消息后退出",
|
||||
"cli.help.via": "选择 CLI 如何连接到智能体运行时。",
|
||||
"cli.help.gateway_url": "Gateway 基础地址,例如 http://127.0.0.1:8787",
|
||||
"cli.help.gateway_host": "覆盖 gateway 主机地址",
|
||||
"cli.help.gateway_port": "覆盖 gateway 端口",
|
||||
"cli.help.gateway_config": "JSON 配置文件路径",
|
||||
"config.sync.created": "已创建 VoidBot 配置:{path}",
|
||||
"config.sync.updated": "已更新 VoidBot 配置:{path}",
|
||||
"config.sync.added_fields": "新增缺失字段:",
|
||||
"config.sync.no_changes": "没有新增任何缺失字段。",
|
||||
"config.sync.home": "VoidBot 主目录:{path}",
|
||||
"config.opened": "已打开 {path}",
|
||||
"gateway.listening": "VoidBot gateway 正在监听 http://{host}:{port}",
|
||||
"ui.title": "终端智能体",
|
||||
"ui.session": "会话",
|
||||
"ui.mode": "模式={value}",
|
||||
"ui.provider": "模型源={id} {label}",
|
||||
"ui.provider_gateway": "模型源=(仅 gateway)",
|
||||
"ui.model": "模型={value}",
|
||||
"ui.gateway": "gateway={value}",
|
||||
"ui.welcome": "Enter 提交,Esc+Enter 换行,Ctrl+L 清屏",
|
||||
"ui.model_help": "/use <id> 切换模型,/models 查看模型列表",
|
||||
"ui.prompt.input": "输入消息",
|
||||
"ui.user": "主人",
|
||||
"ui.assistant": "小月",
|
||||
"ui.busy.local": "VoidBot 正在思考与调用工具",
|
||||
"ui.busy.gateway": "VoidBot 正在等待 gateway 返回",
|
||||
"ui.input_cancelled": "输入已取消",
|
||||
"ui.fallback": "gateway 不可用,已回退本地执行:{error}",
|
||||
"ui.exit_hint": "• exit quit/exit ",
|
||||
"ui.toolbar": " via {via} • 模型源 {provider_id}:{provider_label} • 模型 {model} • gateway {gateway} ",
|
||||
"agent.models.title": "可用模型列表:",
|
||||
"agent.models.switch_hint": "使用 `/use <id>` 可切换当前会话的模型。",
|
||||
"agent.use.switched": "已切换到模型 {id}:{label} / {model}",
|
||||
"agent.provider.unknown": "未知模型编号 '{provider_id}',可选值有:{available}",
|
||||
"agent.local_requires_config": "本地模式需要带有模型凭据的配置",
|
||||
"agent.gateway_requires_url": "gateway 模式需要 --gateway-url 或配置中的 gateway 地址",
|
||||
"agent.auto_no_fallback": "gateway 调用失败,且没有可回退的本地配置:{error}",
|
||||
"reply.mode": "mode={value}",
|
||||
"reply.iter": "iter={value}",
|
||||
"reply.tools": "tools={value}",
|
||||
"reply.provider": "provider={value}",
|
||||
"reply.model": "model={value}",
|
||||
"reply.run": "run={value}",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_language() -> str:
|
||||
"""Resolve the runtime UI language."""
|
||||
override = os.getenv("VOIDBOT_LANG")
|
||||
if override:
|
||||
return _normalize(override)
|
||||
|
||||
for key in ("LC_ALL", "LC_MESSAGES", "LANG"):
|
||||
value = os.getenv(key)
|
||||
if value:
|
||||
return _normalize(value)
|
||||
|
||||
current = locale.getlocale()[0] or locale.getdefaultlocale()[0] or ""
|
||||
return _normalize(current)
|
||||
|
||||
|
||||
def _normalize(raw: str) -> str:
|
||||
lowered = raw.replace("_", "-").lower()
|
||||
if lowered.startswith("zh"):
|
||||
return "zh-CN"
|
||||
return "en"
|
||||
|
||||
|
||||
def t(key: str, **kwargs: object) -> str:
|
||||
"""Translate one runtime key."""
|
||||
language = get_language()
|
||||
template = TRANSLATIONS.get(language, TRANSLATIONS["en"]).get(
|
||||
key,
|
||||
TRANSLATIONS["en"].get(key, key),
|
||||
)
|
||||
return template.format(**kwargs)
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
|
||||
from voidbot.config import AppConfig, ProviderConfig
|
||||
from voidbot.i18n import t
|
||||
from voidbot.providers.openai_compatible import OpenAICompatibleProvider
|
||||
from voidbot.providers.registry import get_provider_spec
|
||||
|
||||
@@ -28,7 +29,11 @@ class ProviderManager:
|
||||
return profile
|
||||
available = ", ".join(profile.id for profile in self.list_profiles())
|
||||
raise ValueError(
|
||||
f"unknown provider id '{provider_id}', expected one of: {available}"
|
||||
t(
|
||||
"agent.provider.unknown",
|
||||
provider_id=provider_id,
|
||||
available=available,
|
||||
)
|
||||
)
|
||||
|
||||
def build(self, provider_id: str | None = None) -> OpenAICompatibleProvider:
|
||||
|
||||
+18
-2
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from voidbot.agent import AgentRuntime
|
||||
from voidbot.config import AppConfig, ProviderConfig
|
||||
@@ -147,11 +148,25 @@ class AgentRuntimeTests(unittest.TestCase):
|
||||
|
||||
result = runtime.run_turn(inbound)
|
||||
|
||||
self.assertIn("可用模型列表", result.reply)
|
||||
self.assertIn("Available models", result.reply)
|
||||
self.assertIn("1. Model One", result.reply)
|
||||
self.assertIn("2. Model Two", result.reply)
|
||||
self.assertEqual(result.provider_id, "1")
|
||||
|
||||
def test_models_command_uses_chinese_when_locale_is_zh(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
runtime = self._make_runtime(Path(temp_dir))
|
||||
inbound = InboundMessageContext(
|
||||
session_id="main",
|
||||
raw_body="/models",
|
||||
body_for_agent="/models",
|
||||
)
|
||||
|
||||
with patch.dict("os.environ", {"VOIDBOT_LANG": "zh-CN"}, clear=False):
|
||||
result = runtime.run_turn(inbound)
|
||||
|
||||
self.assertIn("可用模型列表", 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))
|
||||
@@ -160,7 +175,7 @@ class AgentRuntimeTests(unittest.TestCase):
|
||||
raw_body="/use 2",
|
||||
body_for_agent="/use 2",
|
||||
)
|
||||
runtime.run_turn(switch)
|
||||
switch_result = runtime.run_turn(switch)
|
||||
|
||||
followup = InboundMessageContext(
|
||||
session_id="main",
|
||||
@@ -174,6 +189,7 @@ class AgentRuntimeTests(unittest.TestCase):
|
||||
self.assertEqual(state.provider_id, "2")
|
||||
self.assertEqual(result.provider_id, "2")
|
||||
self.assertEqual(result.model_name, "model-two")
|
||||
self.assertIn("Switched to model 2", switch_result.reply)
|
||||
self.assertIn("model-two", result.reply)
|
||||
|
||||
|
||||
|
||||
@@ -166,6 +166,12 @@ class GatewayTests(unittest.TestCase):
|
||||
self.assertIn("VoidBot config updated", output)
|
||||
self.assertIn("default_provider", output)
|
||||
|
||||
def test_parser_description_switches_with_locale(self) -> None:
|
||||
with patch.dict("os.environ", {"VOIDBOT_LANG": "zh-CN"}, clear=False):
|
||||
parser = build_parser()
|
||||
|
||||
self.assertIn("命令行", parser.description)
|
||||
|
||||
def test_config_path_command_prints_default_path(self) -> None:
|
||||
buffer = io.StringIO()
|
||||
with patch("sys.stdout", buffer):
|
||||
@@ -174,12 +180,14 @@ class GatewayTests(unittest.TestCase):
|
||||
self.assertIn(".voidbot/config.json", buffer.getvalue())
|
||||
|
||||
def test_config_open_command_opens_synced_path(self) -> None:
|
||||
buffer = io.StringIO()
|
||||
with patch(
|
||||
"voidbot.gateway.cli.sync_default_config",
|
||||
return_value=(Path("/tmp/.voidbot/config.json"), True, []),
|
||||
):
|
||||
with patch("voidbot.gateway.cli._open_path") as open_path:
|
||||
run_config_open_command()
|
||||
with patch("sys.stdout", buffer):
|
||||
run_config_open_command()
|
||||
|
||||
open_path.assert_called_once_with(Path("/tmp/.voidbot/config.json"))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user