Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 91a4ba2ab4 | |||
| 5a65320a5d | |||
| 946bf8bc55 | |||
| 050a3b2385 | |||
| ab8296901d | |||
| c09df1d0a2 | |||
| 31c62fafc2 | |||
| 7498810c70 | |||
| 57a9ff4ea1 | |||
| ab063d0674 | |||
| 3d5c02e7a9 | |||
| 4ed6c6a4ee | |||
| f665b83b34 | |||
| 1c07e37932 | |||
| daccc3fd10 | |||
| e62dd7b87b | |||
| 8ccf009958 | |||
| ff1c2e3400 | |||
| bea9debe15 | |||
| 8ac14bdaa2 | |||
| f84c68762b | |||
| 5878ec7a7f | |||
| 77b4f3d74f | |||
| fbfd50eb56 | |||
| 5a7ed44226 | |||
| 0b80ca4830 | |||
| c1da6486a4 | |||
| f877bd6ee8 | |||
| c9e0d689c0 | |||
| cceffd77ec | |||
| 2142e119c6 | |||
| 4ad2ea8e90 | |||
| bbc32dcb46 | |||
| 778c19b088 | |||
| 7e7aea0f48 | |||
| 4effa968ac | |||
| 76d6445ed6 | |||
| b55ce63c6e | |||
| 28a2ede206 | |||
| 1a9229aa75 | |||
| e11e178810 | |||
| 6bcb5d72f8 | |||
| b693f22f61 | |||
| 6e5ea9d3b6 | |||
| 08eecb9e0a |
9
.gitignore
vendored
@@ -87,3 +87,12 @@ Desktop.ini
|
||||
# 调试时生成的临时探针
|
||||
.tmp/
|
||||
.tmp-*
|
||||
|
||||
# 豆包网页版参考镜像(第三方资源,仅本地研究/对照用,不入库)
|
||||
reference/doubao-web-mirror/
|
||||
|
||||
# 嵌入式 Python 缓存(打包 exe 时自动下载;体积 ~10MB,不入库)
|
||||
desktop/build-cache/
|
||||
|
||||
# 豆包网页版抓取脚本的产物
|
||||
.tmp-scrape/
|
||||
|
||||
110
README.md
@@ -1,19 +1,23 @@
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(Web / Windows 版=豆包网页版风格)
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
**主力是安卓端**:一个**完全离线自主**的原生 Android App ——
|
||||
界面是 Kotlin + Jetpack Compose,AI 内核是内嵌的 CPython,**Termux 也是内置的**(不用另外装、不用连电脑)。
|
||||
|
||||
**Web / Windows 端**(v2)换成了**豆包网页版风格**的桌面界面,并且和安卓 App
|
||||
**共用同一份 Python 内核**(exe 内嵌 Python 运行时)—— 功能天然同步。详见 [`docs/网页版.md`](docs/网页版.md)。
|
||||
|
||||
> ⚠️ 学习目的的界面复刻,**与字节跳动没有任何关系**,不含任何来自豆包 App 的代码或素材。
|
||||
> 「豆包」是字节跳动的商标。
|
||||
|
||||
| 平台 | 产物 | 界面 | 内核 |
|
||||
|---|---|---|---|
|
||||
| **Android(主力)** | `dist-android/doubao-debug.apk`(88.4 MB) | **原生 Compose** | **APK 内嵌 CPython 3.13 + 内置 Termux** |
|
||||
| Windows | `…\DoubaoClone\Doubao-win32-x64\豆包.exe` | Lynx(旧版,仍在) | Node(随 Electron 启动) |
|
||||
| 浏览器 | `http://127.0.0.1:5199/` | Lynx(旧版,仍在) | Node |
|
||||
| Windows | `…\DoubaoClone\Doubao-win32-x64\豆包.exe` | **豆包网页版风格 Web UI**(`web/`) | **exe 内嵌 Python + `android/kernel/`(与 App 同一份)** |
|
||||
| 浏览器 | `http://127.0.0.1:5199/` | **豆包网页版风格 Web UI**(`web/`) | **`android/kernel/`(本机 Python)** |
|
||||
|
||||
> 旧的 **Lynx 版**(`app/` + Node 内核 `server/`)没有删,作为历史留档,菜单命令见 §9。
|
||||
> 安卓端**不依赖电脑、不依赖外装 Termux**:Python 运行时、Linux 用户态(bash/apt/pkg)、
|
||||
> MCP 客户端、终端全在 APK 里。装完填个 API Key 就能用。
|
||||
|
||||
@@ -25,26 +29,45 @@
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 早期 Lynx 版(真机实拍) | 浏览器版设置(10 家提供商) | Windows 桌面版 |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
**网页版 / Windows 桌面版(v2,豆包网页版风格):**
|
||||
|
||||
> 最左边那张是**旧的 Lynx 版**在真机上跑的(原生 Compose 版见上面两组)。
|
||||
> 两个版本现在都在仓库里:安卓走原生 Compose,Web / exe 走 Lynx。
|
||||
| 空对话(桌面网页) | 群聊(成员条 + 交接) | Windows exe |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| 智能体 | 设置(10 家提供商 / 22 项超时) | 会议模式(运行日志) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
**AI 界面能力(电脑端也能用了:AI 自己写 HTML 弹界面 / 弹选择框 / 结束对话):**
|
||||
|
||||
| AI 写的界面(show_ui,iframe 渲染) | AI 提问(ask_user,等用户选) | 结束对话(end_conversation) |
|
||||
|---|---|---|
|
||||
|  |  |  |
|
||||
|
||||
| exe 里同样可用(真窗口实拍) | | |
|
||||
|---|---|---|
|
||||
|  | | |
|
||||
|
||||
> 前两组是安卓原生 Compose 版(手机);这两组是电脑上的**网页版**(浏览器 / exe 同一个界面)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 快速开始
|
||||
|
||||
### 浏览器 / 桌面版
|
||||
### 浏览器 / 桌面版(v2:豆包网页版风格,和 App 同一份 Python 内核)
|
||||
|
||||
需要本机有 **Python 3.10+**(内核是纯标准库;Android 端是内嵌 CPython)。
|
||||
|
||||
```bash
|
||||
npm run install:all # app(Lynx 客户端)+ server(Node 内核)
|
||||
npm run build
|
||||
npm start # 打开 http://127.0.0.1:5199/
|
||||
npm start # 起 Python 内核并托管 web/,打开 http://127.0.0.1:5199/
|
||||
PORT=5300 npm start # 换端口
|
||||
```
|
||||
|
||||
Windows 桌面版直接双击 `豆包.exe`(**exe 必须放纯英文路径**,见 §7.1)。
|
||||
Windows 桌面版直接双击 `豆包.exe`(**自带 Python,不用装**;**exe 必须放纯英文路径**,见 §7.1)。
|
||||
重新打包:`npm run exe`。
|
||||
|
||||
> 旧的 Lynx 版还留着:`npm run install:all` + `npm run start:legacy-lynx`。
|
||||
|
||||
### Android(推荐,不需要电脑)
|
||||
|
||||
@@ -92,11 +115,14 @@ adb install -r dist-android/doubao-debug.apk
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
电脑上的 Web/exe 版仍然用 **Node 内核 + Lynx 界面**。两个内核**接口逐字段一致**,
|
||||
所以安卓端把界面换成 Compose 之后,后端一行都不用改。
|
||||
**v2 起,电脑上的 Web/exe 版不再用 Node 内核 + Lynx**,而是:
|
||||
- 界面换成 `web/` 里**豆包网页版风格**的纯静态前端(无构建步骤,内核直接托管);
|
||||
- 后端直接跑**和安卓 App 同一份** `android/kernel/`(纯标准库 Python),
|
||||
桌面版由 Electron 起一个 Python 子进程、并带一个"原生能力桥"(选文件/剪贴板);
|
||||
- 所以「引擎改了另一端必须跟上」这条欠账**没了**:一份内核,两个客户端。
|
||||
旧的 Node 内核(`server/`)和 Lynx 界面(`app/`)留作历史存档。
|
||||
|
||||
怎么做到一致的:`android/kernel/` 是照 `server/src/` 的契约重写的纯标准库实现
|
||||
(`http.server` + `urllib` + 手写 JSON-RPC),不依赖任何第三方包 —— 因为安卓上装不进来。
|
||||
细节见 [`docs/网页版.md`](docs/网页版.md)。
|
||||
|
||||
---
|
||||
|
||||
@@ -435,8 +461,23 @@ python scripts/probe-degraded.py # 幻觉检测 + 不支持 function calli
|
||||
> 而那时整个 App 不可用。`scripts/build-apk.mjs` 里加了这道闸,
|
||||
> 但它拦的是"打包",不是"你刚改的那一行"。
|
||||
|
||||
**还没做的**:Node 端(Web / exe)的智能体系统仍是旧的那套 ——
|
||||
按仓库约定"引擎改了另一端必须跟上",这是欠账。
|
||||
**全部界面和入口在哪**:[`docs/界面总览.md`](docs/界面总览.md) ——
|
||||
把 App 里所有界面画成树(含"每个界面从哪进"),而且
|
||||
`python scripts/audit-ui-tree.py` 会拿它**和源码对拍**:
|
||||
代码里有、文档没画的界面会直接报错("界面做好了但没入口"这类问题光靠人查必然会漏)。
|
||||
|
||||
**Python 脚本在哪跑、各有什么权限**:[`docs/Python脚本.md`](docs/Python脚本.md) ——
|
||||
这个 App 里**六类地方**会跑 Python(AI 的 `python_run` / `shell`、规则脚本、
|
||||
会议 Python 节点、自定义节点、内置 Termux),它们的权限和沙箱**完全不同**。
|
||||
一句话结论:
|
||||
|
||||
> **只有「规则脚本」有沙箱,而且那个沙箱挡得住手滑、挡不住有意。**
|
||||
> 其余几处本质就是"在你手机上跑代码",靠超时兜底,不是权限隔离。
|
||||
|
||||
**Web / exe 端(v2)**:不再维护第二套实现。界面在 `web/`(豆包网页版风格),
|
||||
后端就是上面这份 `android/kernel/`(桌面 exe 内嵌 Python 运行时)。
|
||||
功能对照、架构、验收方式和已知差距全部写在 [`docs/网页版.md`](docs/网页版.md);
|
||||
接口契约在 `docs/kernel-api-chat.md` / `kernel-api-agents.md` / `kernel-api-misc.md`。
|
||||
|
||||
|
||||
---
|
||||
@@ -616,10 +657,16 @@ mock 会按"第一轮返回 tool_call(calc)、第二轮根据工具结果流式
|
||||
|
||||
### 7.1 Windows exe
|
||||
- **exe 必须放纯英文路径**:中文路径下 Electron 的资源加载会失败
|
||||
- 打包用 `electron-packager`,产物在 `…\DoubaoClone\Doubao-win32-x64\`(exe 235 MB,整包 384 MB)
|
||||
- 打包用 `electron-packager`,产物在 `…\DoubaoClone\Doubao-win32-x64\`(exe 235 MB,整包 389 MB)
|
||||
- **v2 架构**:exe 里带一份 **python.org 的嵌入式 Python**(`runtime/python`,约 25 MB 解压后)+
|
||||
**同安卓 App 的 Python 内核**(`runtime/kernel`)+ 网页前端(`runtime/web`)。
|
||||
构建脚本会自动下载 `python-3.13.9-embed-amd64.zip` 缓存到 `desktop/build-cache/`(已 gitignore)
|
||||
- **启动时不要再设 `ELECTRON_RUN_AS_NODE=1`**(本机环境可能全局设了它):那样 Electron 会当 Node 跑,
|
||||
报 `Cannot read properties of undefined (reading 'commandLine')`。开发调试前先清掉这个环境变量
|
||||
- 桌面窗口的验证方式:设 `DOUBAO_CDP_PORT=9444` 启动,
|
||||
再用 `CDP_PORT=9444 node scripts/screenshot.mjs - out.png` 附着上去截图
|
||||
(Electron 界面只有真窗口渲染得出来,光 curl 验不了)
|
||||
- 数据目录默认 `%APPDATA%\Doubao\data`;自动化测试可用 `DOUBAO_USER_DATA` / `DOUBAO_DATA` 覆盖
|
||||
|
||||
### 7.2 Android APK
|
||||
- **`extractNativeLibs` 必须是 true**(Gradle:`packaging.jniLibs.useLegacyPackaging = true`)。
|
||||
@@ -686,28 +733,37 @@ realme / ColorOS 实测:应用自己打的 `Log.i` 在 `adb logcat` 里**一
|
||||
- **内嵌 Python 没有第三方库**(为了离线可构建),要装就走内置 Termux
|
||||
- **语音通话 / 朗读 / 分享**目前只弹提示,没做
|
||||
- **方舟模型 ID 带日期版本**,默认值取自官方 SDK 常量,是否对你这账号可用请看控制台
|
||||
- **网页版(Web/exe)**:`show_ui` / `ask_user` / `end_conversation` 已经能用(走内核的
|
||||
`/api/device/*` HTTP 队列,`wait` 语义和安卓一致);会议画布、立绘背景是二期。
|
||||
详见 `docs/网页版.md` §5.1 / §6
|
||||
|
||||
---
|
||||
|
||||
## 9. 命令速查
|
||||
|
||||
```bash
|
||||
# 开发
|
||||
npm run dev # 起 Node 内核 + Lynx 热更
|
||||
npm run build # 构建 Lynx bundle
|
||||
npm run apk # 构建 APK(--clean 可彻底重建)
|
||||
npm run exe # 打包 Windows exe
|
||||
# 开发(v2:网页版 + Python 内核)
|
||||
npm start # 起内核 + 托管 web/ → http://127.0.0.1:5199/
|
||||
npm run exe # 打包 Windows exe(内嵌 Python)
|
||||
npm run apk # 构建 Android APK(--clean 可彻底重建)
|
||||
node scripts/verify-web-ui.mjs # 网页版验收:逐页截图 + 收集 JS 报错
|
||||
node scripts/verify-ui-bridge.mjs # AI 界面能力:show_ui / ask_user / end_conversation
|
||||
node scripts/scrape-doubao-web.mjs # 扒豆包网页版做视觉参考(reference/,不入库)
|
||||
|
||||
# 旧的 Lynx 版(历史留档)
|
||||
npm run install:all # 装 app(Lynx 客户端)+ server(Node 内核)依赖
|
||||
npm run start:legacy-lynx
|
||||
|
||||
# 验证
|
||||
node scripts/verify-phone.mjs <serial> # 设备端 18 项验收
|
||||
node scripts/parity-thinking.mjs # 两份内核的思考强度对拍
|
||||
node scripts/parity-thinking.mjs # 两份内核的思考强度对拍(历史)
|
||||
node scripts/probe-settings-wipe.mjs <baseUrl> # 设置保存不掉字段(电脑)
|
||||
node scripts/device-settings-attack.mjs <serial> # 设置保存不掉字段(设备)
|
||||
node scripts/test-shell-tool.mjs <serial> [port] # 试内置 Termux 的 shell
|
||||
node scripts/device-state.mjs <serial> # 看设备内核当前设置
|
||||
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍(历史)
|
||||
python scripts/verify-nodekit.py # 节点库与 Python 引擎逐项对拍
|
||||
python scripts/verify-timeouts.py # 超时清单:边界 + 没有硬编码 + Node 端对拍
|
||||
python scripts/verify-seed-tools.py # 内置工具的播种/覆盖规则
|
||||
|
||||
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 253
|
||||
versionName = "2.0.53"
|
||||
versionCode = 283
|
||||
versionName = "2.0.83"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -26,6 +26,16 @@ class SpeechController(
|
||||
private val context: Context,
|
||||
private val client: KernelClient,
|
||||
private val scope: CoroutineScope,
|
||||
/**
|
||||
* 当前说话的是哪个智能体 —— 朗读时把它带给内核,用**它自己的音色**。
|
||||
*
|
||||
* ★★ 这个参数是补上来的:以前 `client.speak(text)` 只传正文,
|
||||
* 内核拿不到 agentId 就一律用全局音色,于是**智能体编辑页里选的声音
|
||||
* 配了也没用**(用户报的"智能体语音咋没生效")。
|
||||
* 做成 lambda 而不是字符串,是因为它会随用户切换智能体而变,
|
||||
* 而这个 controller 是在进聊天页时 remember 一次的。
|
||||
*/
|
||||
private val agentId: () -> String = { "" },
|
||||
) {
|
||||
private val speaker = Speaker(context)
|
||||
private val recorder = Recorder(context)
|
||||
@@ -61,8 +71,18 @@ class SpeechController(
|
||||
|
||||
/* ------------------------------ 朗读 ------------------------------ */
|
||||
|
||||
/** 念第 index 条消息 */
|
||||
fun speak(text: String, index: Int) {
|
||||
/**
|
||||
* 念第 [index] 条消息。
|
||||
*
|
||||
* [who] = **说这句话的智能体**(群聊里每条消息的发言者都不一样)。
|
||||
* 传空串就退回 [agentId] 那个"当前智能体"。
|
||||
*
|
||||
* ★★ 这个参数是补上来的:以前只会拿"当前对话的主人"去要音色,
|
||||
* 于是群聊里小黑和寐眠各配了不同音色,读出来却始终是同一个声音
|
||||
* (用户报的"群聊的时候不同智能体的语音不会切换")。
|
||||
* 内核其实**一直在消息里存 agentId**,只是客户端没读。
|
||||
*/
|
||||
fun speak(text: String, index: Int, who: String = "") {
|
||||
if (text.isBlank()) return
|
||||
// 正在念同一条 → 再点一次就是停
|
||||
if (speakingIndex == index && speaker.isPlaying) {
|
||||
@@ -76,6 +96,7 @@ class SpeechController(
|
||||
cancelRecording()
|
||||
|
||||
speakingIndex = index
|
||||
val voice = who.ifBlank { agentId() }
|
||||
scope.launch {
|
||||
// ★ 首选流式:内核边合成边下发 PCM,这边边收边喂 AudioTrack,
|
||||
// 首句大约 1 秒就能出声(整段合成再播要等 3 秒以上)。
|
||||
@@ -89,7 +110,7 @@ class SpeechController(
|
||||
// 用户看到的就是"一读语音就闪退"。
|
||||
val played = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
client.streamTts(text).use { r ->
|
||||
client.streamTts(text, voice).use { r ->
|
||||
val mime = r.body?.contentType().toString()
|
||||
val source = r.body?.source()
|
||||
source != null && speaker.playStream(mime, source)
|
||||
@@ -107,7 +128,7 @@ class SpeechController(
|
||||
}
|
||||
|
||||
try {
|
||||
val result = client.speak(text)
|
||||
val result = client.speak(text, voice)
|
||||
if (!result.optBoolean("ok")) {
|
||||
// 云端失败就退回系统 TTS —— 用户点了朗读却一点动静都没有是最差的体验
|
||||
val reason = result.optString("error").ifBlank { "云端合成失败" }
|
||||
@@ -157,8 +178,8 @@ class SpeechController(
|
||||
*/
|
||||
private var lastAutoReadKey: String? = null
|
||||
|
||||
/** 自动朗读:新回复刚落地时调它 */
|
||||
fun maybeAutoRead(text: String, index: Int) {
|
||||
/** 自动朗读:新回复刚落地时调它。[who] 同 [speak] —— 群聊里要按发言者挑音色 */
|
||||
fun maybeAutoRead(text: String, index: Int, who: String = "") {
|
||||
if (!autoRead || text.isBlank()) return
|
||||
if (recording) return
|
||||
|
||||
@@ -168,7 +189,7 @@ class SpeechController(
|
||||
if (speakingIndex == index && speaker.isPlaying) return
|
||||
|
||||
lastAutoReadKey = key
|
||||
speak(text, index)
|
||||
speak(text, index, who)
|
||||
}
|
||||
|
||||
/** 手动点朗读时清掉自动朗读的记录,免得"念过了就不再自动念"影响到后面 */
|
||||
|
||||
@@ -43,6 +43,7 @@ import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.R
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.PRESETS
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.foundation.Image
|
||||
|
||||
@@ -65,14 +66,22 @@ import androidx.compose.foundation.Image
|
||||
* ③ **限额 0 就是无限制**,不是"限额为 0"。
|
||||
*/
|
||||
|
||||
/** 外观四件套在界面上的顺序和文案 */
|
||||
/** 除立绘以外的三件套(立绘是**五档**的,单独处理) */
|
||||
private val ASSET_SLOTS = listOf(
|
||||
Triple("front", "角色图", "展示区中间的主体形象;缺了用内置默认人物"),
|
||||
Triple("back", "背景图", "铺在展示区最底层;缺了用内置默认背景"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区;缺了用简单方框"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本;缺了跟主体边框一个样式"),
|
||||
)
|
||||
|
||||
/** 立绘五档各档的说明 —— 每档都要写清"缺了会退回哪张",不然用户不知道该传几张 */
|
||||
private fun portraitHint(preset: String): String = when (preset) {
|
||||
"喜" -> "高兴时用这张;缺了用「平常」那张"
|
||||
"怒" -> "发怒时用这张;缺了用「平常」那张"
|
||||
"哀" -> "悲伤时用这张;缺了用「平常」那张"
|
||||
"死亡" -> "死亡时用这张(那时不能对话);缺了用「平常」那张"
|
||||
else -> "其他档都缺时兜底用这张;连它也没有就用内置默认人物"
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AgentEditScreen(
|
||||
vm: AppViewModel,
|
||||
@@ -95,12 +104,9 @@ fun AgentEditScreen(
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank()) return@rememberLauncherForActivityResult
|
||||
runCatching {
|
||||
val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
val name = (uri.lastPathSegment ?: "image.png").substringAfterLast('/')
|
||||
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
vm.uploadAgentAsset(draft.id, slot, name, b64)
|
||||
}.onFailure { vm.showHint("读不出这张图") }
|
||||
// 读图 / 压缩 / 上传全在 ViewModel 的 IO 线程里 ——
|
||||
// launcher 回调是**主线程**,解码一张 30MB 的手机照片放这儿会卡死界面
|
||||
vm.uploadAgentAssetFrom(ctx.applicationContext, draft.id, slot, uri)
|
||||
}
|
||||
|
||||
// 导出智能体包(需求 2.5):内核打包成 zip → base64 → 这里落盘。
|
||||
@@ -173,6 +179,37 @@ fun AgentEditScreen(
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
// ---- 立绘:五档(v1.2 需求 2.5 / 2.6)----
|
||||
//
|
||||
// ★ 槽位名带档位(`front:喜`),内核按这个落到不同文件 ——
|
||||
// 五档存成一张的话会互相覆盖。
|
||||
Text("角色立绘(按情绪换)", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Hint(
|
||||
"情绪的五档各自一张图,缺哪档就退回「平常」那张。" +
|
||||
"现在显示的是「${draft.image.portrait.ifBlank { "内置默认人物" }}」那张。",
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
for (preset in PRESETS) {
|
||||
AssetRow(
|
||||
title = preset,
|
||||
desc = portraitHint(preset),
|
||||
path = draft.image.slot(preset),
|
||||
onPick = {
|
||||
pendingSlot = "front:$preset"
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
},
|
||||
onClear = { vm.uploadAgentAsset(draft.id, "front:$preset", "", "") },
|
||||
// 立绘空着时显示内置默认人物 —— 那正是回退链的最后一级
|
||||
showDefaultPerson = true,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
// ---- 其余三件套 ----
|
||||
Text("其他三件套", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
for ((key, title, desc) in ASSET_SLOTS) {
|
||||
AssetRow(
|
||||
title = title,
|
||||
@@ -281,6 +318,18 @@ fun AgentEditScreen(
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("用满之后会拦住发送,并附一句告别(那句话可以在设置里改)。留空就是无限制。")
|
||||
Spacer(Modifier.height(12.dp))
|
||||
// ★ v1.2 §6.1:拉起其他智能体的方式。
|
||||
// 内核(`agent_tools.invite_agent`)早就按这个字段分流了,
|
||||
// 但界面上一直**没有入口** —— 于是 `confirm` 那一档
|
||||
// 用户永远打不开,等于需求里这个选项不存在。
|
||||
ToggleRow(
|
||||
title = "拉人要先问我",
|
||||
sub = "打开后,AI 想邀请别的智能体进群时会先问一句;" +
|
||||
"关闭则直接拉进来(都会在正文里说一声)。",
|
||||
checked = draft.inviteMode == "confirm",
|
||||
onChange = { draft = draft.copy(inviteMode = if (it) "confirm" else "silent") },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 技能 ---------------- */
|
||||
@@ -329,7 +378,7 @@ fun AgentEditScreen(
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 记忆 / 用量 ---------------- */
|
||||
/* ---------------- 记忆 / 状态数值 / 用量 ---------------- */
|
||||
if (!isNew) {
|
||||
SectionLabel("它的状态")
|
||||
Row(
|
||||
@@ -339,11 +388,23 @@ fun AgentEditScreen(
|
||||
BigAction("看它记住了什么") { vm.openMemories(draft.id) }
|
||||
BigAction("看它用了多少") { vm.openTokenUsage(draft.id) }
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// ★★ 「它的状态」这个标题下面**原来只有记忆和用量两个按钮** ——
|
||||
// 状态数值页自己写着"三个入口:聊天页状态栏 / 智能体编辑的
|
||||
// 它的状态 / 群成员的状态",而中间那个**从来没做出来**。
|
||||
// 结果是:用户在群里能点到「状态」,在智能体编辑页却点不到。
|
||||
BigAction("看它的数值和状态") { vm.openStats(draft.id) }
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 14.dp)) {
|
||||
Hint(
|
||||
"记忆是 AI 自己攒的(也可能记错),觉得不对就在那里改 —— " +
|
||||
"这是它记错时唯一的兜底。",
|
||||
"这是它记错时唯一的兜底。数值和状态由它绑定的世界观上的" +
|
||||
"「数值状态包」定义。",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -387,28 +448,17 @@ fun AgentEditScreen(
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
private fun AgentImage.pathOf(key: String): String = when (key) {
|
||||
"front" -> front
|
||||
// v1.2:立绘是五档表,编辑界面的**预览**用内核算好的那张
|
||||
// (其他三件套还是单张)
|
||||
"front" -> portrait
|
||||
"back" -> back
|
||||
"border-main" -> borderMain
|
||||
else -> borderInfo
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Card(content: @Composable () -> Unit) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) { content() }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Hint(text: String) {
|
||||
Text(text, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
// ★ `Card` / `Hint` 已经挪到 DoubaoUi.kt 变成公共组件了 ——
|
||||
// 原来它们是这个文件私有的,于是别的界面想用只能复制一份
|
||||
// ([群成员] 就要用),而"同一段逻辑抄两份"是这个仓库的老毛病。
|
||||
|
||||
/** 一行里并排的两个入口按钮(记忆 / 用量这种"跳去另一个界面"的动作) */
|
||||
@Composable
|
||||
@@ -516,6 +566,15 @@ private fun AssetRow(
|
||||
path: String,
|
||||
onPick: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
/**
|
||||
* 空的时候要不要显示**内置默认人物**的缩略图。
|
||||
*
|
||||
* ★ 只有**立绘**该显示它(那正是回退链的最后一级)。
|
||||
* 背景图 / 边框为空时显示一张**人物照**是误导 ——
|
||||
* 用户会以为"我没设背景,怎么有个女的"(截图反馈过)。
|
||||
* 那三个空着就画一个空框 + 一个「空」字,如实表达"这里什么都没有"。
|
||||
*/
|
||||
showDefaultPerson: Boolean = false,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
@@ -527,14 +586,18 @@ private fun AssetRow(
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (path.isBlank()) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
alpha = 0.35f,
|
||||
)
|
||||
if (showDefaultPerson) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
alpha = 0.35f,
|
||||
)
|
||||
} else {
|
||||
Text("空", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
} else {
|
||||
AssetImage(
|
||||
path = path,
|
||||
|
||||
@@ -119,6 +119,7 @@ private const val SHIFT = 0.10f
|
||||
|
||||
@Composable
|
||||
fun AgentSelectScreen(
|
||||
vm: AppViewModel,
|
||||
agents: List<Agent>,
|
||||
activeId: String,
|
||||
/** 选中并进入它的对话界面(需求 2.1:完成选择后进入对应智能体的对话界面) */
|
||||
@@ -152,6 +153,10 @@ fun AgentSelectScreen(
|
||||
val shownAgent = agents.getOrNull(shown) ?: agents.first()
|
||||
val pickedAgent = agents.getOrNull(picked) ?: agents.first()
|
||||
|
||||
// ★ 进这一页就拉一遍所有智能体的数值/状态(卡片上要显示)。
|
||||
// 失败就保持上一份 —— 卡片上少几个数字不该报错打扰用户。
|
||||
LaunchedEffect(Unit) { vm.refreshAllStats() }
|
||||
|
||||
val frontAlpha = remember { Animatable(1f) }
|
||||
val frontShift = remember { Animatable(0f) }
|
||||
val frameAlpha = remember { Animatable(1f) }
|
||||
@@ -236,6 +241,9 @@ fun AgentSelectScreen(
|
||||
picked = picked,
|
||||
onPick = { picked = it },
|
||||
state = listState,
|
||||
// ★★ 用户要求「数字界面在智能体卡片里展示」——
|
||||
// 卡片上直接显示这个角色的数值和状态,不用点进去才看得到。
|
||||
stats = vm.allStats,
|
||||
modifier = Modifier.width(96.dp).fillMaxHeight().padding(8.dp),
|
||||
)
|
||||
|
||||
@@ -256,7 +264,7 @@ fun AgentSelectScreen(
|
||||
Modifier.fillMaxSize().offset(x = (frontShift.value * 200).dp),
|
||||
) {
|
||||
ArtworkFill(
|
||||
shownAgent.image.front,
|
||||
shownAgent.image.portrait,
|
||||
R.drawable.agent_default_character,
|
||||
alpha = frontAlpha.value,
|
||||
scale = ContentScale.Fit,
|
||||
@@ -430,13 +438,15 @@ private fun IntroCard(agent: Agent, modifier: Modifier = Modifier) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 左侧列表:一张卡片 = 缩略图 + 名字;当前项高亮 */
|
||||
/** 左侧列表:一张卡片 = 缩略图 + 名字 + **数值/状态**;当前项高亮 */
|
||||
@Composable
|
||||
private fun AgentList(
|
||||
agents: List<Agent>,
|
||||
picked: Int,
|
||||
onPick: (Int) -> Unit,
|
||||
state: androidx.compose.foundation.lazy.LazyListState,
|
||||
/** agentId → 它的数值/状态(只有挂了规则包的智能体在里面) */
|
||||
stats: Map<String, com.doubao.lynxclone.data.AgentStats>,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
LazyColumn(modifier, state = state, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
@@ -467,7 +477,7 @@ private fun AgentList(
|
||||
// ★ alignment = TopCenter:角色图是竖长的,居中裁剪只会
|
||||
// 裁出"腰到大腿",一排缩略图全是裤子
|
||||
AssetImage(
|
||||
path = agent.image.front,
|
||||
path = agent.image.portrait,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
@@ -491,6 +501,59 @@ private fun AgentList(
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
|
||||
// ★★ 数值和状态(用户要求「数字界面在智能体卡片里展示」)。
|
||||
//
|
||||
// 卡片只有 96dp 宽,所以这里**极简**:
|
||||
// · 第一条数值 + 迷你进度条(一眼看出高低)
|
||||
// · 有状态就再压一行名字(圆点 + 名字,多了就 N 个点)
|
||||
//
|
||||
// ★ 只显示**第一条**数值是有意的:卡片上放大而全的数值表
|
||||
// 等于把 [状态数值] 页塞进 96dp,谁也看不清;
|
||||
// 想细看就点进去。这里要回答的只是"这个角色现在什么情况"。
|
||||
val st = stats[agent.id]
|
||||
if (st != null && st.stats.isNotEmpty()) {
|
||||
val main = st.stats.first()
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
"${main.name} ${fmtNum(main.value)}",
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFFFFE08A),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
// 迷你进度条:3dp 高,一眼看出比例,不占地方
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(3.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(Color(0x33FFFFFF)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(main.ratio())
|
||||
.height(3.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(Color(0xFFFFE08A)),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (st != null && st.statuses.isNotEmpty()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
st.statuses.joinToString(" · ") { it.name },
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFF8FE0A0),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.StatValue
|
||||
import com.doubao.lynxclone.data.StatusInstance
|
||||
|
||||
/**
|
||||
* [状态数值](v1.2 §3.10 数值 / §3.11 状态)。
|
||||
*
|
||||
* ## 三个入口共用这一个界面
|
||||
*
|
||||
* 需求 §6.1 指定的三个入口:**聊天页状态栏** / **智能体编辑的"它的状态"** /
|
||||
* **群成员的「状态」按钮**。三处都调 `vm.openStats(agentId)`。
|
||||
*
|
||||
* ★ 只写一个界面是有意的:三个入口各写一份的话,"数值怎么显示、
|
||||
* 能不能改、状态剩几轮怎么标"这三件事会各有一套说法 ——
|
||||
* 而这个仓库里"同一逻辑抄两份"已经反复出现过。
|
||||
*
|
||||
* ## 用户能直接改数值,AI 不能
|
||||
*
|
||||
* AI 的 `change_stat` 只能申请**增量**,还要过脚本裁决(§3.10)。
|
||||
* 用户是规则的主人 —— 点一下就能直接设成任何值。
|
||||
* 但内核照样会 clamp 到 `[min,max]`:超出范围的值会让进度条和区间注入
|
||||
* 全都错位。所以**回来之后要以返回值刷新**,不能乐观地先用自己填的。
|
||||
*/
|
||||
@Composable
|
||||
fun AgentStatsScreen(
|
||||
vm: AppViewModel,
|
||||
agentId: String,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val stats = vm.agentStats
|
||||
var editing by remember { mutableStateOf("") }
|
||||
var input by remember { mutableStateOf("") }
|
||||
|
||||
FullScreen(
|
||||
title = "状态数值",
|
||||
subtitle = stats?.name?.takeIf { it.isNotBlank() } ?: "读不出来",
|
||||
onBack = onBack,
|
||||
) {
|
||||
if (stats == null) {
|
||||
Hint("正在读……")
|
||||
return@FullScreen
|
||||
}
|
||||
if (stats.rulePackId.isBlank()) {
|
||||
// 没挂规则包就没有数值系统 —— 如实说清楚,别让用户以为是加载失败
|
||||
Hint(
|
||||
"这个智能体还没有数值系统。\n\n" +
|
||||
"数值和状态由「数值状态包」定义 —— 去 资源 → 规则包 " +
|
||||
"建一个(或导入一个),再把它挂到智能体所在的世界观上。",
|
||||
)
|
||||
return@FullScreen
|
||||
}
|
||||
|
||||
SectionLabel("数值")
|
||||
Card {
|
||||
if (stats.stats.isEmpty()) {
|
||||
Hint("这个规则包里没有数值。")
|
||||
}
|
||||
for (s in stats.stats) {
|
||||
StatRow(
|
||||
stat = s,
|
||||
editing = editing == s.name,
|
||||
input = input,
|
||||
onInput = { input = it },
|
||||
onStartEdit = { editing = s.name; input = fmtNum(s.value) },
|
||||
onCancel = { editing = "" },
|
||||
onCommit = {
|
||||
vm.setStatDirect(s.name, input.toDoubleOrNull() ?: s.value)
|
||||
editing = ""
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (stats.rulePackName.isNotBlank()) {
|
||||
Hint("来自规则包「${stats.rulePackName}」。")
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态")
|
||||
Card {
|
||||
if (stats.statuses.isEmpty()) {
|
||||
Hint("身上没有状态。")
|
||||
}
|
||||
for (st in stats.statuses) {
|
||||
// ★ 每条状态都能**清掉**。AI 手里只有 `grant_status`(只能加),
|
||||
// 没有任何工具能移除状态 —— 所以这个按钮是唯一的出口:
|
||||
// `persistent` 状态不会自己过期,没有它就永远下不来。
|
||||
StatusRow(st, onDrop = { vm.dropStatusDirect(st.name) })
|
||||
}
|
||||
}
|
||||
Hint(
|
||||
"定时状态每参与一轮减 1,归零就消失;持久状态不会自己过期。" +
|
||||
"状态提示词会被注入到它的系统提示里。",
|
||||
)
|
||||
|
||||
// ---- 手动挂一个状态 ----
|
||||
//
|
||||
// 只在包里有**还没挂上**的状态定义时才显示 —— 全都挂上了就没东西可加了,
|
||||
// 摆一排点不动的按钮反而让人以为坏了。
|
||||
val notOn = stats.statusDefs.filter { d -> stats.statuses.none { it.name == d.name } }
|
||||
if (notOn.isNotEmpty()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("加一个")
|
||||
Card {
|
||||
Hint("AI 只能给自己加状态,你也可以直接挂 —— 用来测效果或者补剧情。")
|
||||
Spacer(Modifier.height(6.dp))
|
||||
for (d in notOn) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth()
|
||||
.clickable { vm.addStatusDirect(d.name, d.turns) }
|
||||
.padding(vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(d.name, fontSize = 13.sp, color = doubaoText())
|
||||
Text(
|
||||
if (d.isPersistent) "持久 · 不会自己过期"
|
||||
else "定时 · ${d.turns} 轮后消失",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("挂上") { vm.addStatusDirect(d.name, d.turns) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatRow(
|
||||
stat: StatValue,
|
||||
editing: Boolean,
|
||||
input: String,
|
||||
onInput: (String) -> Unit,
|
||||
onStartEdit: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
onCommit: () -> Unit,
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stat.name, fontSize = 13.sp, color = doubaoText(), modifier = Modifier.weight(1f))
|
||||
if (stat.shared) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TinyTag("全世界观共用")
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
if (editing) {
|
||||
// 直接设值 —— 用户主权。★ 就地在行内变成输入框,不再压一层
|
||||
// 对话框(AGENTS.md:一次输入用弹窗也行,但这里已经有上下文,
|
||||
// 就地改更省事,而且弹窗会盖住进度条)
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value = input,
|
||||
onValueChange = onInput,
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.width(84.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
RowAction("好") { onCommit() }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
RowAction("取消") { onCancel() }
|
||||
} else {
|
||||
Text(
|
||||
"${fmtNum(stat.value)} / ${fmtNum(stat.max)}",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("改") { onStartEdit() }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// 进度条:`ratio()` 在模型里(三个入口共用一份换算,圆角和取整才不会各说各话)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(doubaoSurface()),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(stat.ratio())
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Blue),
|
||||
)
|
||||
}
|
||||
if (stat.text.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(stat.text, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusRow(st: StatusInstance, onDrop: () -> Unit) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(st.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TinyTag(if (st.isPersistent) "持久" else "剩 ${st.remaining} 轮")
|
||||
if (st.stacks > 1) {
|
||||
Spacer(Modifier.width(4.dp))
|
||||
TinyTag("×${st.stacks}")
|
||||
}
|
||||
}
|
||||
if (st.hint.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(st.hint, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
// ★ 清掉。这是用户手动移除状态的**唯一出口**(AI 没这个能力)。
|
||||
// 不做二次确认:状态本来就可以再加回来,而多一层确认会让
|
||||
// "连清五个"变成五次弹窗 —— 手机上很烦。
|
||||
RowAction("清掉") { onDrop() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TinyTag(text: String) {
|
||||
Text(
|
||||
text,
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.12f))
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 数值显示:整数就不带小数点(45.0 → 45),不然看着别扭。
|
||||
*
|
||||
* ★ 现在**两处**在用(状态数值页 + 智能体卡片),所以是 `internal` 不是 private ——
|
||||
* 卡片那边要显示同样的数字,抄一份就是第二份实现("同一逻辑只能有一份")。
|
||||
*/
|
||||
internal fun fmtNum(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
@@ -19,6 +19,10 @@ import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
// ★ 扩展函数(`Modifier.verticalScroll`)**不能用全限定名调用** ——
|
||||
// 必须 import 进来。这个坑花了两轮构建才撞明白。
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -146,6 +150,7 @@ fun AppRoot(
|
||||
Screen.Agents -> AgentsScreen(vm)
|
||||
// 智能体选择界面(需求第二章):左列表 + 右角色展示 + 切换动画
|
||||
Screen.AgentSelect -> AgentSelectScreen(
|
||||
vm = vm,
|
||||
agents = vm.agents,
|
||||
activeId = vm.state.settings.activeAgentId,
|
||||
onEnter = { vm.enterAgent(it.id) },
|
||||
@@ -224,6 +229,19 @@ fun AppRoot(
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Settings
|
||||
},
|
||||
// 从抽屉挪进来的三个
|
||||
onNewGroup = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.newGroupTopic()
|
||||
},
|
||||
onOpenNotes = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.openNotes()
|
||||
},
|
||||
onOpenModels = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.modelPickerOpen = true
|
||||
},
|
||||
onClose = { vm.moreSheetOpen = false },
|
||||
)
|
||||
}
|
||||
@@ -263,7 +281,7 @@ fun AppRoot(
|
||||
worldMode = true,
|
||||
loading = false,
|
||||
hint = "",
|
||||
onSetEmotion = {},
|
||||
onSetEmotion = { _, _ -> },
|
||||
onAdd = { _, _ -> },
|
||||
onUpdate = { _, _, _ -> },
|
||||
// 删是可以的:限权只约束 AI,用户有权清掉任何人写的
|
||||
@@ -318,7 +336,7 @@ fun AppRoot(
|
||||
agentNames = vm.agents.associate { it.id to it.name },
|
||||
loading = vm.memoryLoading,
|
||||
hint = vm.memoryHint,
|
||||
onSetEmotion = { vm.setEmotion(it) },
|
||||
onSetEmotion = { preset, text -> vm.setEmotion(preset, text) },
|
||||
onAdd = { t, c -> vm.addMemory(t, c) },
|
||||
onUpdate = { id, t, c -> vm.updateMemory(id, t, c) },
|
||||
onDelete = { vm.deleteMemory(it) },
|
||||
@@ -333,6 +351,87 @@ fun AppRoot(
|
||||
)
|
||||
}
|
||||
|
||||
// 「新建群聊」:挑一个搭子(当前智能体当主角 = 主智能体)
|
||||
//
|
||||
// ★ 用对话框而不是全屏:这是**一次选择**(挑一个人就完了),
|
||||
// 智能体一般不超过十个,一屏放得下 —— 正是 AGENTS.md 里
|
||||
// "一次确认 / 纯菜单用弹窗"那一档。
|
||||
if (vm.pickGroupPeer) {
|
||||
val others = vm.state.agents.filter { it.id != vm.activeAgent?.id }
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.cancelPickGroupPeer() },
|
||||
title = { Text("和谁一起聊") },
|
||||
text = {
|
||||
if (others.isEmpty()) {
|
||||
Text("还没有别的智能体。先去「智能体」里建一个。", fontSize = 13.sp)
|
||||
} else {
|
||||
// ★ 用全限定名:这个文件的 import 列表里没有
|
||||
// verticalScroll / rememberScrollState,
|
||||
// 而它们只在这一处用得到(别的滚动都在各自的界面文件里)
|
||||
// ★ 这层滚动用**全限定调用**:`Modifier.verticalScroll`
|
||||
// 是个扩展函数,光写名字这里解析不到,而为了它一行
|
||||
// 往这个文件顶部加 import 不划算(只此一处用得到)
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
for (a in others) {
|
||||
Text(
|
||||
a.name,
|
||||
fontSize = 14.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { vm.createGroupWith(a.id) }
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { vm.cancelPickGroupPeer() },
|
||||
) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// [规则包编辑](v1.2 附录 D)—— 全屏
|
||||
AnimatedVisibility(
|
||||
visible = vm.editingRulePack != null,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
RulePackEditScreen(vm = vm, onBack = { vm.closeRulePackEdit() })
|
||||
}
|
||||
|
||||
// 「群成员」(v1.2 §3.9)—— 用户手动增删成员无条件
|
||||
AnimatedVisibility(
|
||||
visible = vm.membersConvId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
GroupMembersScreen(
|
||||
vm = vm,
|
||||
conversationId = vm.membersConvId,
|
||||
onBack = { vm.closeMembers() },
|
||||
// 成员行上的「状态」→ 开 [状态数值](三个入口之一)
|
||||
onOpenStats = { vm.openStats(it) },
|
||||
)
|
||||
}
|
||||
|
||||
// [状态数值](v1.2 §3.10 / §3.11)—— 三个入口共用这一个界面:
|
||||
// 聊天页的状态栏、智能体编辑的"它的状态"、群成员的「状态」按钮
|
||||
AnimatedVisibility(
|
||||
visible = vm.statsAgentId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
AgentStatsScreen(
|
||||
vm = vm,
|
||||
agentId = vm.statsAgentId,
|
||||
onBack = { vm.closeStats() },
|
||||
)
|
||||
}
|
||||
|
||||
// 导入记忆:先读文件,再让用户选**合并还是覆盖**(复查报告 4.2.4)。
|
||||
//
|
||||
// ★ 默认是合并:覆盖是破坏性的,用户点错一次就全没了。
|
||||
@@ -493,7 +592,18 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
* 列表这种要滚动的东西不用弹窗或折叠面板)
|
||||
*/
|
||||
// 分区标题:抽屉里两组东西(功能 / 对话)不标一下容易混在一起看
|
||||
SectionLabel("功能", Modifier.padding(horizontal = 20.dp, vertical = 6.dp))
|
||||
// ★ 分组标题的留白也一起放松 —— 只加项间距的话,
|
||||
// 标题会和第一项粘在一起,看着像"标题属于上一组"
|
||||
SectionLabel("功能", Modifier.padding(start = 22.dp, top = 14.dp, bottom = 6.dp))
|
||||
// ★★ 抽屉第一层**只留四件天天用的**(用户明确说"太挤了"、
|
||||
// "把别的放更多里"):
|
||||
//
|
||||
// 开启新话题 · 智能体 · 记忆 · 更多功能
|
||||
//
|
||||
// 笔记 / 模型 / 新建群聊都挪进「更多功能」了。
|
||||
// 「模型」虽然也常用,但它是个**配置**(配好基本不动),
|
||||
// 腾出来的位置留给底下的对话列表更值 ——
|
||||
// 而对话列表才是用户 90% 打开抽屉的目的。
|
||||
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
// ★ 抽屉这一项进的是**选择界面**(需求 2.1 的入口页),
|
||||
@@ -507,31 +617,48 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
vm.drawerOpen = false
|
||||
vm.activeAgent?.id?.let { vm.openMemories(it) }
|
||||
}
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
DrawerItem(Icons.Filled.EditNote, "笔记") {
|
||||
vm.drawerOpen = false
|
||||
vm.openNotes()
|
||||
}
|
||||
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
|
||||
DrawerItem(
|
||||
Icons.Filled.Memory, "模型",
|
||||
trailing = "${shortModel(vm.settings.model)} ${thinkingLabel(vm.settings.thinkingLevel)}",
|
||||
) {
|
||||
vm.modelPickerOpen = true
|
||||
vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Apps, "更多功能") {
|
||||
vm.drawerOpen = false
|
||||
vm.moreSheetOpen = true
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("对话", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
|
||||
|
||||
// ★ 群聊和单聊**分开列**(用户要求)。
|
||||
//
|
||||
// 混在一起排的时候,群聊会被一堆单聊埋到下面去 ——
|
||||
// 而这两类的**行为**本来就不一样:群聊有成员表、点名条、
|
||||
// 谁在说话跟着换;单聊只有一个主人。混在一起用户还得靠标题猜。
|
||||
//
|
||||
// 私聊记录(两个 AI 自己聊的)归到「对话」那一组 ——
|
||||
// 它没有"多个成员在群里"的语义,是两条消息流而已。
|
||||
val groups = vm.state.conversations.filter { it.isGroup }
|
||||
val singles = vm.state.conversations.filter { !it.isGroup }
|
||||
|
||||
LazyColumn(Modifier.weight(1f)) {
|
||||
items(vm.state.conversations.size) { i ->
|
||||
ConversationRow(vm, vm.state.conversations[i])
|
||||
if (groups.isNotEmpty()) {
|
||||
item {
|
||||
SectionLabel("群聊", Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp))
|
||||
}
|
||||
items(groups.size) { i -> ConversationRow(vm, groups[i]) }
|
||||
}
|
||||
item {
|
||||
SectionLabel(
|
||||
if (groups.isEmpty()) "对话" else "单聊",
|
||||
Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp),
|
||||
)
|
||||
}
|
||||
if (singles.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
"还没有单聊。点上面的「开启新话题」挑一个智能体。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 22.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(singles.size) { i -> ConversationRow(vm, singles[i]) }
|
||||
}
|
||||
|
||||
Row(
|
||||
@@ -584,11 +711,14 @@ private fun DrawerItem(
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||
// ★ 项之间的留白从 2dp 提到 6dp、项内从 13dp 提到 16dp。
|
||||
// 原来每项视觉高度只有 ~48dp,七项叠在一起糊成一片 ——
|
||||
// 用户反馈"太挤了"。现在每项 ~60dp,手指点起来也稳。
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(bg)
|
||||
.clickable(interactionSource = source, indication = null, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 13.dp),
|
||||
.padding(horizontal = 12.dp, vertical = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
|
||||
@@ -13,7 +13,9 @@ import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -54,6 +56,7 @@ import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.ChatMessage
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -182,7 +185,13 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
val onPickFile: () -> Unit = { picker.launch(arrayOf("*/*")) }
|
||||
|
||||
// ---------------- 语音 ----------------
|
||||
val speech = remember { SpeechController(context, vm.client, scope) }
|
||||
val speech = remember {
|
||||
SpeechController(context, vm.client, scope) {
|
||||
// ★ 带上当前智能体 —— 不带的话内核一律用全局音色,
|
||||
// 智能体编辑页里选的声音就白配了(用户报的"语音没生效")
|
||||
vm.state.settings.activeAgentId
|
||||
}
|
||||
}
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { speech.release() }
|
||||
}
|
||||
@@ -226,7 +235,9 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
delay(600)
|
||||
val now = vm.messages.lastOrNull()
|
||||
if (now === msg && !now.pending && now.content == msg.content) {
|
||||
speech.maybeAutoRead(now.content, vm.messages.size - 1)
|
||||
// 带上这条消息的发言者 —— 群聊里每个人音色不同,
|
||||
// 不带就一律用"当前智能体"的声音
|
||||
speech.maybeAutoRead(now.content, vm.messages.size - 1, now.agentId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -256,9 +267,16 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||
ChatHeader(vm, agent?.name ?: "豆包", speech)
|
||||
// ★ 顶栏的名字和**背景用的是同一个人**(`backdropAgent`)——
|
||||
// 用户的原话是「还是没换标题和背景呀」:寐眠在说话,
|
||||
// 顶栏和背景就该都是寐眠。两处各取各的必然对不上。
|
||||
val shown = backdropAgent(vm)
|
||||
ChatHeader(vm, shown?.name ?: (agent?.name ?: "豆包"), speech)
|
||||
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
// 立绘/背景铺在**消息下面**(用户要的"整个背景都是角色")
|
||||
ChatBackdrop(vm)
|
||||
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
@@ -272,7 +290,11 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
tagline.endsWith("?") || tagline.contains(","))
|
||||
val greeting =
|
||||
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
|
||||
item { AppearOnce { HeroSection(greeting) } }
|
||||
// ★ 这里原来还有一个 168dp 的圆形立绘(ChatPortrait)——
|
||||
// 背景层(ChatBackdrop)接手之后它就是多余的:两张同一个人的图
|
||||
// 叠在一起,而且圆形 Crop 会把全身图裁到腰上,很难看。
|
||||
item { AppearOnce { HeroText(greeting) } }
|
||||
item { AppearOnce { PortraitHint(vm) } }
|
||||
}
|
||||
items(vm.messages.size) { index ->
|
||||
AppearOnce(offsetY = 10.dp) {
|
||||
@@ -310,7 +332,15 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
|
||||
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
|
||||
|
||||
if (vm.conversationEnded) {
|
||||
// ★ 私聊记录是**只读**的(v1.2 §3.9 形态 B)——那两个 AI 是
|
||||
// 在你不在场的时候聊的,往里插话等于改历史记录。
|
||||
// 这里把输入条整条换掉,而不是"能输入但发不出去"。
|
||||
val privateConv = vm.state.conversations
|
||||
.firstOrNull { it.id == vm.activeConversationId }?.isPrivate == true
|
||||
if (privateConv) {
|
||||
Box(Modifier.weight(1f))
|
||||
Hint("这是两个智能体的私聊记录,只读。想让他们再聊一次,去「群成员」页。")
|
||||
} else if (vm.conversationEnded) {
|
||||
/**
|
||||
* ★★ 对话被 AI 结束了 —— **屏幕中间一个横幅,写着关闭原因**。
|
||||
*
|
||||
@@ -331,6 +361,28 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
} else {
|
||||
// 本次对话的用量(需求 4.1)跟着输入条一起显示 ——
|
||||
// 放在输入框正上方是因为它是"这次对话"的属性,而输入框就是这次对话的入口
|
||||
// ★ 对话被换了归属时的提示(见 AppViewModel 的 rebasedNote)
|
||||
if (vm.rebasedNote.isNotBlank()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
vm.rebasedNote,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
RowAction("知道了") { vm.clearRebasedNote() }
|
||||
}
|
||||
}
|
||||
// ★ 群聊的成员快捷条(v1.2 §3.9):点头像 = @ 点名,被点的人这一轮一定发言
|
||||
//
|
||||
// ★★ 顺序:先「要不要让他接着说」,再点名条 ——
|
||||
// 前者的决策更靠前(它决定这一轮还继不继续),
|
||||
// 而且它只在有待决移交时才出现。
|
||||
HandoffBar(vm)
|
||||
GroupQuickBar(vm)
|
||||
SessionUsageBar(vm)
|
||||
// 额度用完被拦住了 → 给出路(复查报告 2.4)。
|
||||
// 只拦不给入口的话,用户会以为这个智能体坏了。
|
||||
@@ -367,7 +419,64 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
)
|
||||
}
|
||||
}
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
// ★★ 死亡禁言(v1.2 §6.1,需求 3.5)。
|
||||
//
|
||||
// 内核那道拦截是权威,但**界面上也要拦一道** ——
|
||||
// 让用户敲完一整句话、点发送、再被拒绝,是最差的体验。
|
||||
// 提示条点一下直达记忆页的情绪区(那就是复活入口)。
|
||||
//
|
||||
// ★★ 但**群聊不锁输入框**:死了一个,群里还有别人能接话
|
||||
// (内核的 `group_chat.resolve` 会把死人跳过、换下一个人)。
|
||||
// 整条锁掉的话,用户只能干看着一个群不能用 ——
|
||||
// 用户报的「角色死亡输入框怎么不能用了」就是这个。
|
||||
// 群聊里只留一条提示,输入框照给。
|
||||
val deadAgent = vm.activeAgent
|
||||
val dead = deadAgent != null && vm.state.emotions[deadAgent.id]?.dead == true
|
||||
val convNow = vm.state.conversations
|
||||
.firstOrNull { it.id == vm.activeConversationId.ifBlank { "c_main" } }
|
||||
val groupNow = convNow?.isGroup == true
|
||||
if (dead && !groupNow) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x1AD93025))
|
||||
.padding(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"「${deadAgent?.name}」已经死亡,不能对话。",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"去复活 ›",
|
||||
fontSize = 12.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.clickable { deadAgent?.let { vm.openMemories(it.id) } }
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
if (dead && groupNow) {
|
||||
// 群聊:只提示,**不拦**。被点名的人死了的话,
|
||||
// 内核会换下一个人接(不再"回主智能体",群里没有主人)
|
||||
Text(
|
||||
"「${deadAgent?.name}」已经死亡 —— 群里其他人还能接话。",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 14.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -418,7 +527,8 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
) {
|
||||
// 有自定义角色图就显示它(需求 2.5 的资源回退在内核侧已经落定,
|
||||
// 这里 path 为空就还是原来的图标)
|
||||
val art = vm.activeAgent?.image?.front ?: ""
|
||||
// ★ 跟**同一个人**:名字是寐眠、头像却是小黑,用户一眼就看出不对
|
||||
val art = backdropAgent(vm)?.image?.portrait.orEmpty()
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = art,
|
||||
@@ -437,11 +547,15 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
// ★ 当前情绪(复查报告 2.6):AI 自己能改情绪,改了却看不出来,
|
||||
// 这个功能就只是个看不见的字段。放在名字旁边、字号小一半 ——
|
||||
// 它是个状态注脚,不该抢名字的注意力。
|
||||
val emo = vm.state.emotions[vm.activeAgent?.id ?: ""].orEmpty()
|
||||
if (emo.isNotBlank()) {
|
||||
// ★ v1.2:这里显示的是 **preset(五档)**,不是那句自由文本 ——
|
||||
// 自由文本是角色的内心独白,摆在顶栏上不合适;preset 才是
|
||||
// "一眼看出他现在什么情绪"那个粒度。点开记忆页能看到全文。
|
||||
val emo = vm.state.emotions[vm.activeAgent?.id ?: ""]
|
||||
val emoLabel = emo?.preset.orEmpty()
|
||||
if (emoLabel.isNotBlank() && emoLabel != "平常") {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
emo.take(8),
|
||||
emoLabel.take(8),
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 1,
|
||||
@@ -503,22 +617,15 @@ private fun HeaderIcon(
|
||||
/* ------------------------------ 空态大头像 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun HeroSection(greeting: String) {
|
||||
private fun HeroText(greeting: String) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(top = 34.dp, bottom = 18.dp),
|
||||
Modifier.fillMaxWidth().padding(bottom = 18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(168.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(96.dp))
|
||||
}
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(doubaoBubble())
|
||||
.background(doubaoBubbleVeil())
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
) {
|
||||
Text(greeting, fontSize = 16.sp, lineHeight = 26.sp, color = doubaoText())
|
||||
@@ -526,21 +633,199 @@ private fun HeroSection(greeting: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 聊天页顶部的立绘(v1.2 §6.1)。
|
||||
*
|
||||
* ★ **跟随说话者**(设置里可关,默认开):群聊时谁发言就换成谁的立绘 ——
|
||||
* 一眼看出"这句是谁说的"。关掉时固定用主智能体(成员列表第一个)。
|
||||
*
|
||||
* ★ 0.3 秒的 crossfade:立绘是**情绪驱动**的,可能一轮换一次;
|
||||
* 硬切会让人以为界面闪了一下。0.3s 刚好够看出"换了",又不拖沓。
|
||||
* (这也正是需求里点名的 0.3s —— 和群聊背景跟随共用同一套缓动,
|
||||
* 两处各写一个数字的话,将来改一处必漏另一处。)
|
||||
*/
|
||||
/**
|
||||
* 顶栏和背景该显示**谁** —— **当前正在说话的那个人**。
|
||||
*
|
||||
* ★★ 用户的原话:「还是没换标题和背景呀」。
|
||||
*
|
||||
* 我上一版理解成「跟当前对话的主人走」,那是错的 ——
|
||||
* 他要的是**寐眠说话时,顶栏和背景都是寐眠**。
|
||||
*
|
||||
* 「不是让你 @ 谁就换哪个背景」那句,意思是**不要光点一下 @ 按钮
|
||||
* 就提前换**;要跟着**真实的发言者**。内核每轮都 emit 一个
|
||||
* `speaker` 事件(群聊里就是仲裁结果),跟着它走既"立即"又"名副其实"。
|
||||
*
|
||||
* ★ 只在**群聊**里用 `currentSpeakerId`:单聊时它可能还是上一轮群里
|
||||
* 留下的值,会把单聊的顶栏带跑偏。单聊就认会话主人。
|
||||
*
|
||||
* ★ 顶栏、背景、【朗读音色】三处都从这里/`msg.agentId` 取,
|
||||
* 保证同一条消息上的名字、图、声音是**同一个人**。
|
||||
*/
|
||||
private fun backdropAgent(vm: AppViewModel): Agent? {
|
||||
val convId = vm.activeConversationId.ifBlank { "c_main" }
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == convId }
|
||||
if (conv?.isGroup == true && vm.currentSpeakerId.isNotBlank()) {
|
||||
vm.state.agents.firstOrNull { it.id == vm.currentSpeakerId }?.let { return it }
|
||||
}
|
||||
return vm.state.agents.firstOrNull { it.id == conv?.agentId.orEmpty() } ?: vm.activeAgent
|
||||
}
|
||||
|
||||
/**
|
||||
* 聊天页的**立绘背景层**(用户要求:「整个背景都是角色卡」)。
|
||||
*
|
||||
* ★ 以前立绘只在**一句话都没说**的时候露一个 168dp 的圆,
|
||||
* 一开始聊就只剩顶栏那个 24dp 头像 —— 用户的原话是「就头像是立绘」,
|
||||
* 而他要的是整个背景都是这个角色。
|
||||
*
|
||||
* ★★ 显示的是**当前对话的智能体**(`activeAgent`),不是"这一轮谁在说"。
|
||||
* 用户澄清过:「背景是根据当前对话来的,不是让你 @ 谁就换哪个背景」。
|
||||
* 背景表达的是**这个场景是谁的**(和顶栏那个名字同一件事);
|
||||
* 群聊里两个人一来一回时背景跟着闪,既晃眼又和顶栏对不上。
|
||||
* "谁在说话"是**每条消息**自己的事,用 `msg.agentId`(见 [SpeakerTag])。
|
||||
*
|
||||
* ★ 两条硬约束:
|
||||
* · **必须铺在消息下面**(Box 里排在 LazyColumn 之前),否则字被盖住;
|
||||
* · **图要实心、气泡要半透明** —— 这是用户点名要的一对
|
||||
* (「立绘不要透明的」+「聊天框半透明」)。反过来做(图淡化、气泡实心)
|
||||
* 等于两头都不讨好:立绘看不清,气泡也白透。
|
||||
* 所以可读性交给气泡那边([doubaoBubbleVeil]),这里不淡化。
|
||||
*
|
||||
* ★ 立绘用 `ContentScale.Fit` 而不是 `Crop`:角色不能被裁掉半个身子。
|
||||
* 背景图反过来,必须 `Crop` —— `Fit` 会留出底色,铺不满。
|
||||
*/
|
||||
@Composable
|
||||
private fun ChatBackdrop(vm: AppViewModel) {
|
||||
val who = backdropAgent(vm)
|
||||
val back = who?.image?.back.orEmpty()
|
||||
val art = who?.image?.portrait.orEmpty()
|
||||
if (back.isBlank() && art.isBlank()) return
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
if (back.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = back,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
}
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = art,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 没配立绘时**说清楚 + 给入口**。
|
||||
*
|
||||
* ★ 回退链最后一级就是「内置默认人物」(需求 §2.6),所以背景层显示那张图**没错** ——
|
||||
* 但界面上一个字都不说的话,用户只会觉得"立绘功能没生效",
|
||||
* 而不知道**得自己去传**(内置那四个示例智能体默认都没有图)。
|
||||
*
|
||||
* ★ 它原来长在一个 168dp 圆形立绘(`ChatPortrait`)底下,和背景层重复,
|
||||
* 已经拆开:图归背景层,这句话单独留着。
|
||||
*/
|
||||
@Composable
|
||||
private fun PortraitHint(vm: AppViewModel) {
|
||||
val who = backdropAgent(vm) ?: return
|
||||
if (who.image.portrait.isNotBlank()) return
|
||||
Text(
|
||||
"还没有立绘 · 点这里去传一张",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.clickable { vm.openAgentEdit(who) },
|
||||
)
|
||||
}
|
||||
|
||||
/* ------------------------------ 消息 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 气泡上方那行**小字:这条是谁说的**。
|
||||
*
|
||||
* ★ 只在**群聊**显示(用户要求:「对话前面写明是谁在说话」)。
|
||||
* 单聊里只有一个人,每条都标一遍就是噪音 —— 那个名字顶栏已经有了。
|
||||
*
|
||||
* ★ 名字从 `msg.agentId` 查(内核一直在消息里存群聊仲裁后的发言者)。
|
||||
* 老消息没这个字段 → 退回当前智能体;群聊里退错了也只是名字不对,
|
||||
* 不影响别的(比不显示强,因为不显示就完全分不清谁是谁)。
|
||||
*
|
||||
* ★ 自己那侧写「你」而不是昵称:翻记录时"哪句是我说的"要一眼看出来,
|
||||
* 用昵称反而要在脑子里做一次映射。
|
||||
*/
|
||||
@Composable
|
||||
private fun SpeakerTag(vm: AppViewModel, msg: ChatMessage, mine: Boolean) {
|
||||
// ★ 会话 id 可能是空串(内核用 "c_main" 兜底)
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId.ifBlank { "c_main" } }
|
||||
// 单聊只有一个人,每条都标一遍是噪音;群聊和私聊记录(两个 AI 自己聊的)
|
||||
// 都是"多人在场",不标就完全分不清谁是谁
|
||||
if (conv == null || (!conv.isGroup && !conv.isPrivate)) return
|
||||
val name = if (mine) {
|
||||
"你"
|
||||
} else {
|
||||
vm.state.agents.firstOrNull { it.id == msg.agentId }?.name.orEmpty()
|
||||
.ifBlank { vm.activeAgent?.name.orEmpty() }
|
||||
}
|
||||
if (name.isBlank()) return
|
||||
Text(
|
||||
name,
|
||||
fontSize = 11.sp,
|
||||
color = if (mine) doubaoTextSecondary() else Doubao.Blue,
|
||||
modifier = Modifier.padding(start = 4.dp, end = 4.dp, bottom = 3.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: SpeechController) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val speaking = speech.speakingIndex == index
|
||||
// 长按气泡 → 这个菜单(v1.2 §4.3 的「标记重要」)
|
||||
var importantMenu by remember { mutableStateOf(false) }
|
||||
|
||||
if (msg.role == "user") {
|
||||
// ★ 长按**用户**消息才能标重要。需求说的是"消息操作栏加标记重要",
|
||||
// 这里只做用户那一侧,理由是**效果差异**:
|
||||
// 被标的消息在上下文窗口裁剪时破格携带,而 AI 的回复通常就在
|
||||
// 最近几轮里、本来就裁不到;用户想留住的是**很久以前问过的那句**。
|
||||
if (importantMenu) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { importantMenu = false },
|
||||
title = { Text(if (msg.important) "这条标过了" else "这条消息") },
|
||||
text = {
|
||||
Text(
|
||||
if (msg.important) {
|
||||
"取消之后它就按普通消息处理了 —— 攒够一批会被裁掉。"
|
||||
} else {
|
||||
"标成重要之后,以后裁剪上下文时这条会一直留着," +
|
||||
"不管过了多少轮。"
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { vm.toggleImportant(index); importantMenu = false },
|
||||
) { Text(if (msg.important) "取消标记" else "标记重要", color = Doubao.Blue) }
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { importantMenu = false },
|
||||
) { Text("算了") }
|
||||
},
|
||||
)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
SpeakerTag(vm, msg, mine = true)
|
||||
msg.attachments.forEach { file ->
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoBubble())
|
||||
.background(doubaoBubbleMine())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -559,18 +844,35 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
Modifier
|
||||
.widthIn(max = 288.dp)
|
||||
.clip(RoundedCornerShape(18.dp, 18.dp, 4.dp, 18.dp))
|
||||
.background(Doubao.Blue)
|
||||
.background(doubaoBubbleMine())
|
||||
.combinedClickable(
|
||||
onClick = { clipboard.setText(AnnotatedString(msg.content)) },
|
||||
onLongClick = { importantMenu = true },
|
||||
)
|
||||
.padding(horizontal = 14.dp, vertical = 11.dp),
|
||||
) {
|
||||
Text(msg.content, color = Color.White, fontSize = 16.sp, lineHeight = 25.sp)
|
||||
}
|
||||
}
|
||||
// 标过的给一个小标记 —— 不然用户忘了自己标过哪几条,
|
||||
// 而"这条会不会被裁掉"是他自己决定的
|
||||
if (msg.important) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"★ 重要(不会被裁掉)",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start) {
|
||||
// 群聊里标出**这条是谁说的**(用户要求:「对话前面写明是谁在说话」)
|
||||
SpeakerTag(vm, msg, mine = false)
|
||||
|
||||
val hasReasoning = msg.reasoning.isNotBlank()
|
||||
val hasTrace = msg.toolTrace.isNotEmpty()
|
||||
|
||||
@@ -655,7 +957,7 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
Modifier
|
||||
.widthIn(max = 300.dp)
|
||||
.clip(RoundedCornerShape(4.dp, 18.dp, 18.dp, 18.dp))
|
||||
.background(if (msg.error) Doubao.ErrorBg else doubaoBubble())
|
||||
.background(if (msg.error) Doubao.ErrorBg else doubaoBubbleVeil())
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
) {
|
||||
when {
|
||||
@@ -779,7 +1081,8 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
// 手动点朗读时清掉"自动朗读念过了"的记录:
|
||||
// 用户主动点,就该正常播(或再点一次停),不受自动朗读的去重影响
|
||||
speech.forgetAutoRead()
|
||||
speech.speak(msg.content, index)
|
||||
// 用**这条消息**的发言者挑音色(群聊里每个人不一样)
|
||||
speech.speak(msg.content, index, msg.agentId)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
@@ -1002,7 +1305,25 @@ private fun InputBar(
|
||||
|
||||
Spacer(Modifier.width(8.dp))
|
||||
|
||||
if (canSend) {
|
||||
// ★★ 正在生成时,右边那个圆钮变成「停止」。
|
||||
//
|
||||
// 取消能力**一直都有**:内核从 HTTP 到 agent_loop 一路支持 `cancelled`,
|
||||
// ViewModel 里也建好了 `chatJob`(AtomicBoolean)——
|
||||
// 但没有任何界面调它,用户只能干等它把话说完。
|
||||
// 用户的原话就是「对话过程中可中断」。
|
||||
if (vm.streaming) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), CircleShape)
|
||||
.clickable(onClick = { vm.stopGenerating() }),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Stop, "停止生成", tint = Doubao.Blue, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
} else if (canSend) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
@@ -1091,3 +1412,95 @@ private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 「要不要让他接着说」——
|
||||
* AI 用 `talk_to` / `pass_turn` 把话交给别人之后,这里摆两个按钮。
|
||||
*
|
||||
* ★★ 用户的原话:「talk_to 是用户可以选择传递和停止,有自动模式(不用用户确认)」。
|
||||
*
|
||||
* 所以默认(手动)就**停在这儿等用户点**:
|
||||
* · 「让他说」= 继续把这一轮交出去;
|
||||
* · 「停在这」= 到此为止。
|
||||
* 设置里开了「AI 对聊自动模式」就不出现这条,直接接着跑。
|
||||
*
|
||||
* ★ 顺带解决了烧钱:默认不会自己一直聊下去。
|
||||
* ★ 位置在输入框正上方、点名条**上面**:这是"接着聊还是打住"的决策现场。
|
||||
*/
|
||||
@Composable
|
||||
private fun HandoffBar(vm: AppViewModel) {
|
||||
if (vm.pendingHandoffName.isBlank()) return
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"${vm.pendingHandoffFromName.ifBlank { "它" }} 把话交给了 ${vm.pendingHandoffName}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
DoubaoPill(text = "让他说", onClick = { vm.continueHandoff() })
|
||||
Spacer(Modifier.width(6.dp))
|
||||
RowAction("停在这") { vm.stopHandoff() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 群聊的成员快捷条(v1.2 §3.9)。
|
||||
*
|
||||
* ★ 位置在**输入框正上方**:这里是"这一轮要点谁"的决策现场,
|
||||
* 点头像就把 `@名字 ` 插进草稿里 —— 和用户手打 `@` 完全等价
|
||||
* (内核的 `group_chat.mention_in` 就是按 `@名字` 匹配的)。
|
||||
*
|
||||
* ★ 只有群聊才显示。单聊显示一排"只有一个人"的头像没有意义,
|
||||
* 而且会白占一行高度。
|
||||
*/
|
||||
@Composable
|
||||
private fun GroupQuickBar(vm: AppViewModel) {
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId }
|
||||
if (conv == null || !conv.isGroup) return
|
||||
val members = conv.participants.mapNotNull { id ->
|
||||
vm.state.agents.firstOrNull { it.id == id }?.let { id to it.name }
|
||||
}
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// 点名条:**不标"(主)"** —— 用户要求「群聊去掉主人设定」,
|
||||
// 群里没有老大,没人被 @ 时按顺序轮(kernel 的 group_chat.rotate_next)
|
||||
for (pair in members) {
|
||||
// 只插草稿 —— **不碰顶栏/背景**。那两处等内核仲裁完
|
||||
// (`speaker` 事件)才切,不然会"点了还没发就换了人"
|
||||
DoubaoPill(text = "@${pair.second}", onClick = { vm.mentionAgent(pair.second) })
|
||||
}
|
||||
// ★「让他们聊」:按下就让前两个成员**轮流对话**几轮,随时能停。
|
||||
//
|
||||
// 为什么需要这个按钮:光靠 AI 自己 `pass_turn` 是靠不住的 ——
|
||||
// 实测它更愿意把话说完,于是"两个智能体对话"永远发生不了
|
||||
// (用户报的「还是不能互相对话」)。
|
||||
// 这个按钮不依赖 AI 配合,界面直接按顺序把发言权递过去。
|
||||
DoubaoPill(text = "让他们聊", onClick = { vm.startAiTalk() })
|
||||
RowAction("成员") { vm.openMembers(conv.id) }
|
||||
}
|
||||
// ★ 仲裁**理由**(v1.2 §3.9):内核发了 note,界面以前收了但从不显示 ——
|
||||
// 于是"被点的人已死亡,发言权回主智能体"这种事用户只能自己猜。
|
||||
// 只在有话说时占一行,平时不显示。
|
||||
if (vm.speakerNote.isNotBlank()) {
|
||||
Text(
|
||||
vm.speakerNote,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,24 @@ fun doubaoText() = if (isDark()) Doubao.DarkText else Doubao.TextPrimary
|
||||
fun doubaoTextSecondary() = if (isDark()) Doubao.DarkTextSecondary else Doubao.TextSecondary
|
||||
@Composable
|
||||
fun doubaoBubble() = if (isDark()) Doubao.DarkBubble else Doubao.BubbleBot
|
||||
|
||||
/**
|
||||
* 聊天气泡的底色(**半透明**)。
|
||||
*
|
||||
* ★ 聊天页现在有一层**实心**的立绘(`ChatScreen.ChatBackdrop`)垫在下面,
|
||||
* 气泡要是也不透明,那张立绘就白铺了 —— 用户要的正是
|
||||
* 「立绘看得见、字也读得清」这一对。
|
||||
*
|
||||
* ★ 0.78 是这两条的交点:再透字就开始糊在图上,再实立绘就等于没有。
|
||||
* 别的页面(卡片、弹窗)继续用不透明的 [doubaoBubble],
|
||||
* 它们底下没有图,半透明只会显脏。
|
||||
*/
|
||||
@Composable
|
||||
fun doubaoBubbleVeil() = doubaoBubble().copy(alpha = 0.78f)
|
||||
|
||||
/** 用户自己那侧的气泡(蓝色),同样要半透明 —— 理由同 [doubaoBubbleVeil] */
|
||||
@Composable
|
||||
fun doubaoBubbleMine() = Doubao.Blue.copy(alpha = 0.82f)
|
||||
@Composable
|
||||
fun doubaoBorder() = if (isDark()) Doubao.DarkBorder else Doubao.Border
|
||||
@Composable
|
||||
@@ -277,3 +295,33 @@ fun SectionLabel(text: String, modifier: Modifier = Modifier) {
|
||||
fontWeight = FontWeight.Normal,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------- //
|
||||
// 通用小件(v1.2)
|
||||
// --------------------------------------------------------------------------- //
|
||||
//
|
||||
// ★ 这两个原来是 AgentEditScreen 的**私有**函数,于是别的界面想用就只能
|
||||
// 复制一份 —— 而"同一段逻辑抄两份"是这个仓库反复出现的毛病。
|
||||
// 挪到这里之后全局一份。
|
||||
|
||||
/** 一张卡片:横向留白 + 圆角 + 表面色 + 内边距 */
|
||||
@androidx.compose.runtime.Composable
|
||||
internal fun Card(content: @androidx.compose.runtime.Composable () -> Unit) {
|
||||
androidx.compose.foundation.layout.Column(
|
||||
androidx.compose.ui.Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(androidx.compose.foundation.shape.RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) { content() }
|
||||
}
|
||||
|
||||
/** 一行灰字说明 */
|
||||
@androidx.compose.runtime.Composable
|
||||
internal fun Hint(text: String) {
|
||||
androidx.compose.material3.Text(
|
||||
text, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.Conversation
|
||||
|
||||
/**
|
||||
* 群成员(v1.2 §3.9)。
|
||||
*
|
||||
* ## 为什么是全屏而不是弹窗
|
||||
*
|
||||
* 需求里写的是"浮层",但按仓库的界面约定(AGENTS.md):**列表用全屏**。
|
||||
* 一屏弹窗大概只够三四行,成员一多就得在弹窗里滚 —— 那还不如直接开一屏,
|
||||
* 而且这里还要放"加人/移出"两组动作。
|
||||
*
|
||||
* ## 谁不能移出
|
||||
*
|
||||
* ★ **主智能体不能移出**(成员列表第一个):它是"没人被点名时兜底发言"的
|
||||
* 那个人,移掉这个群就会冷场。
|
||||
* 界面上把它的按钮藏起来 —— 但那只是给用户看的,**服务端也拦**
|
||||
* (绕过界面直接调接口的路径也得挡住)。
|
||||
*/
|
||||
@Composable
|
||||
fun GroupMembersScreen(
|
||||
vm: AppViewModel,
|
||||
conversationId: String,
|
||||
onBack: () -> Unit,
|
||||
onOpenStats: (String) -> Unit = {},
|
||||
) {
|
||||
val conv: Conversation? = vm.state.conversations.firstOrNull { it.id == conversationId }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
|
||||
FullScreen(
|
||||
title = "群成员",
|
||||
subtitle = conv?.let { "${it.participants.size} 个人在群里" } ?: "会话不见了",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (!adding) TopTextAction("加人") { adding = true } else TopTextAction("取消") { adding = false }
|
||||
},
|
||||
) {
|
||||
// ---- 加人(就地展开,不再弹一层 —— 弹窗压弹窗是手机上的灾难)----
|
||||
if (adding) {
|
||||
val inGroup = conv?.participants?.toSet() ?: emptySet()
|
||||
// ★★ **只能拉同世界观的**(用户确认过这条规则)。
|
||||
//
|
||||
// 群聊上下文里有 <worldview> 段、共享记忆也按世界观分空间 ——
|
||||
// 世界观不同的两个人拉进同一个群,"这是哪、我们是谁"都对不上。
|
||||
// 内核 `group_chat.add_member` 也会拒,但**界面先筛掉**:
|
||||
// 让人点了才被告知"加不进去"是最差的体验。
|
||||
//
|
||||
// ★ **未绑世界观的放行**:它没有设定会串,和谁都合得来
|
||||
// (用户报的「还是加不了人」,其中"黑化豆包"就是未绑的)。
|
||||
val hostWorldview = vm.state.agents
|
||||
.firstOrNull { it.id == conv?.agentId }?.worldviewId.orEmpty()
|
||||
val sameWorldview = vm.state.agents.filter {
|
||||
it.worldviewId.orEmpty().isBlank() || it.worldviewId.orEmpty() == hostWorldview
|
||||
}
|
||||
val candidates = sameWorldview.filter { it.id !in inGroup }
|
||||
val blocked = vm.state.agents.count { it.id !in inGroup && it !in sameWorldview }
|
||||
SectionLabel("拉谁进来")
|
||||
Card {
|
||||
if (candidates.isEmpty()) {
|
||||
Hint(
|
||||
if (blocked > 0) "没有可以拉的人了。"
|
||||
else "所有能拉的人都在群里了。",
|
||||
)
|
||||
} else {
|
||||
for (a in candidates) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable {
|
||||
// ★ 注意签名:`makeGroup` 是**这个会话还没有群成员**时
|
||||
// 用的(会新建群聊);已经有成员了就走 `addMember`,
|
||||
// 不能混 —— 混了会把当前会话换掉,用户会一头雾水。
|
||||
if (inGroup.isEmpty()) vm.makeGroup(a.id) else vm.addMember(a.id)
|
||||
// ★★ 加完**不收起**(原来这里 `adding = false`)。
|
||||
// 收起的话,用户加了一个就得再点一次「加人」才能加下一个,
|
||||
// 体感就是"群聊只能拉两个"(真机反馈)。
|
||||
// 刷新后 `candidates` 会少一个,接着点就行。
|
||||
}.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(a, 36)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a.name, fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
Hint("想加几个就加几个 —— 点一个加一个,这排不会收起来。")
|
||||
}
|
||||
// ★★ 被世界观挡下的**也列出来**,并说清原因。
|
||||
//
|
||||
// 不列的话用户只看到"某些智能体不见了",以为功能坏了 ——
|
||||
// 他报的「还是加不了人」有一半是这种感觉。
|
||||
val blockedAgents = vm.state.agents.filter { it.id !in inGroup && it !in sameWorldview }
|
||||
if (blockedAgents.isNotEmpty()) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"这些绑的是别的世界观,拉进来会串设定(两套背景、共享记忆也会混):",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
for (a in blockedAgents) {
|
||||
Text(
|
||||
"· ${a.name}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(start = 6.dp, top = 2.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("想拉它们:先去它们的编辑页绑成这个世界观(或者另开一个群)。")
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
}
|
||||
|
||||
if (conv == null) {
|
||||
Hint("这个会话已经不在了。")
|
||||
return@FullScreen
|
||||
}
|
||||
|
||||
SectionLabel("成员")
|
||||
Card {
|
||||
for ((i, id) in conv.participants.withIndex()) {
|
||||
val a: Agent? = vm.state.agents.firstOrNull { it.id == id }
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(a, 40)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
a?.name ?: "(已删除)",
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
// ★ 这里原来标了「主」徽章 + "没人被 @ 的时候由它接话"。
|
||||
// 用户要求「群聊去掉主人设定」—— 群里没有老大,
|
||||
// 没人被 @ 时**按顺序轮**(见 kernel/group_chat.rotate_next)。
|
||||
Text(
|
||||
"第 ${i + 1} 个进群的",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("状态") { onOpenStats(id) }
|
||||
Spacer(Modifier.width(6.dp))
|
||||
// ★ 谁都能移出(原来主智能体移不掉)—— 既然没有主人,
|
||||
// 就没有"动不了"的那一个。内核那边会拦住"最后一个"
|
||||
RowAction("移出") { vm.removeMember(id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint(
|
||||
"在聊天页的输入框上方点成员头像就是 @ 点名 —— " +
|
||||
"被点的人这一轮一定发言。没人被点时**按顺序轮**,不会冷场,也没有谁永远优先。",
|
||||
)
|
||||
|
||||
// ★「让他们私下聊聊」(v1.2 §3.9 形态 B)
|
||||
//
|
||||
// 放这儿而不是抽屉里:抽屉已经有七项了(用户刚说过"太挤了"),
|
||||
// 而**群成员页本来就有成员** —— 从这儿点两个人比在抽屉里
|
||||
// 再开一个挑人对话框顺得多。
|
||||
//
|
||||
// 内核早就完整实现了(10 轮安全网、一方触顶另一方单方面收尾、
|
||||
// 摘要进共享记忆),但界面上一直没有入口 —— 这个需求项碰不到。
|
||||
Spacer(Modifier.height(12.dp))
|
||||
SectionLabel("私下聊聊")
|
||||
Card {
|
||||
Hint(
|
||||
"点两个名字,让他们在后台自主对聊 —— 你不在场。" +
|
||||
"聊完的摘要会写进共享记忆,完整记录在会话列表里能翻。",
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
for (id in conv.participants) {
|
||||
val a = vm.state.agents.firstOrNull { it.id == id }
|
||||
val picked = id in vm.privatePair
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { vm.togglePrivatePick(id) }
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (picked) "✓" else "○",
|
||||
fontSize = 15.sp,
|
||||
color = if (picked) Doubao.Blue else doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a?.name ?: "(已删除)", fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
RowAction("开始私聊") { vm.startPickedPrivateChat() }
|
||||
if (vm.privatePair.isNotEmpty()) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
RowAction("清空选择") { vm.cancelPrivatePick() }
|
||||
}
|
||||
}
|
||||
if (vm.privateChatRunning.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("${vm.privateChatRunning} 正在聊……(要跑一会儿,别退出去)")
|
||||
}
|
||||
if (vm.privateChatResult.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint(vm.privateChatResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 成员的小头像(有立绘用立绘,没有就用名字首字) */
|
||||
@Composable
|
||||
private fun AgentFace(agent: Agent?, size: Int) {
|
||||
val art = agent?.image?.portrait.orEmpty()
|
||||
Box(
|
||||
Modifier
|
||||
.size(size.dp)
|
||||
.clip(CircleShape)
|
||||
.background(doubaoCard()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(art, Modifier.size(size.dp), contentScale = ContentScale.Crop)
|
||||
} else {
|
||||
Text(
|
||||
(agent?.name ?: "?").take(1),
|
||||
fontSize = (size * 0.42).sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
139
android/app/src/main/java/com/doubao/lynxclone/ui/ImagePick.kt
Normal file
@@ -0,0 +1,139 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import android.util.Base64
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/**
|
||||
* 选图 → 读成能上传的 base64。
|
||||
*
|
||||
* ## 为什么必须在这里压缩(这是真机上报回来的 bug)
|
||||
*
|
||||
* 用户选的是**手机相册里的照片**,现在动辄 30~55MB(一亿像素)。
|
||||
* 原样读进来会连撞三堵墙:
|
||||
*
|
||||
* ① `readBytes()` 把 55MB 全读进内存,`Base64` 再翻 4/3 倍 → 低端机直接 OOM;
|
||||
* ② 内核 `read_json_body()` 每条接口有自己的上限,图片这条路走的是小上限,
|
||||
* 38MB 的请求体一进去就被判「请求体过大」;
|
||||
* ③ 更糟的是那个异常被上层吞掉,最后报出来的是
|
||||
* **「不认识的外观槽位」** —— 一个和真实原因毫无关系的错误,
|
||||
* 用户只看到"设置不了",查代码的人也会往槽位名上去找。
|
||||
*
|
||||
* 所以压缩不是优化,是**这条链路能不能用**的前提:
|
||||
* 一张 4000×3000 的照片按最长边 1600 采样后大约是 200~400KB,
|
||||
* 比原来小两个数量级,上面三堵墙一次全绕过。
|
||||
*
|
||||
* ## 两种图**不能**压
|
||||
*
|
||||
* - **GIF**:缩放会丢动画(这个 App 明确支持动图,"动图会动"是写在界面上的);
|
||||
* - **SVG**:本来就是矢量,栅格化等于自毁。
|
||||
*
|
||||
* 这两种原样传,只在超过内核 20MB 上限时明确报错 —— 让用户换个文件,
|
||||
* 而不是静默失败。
|
||||
*/
|
||||
|
||||
/** 压缩后最长边不超过它。1600 在手机上看立绘/背景已经够清楚 */
|
||||
private const val MAX_EDGE = 1600
|
||||
|
||||
/** 压到这么大就收手。经验值:1600 边长的 JPEG 通常在 200~400KB */
|
||||
private const val TARGET_BYTES = 3 * 1024 * 1024
|
||||
|
||||
/** 内核 `_set_asset` 的硬上限,超过它一定传不上去,这里提前拦下来把话说清楚 */
|
||||
private const val MAX_BYTES = 20 * 1024 * 1024
|
||||
|
||||
/** 一张选好的图。[note] 是给用户看的一句话,说明这张图被怎么处理了 */
|
||||
data class PickedImage(val name: String, val base64: String, val note: String)
|
||||
|
||||
private fun mb(n: Int): String = String.format("%.1f", n / 1048576.0)
|
||||
|
||||
/**
|
||||
* 读一张图并压到能传的大小。
|
||||
*
|
||||
* 失败时抛 [IllegalStateException],**消息是可以直接显示给用户的中文** ——
|
||||
* 调用方 `catch` 之后原样 `showHint(e.message)` 就行,
|
||||
* 不要再包一层"上传失败",那样又把原因盖掉了。
|
||||
*/
|
||||
fun readImageForUpload(ctx: Context, uri: Uri): PickedImage {
|
||||
val resolver = ctx.contentResolver
|
||||
val rawName = (uri.lastPathSegment ?: "image").substringAfterLast('/').ifBlank { "image" }
|
||||
// ★ 名字靠不住:SAF 给的常常是 `image_1000018030` 这种没有扩展名的。
|
||||
// MIME 才是可信的(getType 对 content:// 会去查 provider)。
|
||||
val mime = (resolver.getType(uri) ?: "").lowercase()
|
||||
val isGif = mime.contains("gif")
|
||||
val isSvg = mime.contains("svg")
|
||||
|
||||
if (isGif || isSvg) {
|
||||
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
?: throw IllegalStateException("读不出这个文件")
|
||||
if (bytes.isEmpty()) throw IllegalStateException("这个文件是空的")
|
||||
if (bytes.size > MAX_BYTES) {
|
||||
throw IllegalStateException("这张图 ${mb(bytes.size)}MB,超过 20MB 上限了,换一张吧")
|
||||
}
|
||||
return PickedImage(
|
||||
name = rawName,
|
||||
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
|
||||
note = if (isGif) "动图原样上传(压缩会丢动画)" else "SVG 原样上传",
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 位图:先只问尺寸,不解码像素 ----
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
|
||||
throw IllegalStateException("这不是一张能识别的图片")
|
||||
}
|
||||
|
||||
// 压不下来就一轮轮降:边长 ×3/4、质量 ×4/5。四轮足够把任何照片压进 3MB
|
||||
var edge = MAX_EDGE
|
||||
var quality = 88
|
||||
var last = 0
|
||||
repeat(4) {
|
||||
val opts = BitmapFactory.Options().apply { inSampleSize = sampleFor(bounds, edge) }
|
||||
val bmp = resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, opts) }
|
||||
?: throw IllegalStateException("读不出这张图")
|
||||
val hasAlpha = bmp.hasAlpha()
|
||||
val out = ByteArrayOutputStream()
|
||||
bmp.compress(if (hasAlpha) Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG, quality, out)
|
||||
val w = bmp.width
|
||||
val h = bmp.height
|
||||
bmp.recycle()
|
||||
val bytes = out.toByteArray()
|
||||
last = bytes.size
|
||||
|
||||
if (bytes.size <= TARGET_BYTES) {
|
||||
return PickedImage(
|
||||
// ★ 扩展名要跟着真实格式走:压成 JPEG 却叫 .png,虽然解码器看魔数也能认,
|
||||
// 但导出的包里会留下一个名不副实的文件
|
||||
name = "${rawName.substringBeforeLast('.')}.${if (hasAlpha) "png" else "jpg"}",
|
||||
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
|
||||
note = "已压到 ${w}×${h}、${bytes.size / 1024}KB 再上传",
|
||||
)
|
||||
}
|
||||
edge = edge * 3 / 4
|
||||
quality = (quality * 4) / 5
|
||||
}
|
||||
throw IllegalStateException("这张图压到 ${mb(last)}MB 还是太大,换一张吧")
|
||||
}
|
||||
|
||||
/**
|
||||
* 采样率(2 的幂,`BitmapFactory` 只认这个)。
|
||||
*
|
||||
* ★ 判据是**最长边**(写成 `||`),不是"宽高都超"。
|
||||
* 写成 `&&` 的话 4000×3000 一张只缩到 4000(短边 3000 没到阈值就停了),
|
||||
* JPEG 出来还有 2.2MB;按长边缩一档到 2000×1500 就只有它的三分之一。
|
||||
*
|
||||
* 取**解码后仍然 ≥ maxEdge** 的那一档 —— 宁可多留一点,
|
||||
* 后面还有缩小/降质的循环兜着;反过来取小了就再也补不回清晰度。
|
||||
*/
|
||||
private fun sampleFor(bounds: BitmapFactory.Options, maxEdge: Int): Int {
|
||||
var sample = 1
|
||||
while (bounds.outWidth / (sample * 2) >= maxEdge ||
|
||||
bounds.outHeight / (sample * 2) >= maxEdge
|
||||
) {
|
||||
sample *= 2
|
||||
}
|
||||
return sample
|
||||
}
|
||||
@@ -35,6 +35,8 @@ import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.MemoryItem
|
||||
import com.doubao.lynxclone.data.PRESETS
|
||||
import com.doubao.lynxclone.data.PRESET_DEAD
|
||||
import com.doubao.lynxclone.data.MemorySpace
|
||||
|
||||
/*
|
||||
@@ -77,7 +79,8 @@ fun MemoryScreen(
|
||||
worldMode: Boolean = false,
|
||||
loading: Boolean,
|
||||
hint: String,
|
||||
onSetEmotion: (String) -> Unit,
|
||||
/** 保存情绪:preset(五档)+ text(自由一句) */
|
||||
onSetEmotion: (String, String) -> Unit,
|
||||
onAdd: (String, String) -> Unit,
|
||||
onUpdate: (String, String?, String?) -> Unit,
|
||||
onDelete: (String) -> Unit,
|
||||
@@ -96,7 +99,9 @@ fun MemoryScreen(
|
||||
) {
|
||||
var editing by remember { mutableStateOf<MemoryItem?>(null) }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
var emotionDraft by remember(space?.emotion) { mutableStateOf(space?.emotion ?: "") }
|
||||
/** 情绪的双字段草稿(v1.2)。preset 是五档之一、text 是自由文本 */
|
||||
var emotionPreset by remember(space?.emotion) { mutableStateOf(space?.emotion?.preset ?: "平常") }
|
||||
var emotionText by remember(space?.emotion) { mutableStateOf(space?.emotion?.text ?: "") }
|
||||
// 一次确认,正好是弹窗该用的地方(AGENTS.md 那张表)
|
||||
var confirmSummarize by remember { mutableStateOf(false) }
|
||||
/** 调注入窗口(输入条数,0 = 不限) */
|
||||
@@ -308,24 +313,67 @@ fun MemoryScreen(
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"AI 自己能改(emotion_set),你也可以在这里改。它每次对话都会被带进提示词。",
|
||||
"preset 决定系统行为(立绘换哪张、能不能对话、同伴看到什么脸色);" +
|
||||
"下面那句话只是扮演质感。AI 自己能改,你也可以在这里改。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// ★ 五档选择器,顺序就是需求里的顺序(喜 怒 哀 平常 死亡)。
|
||||
// 「死亡」单独标红 —— 它是**唯一有系统后果**的档位。
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
for (p in PRESETS) {
|
||||
val on = p == emotionPreset
|
||||
val danger = p == PRESET_DEAD
|
||||
Text(
|
||||
p,
|
||||
fontSize = 13.sp,
|
||||
color = when {
|
||||
on -> Color.White
|
||||
danger -> Color(0xFFB3261E)
|
||||
else -> doubaoText()
|
||||
},
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(
|
||||
when {
|
||||
on && danger -> Color(0xFFB3261E)
|
||||
on -> Doubao.Blue
|
||||
else -> doubaoCard()
|
||||
},
|
||||
)
|
||||
.clickable { emotionPreset = p }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
// 死亡是唯一需要额外解释的档位:它会让这个智能体**不能对话**。
|
||||
// 不说清楚的话,用户点了「死亡」然后发现消息发不出去,会以为坏了。
|
||||
if (emotionPreset == PRESET_DEAD) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"「死亡」状态下这个智能体不能对话(输入条会禁用)。" +
|
||||
"把它改回其他档就是复活 —— 这是你的权力,AI 自己不能从死亡改活。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = emotionDraft,
|
||||
onValueChange = { emotionDraft = it },
|
||||
placeholder = { Text("比如:刚被夸了,有点得意", fontSize = 13.sp) },
|
||||
value = emotionText,
|
||||
onValueChange = { emotionText = it },
|
||||
placeholder = { Text("他此刻在想什么(自由一句,比如:强作镇定,手心全是汗)", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
|
||||
TextButton(
|
||||
onClick = { onSetEmotion(emotionDraft.trim()) },
|
||||
enabled = emotionDraft.trim() != (space?.emotion ?: ""),
|
||||
onClick = { onSetEmotion(emotionPreset, emotionText.trim()) },
|
||||
enabled = emotionPreset != (space?.emotion?.preset ?: "平常") ||
|
||||
emotionText.trim() != (space?.emotion?.text ?: ""),
|
||||
) { Text("保存情绪", fontSize = 13.sp) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
@@ -21,6 +21,9 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.Dashboard
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Group
|
||||
import androidx.compose.material.icons.filled.Memory
|
||||
import androidx.compose.material.icons.filled.Layers
|
||||
import androidx.compose.material.icons.filled.Public
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
@@ -44,8 +47,11 @@ import androidx.compose.ui.unit.sp
|
||||
* 抽屉原来平铺了 9 个入口,把底下的**对话列表**挤得只剩一条 ——
|
||||
* 而对话列表恰恰是抽屉最主要的功能:用户 90% 打开抽屉是为了切对话。
|
||||
*
|
||||
* 现在抽屉第一层只留天天用的(新话题 / 智能体 / 笔记 / 模型),
|
||||
* 其余收进这里。
|
||||
* ★★ 后来又收了一次(用户第二次说"太挤了"、"把别的放更多里"):
|
||||
* 抽屉第一层现在只剩**四件天天用的**:新话题 / 智能体 / 记忆 / 更多功能。
|
||||
* 笔记、模型、新建群聊都挪进来了 ——
|
||||
* 「模型」虽然也常用,但它是个**配置**,配好基本不动;
|
||||
* 抽屉里腾出来的位置留给对话列表更值。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面
|
||||
*
|
||||
@@ -60,6 +66,9 @@ fun MoreSheetScreen(
|
||||
onOpenMeetings: () -> Unit,
|
||||
onOpenTerminal: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onNewGroup: () -> Unit,
|
||||
onOpenNotes: () -> Unit,
|
||||
onOpenModels: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
@@ -76,6 +85,28 @@ fun MoreSheetScreen(
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item {
|
||||
// 从抽屉挪进来的三个(都是"偶尔用一次"那一档)
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Group,
|
||||
title = "新建群聊",
|
||||
subtitle = "拉几个智能体到一个会话里,可以 @ 点名",
|
||||
) { onNewGroup() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.EditNote,
|
||||
title = "笔记",
|
||||
subtitle = "AI 替你记下来的东西",
|
||||
) { onOpenNotes() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Memory,
|
||||
title = "模型",
|
||||
subtitle = "换模型 / 思考强度(配好基本不用动)",
|
||||
) { onOpenModels() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Dashboard,
|
||||
|
||||
@@ -102,6 +102,10 @@ private val MODEL_FIELDS = listOf(
|
||||
Field("apiKey", "API Key", "留空则用全局设置里那个", password = true),
|
||||
Field("provider", "提供商", "ark / openai / deepseek …(留空则跟随全局)"),
|
||||
Field("pricePerK", "单价(元/千 Token)", "留空 = 不显示费用估算", number = true),
|
||||
// ★ v1.2:命中缓存的单价单独填。各家命中都比未命中便宜得多(常见 1/10),
|
||||
// 不填的话费用按未命中的价格算 —— **越用越高估**,而用户会以为
|
||||
// 自己真花了那些钱。留空 = 按未命中单价算(保守估计,不会低估)。
|
||||
Field("cachePricePerK", "命中单价(元/千 Token)", "留空 = 按上面的单价算(偏保守)", number = true),
|
||||
Field(
|
||||
"noTools", "不支持工具调用",
|
||||
"这个模型不会 function calling(本地小模型、老网关常见)。打开之后不再传 tools," +
|
||||
@@ -121,11 +125,28 @@ private class Kind(
|
||||
val isZip: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* 数值状态包:普通字段只有名字和说明。
|
||||
*
|
||||
* ★ 真正的定义(有哪些数值、哪些状态、各自的区间表和脚本)在
|
||||
* **[规则包编辑]** 全屏界面里改 —— 那是一堆嵌套结构,
|
||||
* 塞进"label + 输入框"的表单里既放不下也说不清。
|
||||
*/
|
||||
private val RULEPACK_FIELDS = listOf(
|
||||
Field("name", "名称", "比如「九州数值规则」"),
|
||||
Field("note", "说明", "给别的使用者看的:这个包是干什么的", multiline = true),
|
||||
)
|
||||
|
||||
private val KINDS = listOf(
|
||||
Kind(
|
||||
"worldviews", "世界观", "世界观", WORLD_FIELDS, isZip = true,
|
||||
hint = "绑定同一个世界观的智能体**共用一份记忆**。导出是一个 zip 包(含设定和四件套图片)。",
|
||||
),
|
||||
Kind(
|
||||
"rulepacks", "数值状态包", "规则包", RULEPACK_FIELDS, isZip = true,
|
||||
hint = "世界观挂上它之后,智能体才有**数值**(好感度、声望……)和**状态**(中毒、庇佑……)。" +
|
||||
"包里可以有 Python 脚本做裁决 —— 导入时内核会让你确认。",
|
||||
),
|
||||
Kind(
|
||||
"skills", "Skill", "Skill", SKILL_FIELDS, isZip = false,
|
||||
hint = "纯文本的「工具使用手册」。内置的记忆/情绪/用量手册**默认就生效**;这里写的是你自己加的规矩。",
|
||||
@@ -149,6 +170,13 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
"worldviews" -> vm.state.worldviews.map {
|
||||
it.id to Triple(it.name, it.setting, it.image)
|
||||
}
|
||||
// v1.2 数值状态包:副标题列出"有几条数值、几条状态、带不带脚本" ——
|
||||
// 那才是用户判断这个包能不能用的信息,光看名字看不出来
|
||||
"rulepacks" -> vm.state.rulePacks.map {
|
||||
val bits = mutableListOf("${it.stats.size} 条数值", "${it.statuses.size} 条状态")
|
||||
if (it.hasScripts) bits += "${it.scripts.size} 个脚本"
|
||||
it.id to Triple(it.name, bits.joinToString(" · "), AgentImage())
|
||||
}
|
||||
"skills" -> vm.state.skills.map { it.id to Triple(it.name, it.content, AgentImage()) }
|
||||
else -> vm.state.modelEntries.map {
|
||||
// ★ 兼容模式在列表上就要看得出来(复查 3.3):进了编辑页才知道
|
||||
@@ -177,13 +205,50 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
}.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") }
|
||||
}
|
||||
}
|
||||
// ---- 规则包的脚本警告 ----
|
||||
//
|
||||
// ★ 这里是全仓库**唯一**该用弹窗的导入场景:内容就是一段警告 + 两个按钮,
|
||||
// 属于"一次确认"(AGENTS.md 的界面约定:一次确认用弹窗,列表/多组配置
|
||||
// 才开全屏)。真正拦得住的是**服务端**那道 `confirmScripts` 关口,
|
||||
// 这个框只是把风险如实告诉用户。
|
||||
if (vm.pendingRulePack.isNotBlank()) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.dismissRulePack() },
|
||||
title = { Text("这个包里带了 Python 脚本") },
|
||||
text = {
|
||||
Text(
|
||||
vm.rulePackWarning.ifBlank {
|
||||
"包里有可执行脚本。导入后它会在你的设备上运行 —— " +
|
||||
"只导入你信得过的来源。"
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { vm.importRulePack(vm.pendingRulePack, confirmed = true) }) {
|
||||
Text("我知道风险,继续", color = Doubao.Blue)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { vm.dismissRulePack() }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val openDoc = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
}.onSuccess { bytes ->
|
||||
if (kind.isZip) {
|
||||
vm.importPackage(kind.id, Base64.encodeToString(bytes, Base64.NO_WRAP), "")
|
||||
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
// ★ 规则包**单独一条路**:它是唯一允许夹带可执行 Python 的
|
||||
// 包类型,内核会让它带 `confirmScripts` 才落库。
|
||||
// 第一次(不确认)会返回 needConfirm + warning,
|
||||
// 界面拿去弹警告;用户点了「我知道风险,继续」再传一次。
|
||||
if (kind.id == "rulepacks") vm.importRulePack(b64)
|
||||
else vm.importPackage(kind.id, b64, "")
|
||||
} else {
|
||||
vm.importPackage(kind.id, "", bytes.toString(Charsets.UTF_8))
|
||||
}
|
||||
@@ -193,7 +258,7 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
|
||||
FullScreen(
|
||||
title = "资源",
|
||||
subtitle = "世界观 · 技能 · 模型(${vm.state.agents.size} 个智能体在引用)",
|
||||
subtitle = "世界观 · 规则包 · 技能 · 模型(${vm.state.agents.size} 个智能体在引用)",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("导入") {
|
||||
@@ -219,7 +284,14 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("新建") { editId = null; editing = true }
|
||||
RowAction("新建") {
|
||||
// ★ 规则包**不是**"填两个字段就完事"的东西 —— 它的内容
|
||||
// (定义表 + 脚本)在独立的全屏编辑页里。
|
||||
// 所以「新建」直接建一个**带模板**的包并进去,
|
||||
// 而不是先弹"名称+说明"的表单、再让用户自己去找编辑器。
|
||||
if (kind.id == "rulepacks") { vm.createRulePackFromTemplate(); return@RowAction }
|
||||
editId = null; editing = true
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState())) {
|
||||
@@ -252,7 +324,13 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { editId = id; editing = true }
|
||||
.clickable {
|
||||
// ★ 规则包走**独立的全屏编辑页** —— 它的内容
|
||||
// (定义表 + 脚本)不是"label + 输入框"那套表单
|
||||
// 能表达的,硬塞进去会变成一堆看不懂的文本框
|
||||
if (kind.id == "rulepacks") { vm.openRulePackEdit(id); return@clickable }
|
||||
editId = id; editing = true
|
||||
}
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
@@ -265,7 +343,7 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
) {
|
||||
AssetImage(
|
||||
path = image.front,
|
||||
path = image.slot("平常"),
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
@@ -342,7 +420,13 @@ private fun ResourceEditScreen(
|
||||
val initial: Map<String, String> = remember(id, kind.id) {
|
||||
when (kind.id) {
|
||||
"worldviews" -> vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
mapOf("name" to it.name, "setting" to it.setting)
|
||||
mapOf(
|
||||
"name" to it.name,
|
||||
"setting" to it.setting,
|
||||
// ★ 世界观挂的数值状态包 —— 不读出来的话,一进编辑页
|
||||
// 选择器就显示"没挂",用户一保存就把原来的关联抹了
|
||||
"rulePackId" to it.rulePackId,
|
||||
)
|
||||
} ?: emptyMap()
|
||||
"skills" -> vm.state.skills.firstOrNull { it.id == id }?.let {
|
||||
mapOf("name" to it.name, "content" to it.content)
|
||||
@@ -369,11 +453,9 @@ private fun ResourceEditScreen(
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank() || id == null) return@rememberLauncherForActivityResult
|
||||
runCatching {
|
||||
val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
val name = (uri.lastPathSegment ?: "image.png").substringAfterLast('/')
|
||||
vm.uploadWorldviewAsset(id, slot, name, Base64.encodeToString(bytes, Base64.NO_WRAP))
|
||||
}.onFailure { vm.showHint("读不出这张图") }
|
||||
// 和智能体编辑页**同一份实现** —— 这条链路的坑(大图、GIF、SAF 没扩展名)
|
||||
// 两边一模一样,抄两份迟早只修一份
|
||||
vm.uploadWorldviewAssetFrom(ctx.applicationContext, id, slot, uri)
|
||||
}
|
||||
// 上传完 image 会变,跟着刷新预览
|
||||
vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
@@ -399,7 +481,11 @@ private fun ResourceEditScreen(
|
||||
extra["pricePerK"] = values["pricePerK"]?.toDoubleOrNull() ?: 0.0
|
||||
extra["noTools"] = values["noTools"] == "1"
|
||||
}
|
||||
if (kind.id == "worldviews") extra["image"] = worldImage
|
||||
if (kind.id == "worldviews") {
|
||||
extra["image"] = worldImage
|
||||
// ★ 世界观挂的数值状态包(空 = 不挂)
|
||||
extra["rulePackId"] = values["rulePackId"].orEmpty()
|
||||
}
|
||||
vm.saveResource(kind.id, id, name, text, extra) { saving = false; onDone() }
|
||||
}
|
||||
},
|
||||
@@ -474,6 +560,84 @@ private fun ResourceEditScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// ★★ 数值状态包:**世界观是它的挂载点**(需求 §3.6)。
|
||||
//
|
||||
// 以前这里**没有这个入口** —— 内核那条链路是通的
|
||||
// (`agent_context.pack_of` 读 `世界观.rulePackId`),
|
||||
// 但界面上根本挂不上,于是整个数值/状态系统在 App 里是死的:
|
||||
// 用户在「资源 → 规则包」里辛苦写完,回来发现没有任何地方能启用它。
|
||||
//
|
||||
// 只在世界观这一种资源上出现(规则包/Skill/模型没有这个概念)。
|
||||
if (kind.id == "worldviews") {
|
||||
SectionLabel("数值状态包")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
Text(
|
||||
"挂上之后,绑这个世界观的智能体就有**数值**(好感度、声望……)" +
|
||||
"和**状态**(中毒、庇佑……)。不挂就没有 —— 提示词里那两段是空的。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
val pickedPack = values["rulePackId"].orEmpty()
|
||||
val packs = vm.state.rulePacks
|
||||
if (packs.isEmpty()) {
|
||||
Text(
|
||||
"还没有数值状态包。去「资源 → 规则包」新建一个(有模板)。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
// 一行一个:手机上横向排不下(包名可能很长),
|
||||
// 而且"选中哪个"要一眼看得出来
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { values = values + ("rulePackId" to "") }
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (pickedPack.isBlank()) "◉" else "○",
|
||||
fontSize = 15.sp,
|
||||
color = if (pickedPack.isBlank()) Doubao.Blue else doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text("不挂(没有数值和状态)", fontSize = 13.sp, color = doubaoText())
|
||||
}
|
||||
for (p in packs) {
|
||||
val on = p.id == pickedPack
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable {
|
||||
values = values + ("rulePackId" to p.id)
|
||||
}.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (on) "◉" else "○",
|
||||
fontSize = 15.sp,
|
||||
color = if (on) Doubao.Blue else doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(p.name.ifBlank { "(未命名)" }, fontSize = 13.sp, color = doubaoText())
|
||||
val bits = mutableListOf<String>()
|
||||
bits.add("${p.stats.size} 条数值")
|
||||
bits.add("${p.statuses.size} 条状态")
|
||||
if (p.hasScripts) bits.add("带脚本")
|
||||
Text(bits.joinToString(" · "), fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- 世界观的四件套(需求 3.6:沿用智能体那一套)---- */
|
||||
if (kind.id == "worldviews") {
|
||||
SectionLabel("外观(四件套)")
|
||||
@@ -501,7 +665,7 @@ private fun ResourceEditScreen(
|
||||
)
|
||||
for ((key, title, desc) in slots) {
|
||||
val path = when (key) {
|
||||
"front" -> worldImage.front
|
||||
"front" -> worldImage.slot("平常")
|
||||
"back" -> worldImage.back
|
||||
"border-main" -> worldImage.borderMain
|
||||
else -> worldImage.borderInfo
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* [规则包编辑](v1.2 附录 D)—— 全屏。
|
||||
*
|
||||
* ## 为什么全屏
|
||||
*
|
||||
* 里面有:名称、说明、两张定义表、若干段 Python 脚本。任何一个都超过
|
||||
* 一屏弹窗能装下的量 —— 按仓库的界面约定,这就是该开全屏的那种。
|
||||
*
|
||||
* ## 脚本框的形状(照抄节点代码组件的做法)
|
||||
*
|
||||
* 两条硬要求,都来自踩过的坑(见 AGENTS.md):
|
||||
*
|
||||
* 1. **不软换行** —— ` else:` 折成两行、缩进全乱,而 Python 的缩进
|
||||
* 就是语法。做法是"把输入框塞进足够宽的横向滚动容器"。
|
||||
* 2. **有高度上限** —— 只写 `heightIn(min=...)` 的话,脚本一长框就长到
|
||||
* 屏幕外,把底下的东西顶出去。
|
||||
*
|
||||
* ## 定义表这版是只读的
|
||||
*
|
||||
* 数值/状态的**结构**(min/max、区间表、叠加层数)是一堆嵌套结构,
|
||||
* 用表单编辑要另做一套增删改。这一版先把**脚本**做成可编辑的
|
||||
* (那是最需要改的部分),定义表只读 + 指路导入导出。
|
||||
* 界面上**如实写着**这一点,不让用户对着只读的表发愣。
|
||||
*/
|
||||
@Composable
|
||||
fun RulePackEditScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
val pack = vm.editingRulePack
|
||||
if (pack == null) {
|
||||
FullScreen(title = "规则包编辑", onBack = onBack) { Hint("正在读……") }
|
||||
return
|
||||
}
|
||||
|
||||
var name by remember(pack.id) { mutableStateOf(pack.name) }
|
||||
var note by remember(pack.id) { mutableStateOf(pack.note) }
|
||||
var scripts by remember(pack.id) { mutableStateOf(pack.scripts) }
|
||||
var editing by remember(pack.id) { mutableStateOf("") }
|
||||
var newScript by remember(pack.id) { mutableStateOf("") }
|
||||
var draft by remember(pack.id) { mutableStateOf("") }
|
||||
|
||||
fun infoJson(): JSONObject {
|
||||
val o = JSONObject()
|
||||
o.put("name", name)
|
||||
o.put("stats", JSONArray().apply {
|
||||
for (s in pack.stats) {
|
||||
put(JSONObject()
|
||||
.put("name", s.name).put("min", s.min).put("max", s.max)
|
||||
.put("shared", s.shared).put("script", s.script)
|
||||
.put("ranges", JSONArray().apply {
|
||||
for (r in s.ranges) {
|
||||
put(JSONObject().put("min", r.min).put("max", r.max).put("text", r.text))
|
||||
}
|
||||
}))
|
||||
}
|
||||
})
|
||||
o.put("statuses", JSONArray().apply {
|
||||
for (s in pack.statuses) {
|
||||
put(JSONObject()
|
||||
.put("name", s.name).put("type", s.kind).put("turns", s.turns)
|
||||
.put("max_stack", s.maxStack).put("script", s.script))
|
||||
}
|
||||
})
|
||||
return o
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = "规则包编辑",
|
||||
subtitle = "${pack.stats.size} 条数值 · ${pack.statuses.size} 条状态 · ${scripts.size} 个脚本",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("保存") { vm.saveRulePack(name, note, infoJson(), scripts) }
|
||||
},
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("名称", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
OutlinedTextField(
|
||||
value = note,
|
||||
onValueChange = { note = it },
|
||||
label = { Text("说明", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
)
|
||||
|
||||
// ---------------- 脚本(可编辑)----------------
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("脚本")
|
||||
if (vm.editingRulePack?.hasScripts != true) {
|
||||
Hint("这个包还没有脚本。数值的裁决、状态的每轮行为、赋予判定都靠脚本。")
|
||||
}
|
||||
Card {
|
||||
for ((fname, src) in scripts) {
|
||||
if (editing == fname) {
|
||||
Text(fname, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
CodeBox(value = draft, onValueChange = { draft = it })
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
RowAction("保存这段") {
|
||||
scripts = scripts + (fname to draft)
|
||||
editing = ""
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("取消") { editing = "" }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("删掉") {
|
||||
scripts = scripts - fname
|
||||
editing = ""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(fname, fontSize = 13.sp, color = doubaoText())
|
||||
Text(
|
||||
"${src.lines().size} 行 · 点开编辑",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("编辑") { editing = fname; draft = src }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
// 新建一段
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = newScript,
|
||||
onValueChange = { newScript = it },
|
||||
label = { Text("新脚本文件名", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("新建") {
|
||||
val f = newScript.trim()
|
||||
if (f.isNotBlank() && !scripts.containsKey(f)) {
|
||||
scripts = scripts + (f to SCRIPT_TEMPLATE)
|
||||
newScript = ""
|
||||
editing = f
|
||||
draft = SCRIPT_TEMPLATE
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 定义(只读)----------------
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("数值定义")
|
||||
Card {
|
||||
if (pack.stats.isEmpty()) Hint("没有数值。")
|
||||
for (s in pack.stats) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
"${fmt(s.min)} ~ ${fmt(s.max)}" + if (s.shared) " · 全世界观共用" else "",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.ranges.isNotEmpty()) {
|
||||
Text(
|
||||
"${s.ranges.size} 段区间:" + s.ranges.joinToString("、") {
|
||||
"${fmt(it.min)}~${fmt(it.max)}「${it.text.take(10)}」"
|
||||
},
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.script.isNotBlank()) {
|
||||
Text("裁决脚本:${s.script}", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态定义")
|
||||
Card {
|
||||
if (pack.statuses.isEmpty()) Hint("没有状态。")
|
||||
for (s in pack.statuses) {
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
(if (s.isPersistent) "持久" else "定时 ${s.turns} 轮") +
|
||||
(if (s.maxStack > 1) " · 最多叠 ${s.maxStack} 层" else ""),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Hint(
|
||||
"定义(数值和状态的增删、区间表)这一版还是只读的 —— " +
|
||||
"用「导出」在电脑上改 info.json 再导入是最快的办法。" +
|
||||
"界面上能改的是脚本,那也是最常改的部分。",
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** 新建脚本时给的骨架(三个入口都列出来,用户知道可以写什么) */
|
||||
private const val SCRIPT_TEMPLATE = """# 可用的三个入口(写哪个都行,不写的就不执行):
|
||||
|
||||
def on_stat_change(name, value, delta):
|
||||
# 数值裁决:返回生效的增量(可以放大、缩小、返回 0 否决)
|
||||
return delta
|
||||
|
||||
|
||||
def on_turn(self_agent, stats_api):
|
||||
# 每轮生成回复之前跑一次(状态脚本)
|
||||
# stats_api['change_stat']('好感度', -1)
|
||||
# stats_api['set_hint']('中毒', '你眼前发黑')
|
||||
# stats_api['narrate']('毒性发作了')
|
||||
return True
|
||||
|
||||
|
||||
def on_grant(status_name, source_agent):
|
||||
# 别人要给你挂状态时,返回 False 就是抵抗掉
|
||||
return True
|
||||
"""
|
||||
|
||||
/**
|
||||
* 代码框:**不软换行** + **有高度上限**。
|
||||
*
|
||||
* ★ 不软换行:` else:` 折成两行、缩进全乱,而 Python 的缩进就是语法。
|
||||
* 做法是"把输入框塞进足够宽的横向滚动容器"(这个 Compose 版本的
|
||||
* `BasicTextField` 经典重载选不中,见 AGENTS.md)。
|
||||
*
|
||||
* ★ 高度上限:只写 `heightIn(min=...)` 的话脚本一长框就长到屏幕外,
|
||||
* 把底下的东西顶出去,用户够不着。
|
||||
*/
|
||||
@Composable
|
||||
private fun CodeBox(value: String, onValueChange: (String) -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 120.dp, max = 320.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState())) {
|
||||
BasicTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
textStyle = TextStyle(
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoText(),
|
||||
),
|
||||
modifier = Modifier.width(900.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun fmt(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
@@ -512,6 +512,59 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
/* ---------------- 个人资料 ---------------- */
|
||||
// 外观(v1.2 §6.1)
|
||||
SettingsCard("外观") {
|
||||
FormSwitch(
|
||||
title = "背景跟随说话者",
|
||||
sub = "群聊时,展示区的立绘和背景跟着当前发言的人换 —— " +
|
||||
"一眼就能看出这句话是谁说的。关掉的话固定用主智能体的。",
|
||||
checked = vm.state.settings.followSpeaker,
|
||||
onChange = { vm.setFollowSpeaker(it) },
|
||||
)
|
||||
}
|
||||
|
||||
// 对话(v1.2 §3.9 / §4.3)
|
||||
//
|
||||
// ★★ 这几个数字内核早就有、界面一直缺着 —— 用户只能手改 settings.json。
|
||||
// 而它们**都要和内核的默认值一致**,不然界面显示"20"而内核按别的跑。
|
||||
SettingsCard("对话") {
|
||||
NumberRow(
|
||||
title = "对话上下文窗口",
|
||||
sub = "每轮最多带最近多少轮对话进模型。超出的直接丢掉(不摘要)—— " +
|
||||
"该记住的走记忆系统。攒够几轮才裁一次,见下一项。",
|
||||
value = vm.state.settings.contextWindow,
|
||||
onChange = { vm.setContextWindow(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
NumberRow(
|
||||
title = "攒够几轮裁一次",
|
||||
sub = "不是「超一点就裁」,而是攒够这个数才裁一批 —— " +
|
||||
"每轮都裁的话前缀缓存每轮都失效,比多带几轮贵得多。",
|
||||
value = vm.state.settings.contextBatch,
|
||||
onChange = { vm.setContextBatch(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
NumberRow(
|
||||
title = "私聊最多几轮",
|
||||
sub = "两个智能体后台对聊时的上限(一轮 = 双方各说一次)。" +
|
||||
"这是安全网 —— 它们没有「该结束了」的内在信号。",
|
||||
value = vm.state.settings.privateChatRounds,
|
||||
onChange = { vm.setPrivateChatRounds(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// ★★ 用户要求:「talk_to 是用户可以选择传递和停止,有自动模式
|
||||
// (不用用户确认)」—— 所以默认是**手动**(关),
|
||||
// 群聊里 AI 交了话就停下来等你点;开了这个才是自动接着跑。
|
||||
FormSwitch(
|
||||
title = "AI 对聊自动模式",
|
||||
sub = "关(默认):群里 AI 把话交给别人时,底下会出现" +
|
||||
"「让他说 / 停在这」两个按钮,由你决定要不要接着聊。" +
|
||||
"开:不用确认,自动一轮轮接着跑(最多几轮)。",
|
||||
checked = vm.state.settings.aiTalkAuto,
|
||||
onChange = { vm.setAiTalkAuto(it) },
|
||||
)
|
||||
}
|
||||
|
||||
SettingsCard("个人资料") {
|
||||
FormLabel("昵称")
|
||||
FormField(
|
||||
@@ -1270,3 +1323,41 @@ private fun secretOrNull(raw: String): String? {
|
||||
if (v.all { it == '•' }) return null
|
||||
return v
|
||||
}
|
||||
|
||||
/**
|
||||
* 一行数字设置(v1.2 的上下文窗口 / 裁剪批量 / 私聊轮数)。
|
||||
*
|
||||
* ★ 独立一个组件而不是塞三个 `OutlinedTextField`:它们长得一样、
|
||||
* 行为也一样(只收数字、失焦/改完就存),抄三遍迟早有一处不一样。
|
||||
*/
|
||||
@Composable
|
||||
private fun NumberRow(
|
||||
title: String,
|
||||
sub: String,
|
||||
value: Int,
|
||||
onChange: (Int) -> Unit,
|
||||
) {
|
||||
var draft by remember(value) { mutableStateOf(value.toString()) }
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(title, fontSize = 14.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = draft,
|
||||
onValueChange = { s ->
|
||||
val digits = s.filter { it.isDigit() }.take(4)
|
||||
draft = digits
|
||||
digits.toIntOrNull()?.takeIf { it > 0 }?.let(onChange)
|
||||
},
|
||||
singleLine = true,
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
|
||||
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number,
|
||||
),
|
||||
modifier = Modifier.width(100.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(sub, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -91,6 +91,24 @@ fun TokenUsageScreen(
|
||||
Spacer(Modifier.width(24.dp))
|
||||
Metric("输出", usage.output)
|
||||
}
|
||||
// ★ 缓存统计(v1.2):**这家没给就不显示**。
|
||||
// 不是每家都返回缓存字段,显示两个恒为 0 的数会让用户
|
||||
// 以为"缓存完全没生效" —— 那是假警报,比不显示更糟。
|
||||
if (usage.hasCacheInfo) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Row {
|
||||
Metric("缓存命中", usage.cacheHit)
|
||||
Spacer(Modifier.width(24.dp))
|
||||
Metric("缓存未命中", usage.cacheMiss)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"命中率 ${(usage.hitRate * 100).toInt()}% —— " +
|
||||
"命中缓存的输入便宜得多,这一段没白存",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
if (usage.pricePerK > 0 && usage.cost != null) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
@@ -180,6 +198,18 @@ fun TokenUsageScreen(
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
// ★ 缓存命中/未命中(v1.2)。**这家没给就不显示这一行** ——
|
||||
// 不是每家都返回缓存字段,显示一个恒为 0 的"命中率"
|
||||
// 会让用户以为"缓存完全没生效"(那是个假警报)
|
||||
if (m.hasCacheInfo) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
"命中 ${fmtTokens(m.cacheHit)} · 未命中 ${fmtTokens(m.cacheMiss)}" +
|
||||
" · 命中率 ${(m.hitRate * 100).toInt()}%",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -213,17 +243,9 @@ fun TokenUsageScreen(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Card(content: @Composable () -> Unit) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) { content() }
|
||||
}
|
||||
// ★ 这里的私有 `Card` 删了 —— 它和 AgentEditScreen 的那个是**同一段代码**
|
||||
// 抄了两份(只有 vertical 内边距差 2dp)。现在统一用 DoubaoUi.kt 里的公共版。
|
||||
// 留着的话两个同签名函数都可见,编译器直接报"重载歧义"。
|
||||
|
||||
@Composable
|
||||
private fun Metric(label: String, value: Long) {
|
||||
|
||||
@@ -39,14 +39,17 @@
|
||||
|
||||
import base64
|
||||
import io
|
||||
import zipfile
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
import agent_context
|
||||
import agentdb
|
||||
import paths
|
||||
import rule_engine
|
||||
import rule_sandbox
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -134,10 +137,41 @@ def _save_assets(owner_id: str, files: dict, image_spec: dict) -> dict:
|
||||
|
||||
★ 为什么存路径而不是存"包内文件名":包解完就没了(用户不会留着那个 zip),
|
||||
而界面每次都要显示它 —— 存文件名的话每次都得再去找一遍包。
|
||||
|
||||
★ v1.2:`front` 是**五档立绘表**,所以它单独处理 —— 每一档各自落盘,
|
||||
文件名带上档位(`front-喜-happy.png`),否则五档会互相覆盖。
|
||||
老格式(单个文件名)落成「平常」档,和需求说的兼容规则一致。
|
||||
"""
|
||||
out = {}
|
||||
target_dir = _asset_dir(owner_id)
|
||||
for key in ('front', 'back', 'border-main', 'border-info'):
|
||||
|
||||
front = (image_spec or {}).get('front')
|
||||
fronts = {}
|
||||
if isinstance(front, dict):
|
||||
for preset, fname in front.items():
|
||||
slot = str(preset or '').strip()
|
||||
if not slot:
|
||||
continue
|
||||
hit = _pick_asset(files, fname)
|
||||
if not hit:
|
||||
continue
|
||||
name, data = hit
|
||||
dest = os.path.join(target_dir, f'front-{_safe_segment(slot)}-{_safe_segment(name)}')
|
||||
with open(dest, 'wb') as fh:
|
||||
fh.write(data)
|
||||
fronts[slot] = dest
|
||||
elif front:
|
||||
hit = _pick_asset(files, front)
|
||||
if hit:
|
||||
name, data = hit
|
||||
dest = os.path.join(target_dir, f'front-{_safe_segment(name)}')
|
||||
with open(dest, 'wb') as fh:
|
||||
fh.write(data)
|
||||
fronts['平常'] = dest
|
||||
if fronts:
|
||||
out['front'] = fronts
|
||||
|
||||
for key in ('back', 'border-main', 'border-info'):
|
||||
hit = _pick_asset(files, (image_spec or {}).get(key))
|
||||
if not hit:
|
||||
continue
|
||||
@@ -268,7 +302,7 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
||||
'activeScope': scope, # 当前生效的是哪个空间
|
||||
'worldviewId': agent.get('worldviewId') or '',
|
||||
'memories': agentdb.memory_list(own),
|
||||
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||
'emotion': agentdb.emotion_state(agent.get('id') or ''),
|
||||
'suggestion': '',
|
||||
}
|
||||
items = agentdb.memory_list(scope)
|
||||
@@ -294,7 +328,7 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
||||
'window': window,
|
||||
'pinnedCount': pinned_count,
|
||||
'injected': injected,
|
||||
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||
'emotion': agentdb.emotion_state(agent.get('id') or ''),
|
||||
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
||||
}
|
||||
|
||||
@@ -328,7 +362,7 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
if len(seg) < 2 or seg[0] != 'api':
|
||||
return False
|
||||
|
||||
def body():
|
||||
def body(limit: int = 0):
|
||||
"""
|
||||
解析请求体。
|
||||
|
||||
@@ -336,10 +370,22 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
★ 但注意:往下传的时候必须**调用它**(`body()`)——
|
||||
直接把函数对象当 dict 传,报的是 `'function' object has no attribute 'get'`,
|
||||
而那个错看起来像"字段名写错了"。这里踩过一次。
|
||||
★ [limit] 给了就用它,不给就走 `read_json_body` 的默认小上限 ——
|
||||
图片那条路是唯一的例外,见 `ASSET_BODY_LIMIT`。
|
||||
|
||||
★★ 失败时**不能只 `return {}`**:那样"请求体太大 / 不是合法 JSON"
|
||||
会在下游表现成"某个字段是空的",于是报出牛头不对马嘴的错误
|
||||
(真机上就是大图报「不认识的外观槽位」)。原因挂到 handler 上,
|
||||
需要的地方用 `body_error(handler)` 取出来。
|
||||
"""
|
||||
# 每次进来先清掉上一次的残留,否则一次失败会永远跟着后面所有请求
|
||||
handler.body_error = ''
|
||||
try:
|
||||
if limit:
|
||||
return handler.read_json_body(limit)
|
||||
return handler.read_json_body()
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception as exc: # noqa: BLE001
|
||||
handler.body_error = str(exc)
|
||||
return {}
|
||||
|
||||
def err(code: int, msg: str):
|
||||
@@ -356,7 +402,7 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
return True
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _import_agent(handler, body(), err)
|
||||
return _import_agent(handler, body(UPLOAD_BODY_LIMIT), err)
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 3:
|
||||
aid = seg[2]
|
||||
@@ -398,12 +444,19 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
err(404, '没有这个智能体')
|
||||
return True
|
||||
if method == 'GET':
|
||||
handler.send_json(200, {'ok': True, 'emotion': agentdb.emotion_get(agent['id'])})
|
||||
handler.send_json(200, {'ok': True, 'emotion': agentdb.emotion_state(agent['id'])})
|
||||
return True
|
||||
if method in ('PUT', 'POST'):
|
||||
emo = str(body().get('emotion') or '')
|
||||
agentdb.emotion_set(agent['id'], emo[:200])
|
||||
handler.send_json(200, {'ok': True, 'emotion': emo[:200]})
|
||||
b = body()
|
||||
# ★ 这条路由是**界面**在用的(记忆页的情绪区)——
|
||||
# 所以它**允许**把「死亡」改回别的值:那是需求 3.5 说的
|
||||
# "用户手动改回是兜底主权"。禁止自愈只发生在 AI 的工具通道上。
|
||||
nxt = agentdb.emotion_set(
|
||||
agent['id'],
|
||||
preset=str(b.get('preset') or '').strip() or None,
|
||||
text=None if b.get('text') is None else str(b.get('text') or '')[:200],
|
||||
)
|
||||
handler.send_json(200, {'ok': True, 'emotion': nxt})
|
||||
return True
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'skills':
|
||||
@@ -434,13 +487,133 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
handler.send_json(200, {'ok': True, **_usage_payload(agent)})
|
||||
return True
|
||||
|
||||
# ---------------- 数值与状态(§3.10 / §3.11)----------------
|
||||
#
|
||||
# GET 读一个智能体的数值和状态([状态数值] 浮层三个入口都用它)
|
||||
# POST 用户**直接改一个数值**(用户主权 —— 需求里 AI 只能申请增量,
|
||||
# 但用户是规则的主人,他可以直接设成任何值)
|
||||
#
|
||||
# ★★ 还有一种:`GET /api/agents/stats`(少了 id 那一段)——
|
||||
# **批量**读所有智能体的,给**智能体卡片**用(缩略图下面显示
|
||||
# "好感度多少、身上有没有状态")。一个一个拉 N 次会把列表拖垮,
|
||||
# 而每次都重算区间、查状态表,成本不低。
|
||||
if seg[1] == 'agents' and len(seg) == 3 and seg[2] == 'stats' and method == 'GET':
|
||||
# 同一世界观下的智能体共用一个包 —— 按 worldviewId 缓存,
|
||||
# 别为了 N 个智能体把同一个世界观查 N 遍
|
||||
pack_cache = {}
|
||||
out = {}
|
||||
for a in store.list_agents():
|
||||
wid = (a.get('worldviewId') or '').strip()
|
||||
if wid not in pack_cache:
|
||||
pack_cache[wid] = agent_context.pack_of(a)
|
||||
pack_id = pack_cache[wid]
|
||||
if not pack_id:
|
||||
continue # 没挂规则包 → 卡片上什么都不显示
|
||||
one = _stats_payload(a, pack_id)
|
||||
# 批量版**不带** statusDefs(那是"能加哪些状态",
|
||||
# 只有点进 [状态数值] 页才需要;卡片用不上,白传一遍)
|
||||
one.pop('statusDefs', None)
|
||||
out[a['id']] = one
|
||||
handler.send_json(200, {'stats': out})
|
||||
return True
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'stats':
|
||||
agent = store.get_agent(seg[2])
|
||||
if not agent:
|
||||
err(404, '没有这个智能体')
|
||||
return True
|
||||
pack_id = agent_context.pack_of(agent)
|
||||
if method == 'GET':
|
||||
handler.send_json(200, _stats_payload(agent, pack_id))
|
||||
return True
|
||||
if method == 'POST':
|
||||
b = body()
|
||||
name = str(b.get('name') or '').strip()
|
||||
|
||||
# ---- 状态管理(用户主权)----
|
||||
#
|
||||
# ★★ AI 手里只有 `grant_status`(**只能加**),没有任何工具能移除状态。
|
||||
# 于是 `persistent` 状态一旦挂上就永远下不来,
|
||||
# `timed` 的状态想立刻清掉也只能干等 —— 用户是规则的主人,
|
||||
# 这些都得能直接拨。所以 [状态数值] 页上给了「清掉」和「加一个」。
|
||||
#
|
||||
# `action` 缺省时保持老行为(改数值),老客户端不受影响。
|
||||
action = str(b.get('action') or 'set').strip()
|
||||
if action in ('addStatus', 'dropStatus'):
|
||||
sd = next((x for x in rule_engine.status_defs(pack_id)
|
||||
if x['name'] == name), None)
|
||||
if not sd:
|
||||
err(404, f'这个世界观里没有叫「{name}」的状态')
|
||||
return True
|
||||
if action == 'dropStatus':
|
||||
rule_engine.drop_status(agent['id'], name)
|
||||
else:
|
||||
# 加:持久状态记 -1;定时状态用定义里的轮数(可被 body 覆盖)
|
||||
try:
|
||||
turns = int(b.get('turns') or sd.get('turns') or 1)
|
||||
except (TypeError, ValueError):
|
||||
turns = int(sd.get('turns') or 1)
|
||||
remaining = -1 if sd.get('kind') == 'persistent' else max(1, turns)
|
||||
rule_engine.put_status(agent['id'], name, remaining, 1, '')
|
||||
handler.send_json(200, _stats_payload(agent, pack_id))
|
||||
return True
|
||||
|
||||
d = next((x for x in rule_engine.stat_defs(pack_id) if x['name'] == name), None)
|
||||
if not d:
|
||||
err(404, f'这个世界观里没有叫「{name}」的数值')
|
||||
return True
|
||||
try:
|
||||
want = float(b.get('value'))
|
||||
except (TypeError, ValueError):
|
||||
err(400, 'value 得是个数字')
|
||||
return True
|
||||
# ★ 用户直接设值:**照样 clamp**(不然界面会显示一个超出
|
||||
# [min,max] 的值,进度条和区间注入全都错位)
|
||||
after = rule_engine.clamp(d, want)
|
||||
rule_engine.set_value(agent, d, after)
|
||||
handler.send_json(200, _stats_payload(agent, pack_id))
|
||||
return True
|
||||
|
||||
|
||||
#
|
||||
# ★ 这是**同步**接口,可能要跑一两分钟(默认 10 轮 = 20 次 LLM 调用)。
|
||||
# 没做成异步任务队列,是因为那要一整套"任务 id + 轮询 + 取消"的机制,
|
||||
# 而私聊是**用户主动发起、等着看结果**的动作 ——
|
||||
# 等一等比"发起之后不知道去哪儿看"更好。
|
||||
# `maxRounds` 可以调小(探针和测试靠它)。
|
||||
# ---------------- 私聊:两个智能体幕后对聊(§3.9 形态 B)----------------
|
||||
if seg[1] == 'private-chat' and method == 'POST':
|
||||
b = body()
|
||||
first = store.get_agent(str(b.get('first') or ''))
|
||||
second = store.get_agent(str(b.get('second') or ''))
|
||||
if not first or not second:
|
||||
err(404, '需要两个智能体')
|
||||
return True
|
||||
if first.get('id') == second.get('id'):
|
||||
err(400, '不能让自己跟自己私聊')
|
||||
return True
|
||||
if agentdb.is_dead(first['id']) or agentdb.is_dead(second['id']):
|
||||
# 死亡的人不能说话(§3.5),私聊同理
|
||||
err(400, '有一方已经死亡,无法私聊')
|
||||
return True
|
||||
import private_chat
|
||||
|
||||
settings = store.read_settings()
|
||||
result = private_chat.run_pair(
|
||||
settings, first, second,
|
||||
max_rounds=private_chat.resolve_rounds(settings, b),
|
||||
opener=str(b.get('opener') or ''),
|
||||
)
|
||||
handler.send_json(200, result)
|
||||
return True
|
||||
|
||||
# ---------------- 智能体包 ----------------
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'package' and method == 'GET':
|
||||
return _export_agent(handler, seg[2], err)
|
||||
|
||||
# ---------------- 外观图片(四件套)----------------
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
|
||||
return _set_asset(handler, 'agents', seg[2], body(), err)
|
||||
return _set_asset(handler, 'agents', seg[2], body(UPLOAD_BODY_LIMIT), err)
|
||||
|
||||
# ---------------- 单条记忆 ----------------
|
||||
if seg[1] == 'memories' and len(seg) == 3:
|
||||
@@ -529,7 +702,7 @@ def _memories(handler, method: str, seg: list, body, err) -> bool:
|
||||
|
||||
# /memories/import
|
||||
if tail == ['import'] and method == 'POST':
|
||||
return _memory_import(handler, agent, body(), err)
|
||||
return _memory_import(handler, agent, body(UPLOAD_BODY_LIMIT), err)
|
||||
|
||||
return False
|
||||
|
||||
@@ -553,7 +726,7 @@ def _memory_export(agent: dict) -> dict:
|
||||
'version': 1,
|
||||
'name': agent.get('name') or '',
|
||||
'smartMemory': items,
|
||||
'Emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||
'Emotion': agentdb.emotion_state(agent.get('id') or ''),
|
||||
}
|
||||
|
||||
|
||||
@@ -606,7 +779,7 @@ def _memory_import(handler, agent: dict, body: dict, err) -> bool:
|
||||
emotion_kept = True
|
||||
if mode == 'replace' and payload.get('Emotion') is not None:
|
||||
# 覆盖模式连情绪一起换(需求 3.4);合并模式保留当前值
|
||||
agentdb.emotion_set(agent.get('id') or '', str(payload.get('Emotion') or ''))
|
||||
agentdb.emotion_set(agent.get('id') or '', **agentdb.emotion_from_export(payload.get('Emotion')))
|
||||
emotion_kept = False
|
||||
|
||||
return _send_json_ok(handler, {
|
||||
@@ -700,9 +873,144 @@ _RES_PATH = {
|
||||
'worldviews': 'worldviews',
|
||||
'model-entries': 'models',
|
||||
'skills': 'skills',
|
||||
# v1.2 数值状态包(需求附录 D)。★ 它是**唯一允许夹带可执行脚本**的包类型 ——
|
||||
# 智能体包/世界观包发现脚本一律拒绝导入(见 _resource_import)
|
||||
'rulepacks': 'rulepacks',
|
||||
}
|
||||
|
||||
|
||||
def _export_rulepack(handler, pid: str, err) -> bool:
|
||||
"""
|
||||
导出数值状态包(zip:`info.json` + 各脚本)。
|
||||
|
||||
★ **只导定义、不导当前值**(需求附录 D 原话:"数值的**定义**进包,
|
||||
**当前值**不进包 —— 经历与人设分离,同记忆")。
|
||||
所以把包发给别人,对方拿到的是规则,不是你的好感度。
|
||||
"""
|
||||
pack = store.get_resource('rulepacks', pid)
|
||||
if not pack:
|
||||
err(404, '没有这个规则包')
|
||||
return True
|
||||
info = dict(pack.get('info') or {})
|
||||
info['name'] = pack.get('name') or info.get('name') or '规则包'
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr('info.json', json.dumps(info, ensure_ascii=False, indent=2))
|
||||
for fname, src in (pack.get('scripts') or {}).items():
|
||||
zf.writestr(str(fname), str(src))
|
||||
return _send_json_ok(handler, {
|
||||
'ok': True,
|
||||
'name': pack.get('name') or '',
|
||||
'data': base64.b64encode(buf.getvalue()).decode('ascii'),
|
||||
'hasScripts': bool(pack.get('scripts')),
|
||||
})
|
||||
|
||||
|
||||
def _import_rulepack(handler, body: dict, err) -> bool:
|
||||
"""
|
||||
导入数值状态包。
|
||||
|
||||
★★ 这是**唯一允许夹带可执行脚本**的包类型(需求附录 D)。
|
||||
所以它比别的包多一道**服务端强制**的确认:
|
||||
|
||||
包里真有 `.py` 而请求没带 `confirmScripts: true` → **拒绝导入**,
|
||||
并把警告文案一起返回,界面拿去显示。
|
||||
|
||||
为什么不做成"界面弹个框就行":那只是界面上的礼貌,绕过界面直接
|
||||
调接口就没了。而这条是**安全底线**(脚本每轮在用户设备上跑)。
|
||||
|
||||
★ 智能体包 / 世界观包**仍然禁止夹带脚本** —— 那条在各自的导入里拦。
|
||||
"""
|
||||
raw = body.get('data') or ''
|
||||
if not raw:
|
||||
err(400, '缺少包内容')
|
||||
return True
|
||||
try:
|
||||
blob = base64.b64decode(raw)
|
||||
files = _read_zip(blob)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'包读不出来:{exc}')
|
||||
return True
|
||||
|
||||
# 先找出脚本 —— 在**解析 info.json 之前**就要决定要不要拦,
|
||||
# 因为"有没有脚本"是用户要先知道的事
|
||||
scripts = {
|
||||
os.path.basename(name): data.decode('utf-8', errors='replace')
|
||||
for name, data in files.items()
|
||||
if name.lower().endswith('.py')
|
||||
}
|
||||
if scripts and not body.get('confirmScripts'):
|
||||
return _send_json_ok(handler, {
|
||||
'ok': False,
|
||||
'needConfirm': True,
|
||||
'scriptCount': len(scripts),
|
||||
'warning': rule_sandbox.IMPORT_WARNING,
|
||||
})
|
||||
|
||||
info = None
|
||||
for name in files:
|
||||
if os.path.basename(name).lower() == 'info.json':
|
||||
try:
|
||||
info = json.loads(files[name].decode('utf-8'))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'info.json 解析失败:{exc}')
|
||||
return True
|
||||
break
|
||||
if not isinstance(info, dict):
|
||||
err(400, '包里没有 info.json —— 这不是一个数值状态包')
|
||||
return True
|
||||
|
||||
name = str(info.get('name') or body.get('name') or '规则包')[:40]
|
||||
item = store.create_resource('rulepacks', {
|
||||
'name': name,
|
||||
'note': str(body.get('note') or ''),
|
||||
'info': info,
|
||||
'scripts': scripts,
|
||||
})
|
||||
# 定义同步进库(值不动 —— 那是"定义进包、值不进包"的另一半)
|
||||
counts = rule_engine.sync_defs(item['id'], info)
|
||||
return _send_json_ok(handler, {
|
||||
'ok': True, 'item': item, 'stats': counts.get('stats', 0),
|
||||
'statuses': counts.get('statuses', 0), 'scripts': len(scripts),
|
||||
})
|
||||
|
||||
|
||||
def _stats_payload(agent: dict, pack_id: str) -> dict:
|
||||
"""
|
||||
一个智能体的数值 + 状态([状态数值] 浮层的三个入口共用这一个形状)。
|
||||
|
||||
★ 数值和状态**一起返回**:界面上它们总是同屏出现的("它现在什么状态、
|
||||
各项数值多少"),分两个接口的话界面要处理"一个到了一个没到"的中间态。
|
||||
"""
|
||||
agent = agent or {}
|
||||
defs = rule_engine.stat_defs(pack_id) if pack_id else []
|
||||
stats = []
|
||||
for d in defs:
|
||||
v = rule_engine.value_of(agent, d)
|
||||
stats.append({
|
||||
"name": d["name"], "value": v, "min": d["min"], "max": d["max"],
|
||||
"shared": bool(d.get("shared")),
|
||||
# 当前命中哪一段(界面可以直接显示,不用再实现一遍区间逻辑)
|
||||
"text": rule_engine.range_text(d, v),
|
||||
})
|
||||
pack = store.get_resource("rulepacks", pack_id) if pack_id else {}
|
||||
return {
|
||||
"agentId": agent.get("id") or "",
|
||||
"name": agent.get("name") or "",
|
||||
"stats": stats,
|
||||
"statuses": rule_engine.list_statuses(agent.get("id") or ""),
|
||||
# ★ 这个包里**定义了哪些状态** —— 界面的「加一个」要从这里挑。
|
||||
# 不带的话界面只能瞎猜名字(而且用户看不出有哪些可用)。
|
||||
"statusDefs": [
|
||||
{"name": d["name"], "kind": d.get("kind") or "timed",
|
||||
"turns": int(d.get("turns") or 1), "maxStack": int(d.get("max_stack") or 1)}
|
||||
for d in (rule_engine.status_defs(pack_id) if pack_id else [])
|
||||
],
|
||||
"rulePackId": pack_id or "",
|
||||
"rulePackName": (pack or {}).get("name") or "",
|
||||
}
|
||||
|
||||
|
||||
def _tag_world_agents(items: list) -> list:
|
||||
"""
|
||||
给每个世界观补一个 `agents: [{id, name}]` —— "谁绑了它"。
|
||||
@@ -737,11 +1045,19 @@ def _resource_route(handler, seg: list, method: str, body, err):
|
||||
name = _RES_PATH[seg[1]]
|
||||
|
||||
# 包 / JSON 的导入导出(世界观包、Skill 文件)
|
||||
#
|
||||
# ★ 规则包要**抢在通用分支前面**:它的格式不一样(zip 里除了 info.json
|
||||
# 还有一堆 .py),而且多一道"含脚本要确认"的关卡。
|
||||
if name == 'rulepacks':
|
||||
if len(seg) == 4 and seg[3] in ('package', 'export') and method == 'GET':
|
||||
return _export_rulepack(handler, seg[2], err)
|
||||
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _import_rulepack(handler, body(UPLOAD_BODY_LIMIT), err)
|
||||
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _resource_import(handler, name, body(), err)
|
||||
return _resource_import(handler, name, body(UPLOAD_BODY_LIMIT), err)
|
||||
if len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
|
||||
# 世界观的外观图(需求 3.6:沿用同一套四件套)
|
||||
return _set_asset(handler, 'worldviews', seg[2], body(), err)
|
||||
return _set_asset(handler, 'worldviews', seg[2], body(UPLOAD_BODY_LIMIT), err)
|
||||
if len(seg) == 4 and seg[3] == 'memories' and method == 'GET':
|
||||
# 世界观的**共享记忆**(大家共同记得什么)—— 只读视角
|
||||
return _world_memories(handler, seg[2], err)
|
||||
@@ -763,20 +1079,57 @@ def _resource_route(handler, seg: list, method: str, body, err):
|
||||
handler.send_json(200, {'ok': True, 'items': items})
|
||||
return True
|
||||
if method == 'POST':
|
||||
handler.send_json(200, {'ok': True, 'item': store.create_resource(name, body())})
|
||||
item = store.create_resource(name, body())
|
||||
# ★★ 规则包建完要**把定义同步进库**(`stat_defs` / `status_defs`)。
|
||||
#
|
||||
# 不同步的话表现是:"包建出来了、列表里显示 2 条数值,
|
||||
# 但智能体身上一条都读不到" —— 两边单独看都对,中间的连接断了。
|
||||
# 导入那条路一直是同步的(`_import_rulepack` 里做了),
|
||||
# 但**新建**这条路上原来漏了。
|
||||
if name == 'rulepacks':
|
||||
rule_engine.sync_defs(item.get('id') or '')
|
||||
handler.send_json(200, {'ok': True, 'item': item})
|
||||
return True
|
||||
|
||||
if len(seg) == 3:
|
||||
rid = seg[2]
|
||||
if method == 'GET':
|
||||
# ★★ 读**单个**资源 —— 原来这条路是**缺的**(只有列表 GET 和
|
||||
# PATCH/DELETE)。表现很隐蔽:`GET /api/rulepacks/<id>` 落到
|
||||
# 末尾返回 None,[规则包编辑] 于是拿到一个**空包** ——
|
||||
# 页面正常打开、标题正常、只是里面"0 条数值 0 条状态"。
|
||||
# 而那个包其实建出来了(列表里看得见),所以用户会以为
|
||||
# "新建之后东西丢了"。
|
||||
item = store.get_resource(name, rid)
|
||||
if item is None:
|
||||
err(404, '没有这一项')
|
||||
else:
|
||||
# 规则包要带上脚本源码(列表接口里是剔掉的)
|
||||
if name == 'rulepacks':
|
||||
item = {**item, 'scriptCount': len(item.get('scripts') or {})}
|
||||
handler.send_json(200, {'ok': True, 'item': item})
|
||||
return True
|
||||
if method == 'PATCH':
|
||||
updated = store.update_resource(name, rid, body())
|
||||
if updated is None:
|
||||
err(404, '没有这一项')
|
||||
else:
|
||||
# 改完定义同样要同步(改了 min/max 或区间表却不入库,
|
||||
# 表现是"改了没反应")
|
||||
if name == 'rulepacks':
|
||||
rule_engine.sync_defs(rid)
|
||||
handler.send_json(200, {'ok': True, 'item': updated})
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
handler.send_json(200, {'ok': True, 'deleted': store.delete_resource(name, rid)})
|
||||
# ★ 删规则包时**连定义一起删** —— 留着的话那些数值定义成了
|
||||
# 孤儿:包里已经没有它们了,但库里还有,而且值还在 `stat_values`。
|
||||
deleted = store.delete_resource(name, rid)
|
||||
if name == 'rulepacks':
|
||||
conn = agentdb._connect()
|
||||
conn.execute('DELETE FROM stat_defs WHERE pack_id = ?', (rid,))
|
||||
conn.execute('DELETE FROM status_defs WHERE pack_id = ?', (rid,))
|
||||
conn.commit()
|
||||
handler.send_json(200, {'ok': True, 'deleted': deleted})
|
||||
return True
|
||||
return None
|
||||
|
||||
@@ -794,6 +1147,9 @@ def _usage_payload(agent: dict) -> dict:
|
||||
used = usage['total']['input'] + usage['total']['output']
|
||||
# 单价(元/千 Token):在**全局模型列表**里配,填了才估费用
|
||||
price = 0.0
|
||||
cache_price = 0.0
|
||||
entry = {} # ★ 先给个空 dict:下面只有 mid 非空才会填它,
|
||||
# 而返回时无条件读 `entry` —— 不初始化会 NameError
|
||||
mid = agent.get('modelId') or ''
|
||||
if mid:
|
||||
entry = store.get_resource('models', mid) or {}
|
||||
@@ -801,11 +1157,22 @@ def _usage_payload(agent: dict) -> dict:
|
||||
price = float(entry.get('pricePerK') or 0)
|
||||
except (TypeError, ValueError):
|
||||
price = 0.0
|
||||
try:
|
||||
cache_price = float(entry.get('cachePricePerK') or 0)
|
||||
except (TypeError, ValueError):
|
||||
cache_price = 0.0
|
||||
return {
|
||||
'agentId': agent.get('id') or '',
|
||||
'name': agent.get('name') or '',
|
||||
'input': usage['total']['input'],
|
||||
'output': usage['total']['output'],
|
||||
# v1.2 缓存统计:两家都没给时是 0/0,界面据此不显示那一列
|
||||
'cacheHit': usage['total'].get('cacheHit', 0),
|
||||
'cacheMiss': usage['total'].get('cacheMiss', 0),
|
||||
# ★ 命中缓存的单价(v1.2)。各家命中都比未命中便宜得多(常见 1/10),
|
||||
# 只按未命中单价算的话费用会**越用越高估** —— 而用户会以为
|
||||
# 自己真花了那些钱。
|
||||
'cachePricePerK': cache_price,
|
||||
'total': used,
|
||||
'byModel': usage['byModel'],
|
||||
'limit': limit,
|
||||
@@ -850,6 +1217,64 @@ def _export_agent(handler, agent_id: str, err) -> bool:
|
||||
#: 外观四件套的槽位名(和需求 2.5 的 smartInfo.json 一一对应)
|
||||
ASSET_KEYS = ('front', 'back', 'border-main', 'border-info')
|
||||
|
||||
#: **上传类**接口单独给的请求体上限(图片槽位 + 四种包导入)。
|
||||
#:
|
||||
#: ★ 为什么别的接口 4MB、这里要 48MB:这些东西进 JSON 之前都要 base64,
|
||||
#: 体积是原件的 4/3 还要加转义。
|
||||
#: - 图片:真机上用户选的是**手机相册的照片**(30~55MB 很常见),
|
||||
#: base64 之后 38~73MB。默认那 4MB 一进去就被 read_json_body 判
|
||||
#: 「请求体过大」,而上层那个 `except` 把异常吞成空 dict,
|
||||
#: 最后报出来的是「不认识的外观槽位」—— 和真实原因毫无关系的一句话,
|
||||
#: 用户只看到"设置不了"。(这就是真机上报回来的那个 bug。)
|
||||
#: - 包导入:带外观图片的智能体包,zip 上到十几 MB,base64 之后还要再大。
|
||||
#:
|
||||
#: 现在前端会先把位图压到 3MB 以内(见 ImagePick.kt),走这里的常态是几百 KB;
|
||||
#: 这个上限留给**不压缩的 GIF/SVG** 和包导入兜底。
|
||||
#:
|
||||
#: ★ 别把这个上限按"最小的那个调用方"给 —— 这个仓库里已经出现过一次
|
||||
#: 「内核说这图可以(20MB),通道却说请求体太大(4MB)」的自相矛盾。
|
||||
UPLOAD_BODY_LIMIT = 48 * 1024 * 1024
|
||||
|
||||
#: v1.2 立绘表支持的五档(和情绪 preset 对齐,需求 2.5)
|
||||
PORTRAIT_PRESETS = ('喜', '怒', '哀', '平常', '死亡')
|
||||
|
||||
|
||||
def portrait_of(image: dict, preset: str) -> str:
|
||||
"""
|
||||
**当前该显示哪张立绘**(需求 2.6 的回退链):
|
||||
|
||||
当前 preset 档 → 平常档 → 旧格式的单一 front → (空串)
|
||||
|
||||
空串的意思是"没有自定义立绘",界面据此用**内置默认人物**
|
||||
(需求 2.6 的最后一级)。
|
||||
|
||||
★ 为什么由内核算好再给界面:回退链是**一条规则**,而选择界面、对话界面、
|
||||
编辑界面的预览三处都要用。各自实现一遍的话,改一处必漏两处 ——
|
||||
而这个仓库里"同一逻辑抄两份、改的时候只改一份"已经反复出现过。
|
||||
|
||||
★ `os.path.isfile` 要查:用户可能手动删过 `agent-assets/` 里的文件,
|
||||
指着不存在的路径会让界面显示空白 —— 那比回退到默认图糟得多。
|
||||
"""
|
||||
if not isinstance(image, dict):
|
||||
return ''
|
||||
front = image.get('front')
|
||||
# 老数据(没归一化的字符串)也要认:有些路径会直接读 JSON,绕过 store
|
||||
if isinstance(front, str):
|
||||
return front.strip()
|
||||
if not isinstance(front, dict):
|
||||
return ''
|
||||
# ① 当前档 ② 平常档
|
||||
for key in (preset, '平常'):
|
||||
path = str(front.get(key) or '').strip()
|
||||
if path and os.path.isfile(path):
|
||||
return path
|
||||
# ③ 字典里任何一个还能用的(用户可能只传了「喜」这一档)
|
||||
for path in front.values():
|
||||
path = str(path or '').strip()
|
||||
if path and os.path.isfile(path):
|
||||
return path
|
||||
return ''
|
||||
|
||||
|
||||
def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
|
||||
"""
|
||||
@@ -874,25 +1299,70 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
|
||||
err(404, '没有这一项')
|
||||
return True
|
||||
|
||||
# ★★ `key` 必须在这里读出来 —— 我改五档槽位时**把这行删掉了**,
|
||||
# 于是下面 `key.partition(':')` 直接 NameError → 整个接口 500。
|
||||
# 表现是"角色图设置不了"(任何图都传不上去)。
|
||||
# 而当时的探针**没测这个接口**,所以一路绿着过去了。
|
||||
key = str(body.get('key') or '').strip()
|
||||
if key not in ASSET_KEYS:
|
||||
err(400, f'不认识的外观槽位:{key}(可选:{"、".join(ASSET_KEYS)})')
|
||||
# ★ v1.2:立绘是**五档**,所以槽位名允许带档位 —— `front:喜`。
|
||||
# 不带档位的 `front` 视为「平常」档(兼容旧界面和旧调用)。
|
||||
base, _, slot = key.partition(':')
|
||||
base = base.strip()
|
||||
slot = slot.strip()
|
||||
if base not in ASSET_KEYS:
|
||||
# ★ 先看请求体是不是根本没读进来(太大 / 不是合法 JSON)。
|
||||
# 那种情况下 `key` 必然是空的,报"槽位不认识"等于把人往完全错误的
|
||||
# 方向带 —— 真机上就是这么发生的:30MB 的照片 → 请求体超上限 →
|
||||
# 报的却是「不认识的外观槽位」,查了半天槽位名。
|
||||
why = getattr(handler, 'body_error', '')
|
||||
if why:
|
||||
err(400, f'上传内容没收全:{why}')
|
||||
else:
|
||||
err(400, f'不认识的外观槽位:{base}(可选:{"、".join(ASSET_KEYS)})')
|
||||
return True
|
||||
if base == 'front':
|
||||
slot = slot or '平常'
|
||||
if slot not in PORTRAIT_PRESETS:
|
||||
err(400, f'立绘档位只能是:{"、".join(PORTRAIT_PRESETS)}')
|
||||
return True
|
||||
|
||||
def save(image: dict):
|
||||
if kind == 'agents':
|
||||
return store.update_agent(owner_id, {'image': image})
|
||||
return store.update_resource('worldviews', owner_id, {'image': image})
|
||||
|
||||
image = dict(owner.get('image') or {})
|
||||
image = store.normalize_image(owner.get('image') or {})
|
||||
raw = body.get('data') or body.get('base64') or ''
|
||||
|
||||
if base == 'front':
|
||||
fronts = dict(image.get('front') or {})
|
||||
if not raw:
|
||||
old = fronts.pop(slot, '')
|
||||
image['front'] = fronts
|
||||
_drop_file(old)
|
||||
return _send_json_ok(handler, {'item': save(image), 'cleared': True})
|
||||
try:
|
||||
blob = base64.b64decode(raw)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'图片数据解不开:{exc}')
|
||||
return True
|
||||
if len(blob) > 20 * 1024 * 1024:
|
||||
err(400, '图片太大了(上限 20MB)')
|
||||
return True
|
||||
name = _safe_segment(str(body.get('name') or f'{slot}.png'))
|
||||
dest = os.path.join(_asset_dir(owner_id), f'front-{_safe_segment(slot)}-{name}')
|
||||
with open(dest, 'wb') as fh:
|
||||
fh.write(blob)
|
||||
_drop_replaced(fronts.get(slot), dest) # 换图时删旧的那张,不然越攒越多
|
||||
fronts[slot] = dest
|
||||
image['front'] = fronts
|
||||
return _send_json_ok(handler, {
|
||||
'item': save(image), 'path': dest, 'bytes': len(blob), 'slot': slot,
|
||||
})
|
||||
|
||||
if not raw:
|
||||
old = image.pop(key, '')
|
||||
if old and os.path.isfile(old):
|
||||
try:
|
||||
os.remove(old)
|
||||
except OSError:
|
||||
pass
|
||||
old = image.pop(base, '')
|
||||
_drop_file(old)
|
||||
return _send_json_ok(handler, {'item': save(image), 'cleared': True})
|
||||
|
||||
try:
|
||||
@@ -904,11 +1374,12 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
|
||||
err(400, '图片太大了(上限 20MB)')
|
||||
return True
|
||||
|
||||
name = _safe_segment(str(body.get('name') or f'{key}.png'))
|
||||
dest = os.path.join(_asset_dir(owner_id), f'{key}-{name}')
|
||||
name = _safe_segment(str(body.get('name') or f'{base}.png'))
|
||||
dest = os.path.join(_asset_dir(owner_id), f'{base}-{name}')
|
||||
with open(dest, 'wb') as fh:
|
||||
fh.write(blob)
|
||||
image[key] = dest
|
||||
_drop_replaced(image.get(base), dest)
|
||||
image[base] = dest
|
||||
return _send_json_ok(handler, {
|
||||
'item': save(image),
|
||||
'path': dest,
|
||||
@@ -916,6 +1387,44 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
|
||||
})
|
||||
|
||||
|
||||
def _drop_file(path) -> None:
|
||||
"""删掉一个不再被引用的资源文件(失败就算了,不值得让整个请求报错)"""
|
||||
p = str(path or '').strip()
|
||||
if not p or not os.path.isfile(p):
|
||||
return
|
||||
try:
|
||||
os.remove(p)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _drop_replaced(old, keep: str) -> None:
|
||||
"""
|
||||
换图时删掉旧的那张 —— 但**新旧是同一个文件时,千万不能删**。
|
||||
|
||||
★★ 这个 bug 是真机上踩出来的(而且随手试一次碰不到):
|
||||
落盘名是 `<槽位>-<原始文件名>`,所以**同一个文件传第二次时新旧同名**,
|
||||
于是这段顺序出问题:
|
||||
open(dest,'wb') 写新内容
|
||||
_drop_file(旧路径) ← 旧路径 == dest,刚写的那张被自己删了
|
||||
image[base] = dest ← 留下一个指向**不存在文件**的引用
|
||||
结果:资源目录空着,state 里却指着一个幽灵路径,界面回退到默认图。
|
||||
表现是"同一张图传第二次就没了"。
|
||||
|
||||
第一次传时用的是 SAF 给的 `image_1000018033` 这种 segment,名字不一样,
|
||||
所以只有"第二次"才触发 —— 用户报的"设置不了"里就混着这一种。
|
||||
"""
|
||||
p = str(old or '').strip()
|
||||
if not p:
|
||||
return
|
||||
try:
|
||||
if os.path.abspath(p) == os.path.abspath(str(keep or '')):
|
||||
return
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
_drop_file(p)
|
||||
|
||||
|
||||
def _import_agent(handler, body, err) -> bool:
|
||||
"""
|
||||
导入智能体包(需求 2.5)。
|
||||
@@ -1057,4 +1566,4 @@ def _resource_import(handler, name: str, body, err) -> bool:
|
||||
|
||||
def _send_json_ok(handler, payload: dict) -> bool:
|
||||
handler.send_json(200, {'ok': True, **payload})
|
||||
return True
|
||||
return True
|
||||
@@ -1,4 +1,4 @@
|
||||
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||||
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||||
|
||||
## 这个模块只做一件事
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import rule_engine
|
||||
import store
|
||||
from defaults import (
|
||||
BUILTIN_SKILL,
|
||||
@@ -40,7 +41,19 @@ from defaults import (
|
||||
)
|
||||
|
||||
# 模板里的段名(顺序就是渲染顺序)。加一段要同时改 defaults.DEFAULT_PROMPT_TEMPLATE。
|
||||
SECTIONS = ('skills', 'worldview', 'emotion', 'memory', 'peer_emotions')
|
||||
#: 段落名,**顺序就是注入顺序**(需求附录 C,v1.2 按缓存友好重排)。
|
||||
#:
|
||||
#: ★★ 为什么顺序这么重要:主流模型的上下文缓存都是**前缀匹配** ——
|
||||
#: 从第一个 token 开始逐段比对,一处不同则**其后全部失效**。
|
||||
#: 所以最稳的排前面(prompt/skills/worldview/memory 组成长前缀),
|
||||
#: 最易变的排最后(stats/status/emotion/peer_emotions)。
|
||||
#:
|
||||
#: 改之前 emotion 在 memory 前面 —— 情绪一变,连最长的 memory 段
|
||||
#: 一起失效。挪到后面之后,情绪变化只影响末尾那几个短段。
|
||||
#:
|
||||
#: ★ 这个元组**同时决定** `render` 处理哪些段:不在里面的占位符不会被替换,
|
||||
#: 会原样留在提示词里(带着 `{xxx}` 大括号)。加新段时两处一起改。
|
||||
SECTIONS = ('skills', 'worldview', 'memory', 'stats', 'status', 'emotion', 'peer_emotions')
|
||||
|
||||
|
||||
def _safe(fn, fallback):
|
||||
@@ -94,11 +107,32 @@ def memory_scope(agent: dict) -> str:
|
||||
|
||||
|
||||
def build_emotion(agent: dict) -> str:
|
||||
"""`<emotion>` 段:自己的情绪(**始终私有**,绑了世界观也不共享 —— 需求 3.5)"""
|
||||
"""
|
||||
`<emotion>` 段:自己的情绪(**始终私有**,绑了世界观也不共享 —— 需求 3.5)。
|
||||
|
||||
v1.2 双字段,两行都带(附录 C 的模板就是这样):
|
||||
|
||||
preset: 怒
|
||||
text: 这背叛让我无法原谅
|
||||
|
||||
`preset` 是给它**自己**用的(它要据此调整行为),`text` 是扮演质感。
|
||||
两个都注入 —— 这是唯一一处两者都出现的地方(给同伴的只有 preset)。
|
||||
|
||||
★ 「平常 + 没写文本」时整段省掉:不然每个没情绪的智能体都白带一段
|
||||
没有信息量的 `<emotion>`,还占 token。空段整段删除是附录 C 的规矩。
|
||||
"""
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
if not agent_id:
|
||||
return ''
|
||||
return (_safe(lambda: agentdb.emotion_get(agent_id), '') or '').strip()
|
||||
st = _safe(lambda: agentdb.emotion_state(agent_id), None) or {}
|
||||
preset = (st.get('preset') or '').strip()
|
||||
text = (st.get('text') or '').strip()
|
||||
if not text and preset in ('', agentdb.PRESET_DEFAULT):
|
||||
return ''
|
||||
lines = [f'preset: {preset or agentdb.PRESET_DEFAULT}']
|
||||
if text:
|
||||
lines.append(f'text: {text}')
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def build_memory(agent: dict) -> str:
|
||||
@@ -239,8 +273,11 @@ def build_peer_emotions(agent: dict) -> str:
|
||||
# ★ `by_id.items()` 给的是 (id, **整个 agent 字典**),不是 (id, 名字)——
|
||||
# 直接 f'{name}-{emo}' 会把 agent 的 JSON 拼进提示词(踩过)
|
||||
name = one.get('name') or '某人'
|
||||
# ★ v1.2:这里给的是 **preset(五档)不是 text**。
|
||||
# text 是那个角色的内心独白,读给别的角色听等于扒开他的脑子;
|
||||
# preset 才是"看得出来他现在什么脸色"这个粒度。
|
||||
emo = emo_by_id.get(aid) or ''
|
||||
parts.append(f'{name}-{emo}' if emo else f'{name}(没说自己在想什么)')
|
||||
parts.append(f'{name}-{emo}' if emo else f'{name}(看不出什么情绪)')
|
||||
return ';'.join(parts)
|
||||
|
||||
|
||||
@@ -285,11 +322,57 @@ def build_system_prompt(settings: dict, agent: dict) -> str:
|
||||
prompt = (agent.get('systemPrompt') or '').strip() or (settings.get('systemPrompt') or '')
|
||||
values = {
|
||||
'prompt': prompt,
|
||||
# ---- 稳定段:它们在提示词最前面,靠它们拿前缀缓存命中 ----
|
||||
'skills': build_skills(agent),
|
||||
'worldview': build_worldview(agent),
|
||||
'emotion': build_emotion(agent),
|
||||
'memory': build_memory(agent),
|
||||
# ---- 易变段:放最后,变了也只让末尾失效 ----
|
||||
# stats / status 是 v1.2 §3.10/3.11 的规则引擎段,实现见阶段 3;
|
||||
# 现在返回空串 → `render` 会把整段删掉(不会留下空标签)
|
||||
'stats': build_stats(agent),
|
||||
'status': build_status(agent),
|
||||
'emotion': build_emotion(agent),
|
||||
'peer_emotions': build_peer_emotions(agent),
|
||||
}
|
||||
template = (settings.get('promptTemplate') or '').strip() or DEFAULT_PROMPT_TEMPLATE
|
||||
return render(template, values)
|
||||
|
||||
|
||||
def pack_of(agent: dict) -> str:
|
||||
"""
|
||||
这个智能体用的规则包 id(`世界观.rulePackId`),没有就空串。
|
||||
|
||||
★ 数值状态包挂在**世界观**上(需求 §3.6:"v1.2 起,世界观同时是
|
||||
数值状态包的挂载点"),所以没绑世界观就没有规则引擎 —— 返回空串,
|
||||
`<stats>` / `<status>` 两段会被整段删掉。
|
||||
"""
|
||||
wid = ((agent or {}).get('worldviewId') or '').strip()
|
||||
if not wid:
|
||||
return ''
|
||||
world = _safe(lambda: store.get_resource('worldviews', wid), None) or {}
|
||||
return (world.get('rulePackId') or '').strip()
|
||||
|
||||
|
||||
def build_stats(agent: dict) -> str:
|
||||
"""
|
||||
`<stats>` 段:数值系统(需求附录 C / §3.10)。
|
||||
|
||||
格式见 `rule_engine.stats_section`。没绑世界观、或世界观没挂规则包 → 空段。
|
||||
"""
|
||||
pack = pack_of(agent)
|
||||
if not pack:
|
||||
return ''
|
||||
return _safe(lambda: rule_engine.stats_section(agent or {}, pack), '')
|
||||
|
||||
|
||||
def build_status(agent: dict) -> str:
|
||||
"""
|
||||
`<status>` 段:状态系统(需求附录 C / §3.11)。
|
||||
|
||||
★ 和 `<stats>` 不同,它**不要求绑世界观**:状态一旦被赋予就挂在智能体
|
||||
自己身上,解绑世界观不该让它身上的状态凭空消失(那和"解绑不丢记忆"
|
||||
是同一个道理)。
|
||||
"""
|
||||
if not ((agent or {}).get('id') or ''):
|
||||
return ''
|
||||
return _safe(lambda: rule_engine.status_section(agent or {}), '')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
|
||||
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||||
@@ -11,6 +11,7 @@ Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from typing import Callable, Optional
|
||||
|
||||
import agent_context
|
||||
@@ -43,11 +44,64 @@ def add_usage(total, one) -> dict:
|
||||
v = one.get(src)
|
||||
if isinstance(v, (int, float)):
|
||||
out[dst] = int(out.get(dst) or 0) + int(v)
|
||||
# 缓存命中也累加(需求 3.1 的 v1.2 新增)。
|
||||
# ★ 累加的是**归一化之后**的两个数,不是原始字段:各家的名字不一样,
|
||||
# 直接并进 out 的话,换了模型那个 key 就消失了。
|
||||
hit, miss = cache_pair(one)
|
||||
if hit or miss:
|
||||
out['cache_hit'] = int(out.get('cache_hit') or 0) + hit
|
||||
out['cache_miss'] = int(out.get('cache_miss') or 0) + miss
|
||||
if 'total_tokens' not in out:
|
||||
out['total_tokens'] = int(out.get('prompt_tokens') or 0) + int(out.get('completion_tokens') or 0)
|
||||
return out
|
||||
|
||||
|
||||
#: 各家的「缓存命中」字段名。**加新提供商只改这一处**,不要在调用点写 if。
|
||||
#:
|
||||
#: DeepSeek prompt_cache_hit_tokens / prompt_cache_miss_tokens(两个都给)
|
||||
#: Claude cache_read_input_tokens(只给命中)
|
||||
#: OpenAI prompt_tokens_details.cached_tokens(嵌套,也只给命中)
|
||||
_CACHE_HIT_KEYS = ('prompt_cache_hit_tokens', 'cache_read_input_tokens', 'cached_tokens')
|
||||
|
||||
|
||||
def cache_pair(usage) -> tuple:
|
||||
"""
|
||||
从 usage 里取出 `(cache_hit, cache_miss)`(需求 3.1 的 v1.2 新增)。
|
||||
|
||||
★ 为什么必须归一化:三家的字段名完全不同,不归一化的话,
|
||||
界面上那个"缓存命中率"会因为换了个模型就**静默变成 0**
|
||||
(而不是报错 —— 静默的 0 最难发现,用户会以为"缓存没生效")。
|
||||
|
||||
★ 两家只给命中、不给未命中(Claude / OpenAI),所以未命中要**自己推**:
|
||||
`prompt_tokens - hit`。推不出来时返回 0,界面据此**不显示那一列** ——
|
||||
显示一个假的 0% 是误导。
|
||||
"""
|
||||
u = usage if isinstance(usage, dict) else {}
|
||||
hit = 0
|
||||
for key in _CACHE_HIT_KEYS:
|
||||
v = u.get(key)
|
||||
if isinstance(v, (int, float)) and v > 0:
|
||||
hit = int(v)
|
||||
break
|
||||
if not hit:
|
||||
# OpenAI 把它塞在嵌套对象里
|
||||
details = u.get('prompt_tokens_details')
|
||||
if isinstance(details, dict):
|
||||
v = details.get('cached_tokens')
|
||||
if isinstance(v, (int, float)) and v > 0:
|
||||
hit = int(v)
|
||||
|
||||
miss = 0
|
||||
v = u.get('prompt_cache_miss_tokens')
|
||||
if isinstance(v, (int, float)) and v > 0:
|
||||
miss = int(v)
|
||||
if hit and not miss:
|
||||
total = u.get('prompt_tokens') or u.get('input_tokens')
|
||||
if isinstance(total, (int, float)) and total >= hit:
|
||||
miss = int(total) - hit
|
||||
return hit, miss
|
||||
|
||||
|
||||
def usage_pair(usage) -> tuple:
|
||||
"""从 usage 里取出 (输入, 输出)。给落库用 —— 字段名差异在这一处抹平"""
|
||||
u = usage if isinstance(usage, dict) else {}
|
||||
@@ -275,9 +329,41 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
# 按开关动态追加,两边永远一致。
|
||||
#
|
||||
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
|
||||
# ★ 新一轮开始:清掉上一轮的发言权移交(v1.2 §3.9 的"一轮最多一次")。
|
||||
# 放这儿是因为它必须**每轮**重置,而且和线程无关(工具跑在 worker 线程里)
|
||||
tools_runtime.begin_round()
|
||||
|
||||
if tools_runtime.ui_tools_enabled(settings):
|
||||
system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip()
|
||||
|
||||
# ★★ 状态脚本要在**重拼 prompt 之前**跑(需求附录 E 的顺序,固定):
|
||||
#
|
||||
# 状态脚本执行 → 重拼 prompt → 生成
|
||||
#
|
||||
# 顺序反了的话,脚本这一轮的改动要等下一轮才生效 ——
|
||||
# 表现是"中毒了但 AI 这轮还生龙活虎"。
|
||||
#
|
||||
# ★ 脚本报错**不中断对话**(需求附录 E):错误收集起来给界面提示,
|
||||
# 对话照常往下走。规则脚本是用户自己写的,写错了是常态,
|
||||
# 一次脚本错误把整轮对话搞崩,用户会以为整个 App 坏了。
|
||||
try:
|
||||
import rule_engine
|
||||
|
||||
_turn = rule_engine.run_turn_scripts(agent or {}, agent_context.pack_of(agent or {}))
|
||||
if _turn.get('narration'):
|
||||
# 脚本返回的旁白"作为系统消息注入下一轮"(需求 §3.10)——
|
||||
# 拼在提示词末尾,比单开一条 user 消息干净(不会污染对话记录)
|
||||
system_prompt = (system_prompt + '\n\n【当前状况】\n'
|
||||
+ '\n'.join(_turn['narration'])).strip()
|
||||
for _e in _turn.get('errors') or []:
|
||||
# ★ 异常要**让用户看见**(需求附录 E:"异常归零 + UI 提示")。
|
||||
# 只 print 到 stderr 的话,用户看到的只是"这轮回复有点怪",
|
||||
# 而完全不知道是脚本报错了 —— 而脚本是他自己写的。
|
||||
emit({'type': 'rule_error', 'message': _e})
|
||||
print(f'[rule] {_e}', file=sys.stderr)
|
||||
except Exception as _exc: # noqa: BLE001 - 规则引擎坏了不该让对话发不出去
|
||||
print(f'[rule] 状态脚本执行失败:{_exc}', file=sys.stderr)
|
||||
|
||||
# ★★ 兼容降级(需求 3.3):这个模型不支持 tools 参数时,换成"正文内调用约定"。
|
||||
#
|
||||
# 为什么要这么绕:记忆/情绪这些能力**全靠工具**,而本地小模型、
|
||||
@@ -342,6 +428,16 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
answer = ''
|
||||
reasoning_all = ''
|
||||
tool_call_count = 0
|
||||
# ★ 工具调用的**明细**(不只次数)。
|
||||
#
|
||||
# 界面上的"工具卡片"(调了什么、成没成、返回了什么)以前只有流式那一刻
|
||||
# 能看到 —— 因为这份明细**从来没落过库**,重启 App 就全没了。
|
||||
# 用户的原话:「工具怎么重启就不显示了」。
|
||||
#
|
||||
# 只留 id/name/ok/result 四样:args 可能很长(贴进去的代码),
|
||||
# 而用户真正想回看的是"它做了什么、拿到什么"。result 也截断,
|
||||
# 不然一条消息能撑爆会话 JSON。
|
||||
tool_trace = []
|
||||
usage = None
|
||||
|
||||
for round_index in range(max_rounds):
|
||||
@@ -408,6 +504,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
return {
|
||||
'content': final, 'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
'toolTrace': tool_trace,
|
||||
}
|
||||
|
||||
convo.append({
|
||||
@@ -463,6 +560,13 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
'result': payload,
|
||||
})
|
||||
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
|
||||
# ★ 记明细(落库用,见上面 tool_trace 的注释)
|
||||
tool_trace.append({
|
||||
'id': tc.get('id') or '',
|
||||
'name': tc.get('name') or '',
|
||||
'ok': bool(result.get('ok')),
|
||||
'result': str(payload)[:800],
|
||||
})
|
||||
|
||||
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
|
||||
emit({
|
||||
@@ -477,4 +581,5 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
'toolTrace': tool_trace,
|
||||
}
|
||||
|
||||
@@ -268,29 +268,62 @@ def memory_suggest_summary(args: dict) -> dict:
|
||||
EMOTION_SET = {
|
||||
'name': 'emotion_set',
|
||||
'description': (
|
||||
'更新**你自己**当前的情绪状态(一小段话,比如"刚被夸了,有点得意")。'
|
||||
'它会跟着你到下一次对话,也会显示在系统提示词里。'
|
||||
'更新**你自己**当前的情绪状态。两个字段都要给:\n'
|
||||
'· preset:五档之一 —— 喜 / 怒 / 哀 / 平常 / 死亡。它决定系统行为'
|
||||
'(立绘换哪张、同伴看到你什么脸色、死亡时能不能继续说话)。\n'
|
||||
'· text:一句自由描述,比如"刚被夸了,有点得意"。这只是扮演质感。\n'
|
||||
'情绪要跟着对话内容自然变化,不用每轮都改。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'emotion': {'type': 'string', 'description': '你现在的情绪'},
|
||||
'preset': {
|
||||
'type': 'string',
|
||||
'enum': list(agentdb.PRESETS),
|
||||
'description': '五档情绪之一',
|
||||
},
|
||||
'text': {'type': 'string', 'description': '一句自由描述(可选)'},
|
||||
},
|
||||
'required': ['emotion'],
|
||||
'required': ['preset'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def emotion_set(args: dict) -> dict:
|
||||
"""
|
||||
写自己的情绪(需求 3.5 双字段)。
|
||||
|
||||
★★ **禁止把自己从「死亡」改活**(需求 3.5 明文)。
|
||||
|
||||
为什么:死亡是"这个角色没了"。能自己复活的话死亡就没有重量 ——
|
||||
用户会看到 AI 上一句刚咽气、下一句又活蹦乱跳,整个系统的可信度就没了。
|
||||
|
||||
复活只有两条**别的**通道,都不经过这里:
|
||||
· 用户手动改(兜底主权,在记忆页的情绪区)
|
||||
· 状态脚本改(定时复活 / 解药剧情,见 §3.11 —— 那条路走沙箱,不走工具)
|
||||
"""
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
emo = str(args.get('emotion') or '').strip()
|
||||
if not emo:
|
||||
raise ValueError('emotion 不能为空(不想保留情绪的话直接别调用这个工具)')
|
||||
agentdb.emotion_set(agent.get('id') or '', emo[:200])
|
||||
return {'emotion': emo[:200], 'note': '已更新你自己的情绪。'}
|
||||
agent_id = agent.get('id') or ''
|
||||
preset = str(args.get('preset') or '').strip()
|
||||
text = str(args.get('text') or '').strip()
|
||||
if preset not in agentdb.PRESETS:
|
||||
raise ValueError(
|
||||
f'preset 只能是这五个之一:{"、".join(agentdb.PRESETS)}(收到的是「{preset}」)'
|
||||
)
|
||||
cur = agentdb.emotion_state(agent_id)
|
||||
if cur.get('preset') == agentdb.PRESET_DEAD and preset != agentdb.PRESET_DEAD:
|
||||
raise ValueError(
|
||||
'你已经是「死亡」状态,**不能自己复活**。'
|
||||
'复活只能由用户手动操作,或者由世界观里的状态脚本触发(比如定时复活、解药剧情)。'
|
||||
)
|
||||
nxt = agentdb.emotion_set(agent_id, preset=preset, text=text or None)
|
||||
return {
|
||||
'preset': nxt['preset'],
|
||||
'text': nxt['text'],
|
||||
'note': '已更新你自己的情绪。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -318,6 +351,9 @@ def get_token_usage(args: dict) -> dict:
|
||||
'used': used,
|
||||
'input': usage['total']['input'],
|
||||
'output': usage['total']['output'],
|
||||
# v1.2:缓存命中/未命中(0 = 这家没提供缓存信息)
|
||||
'cacheHit': usage['total'].get('cacheHit', 0),
|
||||
'cacheMiss': usage['total'].get('cacheMiss', 0),
|
||||
'byModel': usage['byModel'],
|
||||
'limit': limit,
|
||||
'remaining': (None if limit <= 0 else max(0, limit - used)),
|
||||
@@ -325,6 +361,443 @@ def get_token_usage(args: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 规则引擎(v1.2 §3.10 / §3.11)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
CHANGE_STAT = {
|
||||
'name': 'change_stat',
|
||||
'description': (
|
||||
'申请改变**你自己**身上某个数值。\n'
|
||||
'★ 只能给**增量**(+5 / -10),**不能写绝对值** —— 因为数值可能被'
|
||||
'世界观里的规则脚本裁决(放大、缩小、甚至否决),绝对值会让那套规则失效。\n'
|
||||
'真实结果以返回值里的 after 为准:你以为加了 5,可能实际加了 10 或者 0。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type': 'string', 'description': '数值名(见系统提示词的 <stats> 段)'},
|
||||
'delta': {'type': 'number', 'description': '想改变多少(可正可负)'},
|
||||
},
|
||||
'required': ['name', 'delta'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def change_stat(args: dict) -> dict:
|
||||
"""
|
||||
申请数值增量(需求 §3.10)。
|
||||
|
||||
内核流程是固定的:**脚本裁决 → clamp → 写库 → 下一轮注入反映新值**。
|
||||
这里只负责把请求转过去、把**真实结果**回来告诉模型 ——
|
||||
它必须知道"我以为加 5,实际加了 10"(否则下一轮它会按错误的心智继续演)。
|
||||
"""
|
||||
import agent_context
|
||||
import rule_engine
|
||||
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
pack = agent_context.pack_of(agent)
|
||||
if not pack:
|
||||
raise ValueError('你还没有绑定世界观,身上没有数值系统')
|
||||
name = str(args.get('name') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('name 不能为空')
|
||||
raw = args.get('delta')
|
||||
try:
|
||||
delta = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f'delta 得是个数字(收到的是「{raw}」)') from None
|
||||
r = rule_engine.change(agent, pack, name, delta)
|
||||
if not r.get('ok'):
|
||||
raise ValueError(r.get('error') or '改数值失败')
|
||||
out = {
|
||||
'name': name,
|
||||
'applied': r.get('applied'),
|
||||
'before': r.get('before'),
|
||||
'after': r.get('after'),
|
||||
}
|
||||
if r.get('text'):
|
||||
out['now'] = r['text']
|
||||
if r.get('narration'):
|
||||
out['narration'] = r['narration']
|
||||
if r.get('applied') != delta:
|
||||
# ★ 被裁决过了要**明说**,不然模型会以为自己算错了
|
||||
out['note'] = f'你申请的是 {delta:+g},规则裁决后实际生效 {r.get("applied"):+g}。'
|
||||
return out
|
||||
|
||||
|
||||
GRANT_STATUS = {
|
||||
'name': 'grant_status',
|
||||
'description': (
|
||||
'给**同一个世界观里**的另一个智能体施加一个状态(比如中毒、庇佑)。\n'
|
||||
'对方可能**抵抗**(那是他的设定),被抵抗时你会拿到明确回执。\n'
|
||||
'跨世界观一律无效。同名状态重复施加默认**刷新时长**,不会叠层。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '目标的**名字**(或 id)'},
|
||||
'status_name': {'type': 'string', 'description': '状态名(见世界观规则包)'},
|
||||
'turns': {'type': 'integer', 'description': '持续几轮(可选,默认按定义)'},
|
||||
},
|
||||
'required': ['target', 'status_name'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _find_agent(needle: str):
|
||||
"""
|
||||
按名字或 id 找智能体。
|
||||
|
||||
★ 为什么按**名字**找:模型在提示词里看到的伙伴就是名字
|
||||
(`<peer_emotions>` 给的是"仙辰-哀"),它拿不到 id。
|
||||
重名时取第一个 —— 重名本来就不该发生(界面会显示 玄辰/玄辰(2),
|
||||
但那是显示层的事)。
|
||||
"""
|
||||
import store
|
||||
|
||||
key = str(needle or '').strip()
|
||||
if not key:
|
||||
return None
|
||||
for a in store.list_agents():
|
||||
if a.get('id') == key:
|
||||
return a
|
||||
for a in store.list_agents():
|
||||
if (a.get('name') or '').strip() == key:
|
||||
return a
|
||||
return None
|
||||
|
||||
|
||||
def grant_status(args: dict) -> dict:
|
||||
"""给同世界观的另一个智能体施加状态(需求 §3.11)"""
|
||||
import agent_context
|
||||
import rule_engine
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
pack = agent_context.pack_of(me)
|
||||
if not pack:
|
||||
raise ValueError('你还没有绑定世界观,用不了状态系统')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
# 给自己挂状态用别的途径没有意义 —— 直接说不支持,
|
||||
# 免得模型以为"自残"是个正常操作
|
||||
raise ValueError('不能给自己施加状态,只能施加给同世界观的其他智能体')
|
||||
status_name = str(args.get('status_name') or '').strip()
|
||||
try:
|
||||
turns = int(args.get('turns') or 0)
|
||||
except (TypeError, ValueError):
|
||||
turns = 0
|
||||
r = rule_engine.grant(me, pack, target, status_name, turns)
|
||||
if not r.get('ok'):
|
||||
# ★ 被抵抗时**抛错**而不是返回 ok:false —— 需求说"A 必须知道结果",
|
||||
# 而工具抛错是模型一定会看到的那条路(返回里的字段它可能忽略)
|
||||
raise ValueError(r.get('error') or '赋予失败')
|
||||
return {
|
||||
'target': r.get('target'),
|
||||
'status': r.get('name'),
|
||||
'remaining': r.get('remaining'),
|
||||
'refreshed': r.get('refreshed'),
|
||||
'note': ('对方本来就有这个状态,已刷新时长。' if r.get('refreshed')
|
||||
else f'已施加给「{r.get("target")}」。'),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 多智能体对话(v1.2 §3.9)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
INVITE_AGENT = {
|
||||
'name': 'invite_agent',
|
||||
'description': (
|
||||
'把**同一个世界观里**的另一个智能体拉进当前群聊,让他也能说话。\n'
|
||||
'只能拉同世界观的人;单聊会话要先转成群聊。\n'
|
||||
'★ 拉之前先在正文里跟用户说一声 —— 别默默往对话里塞人。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '要拉进来的智能体的名字'},
|
||||
},
|
||||
'required': ['target'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def invite_agent(args: dict) -> dict:
|
||||
"""
|
||||
拉起同世界观的智能体进群(需求 §3.9 形态 A)。
|
||||
|
||||
按智能体自己的配置分流(需求 §6.1 的「拉起其他智能体:静默 / 需确认」):
|
||||
|
||||
· **静默**:直接进场,系统消息播报「仙辰加入了对话」
|
||||
· **需确认**:这次调用**不直接拉人**,而是返回一个"需要确认"的结果,
|
||||
让 AI 在正文里问用户一句;用户答应之后 AI 再调一次。
|
||||
|
||||
★ 关于"需确认":需求写的是"弹窗询问,拒绝结果作为工具返回值回给 AI"。
|
||||
真正的系统弹窗要等界面通道(`ask_user` 那套机制),这一版先退成
|
||||
"让 AI 自己问"。**功能上等价(用户仍是否决者)**,差别是它经过
|
||||
AI 的嘴而不是系统弹窗 —— 这一点在界面做好之前得说清楚,
|
||||
免得以后有人以为这里已经实现了弹窗。
|
||||
"""
|
||||
import agentdb
|
||||
import group_chat
|
||||
import store
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
ctx = tools_runtime.current_context()
|
||||
conv_id = ctx.get('conversationId') or ''
|
||||
conv = store.get_conversation(conv_id) or {}
|
||||
if not conv:
|
||||
raise ValueError('拿不到当前会话')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不用拉自己 —— 你已经在场了')
|
||||
|
||||
my_world = (me.get('worldviewId') or '').strip()
|
||||
if not my_world or my_world != (target.get('worldviewId') or '').strip():
|
||||
raise ValueError(f'「{target.get("name")}」和你不在同一个世界观里,拉不进来')
|
||||
|
||||
# ★★ 「需确认」必须**排在任何拉人动作之前**。
|
||||
#
|
||||
# 以前它排在"单聊 → 转群聊"那个分支的**后面**,于是:
|
||||
# 用户在单聊里让 AI 拉个人 → 走"转群聊"分支直接拉进来了,
|
||||
# **配置的"拉起需要确认"完全没生效**。
|
||||
# 探针里 `c2` 正好被前面删到剩一个(退化成单聊),一拉就中招。
|
||||
#
|
||||
# 正确的顺序是:**先问能不能拉,再决定怎么拉。**
|
||||
mode = str(me.get('inviteMode') or 'silent').lower()
|
||||
if mode == 'confirm':
|
||||
return {
|
||||
'needConfirm': True,
|
||||
'target': target.get('name'),
|
||||
'note': (f'你设置了「拉起需要确认」,所以这次**没有**直接拉人。'
|
||||
f'请在正文里问用户一句"要不要把{target.get("name")}叫来",'
|
||||
f'用户答应之后再调一次这个工具。'),
|
||||
}
|
||||
|
||||
if not group_chat.is_group(conv):
|
||||
# 单聊拉人 → 转成群聊(需求 §3.9:"当前会话中加入多个智能体")
|
||||
group_chat.promote(conv, target['id'])
|
||||
store.update_conversation(conv_id, {
|
||||
'type': 'group', 'participants': conv.get('participants') or [],
|
||||
})
|
||||
return {'joined': target.get('name'), 'becameGroup': True,
|
||||
'note': f'这个会话现在是群聊了,「{target.get("name")}」加入了对话。'}
|
||||
|
||||
if target['id'] in group_chat.member_ids(conv):
|
||||
return {'joined': target.get('name'), 'already': True,
|
||||
'note': f'「{target.get("name")}」已经在对话里了。'}
|
||||
|
||||
import group_chat as gc
|
||||
|
||||
gc.add_member(conv, target['id'])
|
||||
store.update_conversation(conv_id, {'participants': conv.get('participants') or []})
|
||||
return {'joined': target.get('name'), 'note': f'「{target.get("name")}」加入了对话。'}
|
||||
|
||||
|
||||
PASS_TURN = {
|
||||
'name': 'pass_turn',
|
||||
'description': (
|
||||
'把发言权交给群里的另一个智能体。\n'
|
||||
'★ **一轮最多移交一次** —— 转来转去没人接话,用户会看得莫名其妙。\n'
|
||||
'★ 交给已死亡的人无效,发言权会回到主智能体。\n'
|
||||
'不想说话时不用调它,直接正常回复就行。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '接话的智能体的名字'},
|
||||
},
|
||||
'required': ['target'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def pass_turn(args: dict) -> dict:
|
||||
"""
|
||||
移交发言权(需求 §3.9 的点名制)。
|
||||
|
||||
"一轮最多一次"靠 `tools_runtime` 的上下文标记实现 —— 不放在会话里,
|
||||
因为它是**这一轮**的属性,落库反而要额外写清理逻辑。
|
||||
"""
|
||||
import agentdb
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
# ★★ 用 tools_runtime 的**轮次级状态**,不能用工具上下文 ——
|
||||
# 工具跑在 worker 线程里,写进 thread-local 的标记会随线程消失,
|
||||
# 于是"一轮最多一次"永远不生效(踩过,见 tools_runtime.begin_round 的注释)
|
||||
if tools_runtime.handoff_state().get('used'):
|
||||
# ★ 需求明文"一轮最多一次"。第二次直接拒,理由说清楚 ——
|
||||
# 不然模型会以为是"对方有问题",而不是"规则不允许"
|
||||
raise ValueError('这一轮你已经移交过发言权了(一轮最多一次),直接回复就行')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不能把发言权交给自己')
|
||||
if agentdb.is_dead(target['id']):
|
||||
# ★ 需求明文:死亡目标移交无效。这里**如实告诉模型**,
|
||||
# 它就会自己在正文里圆过去(而不是干等着对方开口)
|
||||
raise ValueError(f'「{target.get("name")}」已经死亡,移交无效 —— 你自己接着说,或者交给别人')
|
||||
tools_runtime.note_handoff(target['id'])
|
||||
return {'handed_to': target.get('name'),
|
||||
'note': f'下一轮由「{target.get("name")}」接话。这一轮你不再移交了。'}
|
||||
|
||||
|
||||
TALK_TO = {
|
||||
'name': 'talk_to',
|
||||
'description': (
|
||||
'在群聊里**主动对一个或多个智能体说话**。\n'
|
||||
'★ 和 `pass_turn` 的区别很要紧:那个只是"我不说了,你来",**不带内容** ——\n'
|
||||
' 对方接到的是一片空白,只能凭上下文猜该说什么。\n'
|
||||
' 这个是你**有话要对他说**:内容会进对话,他下一轮看得到并回应你。\n'
|
||||
'★ 一次可以找**好几个人**(`agents` 列表),他们会**挨个**回应。\n'
|
||||
'★ `private=true` 时这条只有**目标**看得到,群里其他智能体看不到 ——\n'
|
||||
' 用户能看到(他是观察者),但别的 AI 不会知道你们说了什么。\n'
|
||||
'★ 一轮最多一次 —— 转来转去没人接话,用户会看得莫名其妙。\n'
|
||||
'★ 单聊里没有"别人",调了会报错。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'agents': {
|
||||
'type': 'array',
|
||||
'items': {'type': 'string'},
|
||||
'description': '对方的名字列表(只找一个人也可以只写一个)。他们会按顺序挨个回应。',
|
||||
},
|
||||
'agent': {
|
||||
'type': 'string',
|
||||
'description': '老写法:只找一个人时可以直接写名字(等价于 agents=[名字])。',
|
||||
},
|
||||
'content': {'type': 'string', 'description': '你要对他们说的话'},
|
||||
'private': {
|
||||
'type': 'boolean',
|
||||
'description': '私聊模式:只有目标能看到这条,群里其他智能体看不到(默认 false)。',
|
||||
},
|
||||
},
|
||||
'required': ['content'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def talk_to(args: dict) -> dict:
|
||||
"""
|
||||
主动找群里的一个或多个智能体说话。
|
||||
|
||||
★★ 三个能力都是用户点名要的:
|
||||
|
||||
① **能说具体的话**(`content`)
|
||||
`pass_turn` 只交发言权、不带内容 —— 对方接到一片空白,聊不起来。
|
||||
|
||||
② **一次找多个人**(`agents`)—— 他们**挨个**回话。
|
||||
发言权排成队列交给 `tools_runtime`,界面逐个接下去。
|
||||
|
||||
③ **私聊模式**(`private=true`)—— 这条只有目标看得到,
|
||||
群里其他人(包括别的 AI)都不知道你们说了什么。
|
||||
落库时打在消息的 `privateTo` 上;`app.py` 组装 history 时
|
||||
会按"是不是给我的"过滤掉,所以别的 AI 真的看不到。
|
||||
|
||||
★ 说完之后把发言权交出去(`note_handoff`,多目标时排队)——
|
||||
界面据此逐个让他们回应;他们也可以反过来再 `talk_to` 回来。
|
||||
"""
|
||||
import group_chat
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
ctx = _ctx()
|
||||
conv_id = str(ctx.get('conversationId') or '')
|
||||
conv = store.get_conversation(conv_id) or {}
|
||||
if not group_chat.is_group(conv):
|
||||
raise ValueError('这条不是群聊 —— 只有群里有「别人」可以聊')
|
||||
|
||||
if tools_runtime.handoff_state().get('used'):
|
||||
# 和 pass_turn 共用"一轮最多一次"那个标记:要么移交、要么找人说,
|
||||
# 一轮里只做一件,否则发言权会被转好几手,用户看着莫名其妙
|
||||
raise ValueError('这一轮你已经把话交给别人了,等他回应完再说')
|
||||
|
||||
# ★ 目标名单:`agents` 列表优先,兼容老的单数 `agent`
|
||||
raw = args.get('agents')
|
||||
wanted = []
|
||||
if isinstance(raw, list):
|
||||
wanted = [str(x or '').strip() for x in raw]
|
||||
elif raw:
|
||||
wanted = [str(raw or '').strip()]
|
||||
if not wanted:
|
||||
single = str(args.get('agent') or '').strip()
|
||||
if single:
|
||||
wanted = [single]
|
||||
wanted = [x for x in wanted if x]
|
||||
if not wanted:
|
||||
raise ValueError('要跟谁说?写 agent 或 agents')
|
||||
|
||||
targets, missing = [], []
|
||||
for name in wanted:
|
||||
t = _find_agent(name)
|
||||
if not t:
|
||||
missing.append(name)
|
||||
continue
|
||||
if t.get('id') == me.get('id'):
|
||||
continue # 自己跳过(一次找多人时很常见)
|
||||
if t['id'] not in group_chat.member_ids(conv):
|
||||
missing.append(f'{t.get("name")}(不在群里)')
|
||||
continue
|
||||
if all(t['id'] != x['id'] for x in targets):
|
||||
targets.append(t)
|
||||
if not targets:
|
||||
raise ValueError(f'一个都没找到:{"、".join(missing) or "(空的)"}')
|
||||
|
||||
content = str(args.get('content') or '').strip()
|
||||
if not content:
|
||||
raise ValueError('要说什么?content 不能是空的')
|
||||
|
||||
is_private = bool(args.get('private'))
|
||||
msg = {
|
||||
'role': 'assistant',
|
||||
'content': content,
|
||||
'agentId': me.get('id'),
|
||||
'at': store.now_iso(),
|
||||
}
|
||||
if is_private:
|
||||
# ★ 私聊:只给这几个目标看(`app.py` 组装 history 时按这个过滤)
|
||||
msg['privateTo'] = [t['id'] for t in targets]
|
||||
|
||||
before = len((store.get_conversation(conv_id) or {}).get('messages') or [])
|
||||
store.append_messages(conv_id, [msg])
|
||||
after = len((store.get_conversation(conv_id) or {}).get('messages') or [])
|
||||
print(f'[talk_to] conv={conv_id} 落库 {before}->{after} private={is_private} '
|
||||
f'targets={[t.get("name") for t in targets]} 内容={content[:20]!r}', file=sys.stderr)
|
||||
|
||||
# ★ 发言权:多目标排成队列,界面逐个接着让他们回应
|
||||
names_out = '、'.join(t.get('name') or '?' for t in targets)
|
||||
tools_runtime.note_handoff(targets[0]['id'], queue=[t['id'] for t in targets])
|
||||
return {
|
||||
'said_to': [t.get('name') for t in targets],
|
||||
'content': content,
|
||||
'private': is_private,
|
||||
'note': (
|
||||
f'已把「{content}」{"(私下)" if is_private else ""}说给「{names_out}」,'
|
||||
'这句话已经写进对话,他们会挨个回应。别再重复调这个工具。'
|
||||
+ (f'(没找到:{"、".join(missing)})' if missing else '')
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 注册
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -338,6 +811,15 @@ AGENT_TOOLS = {
|
||||
'memory_suggest_summary': {'spec': MEMORY_SUGGEST_SUMMARY, 'run': memory_suggest_summary},
|
||||
'emotion_set': {'spec': EMOTION_SET, 'run': emotion_set},
|
||||
'get_token_usage': {'spec': GET_TOKEN_USAGE, 'run': get_token_usage},
|
||||
# v1.2 规则引擎(附录 B 的后两个)
|
||||
'change_stat': {'spec': CHANGE_STAT, 'run': change_stat},
|
||||
'grant_status': {'spec': GRANT_STATUS, 'run': grant_status},
|
||||
# v1.2 多智能体对话(附录 B 的 invite_agent / pass_turn)
|
||||
'invite_agent': {'spec': INVITE_AGENT, 'run': invite_agent},
|
||||
'pass_turn': {'spec': PASS_TURN, 'run': pass_turn},
|
||||
# ★ 主动找另一个智能体说话(用户要求:参数是「智能体 + 内容」)。
|
||||
# `pass_turn` 只交发言权、不带内容,所以那个聊不起来。
|
||||
'talk_to': {'spec': TALK_TO, 'run': talk_to},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -93,7 +93,13 @@ CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS emotions (
|
||||
agent_id TEXT PRIMARY KEY,
|
||||
emotion TEXT NOT NULL DEFAULT '',
|
||||
-- v1.2(需求 3.5)把情绪拆成双字段:
|
||||
-- preset 五档枚举,**驱动系统行为**(立绘切换、死亡规则)
|
||||
-- text AI 自写的自由文本,只管**扮演质感**
|
||||
-- 老库里的 `emotion` 单列由 _migrate() 搬进 text,列本身留着不动
|
||||
-- (SQLite 删列要重建表,不值当;留着也永远不会有人再读它)
|
||||
preset TEXT NOT NULL DEFAULT '平常',
|
||||
text TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
@@ -103,6 +109,12 @@ CREATE TABLE IF NOT EXISTS token_usage (
|
||||
model TEXT NOT NULL DEFAULT '',
|
||||
input INTEGER NOT NULL DEFAULT 0,
|
||||
output INTEGER NOT NULL DEFAULT 0,
|
||||
-- v1.2:缓存命中 / 未命中。各家的字段名完全不同,存进来的是
|
||||
-- agent_loop.cache_pair() **归一化之后**的两个数。
|
||||
-- 都是 0 表示"这家没提供缓存信息"——界面据此**不显示**那一列,
|
||||
-- 而不是显示一个假的 0%(那是误导)。
|
||||
cache_hit INTEGER NOT NULL DEFAULT 0,
|
||||
cache_miss INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_token_agent ON token_usage(agent_id);
|
||||
@@ -113,6 +125,66 @@ CREATE TABLE IF NOT EXISTS agent_skills (
|
||||
ord INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (agent_id, skill_id)
|
||||
);
|
||||
|
||||
-- ============ v1.2 规则引擎(需求 §3.10 数值 / §3.11 状态)============
|
||||
--
|
||||
-- 和记忆一个思路:**定义**挂世界观、**值**按 scope 存。
|
||||
--
|
||||
-- 为什么定义不挂智能体:需求 §3.10 原话"定义统一收进数值状态包
|
||||
-- (世界观层),智能体不再自带数值定义" —— 一份定义、多个实例。
|
||||
--
|
||||
-- 值的 scope 有两种,由 def 的 shared 决定:
|
||||
-- shared=0 → "agent:<uuid>" 好感度各算各的
|
||||
-- shared=1 → "world:<uuid>" 灵气浓度全世界观一份
|
||||
-- 这和记忆的 scope 写法**故意一致**(`scope_of` 那套),
|
||||
-- 于是"绑定/解绑世界观只是换读写空间、值不迁移不丢失"这条也自动成立。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stat_defs (
|
||||
-- ★ key 是**规则包** id 不是世界观 id:同一个包可以被多个世界观引用,
|
||||
-- 定义只存一份(改一次全生效)。世界观只是"挂载点"。
|
||||
pack_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- min / max 是 SQL 关键字,所以列名带后缀
|
||||
min_value REAL NOT NULL DEFAULT 0,
|
||||
max_value REAL NOT NULL DEFAULT 100,
|
||||
shared INTEGER NOT NULL DEFAULT 0,
|
||||
-- ranges 是 JSON 字符串:[{"min":0,"max":20,"text":"冷淡:……"}],
|
||||
-- 命中哪段注入哪段的 text(需求 §3.10 的"声明式区间表")
|
||||
ranges TEXT NOT NULL DEFAULT '[]',
|
||||
script TEXT NOT NULL DEFAULT '',
|
||||
ord INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (pack_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stat_values (
|
||||
scope TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
value REAL NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (scope, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS status_defs (
|
||||
pack_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- persistent(持久,每轮执行脚本)/ timed(定时,每轮递减归零消失)
|
||||
kind TEXT NOT NULL DEFAULT 'timed',
|
||||
turns INTEGER NOT NULL DEFAULT 1,
|
||||
max_stack INTEGER NOT NULL DEFAULT 1,
|
||||
script TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (pack_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS status_instances (
|
||||
agent_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- 剩余轮数:timed 每轮 -1,归零消失;persistent 恒为 -1(不过期)
|
||||
remaining INTEGER NOT NULL DEFAULT 0,
|
||||
stacks INTEGER NOT NULL DEFAULT 1,
|
||||
-- 状态提示词:脚本可以改写它(需求 §3.11 的脚本权限之一)
|
||||
hint TEXT NOT NULL DEFAULT '',
|
||||
granted_at TEXT NOT NULL,
|
||||
PRIMARY KEY (agent_id, name)
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
@@ -126,10 +198,56 @@ def init() -> None:
|
||||
return
|
||||
conn = _connect()
|
||||
conn.executescript(SCHEMA)
|
||||
_migrate(conn)
|
||||
conn.commit()
|
||||
_init_done = True
|
||||
|
||||
|
||||
def _migrate(conn) -> None:
|
||||
"""
|
||||
老库的结构升级(幂等,每次 init 都跑一遍,没得升就什么都不做)。
|
||||
|
||||
★ 为什么要单独一个函数、而不是只靠 `CREATE TABLE IF NOT EXISTS`:
|
||||
那个只在**表不存在**时建表。表已经存在的话,加列它一概不管 ——
|
||||
于是老用户的库里 `emotions` 表永远只有 `emotion` 一列,
|
||||
而新代码读的是 `preset` / `text`,一读就是 `no such column`。
|
||||
|
||||
v1.2 这一条:`emotion`(单字段自由文本)→ `preset` + `text`。
|
||||
老的那列**留着不动**(SQLite 删列要重建整张表,不值当),
|
||||
它的内容搬进 `text` —— 因为老字段本来存的就是自由文本。
|
||||
"""
|
||||
cols = {r['name'] for r in conn.execute('PRAGMA table_info(emotions)').fetchall()}
|
||||
if 'preset' not in cols:
|
||||
conn.execute("ALTER TABLE emotions ADD COLUMN preset TEXT NOT NULL DEFAULT '平常'")
|
||||
if 'text' not in cols:
|
||||
conn.execute("ALTER TABLE emotions ADD COLUMN text TEXT NOT NULL DEFAULT ''")
|
||||
if 'emotion' in cols:
|
||||
# 老数据的自由文本 → text;preset 全是默认的「平常」
|
||||
conn.execute('UPDATE emotions SET text = emotion')
|
||||
|
||||
# v1.2 第二条:token_usage 加缓存两列(老库没有,读的时候会 no such column)
|
||||
tcols = {r['name'] for r in conn.execute('PRAGMA table_info(token_usage)').fetchall()}
|
||||
if tcols:
|
||||
if 'cache_hit' not in tcols:
|
||||
conn.execute('ALTER TABLE token_usage ADD COLUMN cache_hit INTEGER NOT NULL DEFAULT 0')
|
||||
if 'cache_miss' not in tcols:
|
||||
conn.execute('ALTER TABLE token_usage ADD COLUMN cache_miss INTEGER NOT NULL DEFAULT 0')
|
||||
|
||||
|
||||
#: v1.2 情绪的五档枚举(需求 3.5)。
|
||||
#:
|
||||
#: `preset` 和 `text` 的分工是这个设计的关键:
|
||||
#: · preset **驱动系统行为** —— 立绘切哪张、能不能对话(死亡)、
|
||||
#: 以及注入给同世界观伙伴的那个"脸色"
|
||||
#: · text 只是 **AI 自写的自由文本**,管扮演质感
|
||||
#:
|
||||
#: 合成一个字段做不到:系统要按 preset 分支,而自然语言没法当分支条件;
|
||||
#: 只用 preset 又太干,"怒"和"悲愤交加但强作镇定"是两回事。
|
||||
PRESETS = ('喜', '怒', '哀', '平常', '死亡')
|
||||
PRESET_DEFAULT = '平常'
|
||||
PRESET_DEAD = '死亡'
|
||||
|
||||
|
||||
def reset_init() -> None:
|
||||
"""测试用:换过数据目录之后强制重新建表"""
|
||||
global _init_done
|
||||
@@ -324,39 +442,106 @@ def memory_titles(scope: str) -> list:
|
||||
# 情绪(始终按智能体私有,即使绑定了世界观 —— 需求 3.5)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def emotion_get(agent_id: str) -> str:
|
||||
def emotion_state(agent_id: str) -> dict:
|
||||
"""
|
||||
读一个智能体的情绪 → `{'preset': ..., 'text': ...}`(需求 3.5 双字段)。
|
||||
|
||||
★ 没记过情绪时返回默认值(「平常」+ 空文本),而不是空 —— 调用方
|
||||
(注入模板、界面)就不用各自处理 None 了。
|
||||
"""
|
||||
init()
|
||||
row = _connect().execute(
|
||||
'SELECT emotion FROM emotions WHERE agent_id = ?', (agent_id or '',),
|
||||
'SELECT preset, text FROM emotions WHERE agent_id = ?', (agent_id or '',),
|
||||
).fetchone()
|
||||
return row['emotion'] if row else ''
|
||||
if not row:
|
||||
return {'preset': PRESET_DEFAULT, 'text': ''}
|
||||
preset = (row['preset'] or '').strip() or PRESET_DEFAULT
|
||||
return {'preset': preset, 'text': (row['text'] or '')}
|
||||
|
||||
|
||||
def emotion_set(agent_id: str, emotion: str) -> str:
|
||||
def emotion_set(agent_id: str, preset: str = None, text: str = None) -> dict:
|
||||
"""
|
||||
写情绪(双字段,**只写传进来的那些**)。
|
||||
|
||||
★★ 这里**不做死亡校验** —— 校验放在 AI 的通道上
|
||||
(`agent_tools.emotion_set`),不在数据层。
|
||||
|
||||
为什么:需求 3.5 说"用户手动改回是兜底主权"。数据层要是拦了,
|
||||
**界面就没办法复活了** —— 那是把用户的权力一起拦掉了。
|
||||
权限的边界在"谁在改"(AI / 用户),不在"改什么",所以它在通道上。
|
||||
"""
|
||||
init()
|
||||
cur = emotion_state(agent_id)
|
||||
nxt = {
|
||||
'preset': (preset or cur['preset'] or PRESET_DEFAULT),
|
||||
'text': cur['text'] if text is None else (text or ''),
|
||||
}
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'INSERT INTO emotions (agent_id, emotion, updated_at) VALUES (?, ?, ?) '
|
||||
'ON CONFLICT(agent_id) DO UPDATE SET emotion = excluded.emotion, updated_at = excluded.updated_at',
|
||||
(agent_id or '', emotion or '', now_iso()),
|
||||
'INSERT INTO emotions (agent_id, preset, text, updated_at) VALUES (?, ?, ?, ?) '
|
||||
'ON CONFLICT(agent_id) DO UPDATE SET preset = excluded.preset, '
|
||||
'text = excluded.text, updated_at = excluded.updated_at',
|
||||
(agent_id or '', nxt['preset'], nxt['text'], now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
return emotion or ''
|
||||
return nxt
|
||||
|
||||
|
||||
def is_dead(agent_id: str) -> bool:
|
||||
"""这个智能体是不是「死亡」状态(需求 3.5:死亡的不能对话)"""
|
||||
return emotion_state(agent_id)['preset'] == PRESET_DEAD
|
||||
|
||||
|
||||
def emotion_from_export(raw) -> dict:
|
||||
"""
|
||||
解析记忆/情绪导出文件里的 `Emotion` 字段,返回**可以直接展开给
|
||||
`emotion_set(**...)` 的关键字参数**。
|
||||
|
||||
★★ 两种格式都得认:
|
||||
|
||||
· **v1.1**:`"Emotion": "刚被夸了,有点得意"` —— 一个字符串
|
||||
· **v1.2**:`"Emotion": {"preset": "喜", "text": "……"}` —— 一个对象
|
||||
|
||||
用户手里可能存着 v1.1 导出的文件。只认新格式的话,他导入时会
|
||||
**在情绪这一步直接抛异常**,而前半截记忆已经写进去了 ——
|
||||
留下一个"记忆进来了、情绪没进来"的半成品,最难查。
|
||||
|
||||
`None` 表示"这一项不要动"(`emotion_set` 的语义:只写传进来的)。
|
||||
"""
|
||||
if isinstance(raw, dict):
|
||||
preset = str(raw.get('preset') or '').strip() or None
|
||||
# 老库里 preset 可能不在五档里(用户手改过文件)—— 夹一下,
|
||||
# 不认识就当没给,免得把界面搞出一个选不中的档位
|
||||
if preset and preset not in PRESETS:
|
||||
preset = None
|
||||
text = raw.get('text')
|
||||
return {'preset': preset, 'text': None if text is None else str(text)}
|
||||
|
||||
if isinstance(raw, str):
|
||||
# v1.1 的单字段:它本来存的就是自由文本 → 全给 text,preset 不动
|
||||
return {'preset': None, 'text': raw}
|
||||
|
||||
return {'preset': None, 'text': None}
|
||||
|
||||
|
||||
def peer_emotions(worldview_id: str, exclude_agent: str, agent_ids: list) -> list:
|
||||
"""
|
||||
同世界观、**其他**智能体的「名字 + 情绪」(情绪感知开关打开时才注入)。
|
||||
同世界观、**其他**智能体的「id + preset」。
|
||||
|
||||
★ v1.2 起注入的是 **preset(五档)而不是自由文本**(需求 3.5 原文:
|
||||
"开启后注入同世界观其他智能体的「名字 + preset」")。
|
||||
原因:`text` 是那个角色的**内心独白**,读给别的角色听等于扒开他的脑子;
|
||||
preset 是"看得出来他现在什么脸色"——那才是别人该看到的信息粒度。
|
||||
|
||||
[agent_ids] 是绑定了这个世界观的全部智能体 id(由调用方从 agents.json 里挑,
|
||||
这里不碰 JSON —— 数据层只管数据库里有什么)。返回 [(agent_id, emotion)]。
|
||||
这里不碰 JSON —— 数据层只管数据库里有什么)。返回 [(agent_id, preset)]。
|
||||
"""
|
||||
init()
|
||||
out = []
|
||||
for aid in agent_ids or []:
|
||||
if not aid or aid == exclude_agent:
|
||||
continue
|
||||
out.append((aid, emotion_get(aid)))
|
||||
out.append((aid, emotion_state(aid)['preset']))
|
||||
return out
|
||||
|
||||
|
||||
@@ -364,20 +549,26 @@ def peer_emotions(worldview_id: str, exclude_agent: str, agent_ids: list) -> lis
|
||||
# Token 统计
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def token_add(agent_id: str, model: str, input_tokens: int, output_tokens: int) -> None:
|
||||
def token_add(agent_id: str, model: str, input_tokens: int, output_tokens: int,
|
||||
cache_hit: int = 0, cache_miss: int = 0) -> None:
|
||||
"""
|
||||
记一次消耗。
|
||||
|
||||
★ 输入 / 输出**分开记**(需求 3.1),而且按**模型**分桶 ——
|
||||
"按模型"是靠每行带 model 名做到的:桶是查询时 group by 出来的,
|
||||
不是提前建好的。这样换模型不会有"桶没建好"的问题。
|
||||
|
||||
★ v1.2 多两个参数:缓存命中 / 未命中。**默认 0** 是有意的 ——
|
||||
`agent_loop.cache_pair()` 归一化之后如果两家都没给,就是 0/0,
|
||||
界面据此不显示那一列(显示假的 0% 是误导)。
|
||||
"""
|
||||
init()
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'INSERT INTO token_usage (agent_id, model, input, output, created_at) '
|
||||
'VALUES (?, ?, ?, ?, ?)',
|
||||
(agent_id or '', model or '', int(input_tokens or 0), int(output_tokens or 0), now_iso()),
|
||||
'INSERT INTO token_usage (agent_id, model, input, output, cache_hit, cache_miss, created_at) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
(agent_id or '', model or '', int(input_tokens or 0), int(output_tokens or 0),
|
||||
int(cache_hit or 0), int(cache_miss or 0), now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
@@ -386,23 +577,36 @@ def token_usage(agent_id: str) -> dict:
|
||||
"""
|
||||
这个智能体的累计用量。
|
||||
|
||||
返回 `{'total': {'input':..,'output':..}, 'byModel': [{'model':..,'input':..,'output':..}]}`
|
||||
返回 `{'total': {input, output, cacheHit, cacheMiss},
|
||||
'byModel': [{model, input, output, cacheHit, cacheMiss}]}`
|
||||
|
||||
★ 缓存那两个数是 v1.2 加的;全为 0 时界面**不显示**那一列 ——
|
||||
不是每家提供商都返回缓存信息,显示一个恒为 0 的"命中率"是误导。
|
||||
"""
|
||||
init()
|
||||
conn = _connect()
|
||||
rows = conn.execute(
|
||||
'SELECT model, SUM(input) AS i, SUM(output) AS o FROM token_usage '
|
||||
'SELECT model, SUM(input) AS i, SUM(output) AS o, '
|
||||
'SUM(cache_hit) AS h, SUM(cache_miss) AS m FROM token_usage '
|
||||
'WHERE agent_id = ? GROUP BY model ORDER BY (SUM(input) + SUM(output)) DESC',
|
||||
(agent_id or '',),
|
||||
).fetchall()
|
||||
by_model = [
|
||||
{'model': r['model'] or '(未知)', 'input': int(r['i'] or 0), 'output': int(r['o'] or 0)}
|
||||
{
|
||||
'model': r['model'] or '(未知)',
|
||||
'input': int(r['i'] or 0),
|
||||
'output': int(r['o'] or 0),
|
||||
'cacheHit': int(r['h'] or 0),
|
||||
'cacheMiss': int(r['m'] or 0),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
return {
|
||||
'total': {
|
||||
'input': sum(m['input'] for m in by_model),
|
||||
'output': sum(m['output'] for m in by_model),
|
||||
'cacheHit': sum(m['cacheHit'] for m in by_model),
|
||||
'cacheMiss': sum(m['cacheMiss'] for m in by_model),
|
||||
},
|
||||
'byModel': by_model,
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ HTTP 路由:把 Node 版 server/src/index.mjs 的接口逐条搬到 stdlib 上
|
||||
GET /api/agents POST /api/agents PATCH/PUT/DELETE /api/agents/<id>
|
||||
POST /api/upload POST /api/pick-file GET /api/uploads/pending
|
||||
POST /api/clipboard POST /api/chat(SSE)
|
||||
界面能力(show_ui / ask_user / end_conversation 的电脑/网页端通道):
|
||||
GET /api/device/pending POST /api/device/answer
|
||||
静态:/ /main.web.bundle /lynx-web/* /static/* /uploads/*
|
||||
"""
|
||||
|
||||
@@ -42,6 +44,9 @@ import timeouts
|
||||
import agentdb
|
||||
import agent_api
|
||||
import agent_context
|
||||
import context_window
|
||||
import group_chat
|
||||
import rule_engine
|
||||
import tools_runtime
|
||||
import uploads
|
||||
from defaults import PROVIDER_PRESETS
|
||||
@@ -107,12 +112,179 @@ INDEX_MISSING_HINT = (
|
||||
)
|
||||
|
||||
# 安卓侧(Kotlin/Chaquopy)可以挂上原生能力钩子,等价于 Electron 主进程挂的 __doubaoXxx
|
||||
_hooks = {'clipboard': None, 'pick_file': None, 'reveal': None}
|
||||
#
|
||||
# `device` 是"界面能力"的通用入口:show_ui / ask_user / end_conversation 三个工具
|
||||
# 都通过 tools/_ui_bridge.call_device() 发一个 JSON 到这里,等一个 JSON 回去。
|
||||
# · 安卓:doubao_entry 让 Kotlin 的 NativeBridge.device(json)->json 直接可用
|
||||
# (tools/_ui_bridge 优先走它,根本到不了这里);
|
||||
# · 电脑 / 网页:没有原生桥,_ui_bridge 回落到本模块的 `_web_device()` ——
|
||||
# 内核开一条"设备请求队列",网页轮询 /api/device/pending 取走、弹界面,
|
||||
# 用户操作后 POST /api/device/answer 把结果送回来(阻塞语义和安卓一致)。
|
||||
_hooks = {'clipboard': None, 'pick_file': None, 'reveal': None, 'device': None}
|
||||
|
||||
|
||||
def set_native_hooks(clipboard=None, pick_file=None, reveal=None) -> None:
|
||||
"""注册原生钩子:clipboard(text) / pick_file()->[路径] / reveal(路径)->错误串或 None。"""
|
||||
def set_native_hooks(clipboard=None, pick_file=None, reveal=None, device=None) -> None:
|
||||
"""
|
||||
注册原生钩子:
|
||||
clipboard(text) 写剪贴板
|
||||
pick_file() -> [路径]
|
||||
reveal(路径) -> 错误串或 None
|
||||
device(json_str) -> json_str(界面能力;安卓侧挂 NativeBridge.device)
|
||||
"""
|
||||
_hooks.update({'clipboard': clipboard, 'pick_file': pick_file, 'reveal': reveal})
|
||||
if device is not None:
|
||||
_hooks['device'] = device
|
||||
|
||||
|
||||
def get_native_device_hook():
|
||||
"""
|
||||
给 tools/_ui_bridge 用:返回"电脑端界面能力"的实现。
|
||||
|
||||
安卓上 _ui_bridge 会先拿到 doubao_entry._android,不会走到这里;
|
||||
电脑/网页上没有原生桥,就交给下面的 HTTP 队列(浏览器和 exe 共用同一条路)。
|
||||
"""
|
||||
hook = _hooks.get('device')
|
||||
if callable(hook):
|
||||
return hook
|
||||
return _web_device
|
||||
|
||||
|
||||
# ---- 网页端"界面能力"队列 ------------------------------------------------ #
|
||||
#
|
||||
# 为什么用队列 + 轮询而不是 WebSocket:内核是 http.server 的零依赖实现,
|
||||
# 整套项目里没有 WS;网页本来就在轮询 /api/chat/poll,多一个 700ms 的小轮询
|
||||
# 是最小改动。也不需要区分 Electron / 浏览器 —— 两边都是普通 HTTP 客户端。
|
||||
#
|
||||
# ★ 阻塞请求用 **FIFO 队列** 而不是"一个槽位":用户可能同时开着两个对话/两个标签页,
|
||||
# 或者上一个请求还没答就发起了新的一轮。一个槽位会让后来的请求把前面的**静默顶掉**
|
||||
# (前面那个工具线程要一直等到超时),表现为"AI 问了我但界面没弹出来"。
|
||||
_DEVICE_LOCK = threading.Lock()
|
||||
_DEVICE_QUEUE = [] # 正在等用户回答的请求(网页一次处理一个,先来先到)
|
||||
_DEVICE_NOTIFY = {} # 不需要回答、只要弹出来给用户看的界面(show_ui wait=false)
|
||||
_DEVICE_DEFAULT_WAIT_S = 3600.0 # 网页没给 timeoutMs 时的兜底上限(不做无限阻塞)
|
||||
_DEVICE_QUEUE_LIMIT = 8 # 队列上限:防止网页一直不答导致线程越积越多
|
||||
|
||||
|
||||
def _json_out(obj: dict) -> str:
|
||||
return json.dumps(obj, ensure_ascii=False)
|
||||
|
||||
|
||||
def _web_device(payload_json: str) -> str:
|
||||
"""
|
||||
电脑/网页端的 device 实现(show_ui / ask_user / end_conversation)。
|
||||
|
||||
返回 JSON 字符串,形状和安卓 NativeBridge.device() 一致:
|
||||
· ui_screen(wait=true) → {timeout, closed, value, screenId}
|
||||
· ui_screen(wait=false)→ {ok:true, screenId},另外丢进"通知队列"让网页弹出来
|
||||
· ui_dialog → {timeout, cancelled, multiple, choice, values}
|
||||
· end_conversation → {ok:true, conversationId}(纯内核写操作,不用麻烦网页)
|
||||
"""
|
||||
global _DEVICE_QUEUE
|
||||
|
||||
try:
|
||||
payload = json.loads(payload_json or '{}')
|
||||
except (TypeError, ValueError):
|
||||
payload = {}
|
||||
if not isinstance(payload, dict):
|
||||
payload = {}
|
||||
action = str(payload.get('action') or '')
|
||||
|
||||
# ① 结束对话:内核自己就能落盘(和安卓那边 PATCH /api/conversations/<id> 等价)
|
||||
if action == 'end_conversation':
|
||||
conv = str(payload.get('conversationId') or '')
|
||||
if not conv:
|
||||
return _json_out({'error': '没有 conversationId,无法结束对话'})
|
||||
patch = {
|
||||
'ended': True,
|
||||
'endedAt': int(time.time() * 1000),
|
||||
'endedReason': str(payload.get('reason') or ''),
|
||||
}
|
||||
summary = str(payload.get('summary') or '')
|
||||
if summary:
|
||||
patch['endedSummary'] = summary
|
||||
if not store.update_conversation(conv, patch):
|
||||
return _json_out({'error': '会话不存在'})
|
||||
return _json_out({'ok': True, 'conversationId': conv})
|
||||
|
||||
# ② 弹界面:先落盘一份(用户关掉之后还能再打开,/api/screens 也能列出来)
|
||||
screen_id = ''
|
||||
if action == 'ui_screen':
|
||||
item = store.save_screen(
|
||||
str(payload.get('conversationId') or ''),
|
||||
str(payload.get('html') or ''),
|
||||
str(payload.get('title') or ''),
|
||||
bool(payload.get('full_html')),
|
||||
) or {}
|
||||
screen_id = str(item.get('id') or '')
|
||||
payload = dict(payload)
|
||||
payload['screenId'] = screen_id
|
||||
if not payload.get('wait'):
|
||||
# 不阻塞:挂进通知队列,让网页下一个轮询把它弹出来
|
||||
req_id = 'n' + uuid.uuid4().hex[:12]
|
||||
with _DEVICE_LOCK:
|
||||
_DEVICE_NOTIFY[req_id] = payload
|
||||
return _json_out({'ok': True, 'screenId': screen_id})
|
||||
|
||||
# ③ 其余都是"要等用户操作"的:挂进阻塞队列,等网页 POST 答案
|
||||
req_id = 'd' + uuid.uuid4().hex[:12]
|
||||
try:
|
||||
timeout_ms = int(payload.get('timeoutMs') or 0)
|
||||
except (TypeError, ValueError):
|
||||
timeout_ms = 0
|
||||
timeout_s = (timeout_ms / 1000.0) if timeout_ms > 0 else _DEVICE_DEFAULT_WAIT_S
|
||||
timeout_s = max(1.0, min(3600.0, timeout_s))
|
||||
|
||||
request = {
|
||||
'id': req_id,
|
||||
'payload': payload,
|
||||
'event': threading.Event(),
|
||||
'result': None,
|
||||
'at': time.time(),
|
||||
}
|
||||
with _DEVICE_LOCK:
|
||||
if len(_DEVICE_QUEUE) >= _DEVICE_QUEUE_LIMIT:
|
||||
return _json_out({
|
||||
'error': '界面请求太多,网页那边一直没响应(先把窗口里的弹窗处理掉再试)',
|
||||
})
|
||||
_DEVICE_QUEUE.append(request)
|
||||
|
||||
answered = request['event'].wait(timeout_s)
|
||||
with _DEVICE_LOCK:
|
||||
try:
|
||||
_DEVICE_QUEUE.remove(request)
|
||||
except ValueError:
|
||||
pass
|
||||
result = request.get('result')
|
||||
|
||||
if not answered or not isinstance(result, dict):
|
||||
# 超时 / 网页一直没回:按工具侧的约定给"超时"形状(工具会注明用户没操作)
|
||||
if action == 'ui_dialog':
|
||||
return _json_out({
|
||||
'timeout': True, 'cancelled': False,
|
||||
'multiple': bool(payload.get('multiple')), 'choice': '', 'values': [],
|
||||
})
|
||||
return _json_out({'timeout': True, 'closed': False, 'value': '', 'screenId': screen_id})
|
||||
|
||||
if action == 'ui_dialog':
|
||||
values = result.get('values')
|
||||
if not isinstance(values, list):
|
||||
one = str(result.get('choice') or '')
|
||||
values = [one] if one else []
|
||||
values = [str(v) for v in values if str(v or '').strip()]
|
||||
return _json_out({
|
||||
'timeout': bool(result.get('timeout')),
|
||||
'cancelled': bool(result.get('cancelled')),
|
||||
'multiple': bool(payload.get('multiple')),
|
||||
'choice': values[0] if values else '',
|
||||
'values': values,
|
||||
})
|
||||
|
||||
return _json_out({
|
||||
'timeout': bool(result.get('timeout')),
|
||||
'closed': bool(result.get('closed')),
|
||||
'value': str(result.get('value') or ''),
|
||||
'screenId': screen_id,
|
||||
})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -293,6 +465,18 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
|
||||
# ------------------------------ 基础设施 ------------------------------ #
|
||||
|
||||
def handle_one_request(self): # noqa: N802 - 基类约定
|
||||
"""
|
||||
浏览器关标签页 / 刷新时,连接会被对端直接掐掉(WinError 10054 / ConnectionReset)。
|
||||
这对内核是**正常现象**,不该在 stderr 里打一整段 traceback —— 以前网页轮询
|
||||
(/api/chat/poll、/api/device/pending)每次关页面都会刷一屏,真出问题时反而看不见。
|
||||
"""
|
||||
try:
|
||||
return super().handle_one_request()
|
||||
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):
|
||||
self.close_connection = True
|
||||
return None
|
||||
|
||||
def log_message(self, fmt, *args): # noqa: A003 - 覆盖基类
|
||||
if not QUIET:
|
||||
print(f'[http] {self.address_string()} {fmt % args}', file=sys.stderr)
|
||||
@@ -581,19 +765,44 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
'mcp': mcp_client.get_mcp_state(),
|
||||
'mcpConfig': mcp_client.read_mcp_config(),
|
||||
'conversations': store.list_conversations(),
|
||||
'agents': store.list_agents(),
|
||||
# 每个智能体当前的情绪(复查报告 2.6)。
|
||||
# ★ 给每个智能体算好"当前该显示哪张立绘"(需求 2.6 的回退链:
|
||||
# 当前 preset 档 → 平常档 → 旧单一 front → 空 = 内置默认人物)。
|
||||
#
|
||||
# 界面(选择界面、对话界面、编辑界面的预览)直接用这个字段,
|
||||
# 不用各自实现一遍回退链 —— 那种"同一逻辑抄三份"的写法,
|
||||
# 改一处必漏两处,而这个仓库里已经反复出现过。
|
||||
'agents': [
|
||||
{**a, 'portrait': agent_api.portrait_of(
|
||||
a.get('image') or {},
|
||||
(agentdb.emotion_state(a.get('id') or '').get('preset') or '平常'),
|
||||
)}
|
||||
for a in store.list_agents()
|
||||
],
|
||||
# 每个智能体当前的情绪(v1.2 双字段)。
|
||||
# ★ 情绪原来只在提示词里生效 —— AI 用 emotion_set 改了情绪,
|
||||
# 用户完全无感知,这个功能就成了一个看不见的字段。
|
||||
# `preset` 驱动界面(立绘、死亡禁言、成员标签),
|
||||
# `text` 是扮演质感。
|
||||
# **有情绪才带上**:没记过的(默认「平常」+ 空文本)不占位。
|
||||
'emotions': {
|
||||
a.get('id'): e for a in store.list_agents()
|
||||
if (e := (agentdb.emotion_get(a.get('id') or '') or '').strip())
|
||||
a.get('id'): st for a in store.list_agents()
|
||||
if (st := agentdb.emotion_state(a.get('id') or ''))
|
||||
and (st.get('text') or st.get('preset') != agentdb.PRESET_DEFAULT)
|
||||
},
|
||||
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
||||
# 都不大(几个到几十个),一次带给界面省得进页面再拉一次
|
||||
'worldviews': store.list_resource('worldviews'),
|
||||
'modelEntries': store.list_resource('models'),
|
||||
'skills': store.list_resource('skills'),
|
||||
# v1.2 数值状态包。★ **剔掉脚本源码**,只给个数 ——
|
||||
# `/api/state` 是每次刷新都调的,把几 KB 的脚本每次都传一遍
|
||||
# 是纯浪费;列表上也只需要"带不带脚本"这一个信息。
|
||||
# 要看源码去 [规则包编辑],那里单独拉。
|
||||
'rulePacks': [
|
||||
{**{k: v for k, v in p.items() if k != 'scripts'},
|
||||
'scriptCount': len(p.get('scripts') or {})}
|
||||
for p in store.list_resource('rulepacks')
|
||||
],
|
||||
# AI 提的"该整理记忆了"(按智能体存),界面据此显示按钮
|
||||
'memorySuggestions': {
|
||||
a.get('id'): store.peek_summary_suggestion(a.get('id') or '')
|
||||
@@ -879,6 +1088,56 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200 if ok else 404, {'ok': ok})
|
||||
return True
|
||||
|
||||
# ---- 网页端的"界面能力"通道(show_ui / ask_user 等)----
|
||||
#
|
||||
# 网页每 700ms 拉一次 pending:
|
||||
# · 有阻塞请求(ask_user / show_ui wait=true)→ 弹界面,用户操作后 POST answer;
|
||||
# · 有通知请求(show_ui wait=false)→ 只弹出来给用户看,取走即可,不用回答。
|
||||
if pathname == '/api/device/pending' and method == 'GET':
|
||||
with _DEVICE_LOCK:
|
||||
req = _DEVICE_QUEUE[0] if _DEVICE_QUEUE else None
|
||||
payload = dict(req['payload']) if req else None
|
||||
req_id = req['id'] if req else ''
|
||||
notify = False
|
||||
if payload is None and _DEVICE_NOTIFY:
|
||||
req_id, payload = next(iter(_DEVICE_NOTIFY.items()))
|
||||
payload = dict(payload)
|
||||
_DEVICE_NOTIFY.pop(req_id, None)
|
||||
notify = True
|
||||
if payload is None:
|
||||
self.send_json(200, {'request': None})
|
||||
else:
|
||||
payload['id'] = req_id
|
||||
payload['notify'] = notify
|
||||
self.send_json(200, {'request': payload})
|
||||
return True
|
||||
|
||||
if pathname == '/api/device/answer' and method == 'POST':
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
req_id = str(body.get('id') or '')
|
||||
result = body.get('result')
|
||||
if not req_id or not isinstance(result, dict):
|
||||
self.send_json(400, {'error': '需要 id 和 result'})
|
||||
return True
|
||||
with _DEVICE_LOCK:
|
||||
req = next((r for r in _DEVICE_QUEUE if r.get('id') == req_id), None)
|
||||
matched = req is not None
|
||||
if matched:
|
||||
req['result'] = result
|
||||
req['event'].set()
|
||||
try:
|
||||
_DEVICE_QUEUE.remove(req)
|
||||
except ValueError:
|
||||
pass
|
||||
if not matched:
|
||||
self.send_json(404, {'ok': False, 'error': '没有这个等待中的请求(可能已超时)'})
|
||||
else:
|
||||
self.send_json(200, {'ok': True})
|
||||
return True
|
||||
|
||||
# ---- AI 界面的数据回流 ----
|
||||
#
|
||||
# ★★★ 这是"AI 自己写进网页里的接口"的落点。
|
||||
@@ -928,14 +1187,68 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
kind = str(body.get('type') or 'single')
|
||||
parts = body.get('participants')
|
||||
self.send_json(200, {'conversation': store.create_conversation(
|
||||
body.get('title') or '新对话',
|
||||
# ★ 新会话要**记住它属于谁** —— 会话隔离的依据就是它。
|
||||
# 不传的话所有会话的主人都是空,切换智能体时就没法判断
|
||||
# "这是不是同一个人的对话",只能一直串着(用户报的 bug)。
|
||||
agent_id=(body.get('agentId') or '').strip(),
|
||||
# ★ v1.2 §3.9:群聊是**独立实体**,出现在每个参与者的会话列表里。
|
||||
# 成员列表的第 0 个是主智能体(无人被点名时由它兜底发言)。
|
||||
kind=kind,
|
||||
participants=parts if isinstance(parts, list) else None,
|
||||
)})
|
||||
return True
|
||||
|
||||
# ---- 群聊成员增删(需求 §3.9:"用户手动增删成员无条件")----
|
||||
#
|
||||
# ★ "无条件"是需求原话:不加"只有主智能体能加人""要对方同意"这类
|
||||
# 限制 —— 会话是用户的,他想拉谁就拉谁。
|
||||
# 唯一的例外是主智能体不能移出(移掉就没有兜底发言的人了)。
|
||||
#
|
||||
# ★★ 这里**绝不能用 `_match_id`**:它要求"id 后面没有斜杠",
|
||||
# 而这条路是 `/api/conversations/<id>/members` —— `rest` 里带 `/`,
|
||||
# 它直接返回 None,**整个分支永远进不去**。
|
||||
# 真机表现就是「点加人没反应、人也加不上」,接口回的是
|
||||
# **404 未知接口**(看着像路由没写,其实写了、被这个门槛拦住了)。
|
||||
if pathname.startswith('/api/conversations/') and '/members' in pathname:
|
||||
head, _, tail = pathname.partition('/members')
|
||||
member_id = unquote(head[len('/api/conversations/'):].strip('/'))
|
||||
conv = store.get_conversation(member_id)
|
||||
if not conv:
|
||||
self.send_json(404, {'error': '会话不存在'})
|
||||
return True
|
||||
head, _, tail = pathname.partition('/members')
|
||||
target = tail.strip('/')
|
||||
if method == 'POST' and not target:
|
||||
try:
|
||||
b = self.read_json_body()
|
||||
except ValueError:
|
||||
b = {}
|
||||
target = str(b.get('agentId') or '').strip()
|
||||
if not group_chat.add_member(conv, target):
|
||||
self.send_json(400, {'error': '加不进去(人不存在或已经在里面了)'})
|
||||
return True
|
||||
elif method == 'DELETE' and target:
|
||||
if not group_chat.remove_member(conv, target):
|
||||
# ★ 错误信息要**如实**:以前这里写"主智能体不能被移出",
|
||||
# 而那个规则已经废了(群里没有主人)。真实原因只剩
|
||||
# "人不在群里"或"就剩他一个了"。
|
||||
self.send_json(400, {'error': '移不出去(群里没这个人,或者就剩他一个了)'})
|
||||
return True
|
||||
else:
|
||||
self.send_json(405, {'error': '不支持的操作'})
|
||||
return True
|
||||
# ★ 只存 `participants` —— "成员超过一个就升级成群聊"那条规则
|
||||
# 收在 `group_chat.add_member` 里了。补在这里的话,
|
||||
# 任何别的调用方都会忘,而忘的代价是"拉了人但他从不说话"。
|
||||
updated = store.update_conversation(
|
||||
member_id, {'participants': conv.get('participants') or []}) or conv
|
||||
self.send_json(200, {'conversation': updated})
|
||||
return True
|
||||
|
||||
conv_id = self._match_id(pathname, '/api/conversations/')
|
||||
if conv_id is not None:
|
||||
if method == 'GET':
|
||||
@@ -958,6 +1271,51 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200 if ok else 404, {'ok': ok})
|
||||
return True
|
||||
|
||||
# 标记某条消息为「重要」(v1.2 §4.3)
|
||||
#
|
||||
# 路径:/api/conversations/<convId>/important,body: {content, role?, important?}
|
||||
#
|
||||
# ★ 只有**用户**能打这个标记(需求原话"仅用户可标")——
|
||||
# AI 那边没有对应的工具,它有 `memory_add` 去记该记的东西。
|
||||
# 被标记的消息在**上下文窗口裁剪**时"破格永久携带"。
|
||||
#
|
||||
# ★★ 按**内容**定位而不是下标(踩过):
|
||||
# 界面上那份消息列表和存储里的**不保证一一对应**(本地生成的内容、
|
||||
# 还没落地的流式消息……),按下标"长按第 3 条"会把标记打到第 1 条上,
|
||||
# 而且**静默标错** —— 用户要等哪天发现某句话莫名没被裁掉才知道。
|
||||
# 找不到就报 404,绝不猜一条标上去。
|
||||
if pathname.startswith('/api/conversations/') and pathname.endswith('/important') \
|
||||
and method == 'POST':
|
||||
cid = pathname[len('/api/conversations/'):-len('/important')].strip('/')
|
||||
if cid and '/' not in cid:
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
content = body.get('content')
|
||||
if content is None:
|
||||
self.send_json(400, {'error': '要带上 content(按内容定位那条消息)'})
|
||||
return True
|
||||
want = body.get('important')
|
||||
if want is None:
|
||||
# 不传就取反:界面上是个开关,点一下切一次。
|
||||
# ★ 用**存储里**那条的当前状态取反(不是界面传来的),
|
||||
# 免得界面和服务端状态不一致时越切越乱
|
||||
conv = store.get_conversation(cid) or {}
|
||||
cur = False
|
||||
for m in reversed(conv.get('messages') or []):
|
||||
if str(m.get('content') or '') == str(content):
|
||||
cur = bool(m.get('important'))
|
||||
break
|
||||
want = not cur
|
||||
msg = store.mark_important_by_content(
|
||||
cid, content, str(body.get('role') or ''), bool(want))
|
||||
if msg is None:
|
||||
self.send_json(404, {'error': '没找到这条消息(内容对不上)'})
|
||||
else:
|
||||
self.send_json(200, {'ok': True, 'important': bool(want)})
|
||||
return True
|
||||
|
||||
# 会议模式
|
||||
if pathname == '/api/meetings' and method == 'GET':
|
||||
self.send_json(200, {'meetings': meeting.list_meetings()})
|
||||
@@ -1584,7 +1942,15 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
conversation_id = body.get('conversationId') or 'c_main'
|
||||
text = str(body.get('message') or '').strip()
|
||||
attachments = body.get('attachments') if isinstance(body.get('attachments'), list) else []
|
||||
if not text and not attachments:
|
||||
# ★★ 自动续的那几轮(`autoContinue` / `forceSpeaker`)**本来就没有用户消息** ——
|
||||
# 那是让群里下一个人接着说话,不是用户在打字。
|
||||
#
|
||||
# 不放行的话,每一轮都会被这条校验打回 400,
|
||||
# 用户在界面上看到的是**一屏「出错了:消息为空」**,
|
||||
# 而"两个智能体对话"永远发生不了(真机反馈「还是不能互相对话」,
|
||||
# 现场就是六条这个错误)。
|
||||
auto_continue = bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))
|
||||
if not text and not attachments and not auto_continue:
|
||||
self.send_json(400, {'error': '消息为空'})
|
||||
return
|
||||
|
||||
@@ -1637,9 +2003,10 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
existing = store.get_conversation(conversation_id) or {}
|
||||
history_source = body.get('history') if isinstance(body.get('history'), list) else \
|
||||
existing.get('messages') or []
|
||||
history = [
|
||||
{'role': m.get('role'), 'content': m.get('content')}
|
||||
for m in history_source
|
||||
# ★ 先只做**过滤**,真正的窗口裁剪放到下面(`agent` 解析之后)——
|
||||
# 因为窗口大小是**按智能体配**的(需求 4.3),这里还不知道是谁。
|
||||
raw_history = [
|
||||
m for m in history_source
|
||||
if isinstance(m, dict) and m.get('role') in ('user', 'assistant')
|
||||
]
|
||||
|
||||
@@ -1667,6 +2034,108 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId'))
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
|
||||
# ★★ 群聊的发言权仲裁(需求 v1.2 §3.9)。
|
||||
#
|
||||
# 单聊时这里是**恒等操作**(`resolve` 原样返回传进去的那个人),
|
||||
# 判断收在 `is_group` 里 —— 只有群聊才真去仲裁。
|
||||
#
|
||||
# 三种来源,优先级从高到低:
|
||||
# ① 用户 @ 的人(用户主权)
|
||||
# ② AI 上一轮 `pass_turn` 移交的人(一轮最多一次)
|
||||
# ③ 主智能体兜底 —— **永不冷场**,没人被点名时也有人接话
|
||||
conv0 = store.get_conversation(conversation_id) or {}
|
||||
if group_chat.is_group(conv0):
|
||||
all_agents = store.list_agents()
|
||||
names = [(x['id'], x.get('name') or '') for x in all_agents]
|
||||
# ★★ 用户这一轮 @ 了谁 —— **只看这一条消息**。
|
||||
#
|
||||
# 这个顺序很容易写错:本函数是「先仲裁、后落库」,
|
||||
# 所以 `raw_history` 里**根本没有本次这条用户消息**。
|
||||
# 拿它去找"最后一条 user",找到的是**上一次**用户说的话。
|
||||
#
|
||||
# 踩过两次:
|
||||
# ① 用户打 `@寐眠 在吗` → 按上一条(没点名)仲裁 → 小黑替寐眠答
|
||||
# ② **自动续轮时又从历史回退** → 把上一轮的 `@寐眠` 又拿来用,
|
||||
# 于是 `talk_to` 明明把话交给了别人,仲裁还是给寐眠 ——
|
||||
# 表现是"下回还是 A 说话"(真机反馈)。
|
||||
#
|
||||
# ★ 续轮(`autoContinue`)**本来就没有新用户消息**,
|
||||
# 那一轮该由 `forced` / `passed` / 轮流来定,
|
||||
# 绝不能去翻历史里的 `@` —— 那是上一件事了。
|
||||
want = group_chat.mention_in(text or '', names)
|
||||
pick = group_chat.resolve(
|
||||
conv0,
|
||||
want=want,
|
||||
# ★★ 从**上一轮**的移交状态取,**不是**从 HTTP body ——
|
||||
# 界面(Kotlin)从来不发 handoffTo 这个字段,
|
||||
# 以前读 body 等于永远拿到空串,② AI 移交那条分支是**死代码**。
|
||||
# 现在 pass_turn 写在 tools_runtime 的轮次状态里,这里读它。
|
||||
passed=str(tools_runtime.handoff_state().get('to') or ''),
|
||||
# ★ 界面点「让他们聊」时指定的人(优先级最高)。
|
||||
# 不这样做的话,"两个 AI 对话"就得指望 AI 自己愿意 pass_turn ——
|
||||
# 实测它并不总会,用户按了也没反应。
|
||||
forced=str(body.get('forceSpeaker') or ''),
|
||||
alive={x['id']: not agentdb.is_dead(x['id']) for x in all_agents},
|
||||
)
|
||||
speaker = store.get_agent(pick.get('speaker'))
|
||||
if speaker:
|
||||
agent, agent_id = speaker, speaker.get('id') or ''
|
||||
# 界面据此显示"这一轮谁在说、为什么是他"
|
||||
emit({'type': 'speaker', 'agentId': agent_id,
|
||||
'reason': pick.get('reason') or '', 'note': pick.get('note') or ''})
|
||||
|
||||
# ★★ 对话上下文窗口(需求 v1.2 §4.3)。
|
||||
#
|
||||
# 只把"最近 N 轮 + 用户标了重要的那几条"送进模型。
|
||||
# 超出的**直接丢弃、不做摘要**(需求原话)—— 沉淀走记忆系统,
|
||||
# 不搞第二套摘要管线(摘要自己也要花一次调用,还会丢信息且不可追溯)。
|
||||
#
|
||||
# ★ 命名:这里叫「上下文窗口」,和记忆侧的「记忆注入窗口」不是一回事。
|
||||
# 后者管"塞多少条记忆",超出部分**还能 memory_search 搜到**;
|
||||
# 这里管"送几轮对话",超出就真的不送了。
|
||||
#
|
||||
# ★ `strip_for_model` 是**新建** dict,不原地改历史 ——
|
||||
# 改一个字,从那儿往后的前缀缓存全废(需求 4.3 的"字节冻结")。
|
||||
win_rounds, win_batch = context_window.resolve(settings, agent)
|
||||
window = context_window.trim(raw_history, win_rounds, win_batch)
|
||||
history = [context_window.strip_for_model(m) for m in window['messages']]
|
||||
if window.get('reason'):
|
||||
print(f'[context] {context_window.describe(window)}', file=sys.stderr)
|
||||
|
||||
# ★★ 群聊:给送进模型的每条消息标上**是谁说的**,并过滤私聊消息。
|
||||
#
|
||||
# ① 以前 history 里只有 role/content —— 群里**别人说的话**
|
||||
# 模型根本分不清是谁,只能当成自己说过/用户说过。
|
||||
# 用户的原话:「智能体可以读取群聊所有智能体的对话信息」。
|
||||
# 这里在内容的**前面**加 `[名字] `,只改"送给模型的这份",
|
||||
# 落库的正文保持干净(界面显示不受影响)。
|
||||
#
|
||||
# ② `talk_to` 的私聊模式(`privateTo`):那条消息只有**目标智能体**
|
||||
# 和**用户**看得到,别人(包括模型)都不该有。所以在送进模型之前
|
||||
# 就把"不是给我的私聊"剔掉 —— 在窗口裁剪之后剔除,
|
||||
# 这样裁剪的"轮数"还是按全群算的,不会因为私聊把窗口算歪。
|
||||
_is_group = group_chat.is_group(existing)
|
||||
if _is_group:
|
||||
_name_of = {x['id']: (x.get('name') or '') for x in store.list_agents()}
|
||||
_filtered = []
|
||||
for _m in history:
|
||||
_to = _m.get('privateTo')
|
||||
if isinstance(_to, list) and _to and agent_id not in _to:
|
||||
# 这条是别人之间的私聊 —— 你看不到(用户能看到,那是用户的事)
|
||||
continue
|
||||
_who = ''
|
||||
if _m.get('role') == 'assistant':
|
||||
_who = _name_of.get(str(_m.get('agentId') or ''), '')
|
||||
elif _m.get('role') == 'user':
|
||||
_who = '用户'
|
||||
if _who:
|
||||
_m = dict(_m)
|
||||
_content = _m.get('content')
|
||||
if isinstance(_content, str):
|
||||
_m['content'] = f'[{_who}] {_content}'
|
||||
_filtered.append(_m)
|
||||
history = _filtered
|
||||
|
||||
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
|
||||
#
|
||||
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
|
||||
@@ -1678,7 +2147,13 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
# · 老会话(本次改动之前建的)没有 agentId —— 那种**认领**它,
|
||||
# 而不是也另起一个,否则所有历史会话第一次聊天都会跳走。
|
||||
owner = (existing.get('agentId') or '').strip()
|
||||
if existing and agent_id:
|
||||
# ★★ **群聊不做这个隔离**:群聊本来就是多智能体的,上面
|
||||
# `group_chat.resolve` 刚把 `agent_id` 定成「本轮的发言人」,
|
||||
# 它不是「会话的主人」。照单聊这样比一下,群里每换一个人说话
|
||||
# 就会另起一个会话 —— 用户 @ 谁,界面就跳到谁的对话去
|
||||
# (真机反馈原话:「群聊一@就跑到别的对话去了」)。
|
||||
# `is_group` 既认 `type` 也认 `participants`,老会话也吃得住。
|
||||
if existing and agent_id and not group_chat.is_group(existing):
|
||||
if not owner:
|
||||
store.set_conversation_agent(conversation_id, agent_id)
|
||||
elif owner != agent_id:
|
||||
@@ -1688,6 +2163,23 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
emit({'type': 'rebased', 'conversationId': conversation_id,
|
||||
'reason': 'agent_changed'})
|
||||
|
||||
# ★★ 死亡的智能体**不能对话**(需求 3.5)。
|
||||
#
|
||||
# 判定放在**发起前**,和 Token 限额同一层:不是在生成时才拦
|
||||
# (那时候已经花了钱),而是根本不让这一轮开始。
|
||||
#
|
||||
# 复活只有两条通道,都不在这里:
|
||||
# · 用户手动改(界面上的情绪区,兜底主权)
|
||||
# · 状态脚本改(定时复活/解药剧情,走沙箱)
|
||||
if agent_id and agentdb.is_dead(agent_id):
|
||||
emit({
|
||||
'type': 'error',
|
||||
'code': 'agent_dead',
|
||||
'message': f'「{(agent or {}).get("name") or "这个智能体"}」已经死亡,无法对话。',
|
||||
'hint': '在「记忆 → 情绪」里把它改回其他状态就能复活。',
|
||||
})
|
||||
return
|
||||
|
||||
# ★★ Token 限额:**发起前**拦(需求 3.1)。
|
||||
#
|
||||
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
||||
@@ -1726,19 +2218,57 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
})
|
||||
return
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'user',
|
||||
'content': text or f'(已发送 {len(attachment_meta)} 个附件)',
|
||||
'attachments': attachment_meta,
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
if text:
|
||||
store.auto_title(conversation_id, text)
|
||||
# ★★ `autoContinue`:这一轮是**界面替 AI 自动续的**,不是用户说的话。
|
||||
#
|
||||
# 群聊里 AI 用 `pass_turn` 把话交给另一个人时,界面会接着再发一次
|
||||
# (不带用户消息)—— 这样两个人就能真的聊起来,而不是
|
||||
# "用户说一句、AI 移交一次、然后就没下文了"。
|
||||
#
|
||||
# ★ 不追加用户消息:追加的话对话里会冒出一堆空消息,
|
||||
# 而且模型会以为用户又说话了。移交状态本来就从
|
||||
# `tools_runtime.handoff_state()` 里读(上一轮留下的),
|
||||
# 所以下一轮的发言人自然是接得上的。
|
||||
# ★ 判据必须和 `_handle_chat` 开头那条校验**完全一致**
|
||||
# (`autoContinue` 或 `forceSpeaker`)—— 两处不一致的话,
|
||||
# 一边放行一边往里塞空用户消息,对话里就会冒出一堆空条目。
|
||||
auto_continue = bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))
|
||||
if not auto_continue:
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'user',
|
||||
'content': text or f'(已发送 {len(attachment_meta)} 个附件)',
|
||||
'attachments': attachment_meta,
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
if text:
|
||||
store.auto_title(conversation_id, text)
|
||||
|
||||
# ★★ 自动续轮(`autoContinue`)**不能再追加一条空的 user 消息**。
|
||||
#
|
||||
# 以前不管是不是续轮都拼一条 `{'role':'user','content':user_content}`,
|
||||
# 而续轮没有用户输入 → `user_content` 是空串。
|
||||
# 模型看到的是"用户刚发了一条空消息",于是它自己都懵了 ——
|
||||
# 真机上的原话是:「这条又是空的,我这边没收到内容。猜两种可能:…」
|
||||
# (用户报的「talk_to 没有内容呀」)。
|
||||
#
|
||||
# 而 `talk_to` 说的那句话**就在历史里**(落库了),
|
||||
# 不追加空消息它自然就看到了。
|
||||
msgs_for_model = list(history)
|
||||
if not auto_continue:
|
||||
msgs_for_model.append({'role': 'user', 'content': user_content})
|
||||
else:
|
||||
# 续轮补一句**极短的指令**而不是空消息:模型需要知道
|
||||
# "现在轮到你接话",但不该以为用户说了什么。
|
||||
# 这条**不落库**(只进这一轮给模型的 messages),
|
||||
# 所以用户在聊天记录里看不到它。
|
||||
msgs_for_model.append({
|
||||
'role': 'user',
|
||||
'content': '(系统:现在轮到你接着说,不用等用户输入。直接接着上面的内容回应。)',
|
||||
})
|
||||
|
||||
result = agent_loop.run_agent(
|
||||
settings=settings,
|
||||
agent=agent,
|
||||
messages=[*history, {'role': 'user', 'content': user_content}],
|
||||
messages=msgs_for_model,
|
||||
emit=emit,
|
||||
should_stop=cancelled,
|
||||
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
|
||||
@@ -1769,15 +2299,65 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
int(result.get('toolCalls') or 0),
|
||||
bool((settings.get('tools') or {}).get('python', True)),
|
||||
),
|
||||
# ★ 工具调用明细要落库 —— 不落的话界面上那些"工具卡片"
|
||||
# 只有流式那一刻能看到,**重启 App 就全没了**
|
||||
# (用户报的「工具怎么重启就不显示了」)。
|
||||
'toolTrace': result.get('toolTrace') or [],
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
|
||||
# ★★ 这一轮 AI 用 `pass_turn` 把话交给了别人吗?交了就**告诉界面**。
|
||||
#
|
||||
# 光靠上面那个 `speaker` 事件不够 —— 它是在**轮前**发的,
|
||||
# 而 `pass_turn` 是**轮中**才调用的。于是最常见的那个剧本:
|
||||
# ① 用户没点名(或点名的人不在场)→ 兜底给主智能体,reason = "host"
|
||||
# ② 主智能体说完话,轮中调 `pass_turn` 让给另一个人
|
||||
# 界面看到的 reason 是 "host",以为没人移交,就**不再续轮** ——
|
||||
# 被让的那个人永远开不了口(用户报的"还是不能互相对话")。
|
||||
#
|
||||
# ★ 判据用 `tools_runtime.handoff_state()`(模块级轮次状态),
|
||||
# 不是线程局部变量 —— 工具跑在 worker 线程上,
|
||||
# 这个坑在 `pass_turn` 上已经踩过一次了。
|
||||
hs = tools_runtime.handoff_state()
|
||||
if hs.get('used') and hs.get('to'):
|
||||
emit({'type': 'handoff', 'to': hs['to'],
|
||||
# ★ `talk_to` 一次找多个人时,剩下的人在这里 ——
|
||||
# 界面逐个接下去让他们回应(用户要求"目标智能体挨个回话")
|
||||
'queue': hs.get('queue') or [],
|
||||
'from': agent_id})
|
||||
|
||||
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
|
||||
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
|
||||
if agent_id and (in_tok or out_tok):
|
||||
try:
|
||||
agentdb.token_add(agent_id, model_name, in_tok, out_tok)
|
||||
# ★ v1.2:缓存命中 / 未命中一起落库。
|
||||
# `cache_pair` 已经把三家的字段名归一化过
|
||||
# (DeepSeek 两个都给、Claude/OpenAI 只给命中要自己推);
|
||||
# 两家都没给就是 0/0,界面据此**不显示**那一列。
|
||||
hit, miss = agent_loop.cache_pair(result.get('usage'))
|
||||
agentdb.token_add(agent_id, model_name, in_tok, out_tok, hit, miss)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[usage] 记 Token 用量失败:{exc}', file=sys.stderr)
|
||||
|
||||
# ★ 状态每参与一轮减 1(需求 §3.11)。
|
||||
#
|
||||
# 放在**生成之后**:这一轮它确实开口了,才该扣。
|
||||
# 放在之前的话,被额度拦下、被死亡拦下的那些轮次也会扣 ——
|
||||
# 而它根本没说话。
|
||||
#
|
||||
# 过期要播报("中毒已经消退了")—— 那是个用户能感知的变化。
|
||||
if agent_id:
|
||||
try:
|
||||
for ev in rule_engine.tick_statuses(agent_id):
|
||||
emit({
|
||||
'type': 'status',
|
||||
'name': ev.get('name'),
|
||||
'expired': bool(ev.get('expired')),
|
||||
'remaining': ev.get('remaining', 0),
|
||||
})
|
||||
except Exception as exc: # noqa: BLE001 - 状态系统坏了不该让回复发不出去
|
||||
print(f'[rule] 状态递减失败:{exc}', file=sys.stderr)
|
||||
|
||||
conv = store.get_conversation(conversation_id) or {}
|
||||
emit({'type': 'saved', 'conversationId': conversation_id, 'title': conv.get('title')})
|
||||
except Exception as exc: # noqa: BLE001 - 出错也要以 error 事件收尾,前端才知道停了
|
||||
@@ -1838,6 +2418,12 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
if target and os.path.isfile(target):
|
||||
return self.serve_file(target)
|
||||
|
||||
# 新网页版(web/ 目录)的静态资源:/assets/* /js/* 之类。
|
||||
# 旧 Lynx 宿主页只用 / 和 /static/*,上面几条已经先匹配掉了,这里不会抢路由。
|
||||
web_file = safe_join(p.web_dir, pathname.lstrip('/'))
|
||||
if web_file and os.path.isfile(web_file):
|
||||
return self.serve_file(web_file)
|
||||
|
||||
if pathname in ('/main.web.bundle', '/main.lynx.bundle'):
|
||||
return self.serve_file(os.path.join(p.dist_dir, os.path.basename(pathname)))
|
||||
|
||||
|
||||
230
android/kernel/context_window.py
Normal file
@@ -0,0 +1,230 @@
|
||||
"""对话上下文窗口(需求 v1.2 §4.3)。
|
||||
|
||||
## 命名纪律
|
||||
|
||||
需求里特别强调了一句,照抄过来:
|
||||
|
||||
> 记忆侧叫「**记忆注入窗口**」,对话侧叫「**上下文窗口**」,文档与 UI 永不混用。
|
||||
|
||||
两个东西确实像但完全不同:
|
||||
|
||||
· 记忆注入窗口(§3.2)—— 每轮往 system prompt 里塞**多少条记忆**,
|
||||
超出部分**降级为可检索**(AI 还能 memory_search 找到)
|
||||
· 对话上下文窗口(§4.3)—— 往模型送**最近多少轮对话**,
|
||||
超出部分**直接丢弃、不做摘要**(沉淀走记忆系统,不搞第二套摘要管线)
|
||||
|
||||
混着叫的话,用户问"我调窗口怎么没用"时你都不知道他调的是哪个。
|
||||
|
||||
## 四条规则
|
||||
|
||||
1. **窗口 = 最近 N 轮 + 重要标记消息**(N 默认 20,按智能体配置)
|
||||
2. **重要标记只有用户能打**(AI 有 memory_add,标记是用户主权)。
|
||||
被标记的消息**破格永久携带**,按**原始时间序**插回去 ——
|
||||
不是塞到最前面:那会打乱因果,模型会看到"先发生的事在后面"。
|
||||
3. **成批对齐裁剪**:不是"超一点就裁一点",而是攒够一批才裁一批。
|
||||
目的是**摊薄前缀缓存失效次数** —— 每轮都裁的话,前缀每轮都变,
|
||||
上下文缓存一次都命中不了,比不裁还贵。
|
||||
4. **字节冻结**:送进去的历史消息**永不原地修改**。
|
||||
改一个字,从那个字往后的前缀缓存全废。
|
||||
|
||||
## 为什么"直接丢弃、不做摘要"
|
||||
|
||||
需求原话。看起来粗暴,但想清楚了:
|
||||
|
||||
· 摘要本身要花一次 LLM 调用(比省下的那点 token 还贵)
|
||||
· 而且摘要会**丢信息且不可追溯** —— 用户翻到三个月前那句话还在界面上,
|
||||
但模型完全不知道,他会以为 AI"忘了"是 bug
|
||||
· 该记住的东西本来就该走 `memory_add` 进记忆系统(那里有检索、有署名、
|
||||
有置顶,是**为长期记忆设计的**)。两套摘要管线只会互相打架。
|
||||
"""
|
||||
import os
|
||||
|
||||
#: 默认窗口(轮)。需求定的 20。
|
||||
DEFAULT_ROUNDS = 20
|
||||
|
||||
#: 默认裁剪批量(轮)。需求定的 5。
|
||||
DEFAULT_BATCH = 5
|
||||
|
||||
#: 窗口上限/下限(用户填什么都不至于把上下文搞爆或搞没)
|
||||
MIN_ROUNDS = 4
|
||||
MAX_ROUNDS = 200
|
||||
|
||||
|
||||
def resolve(settings: dict, agent: dict = None) -> tuple:
|
||||
"""
|
||||
算出这次该用多少:**智能体配置 > 全局设置 > 默认**(返回 `(轮数, 批量)`)。
|
||||
|
||||
★ 和 provider_info / voice_for 一个套路:智能体可以单独配,
|
||||
没配就继承全局。三处规则长得一样,但**不能合并**(数据来源不同)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
settings = settings or {}
|
||||
|
||||
def pick(key, default, lo, hi):
|
||||
for src in (agent.get(key), settings.get(key)):
|
||||
try:
|
||||
v = int(float(src))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if v > 0:
|
||||
return max(lo, min(hi, v))
|
||||
return default
|
||||
|
||||
rounds = pick('contextWindow', DEFAULT_ROUNDS, MIN_ROUNDS, MAX_ROUNDS)
|
||||
batch = pick('contextBatch', DEFAULT_BATCH, 1, 50)
|
||||
return rounds, batch
|
||||
|
||||
|
||||
def split_rounds(messages: list) -> list:
|
||||
"""
|
||||
把消息流切成"轮"。
|
||||
|
||||
★ 一轮 = 从一条 user 到**下一条 user 之前**(含它后面的 assistant 和
|
||||
任何工具痕迹)。不用"user/assistant 配对"来切,是因为:
|
||||
· 工具调用会产生 assistant → tool → assistant 这种多段结构
|
||||
· 界面上用户也可能连发两条
|
||||
按 user 划线对这两种都稳,而且**永远不会切出半轮**(需求要求
|
||||
"按完整轮对齐,不裁半轮")。
|
||||
"""
|
||||
groups = []
|
||||
cur = []
|
||||
for m in messages or []:
|
||||
if not isinstance(m, dict):
|
||||
continue
|
||||
if m.get('role') == 'user' and cur:
|
||||
groups.append(cur)
|
||||
cur = []
|
||||
cur.append(m)
|
||||
if cur:
|
||||
groups.append(cur)
|
||||
return groups
|
||||
|
||||
|
||||
def _indexed_rounds(msgs: list) -> list:
|
||||
"""
|
||||
和 `split_rounds` 一样切轮,但**每条带原始下标** `[(i, msg)]`。
|
||||
|
||||
★ 为什么需要下标:被裁掉的那批里如果有"用户标了重要"的消息,
|
||||
得把它**按原始时间序插回**去 —— 没有下标就只能塞最前面,
|
||||
而那会打乱因果(模型会看到"先发生的事在后面")。
|
||||
"""
|
||||
groups = []
|
||||
cur = []
|
||||
for i, m in enumerate(msgs):
|
||||
if m.get('role') == 'user' and cur:
|
||||
groups.append(cur)
|
||||
cur = []
|
||||
cur.append((i, m))
|
||||
if cur:
|
||||
groups.append(cur)
|
||||
return groups
|
||||
|
||||
|
||||
def trim(messages: list, rounds: int, batch: int = DEFAULT_BATCH) -> dict:
|
||||
"""
|
||||
按窗口裁历史,返回一份**报告**:
|
||||
|
||||
{
|
||||
'messages': 送进模型的那一串(裁过的,或原样),
|
||||
'kept': 保留几条,
|
||||
'dropped': 丢了几条,
|
||||
'reason': '' | 'window' | 'within_batch',
|
||||
'rounds': 总轮数, 'keptRounds': 保留几轮,
|
||||
}
|
||||
|
||||
★ 返回报告而不是只返回列表:调用方要能把这几个数**写给界面**
|
||||
("这次带了 18 轮进来"),也是探针唯一能断言的抓手。
|
||||
"""
|
||||
msgs = [m for m in (messages or []) if isinstance(m, dict)]
|
||||
total = len(msgs)
|
||||
groups = _indexed_rounds(msgs)
|
||||
|
||||
keep_all = {
|
||||
'messages': msgs, 'kept': total, 'dropped': 0, 'reason': '',
|
||||
'rounds': len(groups), 'keptRounds': len(groups),
|
||||
}
|
||||
if rounds <= 0 or len(groups) <= rounds:
|
||||
return keep_all
|
||||
|
||||
extra = len(groups) - rounds
|
||||
# ★ 成批对齐:超出量不到一批就先忍着。
|
||||
# 代价是"实际保留的比窗口多几轮",换来的是**前缀缓存能连续命中**。
|
||||
# 每轮都裁的话前缀每轮都变,缓存一次都命中不了 —— 那比多带几轮贵得多。
|
||||
if extra < batch:
|
||||
out = dict(keep_all)
|
||||
out['reason'] = 'within_batch'
|
||||
out['rounds'] = len(groups)
|
||||
return out
|
||||
|
||||
cut = (extra // batch) * batch
|
||||
kept_idx = [pair for g in groups[cut:] for pair in g]
|
||||
dropped_idx = [pair for g in groups[:cut] for pair in g]
|
||||
|
||||
# ★ 重要标记**破格永久携带**(需求 4.3):从被裁的那批里捞回来
|
||||
important = [pair for pair in dropped_idx if pair[1].get('important')]
|
||||
|
||||
merged = sorted(kept_idx + important, key=lambda p: p[0])
|
||||
out_msgs = [m for _, m in merged]
|
||||
return {
|
||||
'messages': out_msgs,
|
||||
'kept': len(out_msgs),
|
||||
'dropped': total - len(out_msgs),
|
||||
'reason': 'window',
|
||||
'rounds': len(groups),
|
||||
'keptRounds': len(groups) - cut,
|
||||
'rescued': len(important),
|
||||
}
|
||||
|
||||
|
||||
def describe(report: dict) -> str:
|
||||
"""给界面/日志的一行话(不要让它各处自己拼)"""
|
||||
r = report or {}
|
||||
total = r.get('rounds') or 0
|
||||
if not r.get('reason'):
|
||||
return f'{total} 轮全部带上'
|
||||
if r.get('reason') == 'within_batch':
|
||||
return f'{total} 轮(超出窗口但没攒够一批,先不动)'
|
||||
bits = [f'带了最近 {r.get("keptRounds")} 轮(共 {total} 轮)']
|
||||
if r.get('rescued'):
|
||||
bits.append(f'其中 {r["rescued"]} 条是你标了重要的')
|
||||
if r.get('dropped'):
|
||||
bits.append(f'另有 {r["dropped"]} 条较早的没带进来')
|
||||
return ','.join(bits)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 重要标记(需求 4.3:**只有用户能打**)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def is_important(msg: dict) -> bool:
|
||||
return bool((msg or {}).get('important'))
|
||||
|
||||
|
||||
def can_mark(role: str) -> bool:
|
||||
"""
|
||||
谁能打这个标记。**只有界面(用户)** —— AI 没有这个工具(需求原话
|
||||
"AI 有 memory_add,标记是用户主权")。
|
||||
|
||||
★ 这个函数存在的意义是"写下来":将来有人想给 AI 加个 mark_important
|
||||
工具时,会先看到这里写着为什么不行。
|
||||
"""
|
||||
return role == 'user'
|
||||
|
||||
|
||||
def strip_for_model(msg: dict) -> dict:
|
||||
"""
|
||||
把一条消息变成**送进模型的样子**:只留 role / content。
|
||||
|
||||
★★ 顺带就是"字节冻结"的落点:**永远新建一个 dict,绝不原地改** ——
|
||||
原地改(哪怕只是删掉一个 `important` 字段)会让那一条的字节变化,
|
||||
而从它往后的前缀缓存全部失效。需求 4.3 把这条写成"内核纪律"。
|
||||
"""
|
||||
m = msg or {}
|
||||
return {'role': m.get('role'), 'content': m.get('content')}
|
||||
|
||||
|
||||
__all__ = [
|
||||
'DEFAULT_ROUNDS', 'DEFAULT_BATCH', 'MIN_ROUNDS', 'MAX_ROUNDS',
|
||||
'resolve', 'split_rounds', 'trim', 'describe', 'is_important',
|
||||
'can_mark', 'strip_for_model',
|
||||
]
|
||||
@@ -175,6 +175,20 @@ DEFAULT_SETTINGS = {
|
||||
# 被裁掉的没丢,AI 还能用 memory_search 检索到("降级为仅可检索")。
|
||||
# 0 = 不限(退回全量注入)。
|
||||
'memoryWindow': 50,
|
||||
# 背景(立绘 + 背景图)**跟随当前说话者**(v1.2 §6.1,默认开)。
|
||||
#
|
||||
# ★ 群聊里才有区别:关掉时展示区一直用**主智能体**的立绘,
|
||||
# 打开时谁发言就换成谁的 —— 后者能让用户一眼看出"这句是谁说的",
|
||||
# 所以默认开。做成开关是因为**有人就是想要固定的主视觉**。
|
||||
# ★ 单聊时这个开关没有任何效果(说话者永远是同一个人),
|
||||
# 但设置项不隐藏 —— 隐藏的开关比没用的开关更让人困惑。
|
||||
'followSpeaker': True,
|
||||
# 对话上下文窗口(轮,v1.2 §4.3):每轮最多带最近多少轮对话。
|
||||
# 攒够 `contextBatch` 轮才裁一次(摊薄前缀缓存失效),见 context_window。
|
||||
'contextWindow': 20,
|
||||
'contextBatch': 5,
|
||||
# 私聊(幕后对聊)最多几轮,v1.2 §3.9。一轮 = 双方各说一次。
|
||||
'privateChatRounds': 10,
|
||||
'provider': 'ark',
|
||||
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
||||
@@ -255,13 +269,54 @@ BUILTIN_SKILL = '\n'.join([
|
||||
' 情绪要跟着对话内容自然变化;别每轮都改,也别一直用同一个词。',
|
||||
'',
|
||||
'【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。',
|
||||
'',
|
||||
# ★★ 群聊的用法(用户反馈「智能体好像不怎么会用」)。
|
||||
#
|
||||
# 工具描述只讲"怎么调",而模型最容易错的是"**什么时候该用哪个**" ——
|
||||
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
|
||||
# 于是对方接到一片空白,两个人永远聊不起来。这段就是纠这个。
|
||||
'【群聊】你可能在一个群里(群里有别人)。',
|
||||
'· 你能**看到群里所有人的发言**(送进上下文的每条都有 `[名字]` 前缀,'
|
||||
'「[用户]」是你对面那个人说的)。别把别人说的话当成自己说过。',
|
||||
'· 想**主动对某个智能体说一句具体的话**:用 talk_to(agent=他的名字, content=你要说的话)。',
|
||||
' 那句话会真的写进对话,他下一轮看得到、会回应你 —— 这是你和别人**来回聊**的唯一办法。',
|
||||
'· 一次想找**好几个人**:talk_to(agents=["甲","乙"], content=...),他们会**挨个**回应。',
|
||||
'· 想**私下**跟某人说(只有他知道、群里其他 AI 看不到):加 `private=true`。'
|
||||
' 用户还是看得到(他是观察者)—— 所以别以为私聊就可以说见不得人的话。',
|
||||
'· **不要**拿 pass_turn 当"跟他说话":它只交发言权、不带内容,',
|
||||
' 对方接到的是一片空白,只能凭上下文猜(所以那样聊不起来)。',
|
||||
' pass_turn 只在"我没什么可说了,换你"的时候用。',
|
||||
'· 一轮最多一次:talk_to 和 pass_turn 二选一,别两个都调。',
|
||||
'· 单聊里没有"别人",talk_to 会报错 —— 想跟某个人单独聊,让用户去建群或者私聊。',
|
||||
'· 别为了"显得在忙"反复调 talk_to:一轮一次,说人话就行。',
|
||||
])
|
||||
|
||||
# system prompt 的注入模板(需求附录 C)。
|
||||
# system prompt 的注入模板(需求附录 C,v1.2 修订了段序)。
|
||||
#
|
||||
# 顺序是**固定**的:人设 → skills → worldview → emotion → memory → peer_emotions。
|
||||
# 可以整段替换(存全局设置 promptTemplate),但占位符名字别改 ——
|
||||
# agent_context.py 就是按这些名字找段落、空段整段删掉的。
|
||||
# ★★ **缓存友好排序**(附录 C 的 v1.2 修订):
|
||||
#
|
||||
# 主流模型的上下文缓存都是**前缀匹配** —— 从第一个 token 开始逐段比对,
|
||||
# 一旦有一处不同,**那之后的所有内容全部失效**(要么重算、要么按未命中计费)。
|
||||
#
|
||||
# 所以段序要按**稳定性**排:最稳的在前、最易变的在最后。
|
||||
#
|
||||
# 稳 → {prompt} 几乎不变(用户很少改人设)
|
||||
# <skills> 很少变
|
||||
# <worldview> 很少变
|
||||
# <memory> 偶尔加几条
|
||||
# ────────────────────────────────────── 上面是长前缀,尽量保持命中
|
||||
# <stats> 数值一变就变
|
||||
# <status> 每轮都可能变(轮数在减)
|
||||
# <emotion> 情绪一变就变
|
||||
# <peer_emotions> 别人的情绪,最不可控
|
||||
# 变 →
|
||||
#
|
||||
# 改之前 emotion 在 memory **前面** —— 情绪一变,后面整段(含最长的 memory)
|
||||
# 缓存全废。挪到最后之后,情绪变化只让最后那两个短段失效。
|
||||
#
|
||||
# 这是这个文件里性价比最高的一处改动:不改任何功能,只改顺序。
|
||||
#
|
||||
# 占位符名字别改 —— agent_context.py 就是按这些名字找段落、空段整段删掉的。
|
||||
DEFAULT_PROMPT_TEMPLATE = '\n'.join([
|
||||
'{prompt}',
|
||||
'',
|
||||
@@ -273,14 +328,23 @@ DEFAULT_PROMPT_TEMPLATE = '\n'.join([
|
||||
'{worldview}',
|
||||
'</worldview>',
|
||||
'',
|
||||
'<emotion>',
|
||||
'{emotion}',
|
||||
'</emotion>',
|
||||
'',
|
||||
'<memory>',
|
||||
'{memory}',
|
||||
'</memory>',
|
||||
'',
|
||||
# ---- 以下是易变段,放最后 ----
|
||||
'<stats>',
|
||||
'{stats}',
|
||||
'</stats>',
|
||||
'',
|
||||
'<status>',
|
||||
'{status}',
|
||||
'</status>',
|
||||
'',
|
||||
'<emotion>',
|
||||
'{emotion}',
|
||||
'</emotion>',
|
||||
'',
|
||||
'<peer_emotions>',
|
||||
'{peer_emotions}',
|
||||
'</peer_emotions>',
|
||||
|
||||
270
android/kernel/group_chat.py
Normal file
@@ -0,0 +1,270 @@
|
||||
"""群聊的发言权仲裁(需求 v1.2 §3.9)。
|
||||
|
||||
## 点名制
|
||||
|
||||
需求原话:
|
||||
|
||||
> **发言权仲裁:点名制**。被 @ 者发言;AI 可通过 `pass_turn` 指定下一位
|
||||
> 发言者,**一轮最多一次移交**;无人被点名时由主智能体(会话发起者)兜底,
|
||||
> **永不冷场**。
|
||||
|
||||
翻译成优先级(从高到低):
|
||||
|
||||
① 用户 @ 的人 用户主权,最高
|
||||
② AI 上一轮 pass_turn 的人 一轮最多一次
|
||||
③ 主智能体(participants[0])兜底,永不冷场
|
||||
|
||||
## 死亡的人不能接
|
||||
|
||||
> 死亡智能体被点名时移交无效,换下一个人接。
|
||||
|
||||
这条单独写出来,是因为"移交无效"有三种可能的处置:
|
||||
报错、随机选一个、回主智能体 —— 需求选了第三种。
|
||||
**回主智能体**也对:它会接着把话头圆下去,用户不会看到"没人应"。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
仲裁是**纯逻辑**(给一群人和几个标记,返回谁说话),没有 IO。
|
||||
放在 `app.py` 的对话循环里就没法逐条测 —— 而它的分支(点名/移交/
|
||||
兜底/死亡/不在场)有五种,正是最该测的那种。
|
||||
"""
|
||||
|
||||
#: 一轮最多移交一次。需求明文,所以做成一个常量而不是散在代码里的布尔。
|
||||
MAX_HANDOFF_PER_ROUND = 1
|
||||
|
||||
import store # noqa: E402 —— 加成员时要查世界观(只读,不参与仲裁)
|
||||
|
||||
|
||||
def member_ids(conv: dict) -> list:
|
||||
"""群聊的成员 id 列表(顺序就是加入顺序,**第 0 个是主智能体**)"""
|
||||
conv = conv or {}
|
||||
ids = conv.get('participants')
|
||||
if not isinstance(ids, list):
|
||||
return []
|
||||
return [str(x) for x in ids if str(x or '').strip()]
|
||||
|
||||
|
||||
def is_group(conv: dict) -> bool:
|
||||
return (conv or {}).get('type') == 'group'
|
||||
|
||||
|
||||
def host_id(conv: dict) -> str:
|
||||
"""
|
||||
⚠️ **不再用于"决定谁发言"** —— 用户明确要求「群聊去掉主人设定」。
|
||||
|
||||
它现在只剩一个用途:`remove_member` 里判断"不能把最后一个人踢走"。
|
||||
决定发言的那条路走 [rotate_next](轮流),不再有"老大"。
|
||||
"""
|
||||
ids = member_ids(conv)
|
||||
return ids[0] if ids else (conv or {}).get('agentId') or ''
|
||||
|
||||
|
||||
def rotate_next(conv: dict, ids: list = None) -> str:
|
||||
"""
|
||||
没人被点名时该谁说 —— **按成员顺序轮**,不设主人。
|
||||
|
||||
★★ 用户原话:「群聊去掉主人设定」。
|
||||
|
||||
原来兜底永远是"会话发起者"(成员列表第一个)——
|
||||
那等于群里有个老大:其他人不 @ 就不开口,@ 了才有台词。
|
||||
现在看**最近一条 AI 消息是谁说的**,下一个人接上,谁都不欠谁。
|
||||
|
||||
★ 找不到上一条(新群、或者老消息没有 agentId)就从第一个开始。
|
||||
"""
|
||||
ids = list(ids if ids is not None else member_ids(conv))
|
||||
if not ids:
|
||||
return ''
|
||||
last = ''
|
||||
for m in reversed((conv or {}).get('messages') or []):
|
||||
if m.get('role') != 'assistant':
|
||||
continue
|
||||
aid = str(m.get('agentId') or '')
|
||||
if aid in ids:
|
||||
last = aid
|
||||
break
|
||||
if not last:
|
||||
return ids[0]
|
||||
return ids[(ids.index(last) + 1) % len(ids)]
|
||||
|
||||
|
||||
def mention_in(text: str, names: list) -> str:
|
||||
"""
|
||||
从用户输入里找出被 @ 的人(返回 id,没有就空串)。
|
||||
|
||||
★ 按**名字**匹配而不是 id:界面上的"成员快捷条"插进去的就是 `@玄辰`
|
||||
(用户看到的是名字)。重名时取**最长的那个**匹配 ——
|
||||
有"玄辰"和"玄辰二号"时,输入 `@玄辰二号` 不该命中"玄辰"。
|
||||
"""
|
||||
t = str(text or '')
|
||||
hit = ''
|
||||
best = ''
|
||||
for aid, name in (names or []):
|
||||
n = str(name or '').strip()
|
||||
if not n or f'@{n}' not in t:
|
||||
continue
|
||||
if len(n) > len(best):
|
||||
best, hit = n, aid
|
||||
return hit
|
||||
|
||||
|
||||
def resolve(conv: dict, want: str = '', passed: str = '',
|
||||
alive: dict = None, handoffs: int = 0, forced: str = '') -> dict:
|
||||
"""
|
||||
决定这一轮谁发言。
|
||||
|
||||
[want] 用户 @ 出来的人(`mention_in` 的结果)
|
||||
[passed] AI 上一轮 `pass_turn` 指定的人
|
||||
[alive] `{agent_id: bool}`,缺省视为活着
|
||||
[handoffs] 这一轮已经移交过几次(用于"一轮最多一次")
|
||||
[forced] 界面点「让他们聊」时**指定**的发言者,优先级最高
|
||||
|
||||
返回 `{'speaker': id, 'reason': 'mention'|'handoff'|'rotate'|'handoff_denied'|'forced', 'note': ''}`。
|
||||
|
||||
★★ 为什么要有 [forced](真机反馈「还是不能互相对话」):
|
||||
下面三条路都要求**用户点名**或者**AI 自己愿意移交**。
|
||||
实测下来 AI 并不总会调 `pass_turn` —— 它更愿意自己把话说完,
|
||||
于是"两个智能体对话"这件事就永远发生不了。
|
||||
用户要的是一个**明确能按下去的入口**:点「让他们聊」,
|
||||
界面就一轮一轮地把发言权在两个人之间递过去,不需要 AI 配合。
|
||||
这是唯一能保证"一定聊得起来"的做法。
|
||||
"""
|
||||
conv = conv or {}
|
||||
alive = alive or {}
|
||||
ids = member_ids(conv)
|
||||
# ★ 兜底**不再是主人**,是轮流(用户要求「群聊去掉主人设定」)
|
||||
nxt = rotate_next(conv, ids)
|
||||
|
||||
def ok(aid: str) -> bool:
|
||||
return bool(aid) and aid in ids and alive.get(aid, True)
|
||||
|
||||
# ① 用户 @ 的人 —— **压过 forced**。
|
||||
#
|
||||
# ★★ 顺序不能反(真机反馈:「@ 的时候立即切换」「对话时没上下文」)。
|
||||
# 现场是这样的:用户点了「让他们聊」,那几轮还在跑;
|
||||
# 这时用户打了一句 `@寐眠 别` —— 界面那一轮仍然带着 `forceSpeaker`
|
||||
# (正轮到小黑),于是**小黑替寐眠答了**。
|
||||
# 用户看到的是"我明明 @ 了他,回答的却是别人",感受上就是"没上下文"。
|
||||
#
|
||||
# 用户的手是最后发言权:他一旦点名,自动对聊必须让位。
|
||||
# (界面那边也会在用户发消息时把自动对聊直接掐掉,这里是第二道。)
|
||||
if want:
|
||||
if ok(want):
|
||||
return {'speaker': want, 'reason': 'mention', 'note': ''}
|
||||
# 被 @ 的人死了或不在场:回主智能体,而不是报错
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': '被点的人不在场或已死亡,换下一个人接'}
|
||||
|
||||
# ② 界面指定的(「让他们聊」)—— 用户没点名时才轮到它
|
||||
#
|
||||
# 它只出现在界面的自动续轮里;用户手打消息时不会带上。
|
||||
if forced:
|
||||
if ok(forced):
|
||||
return {'speaker': forced, 'reason': 'forced', 'note': ''}
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': '指定的人不在场或已死亡,换下一个人接'}
|
||||
|
||||
# ③ AI 的移交(一轮最多一次)
|
||||
if passed:
|
||||
if handoffs >= MAX_HANDOFF_PER_ROUND:
|
||||
return {'speaker': nxt, 'reason': 'handoff_denied',
|
||||
'note': '这一轮已经移交过了,不再移交'}
|
||||
if ok(passed):
|
||||
return {'speaker': passed, 'reason': 'handoff', 'note': ''}
|
||||
# ★ 死亡的人被点名时**移交无效**,换下一个人接(需求明文)
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': f'「{passed}」已死亡或不在场,移交无效,换下一个人接'}
|
||||
|
||||
# ③ 兜底:永不冷场
|
||||
return {'speaker': nxt, 'reason': 'rotate', 'note': ''}
|
||||
|
||||
|
||||
def add_member(conv: dict, agent_id: str) -> bool:
|
||||
"""
|
||||
加一个成员(用户手动增删基本无条件 —— 用户主权)。
|
||||
|
||||
★ 加完**自动升级成 group**:成员超过一个时 `type` 必须是 `group`,
|
||||
不然成员列表里有人、仲裁逻辑还按单聊跑 ——
|
||||
表现是"我把人拉进来了,但他从来不说话"。
|
||||
这条收在这里而不是让调用方自己补,是因为"忘记补"的代价不对称:
|
||||
补错了只是类型不对,忘补了就是功能整个不生效。
|
||||
|
||||
★ 单聊要拉人 → 那个会话**就地转成群聊**,而不是偷偷往
|
||||
`participants` 里塞一个 id 却把 `type` 留着。
|
||||
|
||||
★★ **只能拉同世界观的**(用户确认过这条规则)。
|
||||
理由不是洁癖:群聊的上下文里有 `<worldview>` 段,视野不同的两个人
|
||||
看到的是两套设定 —— 同一个群里会出现"这是哪、我们是谁"对不上的情况,
|
||||
而且记忆空间也是按世界观分的(共享记忆会串)。
|
||||
判定以**群主**(`agentId`)的世界观为准;空对空(都没绑)也算同。
|
||||
"""
|
||||
c = conv or {}
|
||||
aid = str(agent_id or '').strip()
|
||||
if not aid:
|
||||
return False
|
||||
ids = member_ids(c)
|
||||
if aid in ids:
|
||||
return False
|
||||
|
||||
# ★ 世界观一致才让进 —— 但**未绑世界观的放行**。
|
||||
#
|
||||
# 未绑 = 这个智能体没有世界观设定,和谁都合得来,拉进来不会串。
|
||||
# 一开始我写成"必须相等",于是没绑世界观的智能体也进不来 ——
|
||||
# 用户报的「还是加不了人」,其中那个"黑化豆包"就是未绑的。
|
||||
target = store.get_agent(aid) or {}
|
||||
if target:
|
||||
mine = (store.get_agent(str(c.get('agentId') or '')) or {}).get('worldviewId') or ''
|
||||
theirs = target.get('worldviewId') or ''
|
||||
if theirs and theirs != mine:
|
||||
return False
|
||||
|
||||
ids.append(aid)
|
||||
c['participants'] = ids
|
||||
if len(ids) > 1 and (c.get('type') or 'single') != 'group':
|
||||
c['type'] = 'group'
|
||||
return True
|
||||
|
||||
|
||||
def remove_member(conv: dict, agent_id: str) -> bool:
|
||||
"""
|
||||
移出一个成员。
|
||||
|
||||
★★ **谁都能移出** —— 用户要求「群聊去掉主人设定」之后,
|
||||
"主智能体不能移出"这条就失去了依据:群里已经没有"主人"这回事了,
|
||||
没人被 @ 时按顺序轮(`rotate_next`)。
|
||||
以前这里还留着 `aid == host_id(c)` 的拦截,于是**第一个进群的人删不掉**
|
||||
—— 界面上「移出」按钮人人都有,点了却没反应(真机反馈"群聊删不了人")。
|
||||
|
||||
★ 唯一的拒绝条件:**不能删到一个人都不剩**(空群没法开会话)。
|
||||
删到剩 1 个是允许的 —— 那时退化成单聊,`type` 要跟着改回去,
|
||||
不然界面还按群聊渲染、仲裁还按群聊跑,而群里只剩一个人。
|
||||
"""
|
||||
c = conv or {}
|
||||
aid = str(agent_id or '').strip()
|
||||
ids = member_ids(c)
|
||||
if aid not in ids or len(ids) <= 1:
|
||||
return False
|
||||
ids.remove(aid)
|
||||
c['participants'] = ids
|
||||
if len(ids) <= 1:
|
||||
# 只剩一个人 → 退回单聊,并把对话主人设成他
|
||||
c['type'] = 'single'
|
||||
c['agentId'] = ids[0] if ids else ''
|
||||
return True
|
||||
|
||||
|
||||
def promote(conv: dict, agent_id: str) -> None:
|
||||
"""把单聊转成群聊(拉第二个人进来时用)"""
|
||||
c = conv or {}
|
||||
if c.get('type') != 'group':
|
||||
first = (c.get('agentId') or '').strip()
|
||||
c['type'] = 'group'
|
||||
c['participants'] = [x for x in [first] if x]
|
||||
add_member(c, agent_id)
|
||||
|
||||
|
||||
def describe(conv: dict) -> str:
|
||||
"""给界面/日志的一行话(不要各处自己拼)"""
|
||||
c = conv or {}
|
||||
n = len(member_ids(c))
|
||||
kind = {'group': '群聊', 'private': '私聊记录'}.get(c.get('type') or '', '单聊')
|
||||
return f'{kind}({n} 人)' if n > 1 else kind
|
||||
@@ -150,6 +150,44 @@ def start_kernel(
|
||||
return handle
|
||||
|
||||
|
||||
def register_desktop_hooks(bridge_url: str) -> None:
|
||||
"""
|
||||
桌面(Electron)版把原生能力委托给主进程:选文件、写剪贴板、在资源管理器里显示。
|
||||
|
||||
为什么要绕一道 HTTP:内核是 Electron 起的**子进程**,Python 里没有 Electron 的
|
||||
dialog/clipboard。安卓侧是 Kotlin 直接调 `app.set_native_hooks(...)`(见 doubao_entry.py),
|
||||
桌面侧就由主进程开一个只监听 127.0.0.1 的小桥(desktop/main.cjs),Python 通过 HTTP 调它。
|
||||
这样内核代码两边共用一份,不用为桌面另写一套。
|
||||
"""
|
||||
import urllib.request
|
||||
|
||||
def _call(path: str, payload: dict | None = None):
|
||||
data = json.dumps(payload or {}).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
bridge_url.rstrip('/') + path,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310 - 只连本机主进程
|
||||
return json.loads(resp.read().decode('utf-8') or '{}')
|
||||
|
||||
def _clipboard(text: str):
|
||||
_call('/clipboard', {'text': text})
|
||||
|
||||
def _pick_file():
|
||||
return list(_call('/pick-file').get('paths') or [])
|
||||
|
||||
def _reveal(target: str):
|
||||
# 约定:成功返回 None,失败返回一句人话(app.py 直接把它回给界面)
|
||||
try:
|
||||
result = _call('/reveal', {'path': target})
|
||||
except Exception as exc: # noqa: BLE001 - 桥挂了也要给人话,不能让接口 500
|
||||
return f'打开文件夹失败:{exc}'
|
||||
return None if result.get('ok') else str(result.get('error') or '打开文件夹失败')
|
||||
|
||||
app.set_native_hooks(clipboard=_clipboard, pick_file=_pick_file, reveal=_reveal)
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog='doubao-kernel',
|
||||
@@ -169,6 +207,8 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
parser.add_argument('--dist-dir', default=None, help='Lynx 产物目录(默认 app/dist)')
|
||||
parser.add_argument('--web-core', default=None, help='@lynx-js/web-core 静态资源目录')
|
||||
parser.add_argument('--no-mcp-autostart', action='store_true', help='启动时不自动连 MCP 服务器')
|
||||
parser.add_argument('--desktop-bridge', default=None,
|
||||
help='桌面版原生能力桥(http://127.0.0.1:<port>),由 Electron 主进程提供')
|
||||
parser.add_argument('--quiet', action='store_true', help='不打印访问日志和启动横幅')
|
||||
parser.add_argument('--json', action='store_true', help='启动后打印一行 JSON(含真实端口),便于脚本拉起')
|
||||
return parser
|
||||
@@ -191,6 +231,13 @@ def main(argv=None) -> int:
|
||||
if args.json:
|
||||
print(json.dumps(handle.as_dict(), ensure_ascii=False), flush=True)
|
||||
|
||||
# 桌面版:把选文件/剪贴板/打开文件夹委托给 Electron 主进程(安卓不走这里)
|
||||
if args.desktop_bridge:
|
||||
try:
|
||||
register_desktop_hooks(args.desktop_bridge)
|
||||
except Exception as exc: # noqa: BLE001 - 桥连不上不该让内核起不来
|
||||
print(f'[kernel] 桌面能力桥注册失败:{exc}', file=sys.stderr)
|
||||
|
||||
stop = threading.Event()
|
||||
|
||||
def _on_signal(signum, _frame): # noqa: ANN001 - 信号回调签名固定
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
运行期路径与平台判断。
|
||||
|
||||
为什么单独一个模块:
|
||||
@@ -95,6 +95,12 @@ class Paths:
|
||||
self.worldviews_file = os.path.join(self.data_dir, 'worldviews.json')
|
||||
self.models_file = os.path.join(self.data_dir, 'models.json')
|
||||
self.skills_file = os.path.join(self.data_dir, 'skills.json')
|
||||
# 数值状态包(需求附录 D):定义 + 对应的 Python 脚本源码。
|
||||
# 量级小、而且用户会想看自己写了什么 → 还是 JSON
|
||||
self.rulepacks_file = os.path.join(self.data_dir, 'rulepacks.json')
|
||||
# 规则脚本**落盘**的位置:脚本要作为文件被 exec 起来,
|
||||
# 所以从包里解出来之后得写到磁盘上(不能只存在 JSON 里)
|
||||
self.rule_scripts_dir = os.path.join(self.data_dir, 'rule-scripts')
|
||||
# 智能体系统的 SQLite(记忆 / 情绪 / Token / 绑定关系)
|
||||
self.agent_db_file = os.path.join(self.data_dir, 'agent.db')
|
||||
# 智能体包解出来的图片等资源(导入 zip 时落到这儿)
|
||||
@@ -116,7 +122,7 @@ class Paths:
|
||||
|
||||
def ensure_dirs(self) -> None:
|
||||
for folder in (self.data_dir, self.uploads_dir, self.tmp_dir, self.screens_dir,
|
||||
self.notes_dir, self.agent_assets_dir):
|
||||
self.notes_dir, self.agent_assets_dir, self.rule_scripts_dir):
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死
|
||||
|
||||
249
android/kernel/private_chat.py
Normal file
@@ -0,0 +1,249 @@
|
||||
"""私聊:两个智能体在后台自主对聊(需求 v1.2 §3.9 形态 B)。
|
||||
|
||||
## 需求原文
|
||||
|
||||
> **形态 B · 私聊(幕后制)**:两个智能体在后台自主对聊,用户不在场。
|
||||
>
|
||||
> - **安全网**:默认最多 10 轮交替发言(可配),到顶强制收尾;
|
||||
> 一方 Token 触顶则另一方单方面收尾后立即结束,**不撑独角戏**。
|
||||
> - 结束后生成摘要写入共享记忆(复用总结管线),完整记录可翻看。
|
||||
> - Token 消耗按各自发言分别计入各智能体统计、分别受各自限额约束。
|
||||
|
||||
## 三个必须想清楚的点
|
||||
|
||||
**① "安全网"防的是什么**
|
||||
|
||||
两个 AI 互相对话最大的风险是**停不下来**:A 说一句、B 接一句、A 再
|
||||
接回来……它们没有"该结束了"的内在信号(用户不在场,没人喊停)。
|
||||
所以轮数上限不是优化,是**防失控**。
|
||||
|
||||
**② "不撑独角戏"**
|
||||
|
||||
一方 Token 触顶时,**不能**让另一方继续自言自语。
|
||||
需求的做法是:另一方**单方面收尾**(说一句告别/结语)然后立刻结束。
|
||||
独白读起来很怪,而且白花钱。
|
||||
|
||||
**③ 每轮的"用户"是谁**
|
||||
|
||||
对 A 来说,B 说的话就是**用户消息**;对 B 来说反过来。
|
||||
这是私聊能跑起来的关键 —— 两个 AI 都在"跟对方聊天",
|
||||
而不是"在同一个上下文里各写各的"。
|
||||
"""
|
||||
|
||||
import agent_loop
|
||||
import agentdb
|
||||
import store
|
||||
|
||||
#: 默认最多几轮(**一轮 = A 说一次 + B 说一次**)。需求定的 10。
|
||||
DEFAULT_MAX_ROUNDS = 10
|
||||
|
||||
#: 上限的硬顶:用户可以在设置里调,但不该调到能刷爆账单的规模。
|
||||
#: 一轮两次 LLM 调用,100 轮就是 200 次 —— 那不是"聊天",是失控。
|
||||
MAX_ROUNDS_CAP = 60
|
||||
|
||||
|
||||
def resolve_rounds(settings: dict, body: dict = None) -> int:
|
||||
"""
|
||||
这次私聊最多几轮:**调用方指定 > 全局设置 > 默认**,并且夹在硬顶内。
|
||||
|
||||
★ 需求说"默认最多 10 轮(**可配**)"—— 可配的入口是
|
||||
`settings.privateChatRounds`,不是每次调用随便传(那样界面就没法
|
||||
给用户一个稳定的默认值了)。[body] 只给"这一次特殊"用。
|
||||
"""
|
||||
for src in ((body or {}).get('maxRounds'), (settings or {}).get('privateChatRounds')):
|
||||
try:
|
||||
v = int(float(src))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if v > 0:
|
||||
return max(1, min(MAX_ROUNDS_CAP, v))
|
||||
return DEFAULT_MAX_ROUNDS
|
||||
|
||||
|
||||
def _used(agent: dict) -> int:
|
||||
u = agentdb.token_usage((agent or {}).get('id') or '')
|
||||
return int(u['total']['input']) + int(u['total']['output'])
|
||||
|
||||
|
||||
def limit_hit(agent: dict) -> bool:
|
||||
"""
|
||||
这个智能体的额度用完了吗(0 = 无限制)。
|
||||
|
||||
★ 和 `/api/chat` 那道检查**同一个判据**:用掉的总量 >= 上限。
|
||||
两处不一致的话,会出现"私聊里还能说、回到对话里被拦"这种精神分裂。
|
||||
"""
|
||||
agent = agent or {}
|
||||
try:
|
||||
limit = int(float(agent.get('tokenLimit') or 0))
|
||||
except (TypeError, ValueError):
|
||||
limit = 0
|
||||
return limit > 0 and _used(agent) >= limit
|
||||
|
||||
|
||||
def _history_for(speaker_id: str, turns: list) -> list:
|
||||
"""
|
||||
把"到目前为止的对话"翻译成**这个说话者视角**的消息列表。
|
||||
|
||||
对方说的 → `user`(它在跟我说话)
|
||||
我说的 → `assistant`(我说的)
|
||||
|
||||
★ 这是私聊能跑起来的关键:两个 AI 各自都是"在跟对方聊天",
|
||||
而不是"在同一个上下文里各写各的"。
|
||||
"""
|
||||
out = []
|
||||
for t in turns:
|
||||
if not t.get('content'):
|
||||
continue
|
||||
mine = t.get('agentId') == speaker_id
|
||||
out.append({'role': 'assistant' if mine else 'user', 'content': t['content']})
|
||||
return out
|
||||
|
||||
|
||||
def run_pair(settings: dict, first: dict, second: dict, max_rounds: int = 0,
|
||||
opener: str = '', emit=None) -> dict:
|
||||
"""
|
||||
让两个智能体在后台对聊。
|
||||
|
||||
[first] 先开口的那个(也是这个会话的"主")
|
||||
[opener] 给先开口者的由头(比如"用户把你俩拉到了一起")。
|
||||
|
||||
返回:
|
||||
{
|
||||
'ok': True,
|
||||
'conversationId': ...,
|
||||
'turns': [{'agentId','name','content'}],
|
||||
'rounds': 实际说了几轮,
|
||||
'endReason': 'rounds' | 'limit' | 'error',
|
||||
'endedBy': 谁触顶了(endReason=limit 时),
|
||||
'summary': 摘要(有的话),
|
||||
}
|
||||
"""
|
||||
settings = settings or {}
|
||||
first, second = first or {}, second or {}
|
||||
if not (first.get('id') and second.get('id')):
|
||||
return {'ok': False, 'error': '需要两个智能体'}
|
||||
rounds_cap = max_rounds or resolve_rounds(settings)
|
||||
say = emit or (lambda ev: None)
|
||||
|
||||
conv = store.create_conversation(
|
||||
title=f'{(first.get("name") or "?")} 与 {(second.get("name") or "?")} 的私聊',
|
||||
agent_id=first.get('id') or '',
|
||||
# ★ `private` 是独立类型:它出现在**两个参与者的**会话列表里,
|
||||
# 而界面上只读翻看(用户不在场,不该能插话)
|
||||
kind='private',
|
||||
participants=[first.get('id') or '', second.get('id') or ''],
|
||||
)
|
||||
cid = conv['id']
|
||||
turns = []
|
||||
end_reason = 'rounds'
|
||||
ended_by = ''
|
||||
|
||||
def _record(speaker: dict, text: str) -> None:
|
||||
turns.append({'agentId': speaker.get('id') or '',
|
||||
'name': speaker.get('name') or '', 'content': text})
|
||||
store.append_messages(cid, [{
|
||||
'role': 'assistant',
|
||||
'content': text,
|
||||
'agentId': speaker.get('id') or '',
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
|
||||
for i in range(rounds_cap):
|
||||
for who in (first, second):
|
||||
if limit_hit(who):
|
||||
# ★★ 一方触顶 → 另一方**单方面收尾**后立即结束(需求明文)。
|
||||
# 不收尾直接断的话,对话会停在一句没头没尾的话上;
|
||||
# 让另一个人继续说的话,就成了"独角戏"(需求明确说不要)。
|
||||
other = second if who.get('id') == first.get('id') else first
|
||||
if not limit_hit(other):
|
||||
try:
|
||||
_closing = _speak(settings, other, turns, cid, rounds_cap, i,
|
||||
hint='对方的额度用完了,这次对话到此为止 —— '
|
||||
'你说一句收尾的话,不要再问问题。')
|
||||
if _closing:
|
||||
_record(other, _closing)
|
||||
except Exception as exc: # noqa: BLE001 - 收尾失败也要结束
|
||||
say({'type': 'private_error', 'message': str(exc)})
|
||||
end_reason, ended_by = 'limit', who.get('name') or ''
|
||||
break
|
||||
if not turns and who.get('id') == first.get('id'):
|
||||
# 给先开口者一个由头(不然它不知道"跟谁、为什么")
|
||||
turns_seed = opener or f'你和「{second.get("name") or "对方"}」被单独留在了一间屋子里。'
|
||||
else:
|
||||
turns_seed = ''
|
||||
try:
|
||||
text = _speak(settings, who, turns, cid, rounds_cap, i, hint=turns_seed)
|
||||
except Exception as exc: # noqa: BLE001 - 一次生成失败不该让整场私聊崩
|
||||
say({'type': 'private_error', 'message': str(exc)})
|
||||
end_reason = 'error'
|
||||
break
|
||||
if not text:
|
||||
# 模型返回空 —— 当作"它不想说了",正常收尾而不是报错
|
||||
end_reason = 'rounds'
|
||||
break
|
||||
_record(who, text)
|
||||
say({'type': 'private_turn', 'agentId': who.get('id') or '',
|
||||
'name': who.get('name') or '', 'content': text})
|
||||
if end_reason in ('limit', 'error'):
|
||||
break
|
||||
|
||||
out = {
|
||||
'ok': True, 'conversationId': cid, 'turns': turns,
|
||||
'rounds': len(turns), 'endReason': end_reason, 'endedBy': ended_by,
|
||||
}
|
||||
# ★ 结束后生成摘要写入共享记忆(需求:复用总结管线)
|
||||
try:
|
||||
summary = summarize_to_memory(first, second, turns)
|
||||
if summary:
|
||||
out['summary'] = summary
|
||||
except Exception as exc: # noqa: BLE001 - 摘要失败不影响"私聊已经结束"这件事
|
||||
say({'type': 'private_error', 'message': f'摘要失败:{exc}'})
|
||||
store.update_conversation(cid, {'title': conv['title']})
|
||||
return out
|
||||
|
||||
|
||||
def _speak(settings: dict, speaker: dict, turns: list, cid: str,
|
||||
cap: int, round_index: int, hint: str = '') -> str:
|
||||
"""让一个智能体说一句。返回正文(空串 = 它没说话)"""
|
||||
history = _history_for(speaker.get('id') or '', turns)
|
||||
if hint:
|
||||
history = history + [{'role': 'user', 'content': hint}]
|
||||
if not history:
|
||||
history = [{'role': 'user', 'content': '开始吧。'}]
|
||||
result = agent_loop.run_agent(
|
||||
settings=settings,
|
||||
messages=history,
|
||||
agent=speaker,
|
||||
emit=lambda ev: None,
|
||||
conversation_id=cid,
|
||||
# ★ 私聊是**幕后**行为,不能再往里递归拉起别的对话 ——
|
||||
# 加一层深度限制,免得 A 拉 B、B 拉 C 无限套下去
|
||||
send_depth=1,
|
||||
)
|
||||
return str((result or {}).get('content') or '').strip()
|
||||
|
||||
|
||||
def summarize_to_memory(first: dict, second: dict, turns: list) -> str:
|
||||
"""
|
||||
把这场私聊的摘要写进**共享记忆**(需求:复用总结管线)。
|
||||
|
||||
★ 写到哪:两人的**共享空间**(同世界观 → `world:<id>`),
|
||||
这样以后两人聊天时都"记得"这次私聊发生过。
|
||||
没有共同世界观的话**不写** —— 硬塞进某一个人的私有空间,
|
||||
等于替他记了一件他没参与的事。
|
||||
"""
|
||||
if not turns:
|
||||
return ''
|
||||
a, b = first or {}, second or {}
|
||||
wid = (a.get('worldviewId') or '').strip()
|
||||
if not wid or wid != (b.get('worldviewId') or '').strip():
|
||||
return ''
|
||||
body = '\n'.join(f'{(t.get("name") or "?")}:{t.get("content") or ""}' for t in turns)
|
||||
# 摘要是**规则化**的,不再花一次 LLM 调用 —— 私聊本身已经烧了
|
||||
# 2×N 次调用了,为了压两句话再烧一次不划算(需求说的"复用总结管线"
|
||||
# 指的是同一套**写入记忆**的通道,不是非要再调一次模型)
|
||||
title = f'和{(b.get("name") or "对方")}的一次私下交谈'
|
||||
content = f'({len(turns)} 句)' + body[:400]
|
||||
return agentdb.memory_add(
|
||||
agentdb.world_scope(wid), title, content, author_agent=a.get('id') or '',
|
||||
) and title
|
||||
694
android/kernel/rule_engine.py
Normal file
@@ -0,0 +1,694 @@
|
||||
"""规则引擎:数值系统 + 状态系统(需求 v1.2 §3.10 / §3.11)。
|
||||
|
||||
## 一句话分工
|
||||
|
||||
· **定义**在「数值状态包」里(独立资源,可被多个世界观引用)
|
||||
· **值**按 scope 存(`shared` 决定是每个智能体一份还是全世界观一份)
|
||||
· **注入**走 `<stats>` / `<status>` 两个段(附录 C,排在提示词最后)
|
||||
· **操作**只有 `change_stat`(只申请增量,不许写绝对值)
|
||||
|
||||
## 为什么"只申请增量"这条不能通融
|
||||
|
||||
需求 §3.10 原话:`change_stat(name, delta)` —— 只申请增量,内核流程固定:
|
||||
|
||||
脚本裁决(如有)→ clamp 到 [min,max] → 写库 → 下一轮注入反映新值
|
||||
|
||||
如果允许 AI 写绝对值,那"脚本裁决"就没意义了 —— 修正器要的是
|
||||
"你想加 5 点,我判成加 10 点",而不是"你想设成 100,我判……多少"。
|
||||
而且并发时(群聊里两个智能体同时改同一个 shared 数值)
|
||||
绝对值会互相覆盖,增量不会。
|
||||
|
||||
## 值的 scope
|
||||
|
||||
和记忆**故意用同一套写法**:
|
||||
|
||||
shared=0 → "agent:<uuid>" 好感度各算各的
|
||||
shared=1 → "world:<uuid>" 灵气浓度全世界观一份
|
||||
|
||||
好处是"绑定/解绑世界观只换读写空间、值不迁移"这条自动成立 ——
|
||||
和记忆的行为一致,用户不用学两套心智模型。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import rule_sandbox
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 定义:从规则包同步进来
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 规则包里数值定义的合法字段(多出来的忽略,不报错 —— 兼容将来扩展)
|
||||
_STAT_KEYS = ('name', 'min', 'max', 'shared', 'ranges', 'script')
|
||||
_STATUS_KEYS = ('name', 'kind', 'turns', 'max_stack', 'script')
|
||||
|
||||
|
||||
def _num(v, default=0.0):
|
||||
try:
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def sync_defs(pack_id: str, info: dict = None) -> dict:
|
||||
"""
|
||||
把一个规则包的 `info.json` 同步进库(**幂等**,重复导入只覆盖定义)。
|
||||
|
||||
★ 只同步**定义**,不动**值**(需求附录 D:"数值的**定义**进包,
|
||||
**当前值**不进包 —— 经历与人设分离,同记忆")。
|
||||
所以重新导入一个包不会把你的好感度清零。
|
||||
|
||||
★ [info] 不传时**从 store 里那个包读**。这是默认路径 ——
|
||||
定义只应该有一处源头(包里的 `info.json`),SQLite 里那两张表是
|
||||
**派生**出来的。两处都能写的话,迟早会出现
|
||||
"包里改了、库里还是旧的",而那种不一致极难查。
|
||||
|
||||
返回 `{'stats': n, 'statuses': m}`。
|
||||
"""
|
||||
if info is None:
|
||||
pack = store.get_resource('rulepacks', pack_id or '') or {}
|
||||
info = pack.get('info') if isinstance(pack.get('info'), dict) else {}
|
||||
info = info or {}
|
||||
sid = (pack_id or '').strip()
|
||||
if not sid:
|
||||
return {'stats': 0, 'statuses': 0}
|
||||
# ★★ 空定义**不动库**。
|
||||
#
|
||||
# "读不到这个包"(id 不对、包刚被删)和"用户真要把定义清空"在这一层
|
||||
# 分不清,而**清空定义是不可逆的**:值还在 `stat_values` 里,
|
||||
# 定义没了它们就成了永远读不到的孤儿。
|
||||
# 真要清空,把那个包删掉就行 —— 那是个明确得多的动作。
|
||||
if not info.get('stats') and not info.get('statuses'):
|
||||
return {'stats': 0, 'statuses': 0}
|
||||
agentdb.init() # ★ 别忘了:这几张表是 v1.2 才加的,惰性建表
|
||||
conn = agentdb._connect()
|
||||
stats = info.get('stats') if isinstance(info.get('stats'), list) else []
|
||||
statuses = info.get('statuses') if isinstance(info.get('statuses'), list) else []
|
||||
|
||||
# 定义表整体替换这个包的(不然删掉的数值会一直留着)
|
||||
conn.execute('DELETE FROM stat_defs WHERE pack_id = ?', (sid,))
|
||||
conn.execute('DELETE FROM status_defs WHERE pack_id = ?', (sid,))
|
||||
|
||||
# ★ 数**实际入库的**,不是输入数组的长度:"你导入了 3 条"和
|
||||
# "3 条里有 1 条没名字被跳过"是两回事,界面拿这个数报给用户。
|
||||
n_stats = 0
|
||||
for i, s in enumerate(stats):
|
||||
s = s or {}
|
||||
name = str(s.get('name') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
lo, hi = _num(s.get('min'), 0.0), _num(s.get('max'), 100.0)
|
||||
if hi <= lo:
|
||||
hi = lo + 1
|
||||
ranges = s.get('ranges') if isinstance(s.get('ranges'), list) else []
|
||||
conn.execute(
|
||||
'INSERT INTO stat_defs (pack_id, name, min_value, max_value, shared, ranges, script, ord) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
(sid, name, lo, hi, 1 if s.get('shared') else 0,
|
||||
json.dumps(ranges, ensure_ascii=False), str(s.get('script') or ''), i),
|
||||
)
|
||||
n_stats += 1
|
||||
|
||||
n_status = 0
|
||||
for s in statuses:
|
||||
s = s or {}
|
||||
name = str(s.get('name') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
kind = 'persistent' if str(s.get('type') or s.get('kind') or '').lower() == 'persistent' else 'timed'
|
||||
conn.execute(
|
||||
'INSERT INTO status_defs (pack_id, name, kind, turns, max_stack, script) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(sid, name, kind, max(1, int(_num(s.get('turns'), 1))),
|
||||
max(1, int(_num(s.get('max_stack'), 1))), str(s.get('script') or '')),
|
||||
)
|
||||
n_status += 1
|
||||
conn.commit()
|
||||
return {'stats': n_stats, 'statuses': n_status}
|
||||
|
||||
|
||||
def stat_defs(pack_id: str) -> list:
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM stat_defs WHERE pack_id = ? ORDER BY ord ASC, name ASC', (pack_id or '',),
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
try:
|
||||
ranges = json.loads(r['ranges'] or '[]')
|
||||
except (TypeError, ValueError):
|
||||
ranges = []
|
||||
out.append({
|
||||
'name': r['name'], 'min': float(r['min_value']), 'max': float(r['max_value']),
|
||||
'shared': bool(r['shared']), 'ranges': ranges if isinstance(ranges, list) else [],
|
||||
'script': r['script'] or '',
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def status_defs(pack_id: str) -> list:
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM status_defs WHERE pack_id = ? ORDER BY name ASC', (pack_id or '',),
|
||||
).fetchall()
|
||||
return [
|
||||
{'name': r['name'], 'kind': r['kind'] or 'timed', 'turns': int(r['turns'] or 1),
|
||||
'max_stack': int(r['max_stack'] or 1), 'script': r['script'] or ''}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 值:按 scope 读写
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def scope_for(agent: dict, definition: dict) -> str:
|
||||
"""
|
||||
一条数值存在哪个空间(`shared` 决定)。
|
||||
|
||||
★ 和记忆用同一套 scope 写法(`agentdb.scope_of` / `world_scope`)——
|
||||
这样"解绑世界观值留在原地"和记忆的行为一致,用户不用学两套。
|
||||
"""
|
||||
agent = agent or {}
|
||||
if (definition or {}).get('shared'):
|
||||
wid = (agent.get('worldviewId') or '').strip()
|
||||
# 没绑世界观却要读"全世界观共享"的值:退回私有空间。
|
||||
# 不报错是因为"刚解绑"是个正常状态,值还在那儿等着再绑回来。
|
||||
return agentdb.world_scope(wid) if wid else agentdb.agent_scope(agent.get('id') or '')
|
||||
return agentdb.agent_scope(agent.get('id') or '')
|
||||
|
||||
|
||||
def value_of(agent: dict, definition: dict) -> float:
|
||||
"""
|
||||
读一条数值的当前值。没写过就取**定义里的初始值** ——
|
||||
用 min 还是 max?
|
||||
|
||||
★ 取 `min`。因为在"好感度 0~100"这种语义里 min 是中性起点;
|
||||
取 max 的话新角色一上来就满好感,明显不对。
|
||||
真想要别的起点,包作者把 min 设成他要的值就行。
|
||||
"""
|
||||
scope = scope_for(agent, definition)
|
||||
agentdb.init()
|
||||
row = agentdb._connect().execute(
|
||||
'SELECT value FROM stat_values WHERE scope = ? AND name = ?',
|
||||
(scope, (definition or {}).get('name') or ''),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return _num((definition or {}).get('min'), 0.0)
|
||||
return float(row['value'])
|
||||
|
||||
|
||||
def set_value(agent: dict, definition: dict, value: float) -> float:
|
||||
"""直接写值(**只给内核用**:脚本裁决和 clamp 之后的落库走这里)"""
|
||||
scope = scope_for(agent, definition)
|
||||
v = _num(value)
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute(
|
||||
'INSERT INTO stat_values (scope, name, value) VALUES (?, ?, ?) '
|
||||
'ON CONFLICT(scope, name) DO UPDATE SET value = excluded.value',
|
||||
(scope, (definition or {}).get('name') or '', v),
|
||||
)
|
||||
conn.commit()
|
||||
return v
|
||||
|
||||
|
||||
def clamp(definition: dict, value: float) -> float:
|
||||
d = definition or {}
|
||||
return max(_num(d.get('min'), 0.0), min(_num(d.get('max'), 100.0), _num(value)))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 区间表:命中哪段注入哪段(需求 §3.10 "声明式区间表")
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def range_text(definition: dict, value: float) -> str:
|
||||
"""
|
||||
命中区间的 text(没命中任何区间就返回空串 = 裸值)。
|
||||
|
||||
★ 区间是**左闭右开** `[min, max)`,除了最后一段是闭的。
|
||||
半开区间是刻意的:0~20 和 20~40 两段,20 该算后一段 ——
|
||||
如果两边都闭,20 会同时命中两段,取哪段就成了未定义行为。
|
||||
"""
|
||||
ranges = (definition or {}).get('ranges')
|
||||
if not isinstance(ranges, list):
|
||||
return ''
|
||||
v = _num(value)
|
||||
total = len(ranges)
|
||||
for i, r in enumerate(ranges):
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
lo = _num(r.get('min'))
|
||||
hi = _num(r.get('max'), lo)
|
||||
last = i == total - 1
|
||||
if (lo <= v < hi) or (last and lo <= v <= hi):
|
||||
return str(r.get('text') or '').strip()
|
||||
return ''
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 注入:<stats> / <status>
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 上一轮的变化量(渲染 `450→500` 那个箭头用)。
|
||||
#:
|
||||
#: ★ 放内存、不放库:需求说箭头"**仅保留一轮**",用完就该没了。
|
||||
#: 放库还要额外写一次清理逻辑,而进程重启丢掉它也无所谓 ——
|
||||
#: 箭头只是个提示,不是数据。
|
||||
_pending_delta = {}
|
||||
|
||||
|
||||
def note_delta(scope: str, name: str, delta: float) -> None:
|
||||
"""记下这次变化了多少,下一轮渲染时显示成箭头"""
|
||||
if delta:
|
||||
_pending_delta[(scope, name)] = float(delta)
|
||||
|
||||
|
||||
def take_delta(scope: str, name: str) -> float:
|
||||
"""取出并**清掉**(所以只显示一轮)"""
|
||||
return _pending_delta.pop((scope, name), 0.0)
|
||||
|
||||
|
||||
def stats_section(agent: dict, pack_id: str) -> str:
|
||||
"""
|
||||
渲染 `<stats>` 段(附录 C 的格式):
|
||||
|
||||
[世界·九州] 声望: 450→500/1000 —— 名震九州:世人皆知你之名
|
||||
[自身] 好感度: 45/100 —— 友善:你对用户态度友善,但保持分寸
|
||||
|
||||
来源前缀(`[世界·xx]` / `[自身]`)+ 当前值 + 变化箭头(仅一轮)+
|
||||
命中区间文本(未命中就是裸值)。
|
||||
"""
|
||||
defs = stat_defs(pack_id)
|
||||
if not defs:
|
||||
return ''
|
||||
agent = agent or {}
|
||||
wname = ''
|
||||
wid = (agent.get('worldviewId') or '').strip()
|
||||
if wid:
|
||||
wname = ((store.get_resource('worldviews', wid) or {}).get('name') or '').strip()
|
||||
|
||||
lines = []
|
||||
for d in defs:
|
||||
scope = scope_for(agent, d)
|
||||
v = value_of(agent, d)
|
||||
delta = take_delta(scope, d['name'])
|
||||
src = f'[世界·{wname}]' if d.get('shared') and wname else '[自身]'
|
||||
# 值那一段:有变化时显示 `旧→新`
|
||||
if delta:
|
||||
old = clamp(d, v - delta)
|
||||
val = f'{_fmt(old)}→{_fmt(v)}/{_fmt(d["max"])}'
|
||||
else:
|
||||
val = f'{_fmt(v)}/{_fmt(d["max"])}'
|
||||
text = range_text(d, v)
|
||||
lines.append(f'{src} {d["name"]}: {val}' + (f' —— {text}' if text else ''))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def _fmt(v: float) -> str:
|
||||
"""数值显示:整数就不带小数点(45.0 → 45),免得看着别扭"""
|
||||
f = float(v)
|
||||
return str(int(f)) if f == int(f) else f'{f:g}'
|
||||
|
||||
|
||||
def status_section(agent: dict) -> str:
|
||||
"""
|
||||
渲染 `<status>` 段(附录 C 的格式):
|
||||
|
||||
中毒(剩 3 轮):你感到眩晕,言语变得迟缓
|
||||
|
||||
状态名(剩余轮数)+ 状态提示词(脚本可改写)。
|
||||
持久状态不显示轮数(它不过期)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
rows = list_statuses(agent.get('id') or '')
|
||||
if not rows:
|
||||
return ''
|
||||
lines = []
|
||||
for r in rows:
|
||||
head = r['name']
|
||||
if r.get('kind') != 'persistent' and r.get('remaining', 0) > 0:
|
||||
head += f'(剩 {r["remaining"]} 轮)'
|
||||
if r.get('stacks', 1) > 1:
|
||||
head += f'×{r["stacks"]}'
|
||||
hint = (r.get('hint') or '').strip()
|
||||
lines.append(head + (f':{hint}' if hint else ''))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 状态实例
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def list_statuses(agent_id: str) -> list:
|
||||
"""这个智能体身上生效中的状态(带定义里的 kind)"""
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM status_instances WHERE agent_id = ? ORDER BY granted_at ASC, name ASC',
|
||||
(agent_id or '',),
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
out.append({
|
||||
'name': r['name'], 'remaining': int(r['remaining'] or 0),
|
||||
'stacks': int(r['stacks'] or 1), 'hint': r['hint'] or '',
|
||||
'grantedAt': r['granted_at'] or '', 'kind': _kind_of(r['name']),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _kind_of(name: str) -> str:
|
||||
"""查一个状态名是持久还是定时(实例表里不存 kind —— 那是定义的事)"""
|
||||
agentdb.init()
|
||||
row = agentdb._connect().execute(
|
||||
'SELECT kind FROM status_defs WHERE name = ? LIMIT 1', (name or '',),
|
||||
).fetchone()
|
||||
return (row['kind'] if row else 'timed') or 'timed'
|
||||
|
||||
|
||||
def put_status(agent_id: str, name: str, remaining: int, stacks: int, hint: str) -> None:
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute(
|
||||
'INSERT INTO status_instances (agent_id, name, remaining, stacks, hint, granted_at) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?) '
|
||||
'ON CONFLICT(agent_id, name) DO UPDATE SET remaining = excluded.remaining, '
|
||||
'stacks = excluded.stacks, hint = excluded.hint',
|
||||
(agent_id or '', name or '', int(remaining), int(stacks), hint or '', agentdb.now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def drop_status(agent_id: str, name: str) -> None:
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute('DELETE FROM status_instances WHERE agent_id = ? AND name = ?',
|
||||
(agent_id or '', name or ''))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def tick_statuses(agent_id: str) -> list:
|
||||
"""
|
||||
"该智能体每参与一轮后减 1"(需求 §3.11)。
|
||||
|
||||
返回 `[{'name':…, 'expired':True/False}]` —— 调用方据此播报
|
||||
"中毒已经消退了"这类消息。
|
||||
|
||||
★ persistent 的是 `remaining = -1`,不参与递减(它不过期)。
|
||||
"""
|
||||
out = []
|
||||
for r in list_statuses(agent_id):
|
||||
if r.get('kind') == 'persistent':
|
||||
continue
|
||||
left = int(r.get('remaining') or 0) - 1
|
||||
if left <= 0:
|
||||
drop_status(agent_id, r['name'])
|
||||
out.append({'name': r['name'], 'expired': True})
|
||||
else:
|
||||
put_status(agent_id, r['name'], left, r.get('stacks') or 1, r.get('hint') or '')
|
||||
out.append({'name': r['name'], 'expired': False, 'remaining': left})
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 脚本执行(需求 §3.10 数值裁决 / §3.11 状态脚本)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 三个入口(需求附录 E 的签名):
|
||||
#
|
||||
# on_stat_change(name, value, delta) -> 生效增量(可放大/缩小/归零否决)
|
||||
# on_turn(self_agent, stats_api) 每轮执行(状态脚本)
|
||||
# on_grant(status_name, source_agent) -> bool(赋予判定,跑在**目标方**)
|
||||
#
|
||||
# 全部走 rule_sandbox 的受限沙箱 + 硬超时。
|
||||
#
|
||||
# ★★ 异常 = 本次操作**归零** + UI 提示,**不中断对话**(需求附录 E)。
|
||||
# 规则脚本是用户自己写的,写错了是常态;一次脚本错误把整轮对话搞崩,
|
||||
# 用户会以为整个 App 坏了 —— 而其实只是他那行 `1/0` 写错了。
|
||||
|
||||
|
||||
def _timeout_s() -> float:
|
||||
import timeouts
|
||||
|
||||
return float(timeouts.get('customNode') or 10)
|
||||
|
||||
|
||||
def script_source(pack_id: str, filename: str) -> str:
|
||||
"""从规则包里取一段脚本源码(空串 = 这个包没带这段脚本)"""
|
||||
if not (filename or '').strip():
|
||||
return ''
|
||||
pack = store.get_resource('rulepacks', pack_id or '') or {}
|
||||
scripts = pack.get('scripts')
|
||||
if not isinstance(scripts, dict):
|
||||
return ''
|
||||
return str(scripts.get(filename) or '')
|
||||
|
||||
|
||||
def run_script(source: str, entry: str, *args) -> tuple:
|
||||
"""
|
||||
跑一段规则脚本,返回 `(结果, 错误说明)`。
|
||||
|
||||
★ **不抛异常**:需求说异常要"归零 + 提示、不中断对话",
|
||||
所以错误在这里就被接住、转成一段人话,由调用方决定怎么显示。
|
||||
抛出去的话,一次脚本报错会顺着调用栈炸到对话主循环。
|
||||
|
||||
★ 超时用 `run_with_timeout`(线程 + join)—— 注意它的说明:
|
||||
超时后线程**杀不掉**,只能放弃等待。所以这里给的默认值不大
|
||||
(`timeouts.customNode`),而且脚本本来就该是"算一下"级别的活。
|
||||
"""
|
||||
if not (source or '').strip():
|
||||
return None, ''
|
||||
|
||||
import builtin_tools
|
||||
|
||||
holder = {}
|
||||
|
||||
def _work():
|
||||
try:
|
||||
ns = rule_sandbox.load(source, '<rule script>', {})
|
||||
holder['value'] = rule_sandbox.call(ns, entry, *args)
|
||||
holder['error'] = ''
|
||||
except rule_sandbox.ScriptRejected as exc:
|
||||
holder['error'] = f'脚本没通过安全检查:{exc}'
|
||||
except KeyError:
|
||||
holder['error'] = f'脚本里没有 `{entry}` 函数'
|
||||
except SyntaxError as exc:
|
||||
holder['error'] = f'脚本第 {exc.lineno} 行有语法错误:{exc.msg}'
|
||||
except Exception as exc: # noqa: BLE001 - 用户脚本什么都能抛
|
||||
holder['error'] = f'脚本报错:{exc.__class__.__name__}: {exc}'
|
||||
|
||||
# 注意:run_with_timeout 返回 None 表示"超时/放弃等待",见它的说明
|
||||
builtin_tools.run_with_timeout(_work, _timeout_s())
|
||||
if holder.get('error'):
|
||||
return None, holder['error']
|
||||
if 'value' not in holder:
|
||||
return None, '脚本超时(已放弃等待,它可能还在后台跑)'
|
||||
return holder['value'], ''
|
||||
|
||||
|
||||
def _stat_api(agent: dict, pack_id: str, narration: list, hints: dict) -> dict:
|
||||
"""
|
||||
给状态脚本的**受限 API**(需求 §3.11 的三项权限 + 旁白)。
|
||||
|
||||
★ 通过**参数**注入,不是做成模块级函数:那样脚本能摸到别的东西,
|
||||
两个脚本也会互相污染。
|
||||
★ 这里没有 `emotion_set` 的死亡检查 —— 需求 §3.11 明说状态脚本是
|
||||
"唯一能让 AI 侧解除死亡的通道"(定时复活 / 解药剧情)。
|
||||
禁止自愈那条只约束 AI 直接调 `emotion_set` 工具。
|
||||
"""
|
||||
def _change_stat(name, delta):
|
||||
r = change(agent, pack_id, str(name or ''), _num(delta))
|
||||
if not r.get('ok'):
|
||||
raise ValueError(r.get('error') or '改数值失败')
|
||||
return r.get('applied', 0)
|
||||
|
||||
def _emotion_set(preset, text=''):
|
||||
import agentdb
|
||||
|
||||
p = str(preset or '').strip()
|
||||
if p not in agentdb.PRESETS:
|
||||
raise ValueError(f'preset 只能是:{"、".join(agentdb.PRESETS)}')
|
||||
agentdb.emotion_set(agent.get('id') or '', preset=p, text=str(text or ''))
|
||||
return True
|
||||
|
||||
def _set_hint(status_name, text):
|
||||
hints[str(status_name or '').strip()] = str(text or '')
|
||||
|
||||
def _narrate(text):
|
||||
t = str(text or '').strip()
|
||||
if t:
|
||||
narration.append(t)
|
||||
|
||||
return {
|
||||
'change_stat': _change_stat,
|
||||
'emotion_set': _emotion_set,
|
||||
'set_hint': _set_hint,
|
||||
'narrate': _narrate,
|
||||
}
|
||||
|
||||
|
||||
def run_turn_scripts(agent: dict, pack_id: str) -> dict:
|
||||
"""
|
||||
每轮**生成回复之前**跑一遍生效状态的脚本(需求 §3.11)。
|
||||
|
||||
顺序是固定的:**状态脚本执行 → 重拼 prompt → 生成**(附录 E)。
|
||||
所以调用点必须在 `build_system_prompt` **之前**,否则脚本这一轮的
|
||||
改动要等下一轮才生效 —— 表现是"中毒了但 AI 这轮还生龙活虎"。
|
||||
|
||||
返回 `{'narration': [...], 'errors': [...], 'changed': [...]}`:
|
||||
· `narration` 是脚本返回的旁白,内核作为系统消息注入下一轮
|
||||
· `errors` 给界面提示(**不中断对话**)
|
||||
"""
|
||||
agent = agent or {}
|
||||
aid = agent.get('id') or ''
|
||||
if not aid:
|
||||
return {'narration': [], 'errors': [], 'changed': []}
|
||||
|
||||
narration, errors = [], []
|
||||
for inst in list_statuses(aid):
|
||||
src = script_source(pack_id, _script_file_of(pack_id, inst['name']))
|
||||
if not src:
|
||||
continue
|
||||
hints = {}
|
||||
api = _stat_api(agent, pack_id, narration, hints)
|
||||
_, err = run_script(src, 'on_turn', dict(agent), api)
|
||||
if err:
|
||||
errors.append(f'状态「{inst["name"]}」的脚本:{err}')
|
||||
continue
|
||||
# 脚本可能改了提示词(需求 §3.11 的权限之一)
|
||||
for sname, text in hints.items():
|
||||
for s in list_statuses(aid):
|
||||
if s['name'] == sname:
|
||||
put_status(aid, sname, s['remaining'], s['stacks'], text)
|
||||
return {'narration': narration, 'errors': errors, 'changed': []}
|
||||
|
||||
|
||||
def _script_file_of(pack_id: str, status_name: str) -> str:
|
||||
"""状态定义里配的脚本文件名"""
|
||||
for d in status_defs(pack_id):
|
||||
if d['name'] == status_name:
|
||||
return d.get('script') or ''
|
||||
return ''
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# change_stat:流程固定(需求 §3.10)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def change(agent: dict, pack_id: str, name: str, delta: float,
|
||||
source_agent: dict = None) -> dict:
|
||||
"""
|
||||
`change_stat(name, delta)` 的**完整流程**,顺序固定:
|
||||
|
||||
脚本裁决(如有)→ clamp 到 [min,max] → 写库 → 下一轮注入反映新值
|
||||
|
||||
★ 为什么"只申请增量、不许写绝对值"这条不能通融:
|
||||
允许写绝对值的话"脚本裁决"就没意义了 —— 修正器要的是
|
||||
"你想加 5 点,我判成加 10 点",而不是"你想设成 100,我判……多少"。
|
||||
而且群聊里两个智能体同时改同一个 shared 数值时,**绝对值会互相覆盖,
|
||||
增量不会**。
|
||||
|
||||
返回 `{'ok':..., 'applied':…, 'before':…, 'after':…, 'narration':…, 'error':…}`
|
||||
"""
|
||||
d = next((x for x in stat_defs(pack_id) if x['name'] == name), None)
|
||||
if not d:
|
||||
return {'ok': False, 'error': f'这个世界观里没有叫「{name}」的数值'}
|
||||
before = value_of(agent, d)
|
||||
want = _num(delta)
|
||||
|
||||
# ① 脚本裁决(可选)
|
||||
narration = []
|
||||
src = script_source(pack_id, d.get('script') or '')
|
||||
if src:
|
||||
out, err = run_script(src, 'on_stat_change', name, before, want)
|
||||
if err:
|
||||
# ★ 异常 = 本次增量**归零**(不是"按原值放行")——
|
||||
# 脚本坏了的时候,宁可这一次不生效,也不能让它失控地改数值
|
||||
return {'ok': False, 'error': err, 'applied': 0, 'before': before, 'after': before}
|
||||
if isinstance(out, (int, float)):
|
||||
want = float(out)
|
||||
elif isinstance(out, (list, tuple)) and out:
|
||||
# 也允许 (增量, 旁白) 这种写法
|
||||
want = _num(out[0])
|
||||
if len(out) > 1 and str(out[1] or '').strip():
|
||||
narration.append(str(out[1]).strip())
|
||||
elif out is None:
|
||||
want = 0.0 # 显式返回 None = 否决
|
||||
|
||||
# ② clamp ③ 写库
|
||||
after = clamp(d, before + want)
|
||||
applied = after - before
|
||||
if applied:
|
||||
set_value(agent, d, after)
|
||||
note_delta(scope_for(agent, d), name, applied)
|
||||
return {
|
||||
'ok': True, 'applied': applied, 'before': before, 'after': after,
|
||||
'narration': narration,
|
||||
'text': range_text(d, after),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# grant_status:赋予流程(需求 §3.11)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def grant(source: dict, pack_id: str, target: dict, status_name: str,
|
||||
turns: int = 0) -> dict:
|
||||
"""
|
||||
A 给 B 挂一个状态。
|
||||
|
||||
流程(需求 §3.11):
|
||||
1. **同世界观**才能赋(不要求同会话在场 —— 否则私聊里没法互相赋予)
|
||||
2. 调 **B 侧的** `on_grant(status_name, source_agent) -> bool`
|
||||
3. 接受 → 实例化到 B;拒绝 → A 收到「被抵抗」回执(**A 必须知道结果**)
|
||||
4. 同名重复赋予默认**刷新轮数**;定义配了 max_stack 才叠层
|
||||
|
||||
跨世界观一律拒绝(第 1 条就挡了)。
|
||||
"""
|
||||
source, target = source or {}, target or {}
|
||||
name = (status_name or '').strip()
|
||||
if not name:
|
||||
return {'ok': False, 'error': '没写状态名'}
|
||||
if not (target.get('id') or ''):
|
||||
return {'ok': False, 'error': '找不到目标智能体'}
|
||||
|
||||
sw = (source.get('worldviewId') or '').strip()
|
||||
tw = (target.get('worldviewId') or '').strip()
|
||||
if not sw or sw != tw:
|
||||
# ★ 跨世界观一律拒绝(需求原话)。也包含"自己没绑世界观"的情况 ——
|
||||
# 那种情况下没有共享的规则体系,赋予本身就没有依据。
|
||||
return {'ok': False, 'error': '你们不在同一个世界观里,赋予无效'}
|
||||
|
||||
d = next((x for x in status_defs(pack_id) if x['name'] == name), None)
|
||||
if not d:
|
||||
return {'ok': False, 'error': f'这个世界观没有叫「{name}」的状态'}
|
||||
|
||||
# ② B 侧的判定脚本
|
||||
src = script_source(pack_id, d.get('script') or '')
|
||||
if src:
|
||||
out, err = run_script(src, 'on_grant', name, source.get('name') or source.get('id') or '')
|
||||
if err:
|
||||
return {'ok': False, 'error': f'对方的判定脚本出错了:{err}'}
|
||||
if out is False:
|
||||
# ★ 拒绝要给 A 一个**明确回执**(需求原话"A 必须知道结果")
|
||||
return {'ok': False, 'resisted': True, 'error': f'「{target.get("name") or "对方"}」抵抗了这个状态'}
|
||||
|
||||
# ④ 叠加规则
|
||||
cur = next((s for s in list_statuses(target['id']) if s['name'] == name), None)
|
||||
if d['kind'] == 'persistent':
|
||||
remaining = -1
|
||||
else:
|
||||
remaining = max(1, int(turns or d.get('turns') or 1))
|
||||
if cur:
|
||||
stacks = min(int(d.get('max_stack') or 1), int(cur.get('stacks') or 1) + 1)
|
||||
if d['kind'] != 'persistent':
|
||||
# 同名重复赋予默认**刷新**轮数(不是累加)
|
||||
remaining = max(remaining, int(cur.get('remaining') or 0))
|
||||
else:
|
||||
stacks = 1
|
||||
hint = cur.get('hint') if cur else ''
|
||||
put_status(target['id'], name, remaining, stacks, hint or '')
|
||||
return {'ok': True, 'name': name, 'remaining': remaining, 'stacks': stacks,
|
||||
'refreshed': bool(cur), 'target': target.get('name') or ''}
|
||||
189
android/kernel/rule_sandbox.py
Normal file
@@ -0,0 +1,189 @@
|
||||
"""规则脚本的沙箱(v1.2 附录 E)。
|
||||
|
||||
# 这个沙箱能挡住什么,挡不住什么
|
||||
|
||||
**先说结论:它能挡手滑,挡不住有意。** 这不是偷懒,是 Python 的性质 ——
|
||||
只要你允许执行任意 Python 代码,就没有"关得严"的做法。所以这里的定位是
|
||||
**提高门槛 + 明确告知**,而不是给用户一个虚假的安全承诺。
|
||||
|
||||
## 三层防线
|
||||
|
||||
1. **静态扫描**(`scan`):源码里出现 `__双下划线__`、`import`、
|
||||
`open/eval/exec/getattr/...` 直接**拒绝执行**。
|
||||
这一层拦的是"手滑"和"抄来的脚本里夹带了东西" —— 规则脚本是**数值修正器**,
|
||||
正经写它根本用不到这些。
|
||||
2. **受限 builtins**:`exec` 时只喂一个白名单,`__import__` / `open` /
|
||||
`eval` / `compile` / `getattr` / `globals` 全都不在里面。
|
||||
没有 `__import__` 就没有模块系统。
|
||||
3. **硬超时**:复用 `timeouts.py` 的 `customNode` 那一项。
|
||||
|
||||
## 为什么说"挡不住有意"
|
||||
|
||||
Python 的属性访问是**语法**,不经过 builtins:
|
||||
|
||||
().__class__.__bases__[0].__subclasses__()
|
||||
|
||||
这一句能摸到进程里几乎所有类。第 1 层扫 `__` 就是为了堵它 ——
|
||||
但**字符串拼接**能绕过去(`getattr` 被禁了,可 `"__cla"+"ss__"` 拼出来再
|
||||
`__getattribute__` 呢?)。真想绕总能绕。
|
||||
|
||||
**所以导入规则包时的警告必须说实话**(见 `agent_api.py` 的导入流程):
|
||||
|
||||
> 此包包含可执行 Python 脚本,每轮在你的设备上运行。
|
||||
> 它**能读到你设备上的文件**,只导入你信得过的包。
|
||||
|
||||
而不是写"安全沙箱,请放心导入"。
|
||||
|
||||
## 为什么不直接用子进程
|
||||
|
||||
v1.2 讨论时定过"子进程 + 资源限制",查完发现**安卓上起不了 Python 子进程**:
|
||||
内核是 Chaquopy 嵌的 CPython,没有独立的解释器可执行文件
|
||||
(证据:`builtin_tools.python_run` 用的是进程内 `exec`,注释写着
|
||||
"这就是本工具存在的意义")。要起真子进程只能用 Termux 的 `python3`,
|
||||
但那要求用户装了 Termux、还得维护一个常驻 worker 和 IPC 协议。
|
||||
|
||||
**为一个"改个数值"的功能上那套,不值。** 所以退回白名单 + 明确告知。
|
||||
如果以后规则脚本变得重要到值得隔离,再上 Termux worker —— 那时
|
||||
这个模块的**接口不用变**(`run()` 的签名就是边界)。
|
||||
"""
|
||||
import re
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 第 1 层:静态扫描
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 危险模式 → 拒绝的理由(给用户看的话,不要写术语)
|
||||
DANGEROUS = (
|
||||
(re.compile(r'__\w+__'),
|
||||
'用了双下划线属性(这是绕过限制的经典手法)'),
|
||||
(re.compile(r'^\s*(import|from)\s+\w', re.M),
|
||||
'写了 import 语句(规则脚本不需要引入模块)'),
|
||||
(re.compile(r'\b(open|eval|exec|compile|input|breakpoint|help)\s*\('),
|
||||
'调用了不允许的内置函数'),
|
||||
(re.compile(r'\b(__import__|getattr|setattr|delattr|globals|locals|vars|dir|type|object|super)\s*\('),
|
||||
'调用了不允许的内置函数'),
|
||||
(re.compile(r'\b(exit|quit)\s*\('),
|
||||
'调用了退出函数'),
|
||||
)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 第 2 层:受限 builtins
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 只放"算数、拼字符串、处理列表字典"这一类。规则脚本要干的事就这些:
|
||||
# 读一个数值、算个增量、按区间挑一句话。
|
||||
#
|
||||
# ★ 不放:__import__ / open / eval / exec / compile / getattr / setattr /
|
||||
# globals / locals / vars / dir / type / object / super / input / help
|
||||
# —— 每一个都是逃逸链上的一环。
|
||||
SAFE_BUILTINS = {
|
||||
# 类型与构造
|
||||
'bool': bool, 'int': int, 'float': float, 'str': str,
|
||||
'list': list, 'dict': dict, 'tuple': tuple, 'set': set,
|
||||
'frozenset': frozenset, 'complex': complex, 'bytes': bytes,
|
||||
# 计算与序列
|
||||
'abs': abs, 'divmod': divmod, 'max': max, 'min': min, 'pow': pow,
|
||||
'round': round, 'sum': sum, 'len': len, 'sorted': sorted,
|
||||
'reversed': reversed, 'enumerate': enumerate, 'zip': zip,
|
||||
'range': range, 'any': any, 'all': all, 'map': map, 'filter': filter,
|
||||
# 字符串
|
||||
'format': format, 'repr': repr, 'ascii': ascii, 'chr': chr, 'ord': ord,
|
||||
'hex': hex, 'oct': oct, 'bin': bin,
|
||||
# 判断
|
||||
'isinstance': isinstance, 'issubclass': issubclass, 'callable': callable,
|
||||
# 常量
|
||||
'True': True, 'False': False, 'None': None,
|
||||
# 异常(脚本要能 try/except,不然一个除零就炸整轮对话)
|
||||
'Exception': Exception, 'ValueError': ValueError, 'TypeError': TypeError,
|
||||
'KeyError': KeyError, 'IndexError': IndexError, 'ZeroDivisionError': ZeroDivisionError,
|
||||
'AttributeError': AttributeError, 'ArithmeticError': ArithmeticError,
|
||||
'RuntimeError': RuntimeError,
|
||||
}
|
||||
|
||||
|
||||
class ScriptRejected(Exception):
|
||||
"""脚本没通过静态扫描 —— 带上给用户看的原因"""
|
||||
|
||||
|
||||
def scan(source: str) -> str:
|
||||
"""
|
||||
静态扫描。返回**拒绝原因**(空串 = 通过)。
|
||||
|
||||
★ 这层拦的是"手滑"和"抄来的脚本夹带了东西",不是"有意攻击"。
|
||||
真要有意,Python 语法层面总有办法绕(见模块 docstring)。
|
||||
"""
|
||||
text = source or ''
|
||||
if len(text) > 200_000:
|
||||
return '脚本太长了(上限 200KB)'
|
||||
for pattern, why in DANGEROUS:
|
||||
m = pattern.search(text)
|
||||
if m:
|
||||
line = text[:m.start()].count('\n') + 1
|
||||
return f'第 {line} 行:{why}(`{m.group(0).strip()}`)'
|
||||
return ''
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 第 3 层:执行
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def build_globals(apis: dict, source_name: str = '<rule>') -> dict:
|
||||
"""
|
||||
给 `exec` 用的命名空间。
|
||||
|
||||
[apis] 是**注入给脚本的能力**(需求 3.11 的三项 + 状态提示词改写)——
|
||||
通过**参数**传进去,而不是做成模块级函数:那样脚本能 `import` 到别的东西,
|
||||
也会让两个脚本互相污染。
|
||||
"""
|
||||
return {
|
||||
'__builtins__': dict(SAFE_BUILTINS),
|
||||
'__name__': 'rule_script',
|
||||
'__file__': source_name,
|
||||
'__doc__': None,
|
||||
'__package__': None,
|
||||
**apis,
|
||||
}
|
||||
|
||||
|
||||
def load(source: str, source_name: str = '<rule>', apis: dict = None) -> dict:
|
||||
"""
|
||||
扫描 → 编译 → 执行模块体,返回那个命名空间(里面应该有入口函数)。
|
||||
|
||||
抛 [ScriptRejected] 表示没通过扫描;语法错误直接抛 SyntaxError
|
||||
(调用方接住,转成"你的脚本第 N 行有语法错误")。
|
||||
"""
|
||||
why = scan(source)
|
||||
if why:
|
||||
raise ScriptRejected(why)
|
||||
ns = build_globals(apis or {}, source_name)
|
||||
code = compile(source or '', source_name, 'exec')
|
||||
exec(code, ns) # noqa: S102 - 见模块 docstring:这是提高门槛,不是真沙箱
|
||||
return ns
|
||||
|
||||
|
||||
def call(ns: dict, entry: str, *args, **kwargs):
|
||||
"""
|
||||
调脚本里的入口函数。
|
||||
|
||||
没定义那个函数时抛 `KeyError`,调用方转成
|
||||
"脚本里没有 `on_turn` 函数"这种能给用户看的话。
|
||||
"""
|
||||
fn = ns.get(entry)
|
||||
if not callable(fn):
|
||||
raise KeyError(entry)
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 给界面看的说明(导入警告用)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: ★ 导入规则包时**原样显示**给用户的话。
|
||||
#: 故意不说"安全沙箱"——它挡得住手滑,挡不住有意(见模块 docstring)。
|
||||
IMPORT_WARNING = (
|
||||
'此包包含可执行 Python 脚本,会**每轮在你的设备上运行**。\n\n'
|
||||
'脚本被限制了模块引入和文件读写(只能用几个安全的计算函数),'
|
||||
'但这**不是**真正的沙箱 —— 精心构造的脚本仍然可能读到设备上的文件,'
|
||||
'也可能占用大量内存或算力拖慢手机。\n\n'
|
||||
'只导入你信得过的来源。'
|
||||
)
|
||||
@@ -41,6 +41,78 @@ def now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def normalize_image(image) -> dict:
|
||||
"""
|
||||
把 `image` 归一化成 v1.2 的形状(读的时候统一调它)。
|
||||
|
||||
★★ v1.2 把 `front` 从**单个文件名**扩成了**五档立绘表**(需求 2.5):
|
||||
|
||||
v1.1: "front": "normal.png"
|
||||
v1.2: "front": {"喜": "happy.png", "怒": "angry.png",
|
||||
"哀": "sad.png", "平常": "normal.png", "死亡": "dead.png"}
|
||||
|
||||
兼容规则是"**旧格式视为仅有「平常」档**"(需求原话)。
|
||||
|
||||
★ 为什么在**读**的时候归一化、而不是在写的时候:老数据已经在磁盘上了
|
||||
(`agents.json` 里存的就是字符串),写的时候归一化管不到它们。
|
||||
读的时候归一化则一次覆盖新旧两种 —— 而且写入路径不用改,
|
||||
"用户手改过 agents.json" 这种情况也不会被冲掉。
|
||||
|
||||
归一化**不丢信息**:字典里多出来的档位原样保留(用户可能自己加了「醉」这种)。
|
||||
|
||||
★★ 还要**解套**:有一版把 `front` 的字典值也 `_as_text` 了一遍,于是磁盘上
|
||||
存成了 `"{'平常': 'C:\\...\\a.png'}"`(**字符串化的字典**)。
|
||||
那种数据要能救回来 —— 不然用户看到的就是"**我设的图不见了**":
|
||||
档位读不出来(是个字符串不是字典),而且每读写一次还多包一层,
|
||||
最后连 `os.path.isfile` 都失败。
|
||||
"""
|
||||
img = dict(image or {})
|
||||
front = img.get('front')
|
||||
if isinstance(front, str) and front.strip().startswith('{'):
|
||||
# ② 字符串化的字典 → 解回真字典
|
||||
img['front'] = _unshell_dict(front)
|
||||
elif isinstance(front, str):
|
||||
# ① v1.1 的单文件名 → 只有「平常」档
|
||||
img['front'] = {'平常': front.strip()} if front.strip() else {}
|
||||
elif isinstance(front, dict):
|
||||
fixed = {}
|
||||
for k, v in front.items():
|
||||
key = str(k)
|
||||
if isinstance(v, str) and v.strip().startswith('{'):
|
||||
# 值本身又被包成了字典 → 摊平(旧数据里反复读写会这样)
|
||||
for ik, iv in _unshell_dict(v).items():
|
||||
if isinstance(iv, str) and iv.strip():
|
||||
fixed[str(ik)] = iv.strip()
|
||||
continue
|
||||
if str(v or '').strip():
|
||||
fixed[key] = str(v).strip()
|
||||
img['front'] = fixed
|
||||
else:
|
||||
img['front'] = {}
|
||||
for key in ('back', 'border-main', 'border-info'):
|
||||
img[key] = str(img.get(key) or '')
|
||||
return img
|
||||
|
||||
|
||||
def _unshell_dict(text: str) -> dict:
|
||||
"""
|
||||
把**字符串化的字典**解回 dict(解不开就给空字典)。
|
||||
|
||||
★ 用 `ast.literal_eval` 而不是 `eval`:它只能求值**字面量**
|
||||
(数字、字符串、列表、字典……),遇到函数调用直接报错。
|
||||
就算那段文本被谁改过,也执行不了任何东西。
|
||||
"""
|
||||
import ast
|
||||
|
||||
try:
|
||||
got = ast.literal_eval(str(text or ''))
|
||||
except (ValueError, SyntaxError):
|
||||
return {}
|
||||
if not isinstance(got, dict):
|
||||
return {}
|
||||
return {str(k): v for k, v in got.items()}
|
||||
|
||||
|
||||
def _read_json(file_path: str):
|
||||
"""读 JSON;文件不存在或坏掉都返回 None(调用方决定怎么兜底)。"""
|
||||
if not os.path.isfile(file_path):
|
||||
@@ -572,13 +644,18 @@ def session_message_count(conv_id: str) -> int:
|
||||
return sum(1 for m in (conv.get('messages') or []) if m.get('aiSent'))
|
||||
|
||||
|
||||
def append_message(conv_id: str, role: str, content: str) -> dict:
|
||||
def append_message(conv_id: str, role: str, content: str, agent_id: str = '') -> dict:
|
||||
"""
|
||||
往会话里追加一条消息(AI 主动发的)。
|
||||
|
||||
★ 走 `update_conversation` 而不是自己写文件:会话的落盘、时间戳、
|
||||
标题自动生成那些逻辑都在那儿,这里再写一份就会不一致
|
||||
(这个仓库里"同一段逻辑两份、加功能只改一份"的坑踩过好几次)。
|
||||
|
||||
★ [agent_id] 是**说这句话的是谁**。群聊里每条消息的发言者都不一样,
|
||||
界面朗读时要按它挑音色 —— 不记的话只能一律用"当前对话的主人",
|
||||
表现就是"群聊时不同智能体的语音不会切换"(真机反馈)。
|
||||
`/api/chat` 那条路一直在写这个字段,只有这里漏了。
|
||||
"""
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
@@ -592,6 +669,8 @@ def append_message(conv_id: str, role: str, content: str) -> dict:
|
||||
# 用来算"这个会话还能主动发几条",界面上不显示、也不给模型看。
|
||||
'aiSent': True,
|
||||
}
|
||||
if agent_id:
|
||||
msg['agentId'] = str(agent_id)
|
||||
msgs.append(msg)
|
||||
update_conversation(conv_id, {'messages': msgs})
|
||||
return msg
|
||||
@@ -890,11 +969,27 @@ def take_summary_suggestion(agent_id: str) -> str:
|
||||
return _pending_summary.pop(agent_id or '', '')
|
||||
|
||||
|
||||
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
|
||||
def create_conversation(title: str = '新对话', agent_id: str | None = None,
|
||||
kind: str = 'single', participants: list | None = None) -> dict:
|
||||
"""
|
||||
新建会话。
|
||||
|
||||
★ v1.2 加了两个字段(需求 §3.9):
|
||||
|
||||
type single(单聊)/ group(群聊)/ private(私聊记录)
|
||||
participants 群聊的成员 id 列表(单聊为空)
|
||||
|
||||
群聊/私聊是**独立实体**,出现在每个参与者的会话列表里 ——
|
||||
不是"每个智能体各存一份",那样三条记录迟早会不同步。
|
||||
"""
|
||||
item = {
|
||||
'id': _rid_conv(),
|
||||
'title': title,
|
||||
'agentId': agent_id or '',
|
||||
# ★ 老会话没有这两个字段 → 读的时候当 single 处理(见 toConversation),
|
||||
# 所以不用写迁移:JSON 里少两个键不影响任何东西
|
||||
'type': kind if kind in ('single', 'group', 'private') else 'single',
|
||||
'participants': [str(p) for p in (participants or []) if str(p or '').strip()],
|
||||
'pinned': False,
|
||||
'createdAt': now_iso(),
|
||||
'updatedAt': now_iso(),
|
||||
@@ -963,6 +1058,72 @@ def append_messages(conv_id: str, messages: list):
|
||||
return item
|
||||
|
||||
|
||||
def mark_important(conv_id: str, index: int, important: bool):
|
||||
"""
|
||||
给第 [index] 条消息打/取消「重要」标记(v1.2 §4.3)。
|
||||
|
||||
★ 需求原话:"**仅用户可标**;被标记消息破格永久携带、按原始时间序插入"。
|
||||
所以这个函数**只由界面调**,AI 那边没有对应的工具 ——
|
||||
它有 `memory_add` 去记该记的东西,标记是用户的主权。
|
||||
|
||||
★★ 按**下标**定位是**不安全**的,已经踩过:界面上那份消息列表可能和
|
||||
存储里的**不是一一对应**(本地生成的内容、还没落地的流式消息……),
|
||||
于是"长按第 3 条"会把标记打到第 1 条上 —— **静默标错**,
|
||||
而用户完全看不出来(要等哪天发现某句话莫名没被裁掉)。
|
||||
所以界面走的是 `mark_important_by_content`,这个按下标的老函数
|
||||
只留给内部/测试用。
|
||||
"""
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
return None
|
||||
msgs = item.get('messages') or []
|
||||
if not (0 <= index < len(msgs)):
|
||||
return None
|
||||
with _lock:
|
||||
# ★ 只改这一个字段,**不动 content** —— 需求把"历史消息字节冻结"
|
||||
# 写成了内核纪律:改一个字,从那儿往后的前缀缓存全废。
|
||||
# 标一个 `important` 是**新增键**,不影响 content 的字节。
|
||||
msgs[index]['important'] = bool(important)
|
||||
item['updatedAt'] = now_iso()
|
||||
_persist_conversations()
|
||||
return msgs[index]
|
||||
|
||||
|
||||
def mark_important_by_content(conv_id: str, content: str, role: str = '',
|
||||
important: bool = True):
|
||||
"""
|
||||
按**内容**找那条消息来打标记(界面的长按走这条路)。
|
||||
|
||||
★ 为什么不用下标:见 `mark_important` 的说明 —— 界面的列表和存储的
|
||||
列表**不保证一一对应**,下标会静默标错。
|
||||
|
||||
★ 从**后往前**找:同一个内容可能重复出现(用户把一句话发了两遍),
|
||||
而他长按的通常是比较靠后的那条。
|
||||
|
||||
★ 找不到就返回 None,让调用方**报错** —— 绝不"猜一条"标上去。
|
||||
标错了用户看不出来,而那比报错糟得多。
|
||||
"""
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
return None
|
||||
want = _as_text(content)
|
||||
if not want:
|
||||
return None
|
||||
msgs = item.get('messages') or []
|
||||
hit = -1
|
||||
for i in range(len(msgs) - 1, -1, -1):
|
||||
m = msgs[i]
|
||||
if _as_text(m.get('content')) != want:
|
||||
continue
|
||||
if role and m.get('role') != role:
|
||||
continue
|
||||
hit = i
|
||||
break
|
||||
if hit < 0:
|
||||
return None
|
||||
return mark_important(conv_id, hit, important)
|
||||
|
||||
|
||||
def auto_title(conv_id: str, text: str) -> None:
|
||||
"""用首条用户消息自动起标题(只改还没起过名的会话)。"""
|
||||
item = get_conversation(conv_id)
|
||||
@@ -1010,10 +1171,17 @@ AGENT_TEXT_FIELDS = (
|
||||
'ttsVoice', # 音色 —— 多人会议里靠它区分谁在说话
|
||||
'modelId', # ← 全局模型列表里的 id
|
||||
'worldviewId', # ← 绑定的世界观 id
|
||||
# ★ v1.2 新增:
|
||||
# inviteMode 拉起其他智能体:silent 直接进场 / confirm 先问用户(§6.1)
|
||||
# contextWindow 对话上下文窗口(§4.3,留空继承全局)
|
||||
# ★ 这两个字段**必须列在这儿** —— 不列的话 _apply_agent_patch 会丢掉,
|
||||
# 表现是"界面上配了、读出来没有"(rulePackId 那个坑一模一样)
|
||||
'inviteMode',
|
||||
)
|
||||
AGENT_NUM_FIELDS = (
|
||||
'ttsSpeed', # 语速
|
||||
'tokenLimit', # 0 = 无限制(不是"限额为 0")
|
||||
'contextWindow', # v1.2 §4.3:这个智能体的对话上下文窗口(轮)
|
||||
)
|
||||
AGENT_BOOL_FIELDS = ('emotionEnabled',)
|
||||
AGENT_LIST_FIELDS = ('skillIds',)
|
||||
@@ -1055,24 +1223,46 @@ def _apply_agent_patch(agent: dict, patch: dict) -> dict:
|
||||
for key in AGENT_DICT_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
raw = patch[key]
|
||||
agent[key] = (
|
||||
{str(k): _as_text(v) for k, v in raw.items()}
|
||||
if isinstance(raw, dict) else {}
|
||||
)
|
||||
# ★★ 和 `_apply_resource_patch` 一样:**不能对每个值调 `_as_text`**。
|
||||
#
|
||||
# 智能体的 `image` 以前只有字符串(文件名),转一下无妨;
|
||||
# 但 v1.2 的立绘是**五档字典**(`front: {'喜': 路径, ...}`)——
|
||||
# 转成字符串之后,那个键就变成了 `"{'喜': 'C:\\...'}"` 这种
|
||||
# 字符串化的字典:
|
||||
# · 回退链按档位找不到(`front['喜']` 从字典里读不到)
|
||||
# · 而且**每读写一次就多包一层**,最后 `os.path.isfile` 失败
|
||||
# —— 表现就是用户说的"**之前设置的图像也没了**"
|
||||
#
|
||||
# 改成 `_json_safe`:保留嵌套结构,只把 JSON 存不下的转字符串。
|
||||
agent[key] = _json_safe(raw) if isinstance(raw, dict) else {}
|
||||
return agent
|
||||
|
||||
|
||||
def list_agents() -> list:
|
||||
"""
|
||||
全部智能体。**出口统一归一化 `image`**(v1.2 的立绘表,见 `normalize_image`)。
|
||||
|
||||
★ 归一化放在这里而不是写入时:老数据(`agents.json` 里 `front` 是字符串)
|
||||
已经在磁盘上了,写时归一化管不到它们。读时归一化一次覆盖新旧两种,
|
||||
而且写入路径一行都不用改。
|
||||
"""
|
||||
file_path = paths.get().agents_file
|
||||
if not os.path.isfile(file_path):
|
||||
_write_json(file_path, {'agents': DEFAULT_AGENTS})
|
||||
return [dict(a) for a in DEFAULT_AGENTS]
|
||||
return [normalize_image_agent(dict(a)) for a in DEFAULT_AGENTS]
|
||||
data = _read_json(file_path)
|
||||
if not isinstance(data, dict) or not isinstance(data.get('agents'), list) or not data['agents']:
|
||||
print('[store] agents.json 损坏,重建内置智能体', file=sys.stderr)
|
||||
_write_json(file_path, {'agents': DEFAULT_AGENTS})
|
||||
return [dict(a) for a in DEFAULT_AGENTS]
|
||||
return data['agents']
|
||||
return [normalize_image_agent(dict(a)) for a in DEFAULT_AGENTS]
|
||||
return [normalize_image_agent(a) for a in data['agents']]
|
||||
|
||||
|
||||
def normalize_image_agent(agent: dict) -> dict:
|
||||
"""把一个智能体(或世界观)的 `image` 归一化。就地改那份 dict,也返回它"""
|
||||
if isinstance(agent, dict):
|
||||
agent['image'] = normalize_image(agent.get('image'))
|
||||
return agent
|
||||
|
||||
|
||||
def get_agent(agent_id: str | None):
|
||||
@@ -1146,16 +1336,34 @@ RESOURCES = {
|
||||
'worldviews': {
|
||||
'file': lambda: paths.get().worldviews_file,
|
||||
'key': 'worldviews',
|
||||
'text': ('name', 'setting'),
|
||||
# ★ rulePackId:这个世界观挂的**数值状态包**(需求 §3.6:
|
||||
# "v1.2 起,世界观同时是数值状态包的挂载点")。
|
||||
# 没有它的话这个字段会被 _apply_resource_patch 丢掉 ——
|
||||
# 表现是"设置界面里配了、读出来没有",排查起来得一路看到字段表。
|
||||
'text': ('name', 'setting', 'rulePackId'),
|
||||
'dict': ('image',),
|
||||
'label': '世界观',
|
||||
},
|
||||
# 数值状态包(需求附录 D):定义 + 对应 Python 脚本
|
||||
'rulepacks': {
|
||||
'file': lambda: paths.get().rulepacks_file,
|
||||
'key': 'rulepacks',
|
||||
'text': ('name', 'note'),
|
||||
# info 是解析好的 info.json(stats / statuses 两张表);
|
||||
# scripts 是 {文件名: 源码} —— **整包一起存**,因为脚本要落盘才能跑
|
||||
'dict': ('info', 'scripts'),
|
||||
'label': '规则包',
|
||||
},
|
||||
# 全局模型列表(需求 3.3):名称 + API 端点 + Key + 模型标识 + 单价
|
||||
'models': {
|
||||
'file': lambda: paths.get().models_file,
|
||||
'key': 'models',
|
||||
'text': ('name', 'apiBase', 'apiKey', 'model', 'provider'),
|
||||
'num': ('pricePerK',), # 元/千 Token,0 = 不显示费用估算
|
||||
# 元/千 Token,0 = 不显示费用估算。
|
||||
# ★ cachePricePerK 是**命中缓存**的单价(v1.2):各家命中都比未命中
|
||||
# 便宜得多(常见 1/10)。只填一个输入单价的话,费用估算会按未命中
|
||||
# 的价格算 —— 用得越多、高估得越离谱,而用户会以为自己真花了那些钱。
|
||||
'num': ('pricePerK', 'cachePricePerK'),
|
||||
# ★ noTools:这个模型不支持 function calling(需求 3.3 的兼容降级)。
|
||||
# 打开之后不传 tools、改成正文内的调用约定 —— 见 agent_loop.DEGRADED_HINT。
|
||||
'bool': ('noTools',),
|
||||
@@ -1220,18 +1428,51 @@ def _apply_resource_patch(name: str, item: dict, patch: dict) -> dict:
|
||||
for key in cfg.get('dict', ()):
|
||||
if patch.get(key) is not None:
|
||||
raw = patch[key]
|
||||
item[key] = (
|
||||
{str(k): _as_text(v) for k, v in raw.items()}
|
||||
if isinstance(raw, dict) else {}
|
||||
)
|
||||
# ★★ **不要对每个值调 `_as_text`**。
|
||||
#
|
||||
# 原来那么写是因为 `image` 的值全是字符串(路径),转一下无妨。
|
||||
# 但 v1.2 的规则包里 `info` 的值是**嵌套结构**
|
||||
# (`stats: [{name, min, max, ranges: [...]}]`)——
|
||||
# 转成字符串之后 `sync_defs` 读到的就是 `"[{'name': 'A'}]"`,
|
||||
# 于是**整个规则引擎静默失效**(解析不出来 → 当成没定义 → 不报错)。
|
||||
# 这种"看起来存进去了、实际全废"的坑最难查。
|
||||
item[key] = _json_safe(raw) if isinstance(raw, dict) else {}
|
||||
return item
|
||||
|
||||
|
||||
def _json_safe(v):
|
||||
"""
|
||||
只留下 JSON 存得下的东西(dict / list / 字符串 / 数字 / 布尔 / None)。
|
||||
|
||||
别的(set、datetime、自定义对象)转成字符串 —— 不让它们把写盘搞炸,
|
||||
同时**保留嵌套结构**(这是 `_as_text` 做不到的)。
|
||||
"""
|
||||
if isinstance(v, dict):
|
||||
return {str(k): _json_safe(x) for k, x in v.items()}
|
||||
if isinstance(v, (list, tuple)):
|
||||
return [_json_safe(x) for x in v]
|
||||
if v is None or isinstance(v, (str, int, float, bool)):
|
||||
return v
|
||||
return str(v)
|
||||
|
||||
|
||||
def create_resource(name: str, payload: dict) -> dict:
|
||||
"""
|
||||
新建一种资源。
|
||||
|
||||
★ 允许 `payload` 里带 `id`(**校验过才用**):规则包需要它 ——
|
||||
数值定义表的 key 是规则包 id(`sync_defs` 用它写库),
|
||||
如果 `create_resource` 自己生成 id,调用方就得"先建再改"两步,
|
||||
中途失败会留下一个没有定义的孤儿包。
|
||||
已经存在同名 id 时**自动换一个**,不覆盖别人的东西。
|
||||
"""
|
||||
cfg = _res(name)
|
||||
items = list_resource(name)
|
||||
want_id = _as_text((payload or {}).get('id')).strip()
|
||||
if want_id and (len(want_id) > 64 or any(x.get('id') == want_id for x in items)):
|
||||
want_id = '' # 不合法或撞了 → 当作没给
|
||||
item = {
|
||||
'id': agentdb.new_id(), # ★ UUID(需求附录 A)
|
||||
'id': want_id or agentdb.new_id(), # ★ UUID(需求附录 A)
|
||||
'name': _as_text((payload or {}).get('name'))[:40],
|
||||
'builtin': False,
|
||||
'createdAt': now_iso(),
|
||||
|
||||
@@ -132,10 +132,30 @@ _ctx = threading.local()
|
||||
|
||||
|
||||
def push_context(**kw) -> None:
|
||||
"""进入一次工具调用(agent_loop 在 execute_tool 前调用)"""
|
||||
"""进入一次工具调用(agent_loop 在 execute_tool 前调用)。
|
||||
|
||||
★ 这是**替换**语义:把整份上下文换成新的。
|
||||
"""
|
||||
_ctx.value = dict(kw)
|
||||
|
||||
|
||||
def update_context(**kw) -> None:
|
||||
"""
|
||||
在**当前上下文里补几个键**(已有的不动)。
|
||||
|
||||
★★ 和 `push_context` 的区别很要紧,踩过一次:
|
||||
|
||||
· `push_context` 是**替换** —— 给"进入一次工具调用"用的
|
||||
· 工具内部想加个标记(比如 `pass_turn` 记"这一轮移交过了")时
|
||||
如果用 `push_context`,会把 `agentId` / `conversationId` 一起冲掉,
|
||||
接着同一个工具里的 `_me()` 就炸了(表现是"拿不到当前智能体",
|
||||
而报错的地方离真正的原因隔着好几步)
|
||||
"""
|
||||
cur = dict(getattr(_ctx, 'value', None) or {})
|
||||
cur.update(kw)
|
||||
_ctx.value = cur
|
||||
|
||||
|
||||
def clear_context() -> None:
|
||||
_ctx.value = None
|
||||
|
||||
@@ -145,6 +165,55 @@ def current_context() -> dict:
|
||||
return dict(getattr(_ctx, 'value', None) or {})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 轮次级状态(发言权移交)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★★ 为什么**不能**用工具上下文(`update_context`)来记这个 —— 踩过:
|
||||
#
|
||||
# 工具跑在 **worker 线程**里(`builtin_tools.run_with_timeout` 起线程),
|
||||
# 而 `_ctx` 是 `threading.local()`。工具在里面写 `update_context(...)`,
|
||||
# 写的是**那个 worker 线程**的副本;线程一结束、`finally` 里把值置 None,
|
||||
# 标记就没了。而主线程每次调用前又 `push_context(...)`(替换语义)——
|
||||
# 于是"这一轮已经移交过"**永远是 False**,`pass_turn` 可以一轮交无限次。
|
||||
#
|
||||
# ★ 更麻烦的是:探针当时是**直接调 `agent_tools.pass_turn`**(主线程),
|
||||
# 标记留在主线程里没被清 → 探针**假通过**。真机上才会露馅。
|
||||
# 所以这里的修复必须配一条**走真实路径**的探针(见 probe-group-chat)。
|
||||
#
|
||||
# 轮次级状态放**模块级**,和线程无关,`agent_loop` 每轮开头重置一次。
|
||||
_handoff = {'to': '', 'used': False, 'queue': []}
|
||||
|
||||
|
||||
def begin_round() -> None:
|
||||
"""一轮对话开始时调用(agent_loop 在生成前调)"""
|
||||
_handoff['to'] = ''
|
||||
_handoff['used'] = False
|
||||
_handoff['queue'] = []
|
||||
|
||||
|
||||
def note_handoff(agent_id: str, queue: list = None) -> None:
|
||||
"""
|
||||
记下"这一轮把话交给了谁"。
|
||||
|
||||
[queue] 是**多目标**时的完整名单(`talk_to` 支持一次找好几个人,
|
||||
他们挨个回话)。`to` 始终是**第一个**,保持老调用方不用改。
|
||||
"""
|
||||
ids = [str(x) for x in (queue or []) if str(x or '').strip()]
|
||||
if not ids and str(agent_id or '').strip():
|
||||
ids = [str(agent_id)]
|
||||
_handoff['to'] = ids[0] if ids else str(agent_id or '')
|
||||
_handoff['used'] = True
|
||||
# 剩下的排进队列(`to` 已经算第一个了)
|
||||
_handoff['queue'] = ids[1:]
|
||||
|
||||
|
||||
def handoff_state() -> dict:
|
||||
"""读这一轮的移交状态(`app.py` 的仲裁要用 `to`,界面要用 `queue`)"""
|
||||
return {'to': _handoff['to'], 'used': _handoff['used'],
|
||||
'queue': list(_handoff.get('queue') or [])}
|
||||
|
||||
|
||||
def ui_tools_enabled(settings: dict) -> bool:
|
||||
"""
|
||||
界面工具开了没有。
|
||||
|
||||
645
desktop/build-cache/embed-test/LICENSE.txt
Normal file
@@ -0,0 +1,645 @@
|
||||
A. HISTORY OF THE SOFTWARE
|
||||
==========================
|
||||
|
||||
Python was created in the early 1990s by Guido van Rossum at Stichting
|
||||
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
|
||||
as a successor of a language called ABC. Guido remains Python's
|
||||
principal author, although it includes many contributions from others.
|
||||
|
||||
In 1995, Guido continued his work on Python at the Corporation for
|
||||
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
|
||||
in Reston, Virginia where he released several versions of the
|
||||
software.
|
||||
|
||||
In May 2000, Guido and the Python core development team moved to
|
||||
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
|
||||
year, the PythonLabs team moved to Digital Creations, which became
|
||||
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
|
||||
https://www.python.org/psf/) was formed, a non-profit organization
|
||||
created specifically to own Python-related Intellectual Property.
|
||||
Zope Corporation was a sponsoring member of the PSF.
|
||||
|
||||
All Python releases are Open Source (see https://opensource.org for
|
||||
the Open Source Definition). Historically, most, but not all, Python
|
||||
releases have also been GPL-compatible; the table below summarizes
|
||||
the various releases.
|
||||
|
||||
Release Derived Year Owner GPL-
|
||||
from compatible? (1)
|
||||
|
||||
0.9.0 thru 1.2 1991-1995 CWI yes
|
||||
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
|
||||
1.6 1.5.2 2000 CNRI no
|
||||
2.0 1.6 2000 BeOpen.com no
|
||||
1.6.1 1.6 2001 CNRI yes (2)
|
||||
2.1 2.0+1.6.1 2001 PSF no
|
||||
2.0.1 2.0+1.6.1 2001 PSF yes
|
||||
2.1.1 2.1+2.0.1 2001 PSF yes
|
||||
2.1.2 2.1.1 2002 PSF yes
|
||||
2.1.3 2.1.2 2002 PSF yes
|
||||
2.2 and above 2.1.1 2001-now PSF yes
|
||||
|
||||
Footnotes:
|
||||
|
||||
(1) GPL-compatible doesn't mean that we're distributing Python under
|
||||
the GPL. All Python licenses, unlike the GPL, let you distribute
|
||||
a modified version without making your changes open source. The
|
||||
GPL-compatible licenses make it possible to combine Python with
|
||||
other software that is released under the GPL; the others don't.
|
||||
|
||||
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
|
||||
because its license has a choice of law clause. According to
|
||||
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
|
||||
is "not incompatible" with the GPL.
|
||||
|
||||
Thanks to the many outside volunteers who have worked under Guido's
|
||||
direction to make these releases possible.
|
||||
|
||||
|
||||
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
|
||||
===============================================================
|
||||
|
||||
Python software and documentation are licensed under the
|
||||
Python Software Foundation License Version 2.
|
||||
|
||||
Starting with Python 3.8.6, examples, recipes, and other code in
|
||||
the documentation are dual licensed under the PSF License Version 2
|
||||
and the Zero-Clause BSD license.
|
||||
|
||||
Some software incorporated into Python is under different licenses.
|
||||
The licenses are listed with code falling under that license.
|
||||
|
||||
|
||||
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
||||
--------------------------------------------
|
||||
|
||||
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
||||
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
||||
otherwise using this software ("Python") in source or binary form and
|
||||
its associated documentation.
|
||||
|
||||
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
||||
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
||||
analyze, test, perform and/or display publicly, prepare derivative works,
|
||||
distribute, and otherwise use Python alone or in any derivative version,
|
||||
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
||||
i.e., "Copyright (c) 2001-2024 Python Software Foundation; All Rights Reserved"
|
||||
are retained in Python alone or in any derivative version prepared by Licensee.
|
||||
|
||||
3. In the event Licensee prepares a derivative work that is based on
|
||||
or incorporates Python or any part thereof, and wants to make
|
||||
the derivative work available to others as provided herein, then
|
||||
Licensee hereby agrees to include in any such work a brief summary of
|
||||
the changes made to Python.
|
||||
|
||||
4. PSF is making Python available to Licensee on an "AS IS"
|
||||
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
||||
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
6. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
7. Nothing in this License Agreement shall be deemed to create any
|
||||
relationship of agency, partnership, or joint venture between PSF and
|
||||
Licensee. This License Agreement does not grant permission to use PSF
|
||||
trademarks or trade name in a trademark sense to endorse or promote
|
||||
products or services of Licensee, or any third party.
|
||||
|
||||
8. By copying, installing or otherwise using Python, Licensee
|
||||
agrees to be bound by the terms and conditions of this License
|
||||
Agreement.
|
||||
|
||||
|
||||
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
|
||||
-------------------------------------------
|
||||
|
||||
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
|
||||
|
||||
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
|
||||
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
|
||||
Individual or Organization ("Licensee") accessing and otherwise using
|
||||
this software in source or binary form and its associated
|
||||
documentation ("the Software").
|
||||
|
||||
2. Subject to the terms and conditions of this BeOpen Python License
|
||||
Agreement, BeOpen hereby grants Licensee a non-exclusive,
|
||||
royalty-free, world-wide license to reproduce, analyze, test, perform
|
||||
and/or display publicly, prepare derivative works, distribute, and
|
||||
otherwise use the Software alone or in any derivative version,
|
||||
provided, however, that the BeOpen Python License is retained in the
|
||||
Software, alone or in any derivative version prepared by Licensee.
|
||||
|
||||
3. BeOpen is making the Software available to Licensee on an "AS IS"
|
||||
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
|
||||
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
|
||||
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
|
||||
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
5. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
6. This License Agreement shall be governed by and interpreted in all
|
||||
respects by the law of the State of California, excluding conflict of
|
||||
law provisions. Nothing in this License Agreement shall be deemed to
|
||||
create any relationship of agency, partnership, or joint venture
|
||||
between BeOpen and Licensee. This License Agreement does not grant
|
||||
permission to use BeOpen trademarks or trade names in a trademark
|
||||
sense to endorse or promote products or services of Licensee, or any
|
||||
third party. As an exception, the "BeOpen Python" logos available at
|
||||
http://www.pythonlabs.com/logos.html may be used according to the
|
||||
permissions granted on that web page.
|
||||
|
||||
7. By copying, installing or otherwise using the software, Licensee
|
||||
agrees to be bound by the terms and conditions of this License
|
||||
Agreement.
|
||||
|
||||
|
||||
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
|
||||
---------------------------------------
|
||||
|
||||
1. This LICENSE AGREEMENT is between the Corporation for National
|
||||
Research Initiatives, having an office at 1895 Preston White Drive,
|
||||
Reston, VA 20191 ("CNRI"), and the Individual or Organization
|
||||
("Licensee") accessing and otherwise using Python 1.6.1 software in
|
||||
source or binary form and its associated documentation.
|
||||
|
||||
2. Subject to the terms and conditions of this License Agreement, CNRI
|
||||
hereby grants Licensee a nonexclusive, royalty-free, world-wide
|
||||
license to reproduce, analyze, test, perform and/or display publicly,
|
||||
prepare derivative works, distribute, and otherwise use Python 1.6.1
|
||||
alone or in any derivative version, provided, however, that CNRI's
|
||||
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
|
||||
1995-2001 Corporation for National Research Initiatives; All Rights
|
||||
Reserved" are retained in Python 1.6.1 alone or in any derivative
|
||||
version prepared by Licensee. Alternately, in lieu of CNRI's License
|
||||
Agreement, Licensee may substitute the following text (omitting the
|
||||
quotes): "Python 1.6.1 is made available subject to the terms and
|
||||
conditions in CNRI's License Agreement. This Agreement together with
|
||||
Python 1.6.1 may be located on the internet using the following
|
||||
unique, persistent identifier (known as a handle): 1895.22/1013. This
|
||||
Agreement may also be obtained from a proxy server on the internet
|
||||
using the following URL: http://hdl.handle.net/1895.22/1013".
|
||||
|
||||
3. In the event Licensee prepares a derivative work that is based on
|
||||
or incorporates Python 1.6.1 or any part thereof, and wants to make
|
||||
the derivative work available to others as provided herein, then
|
||||
Licensee hereby agrees to include in any such work a brief summary of
|
||||
the changes made to Python 1.6.1.
|
||||
|
||||
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
|
||||
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
|
||||
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
6. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
7. This License Agreement shall be governed by the federal
|
||||
intellectual property law of the United States, including without
|
||||
limitation the federal copyright law, and, to the extent such
|
||||
U.S. federal law does not apply, by the law of the Commonwealth of
|
||||
Virginia, excluding Virginia's conflict of law provisions.
|
||||
Notwithstanding the foregoing, with regard to derivative works based
|
||||
on Python 1.6.1 that incorporate non-separable material that was
|
||||
previously distributed under the GNU General Public License (GPL), the
|
||||
law of the Commonwealth of Virginia shall govern this License
|
||||
Agreement only as to issues arising under or with respect to
|
||||
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
|
||||
License Agreement shall be deemed to create any relationship of
|
||||
agency, partnership, or joint venture between CNRI and Licensee. This
|
||||
License Agreement does not grant permission to use CNRI trademarks or
|
||||
trade name in a trademark sense to endorse or promote products or
|
||||
services of Licensee, or any third party.
|
||||
|
||||
8. By clicking on the "ACCEPT" button where indicated, or by copying,
|
||||
installing or otherwise using Python 1.6.1, Licensee agrees to be
|
||||
bound by the terms and conditions of this License Agreement.
|
||||
|
||||
ACCEPT
|
||||
|
||||
|
||||
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
|
||||
--------------------------------------------------
|
||||
|
||||
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
|
||||
The Netherlands. All rights reserved.
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted,
|
||||
provided that the above copyright notice appear in all copies and that
|
||||
both that copyright notice and this permission notice appear in
|
||||
supporting documentation, and that the name of Stichting Mathematisch
|
||||
Centrum or CWI not be used in advertising or publicity pertaining to
|
||||
distribution of the software without specific, written prior
|
||||
permission.
|
||||
|
||||
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
|
||||
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
|
||||
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
||||
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
|
||||
----------------------------------------------------------------------
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
|
||||
|
||||
Additional Conditions for this Windows binary build
|
||||
---------------------------------------------------
|
||||
|
||||
This program is linked with and uses Microsoft Distributable Code,
|
||||
copyrighted by Microsoft Corporation. The Microsoft Distributable Code
|
||||
is embedded in each .exe, .dll and .pyd file as a result of running
|
||||
the code through a linker.
|
||||
|
||||
If you further distribute programs that include the Microsoft
|
||||
Distributable Code, you must comply with the restrictions on
|
||||
distribution specified by Microsoft. In particular, you must require
|
||||
distributors and external end users to agree to terms that protect the
|
||||
Microsoft Distributable Code at least as much as Microsoft's own
|
||||
requirements for the Distributable Code. See Microsoft's documentation
|
||||
(included in its developer tools and on its website at microsoft.com)
|
||||
for specific details.
|
||||
|
||||
Redistribution of the Windows binary build of the Python interpreter
|
||||
complies with this agreement, provided that you do not:
|
||||
|
||||
- alter any copyright, trademark or patent notice in Microsoft's
|
||||
Distributable Code;
|
||||
|
||||
- use Microsoft's trademarks in your programs' names or in a way that
|
||||
suggests your programs come from or are endorsed by Microsoft;
|
||||
|
||||
- distribute Microsoft's Distributable Code to run on a platform other
|
||||
than Microsoft operating systems, run-time technologies or application
|
||||
platforms; or
|
||||
|
||||
- include Microsoft Distributable Code in malicious, deceptive or
|
||||
unlawful programs.
|
||||
|
||||
These restrictions apply only to the Microsoft Distributable Code as
|
||||
defined above, not to Python itself or any programs running on the
|
||||
Python interpreter. The redistribution of the Python interpreter and
|
||||
libraries is governed by the Python Software License included with this
|
||||
file, or by other licenses as marked.
|
||||
|
||||
|
||||
|
||||
--------------------------------------------------------------------------
|
||||
|
||||
This program, "bzip2", the associated library "libbzip2", and all
|
||||
documentation, are copyright (C) 1996-2019 Julian R Seward. All
|
||||
rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. The origin of this software must not be misrepresented; you must
|
||||
not claim that you wrote the original software. If you use this
|
||||
software in a product, an acknowledgment in the product
|
||||
documentation would be appreciated but is not required.
|
||||
|
||||
3. Altered source versions must be plainly marked as such, and must
|
||||
not be misrepresented as being the original software.
|
||||
|
||||
4. The name of the author may not be used to endorse or promote
|
||||
products derived from this software without specific prior written
|
||||
permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
|
||||
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
|
||||
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
Julian Seward, jseward@acm.org
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
|
||||
--------------------------------------------------------------------------
|
||||
|
||||
libffi - Copyright (c) 1996-2022 Anthony Green, Red Hat, Inc and others.
|
||||
See source files for details.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
``Software''), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
https://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
This software is copyrighted by the Regents of the University of
|
||||
California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
|
||||
Corporation and other parties. The following terms apply to all files
|
||||
associated with the software unless explicitly disclaimed in
|
||||
individual files.
|
||||
|
||||
The authors hereby grant permission to use, copy, modify, distribute,
|
||||
and license this software and its documentation for any purpose, provided
|
||||
that existing copyright notices are retained in all copies and that this
|
||||
notice is included verbatim in any distributions. No written agreement,
|
||||
license, or royalty fee is required for any of the authorized uses.
|
||||
Modifications to this software may be copyrighted by their authors
|
||||
and need not follow the licensing terms described here, provided that
|
||||
the new terms are clearly indicated on the first page of each file where
|
||||
they apply.
|
||||
|
||||
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
|
||||
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
|
||||
ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
|
||||
DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
|
||||
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
|
||||
IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
|
||||
NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
|
||||
MODIFICATIONS.
|
||||
|
||||
GOVERNMENT USE: If you are acquiring this software on behalf of the
|
||||
U.S. government, the Government shall have only "Restricted Rights"
|
||||
in the software and related documentation as defined in the Federal
|
||||
Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
|
||||
are acquiring the software on behalf of the Department of Defense, the
|
||||
software shall be classified as "Commercial Computer Software" and the
|
||||
Government shall have only "Restricted Rights" as defined in Clause
|
||||
252.227-7014 (b) (3) of DFARs. Notwithstanding the foregoing, the
|
||||
authors grant the U.S. Government and others acting in its behalf
|
||||
permission to use and distribute the software in accordance with the
|
||||
terms specified in this license.
|
||||
|
||||
This software is copyrighted by the Regents of the University of
|
||||
California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
|
||||
Corporation, Apple Inc. and other parties. The following terms apply to
|
||||
all files associated with the software unless explicitly disclaimed in
|
||||
individual files.
|
||||
|
||||
The authors hereby grant permission to use, copy, modify, distribute,
|
||||
and license this software and its documentation for any purpose, provided
|
||||
that existing copyright notices are retained in all copies and that this
|
||||
notice is included verbatim in any distributions. No written agreement,
|
||||
license, or royalty fee is required for any of the authorized uses.
|
||||
Modifications to this software may be copyrighted by their authors
|
||||
and need not follow the licensing terms described here, provided that
|
||||
the new terms are clearly indicated on the first page of each file where
|
||||
they apply.
|
||||
|
||||
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
|
||||
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
|
||||
ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
|
||||
DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
|
||||
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
|
||||
IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
|
||||
NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
|
||||
MODIFICATIONS.
|
||||
|
||||
GOVERNMENT USE: If you are acquiring this software on behalf of the
|
||||
U.S. government, the Government shall have only "Restricted Rights"
|
||||
in the software and related documentation as defined in the Federal
|
||||
Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
|
||||
are acquiring the software on behalf of the Department of Defense, the
|
||||
software shall be classified as "Commercial Computer Software" and the
|
||||
Government shall have only "Restricted Rights" as defined in Clause
|
||||
252.227-7013 (b) (3) of DFARs. Notwithstanding the foregoing, the
|
||||
authors grant the U.S. Government and others acting in its behalf
|
||||
permission to use and distribute the software in accordance with the
|
||||
terms specified in this license.
|
||||
|
||||
BIN
desktop/build-cache/embed-test/libcrypto-3.dll
Normal file
BIN
desktop/build-cache/embed-test/libffi-8.dll
Normal file
BIN
desktop/build-cache/embed-test/libssl-3.dll
Normal file
BIN
desktop/build-cache/embed-test/python.cat
Normal file
BIN
desktop/build-cache/embed-test/python3.dll
Normal file
5
desktop/build-cache/embed-test/python313._pth
Normal file
@@ -0,0 +1,5 @@
|
||||
python313.zip
|
||||
.
|
||||
|
||||
# Uncomment to run site.main() automatically
|
||||
#import site
|
||||
BIN
desktop/build-cache/embed-test/python313.dll
Normal file
BIN
desktop/build-cache/embed-test/python313.zip
Normal file
BIN
desktop/build-cache/embed-test/sqlite3.dll
Normal file
BIN
desktop/build-cache/embed-test/vcruntime140.dll
Normal file
BIN
desktop/build-cache/embed-test/vcruntime140_1.dll
Normal file
BIN
desktop/build-cache/python-3.13.9-embed-amd64.zip
Normal file
289
desktop/main.cjs
@@ -1,33 +1,39 @@
|
||||
/**
|
||||
* 豆包 · LynxJS 复刻 —— Electron 桌面壳(CommonJS)
|
||||
* 豆包 · 网页版风格桌面壳(Electron,CommonJS)
|
||||
*
|
||||
* 为什么用 CJS:Electron 主进程在 ESM 下解析 'electron' 会命中 npm 包
|
||||
* (那个包的 index.js 只导出二进制路径),拿不到 app/BrowserWindow。
|
||||
* 内核本身是 ESM,用动态 import() 加载即可。
|
||||
* 和旧版最大的区别:**界面不再是 Lynx**,而是一套真正的 Web 前端(web/ 目录),
|
||||
* AI 内核也换成了和 Android App **同一份 Python 内核**(android/kernel)。
|
||||
* 这样 exe / 浏览器 / 手机三端功能天然同步,不用再维护两套内核。
|
||||
*
|
||||
* 主进程做三件事:
|
||||
* 1. 进程内直接启动 AI 内核(不额外起 node 子进程)
|
||||
* 2. 开一个手机比例窗口,加载 ?frame=0 的界面
|
||||
* 3. 数据目录指到 %APPDATA%,避免装到 Program Files 后写不进去
|
||||
* 主进程做四件事:
|
||||
* 1. 开一个只监听 127.0.0.1 的"原生能力桥"(选文件 / 剪贴板 / 打开文件夹)
|
||||
* —— Python 内核是子进程,拿不到 Electron 的 dialog/clipboard,只能由主进程代劳;
|
||||
* 2. 起 Python 内核子进程(--port 0 系统分配端口,--json 打出真实地址);
|
||||
* 3. 开一个桌面尺寸窗口加载内核托管的网页;
|
||||
* 4. 数据目录指到 %APPDATA%,避免装到 Program Files 后写不进去。
|
||||
*/
|
||||
const { app, BrowserWindow, Menu, shell, dialog, clipboard } = require('electron');
|
||||
const fs = require('node:fs');
|
||||
const http = require('node:http');
|
||||
const path = require('node:path');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
/**
|
||||
* 可选:开一个 CDP 调试端口,方便用脚本截图/验证桌面窗口。
|
||||
*
|
||||
* 为什么需要:Electron 的界面只有真窗口才渲染得出来,光跑 curl 验不了;
|
||||
* 有了这个端口就能用 scripts/screenshot.mjs 附着上去截图(设 CDP_PORT 即可)。
|
||||
* 默认不开,避免平时多一个监听端口。
|
||||
* 设 DOUBAO_CDP_PORT=9444 启动,再用 CDP_PORT=9444 node scripts/screenshot.mjs - out.png 附着截图。
|
||||
*/
|
||||
if (process.env.DOUBAO_CDP_PORT) {
|
||||
app.commandLine.appendSwitch('remote-debugging-port', String(process.env.DOUBAO_CDP_PORT));
|
||||
app.commandLine.appendSwitch('remote-allow-origins', '*');
|
||||
}
|
||||
|
||||
// 打包后应用根目录是 resources/app(若打成 asar 则是 resources/app.asar);开发时是仓库根
|
||||
// 用户数据目录:默认 %APPDATA%\Doubao;可用 DOUBAO_USER_DATA 覆盖(开发/自动化测试用,
|
||||
// 避免和已安装的旧版抢同一个 Electron 单实例锁)。
|
||||
if (process.env.DOUBAO_USER_DATA) {
|
||||
app.setPath('userData', path.resolve(process.env.DOUBAO_USER_DATA));
|
||||
}
|
||||
|
||||
// 打包后应用根目录是 resources/app(这里不用 asar);开发时是仓库根
|
||||
const appRoot = app.isPackaged
|
||||
? [
|
||||
path.join(process.resourcesPath, 'app'),
|
||||
@@ -38,59 +44,203 @@ const appRoot = app.isPackaged
|
||||
// 打包后的自有资源放在 <appRoot>/runtime,开发时直接用仓库根
|
||||
const bundledRuntime = path.join(appRoot, 'runtime');
|
||||
const runtimeRoot = fs.existsSync(bundledRuntime) ? bundledRuntime : appRoot;
|
||||
const packaged = fs.existsSync(path.join(runtimeRoot, 'python'));
|
||||
|
||||
process.env.DOUBAO_RESOURCES = runtimeRoot;
|
||||
process.env.DOUBAO_TOOLS = path.join(runtimeRoot, 'tools');
|
||||
process.env.DOUBAO_DATA = path.join(app.getPath('userData'), 'data');
|
||||
const pythonExe = process.env.DOUBAO_PYTHON
|
||||
|| (packaged ? path.join(runtimeRoot, 'python', 'python.exe') : 'python');
|
||||
const kernelEntry = packaged
|
||||
? path.join(runtimeRoot, 'kernel', 'main.py')
|
||||
: path.join(runtimeRoot, 'android', 'kernel', 'main.py');
|
||||
const toolsDir = path.join(runtimeRoot, 'tools');
|
||||
const webDir = path.join(runtimeRoot, 'web');
|
||||
const dataDir = process.env.DOUBAO_DATA || path.join(app.getPath('userData'), 'data');
|
||||
|
||||
const serverEntry = path.join(appRoot, 'server', 'src', 'index.mjs');
|
||||
|
||||
// 给内核挂几个桌面能力钩子:定位配置文件、用系统浏览器打开链接、原生选文件、写剪贴板。
|
||||
// 内核自己不认识 Electron,有钩子就用,没有就降级。
|
||||
globalThis.__doubaoReveal = (target) => shell.showItemInFolder(target);
|
||||
globalThis.__doubaoOpenExternal = (url) => shell.openExternal(url);
|
||||
globalThis.__doubaoClipboard = (text) => clipboard.writeText(String(text));
|
||||
globalThis.__doubaoPickFile = async () => {
|
||||
const result = await dialog.showOpenDialog({
|
||||
title: '选择要发给豆包的文件',
|
||||
buttonLabel: '发送',
|
||||
properties: ['openFile', 'multiSelections'],
|
||||
filters: [
|
||||
{
|
||||
name: '常用文件',
|
||||
extensions: ['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'txt', 'md', 'json', 'csv',
|
||||
'log', 'yml', 'yaml', 'py', 'js', 'ts', 'tsx', 'html', 'css', 'pdf'],
|
||||
},
|
||||
{ name: '所有文件', extensions: ['*'] },
|
||||
],
|
||||
});
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
};
|
||||
|
||||
let kernel = null;
|
||||
let kernelChild = null;
|
||||
let bridgeServer = null;
|
||||
let win = null;
|
||||
|
||||
/** 启动内核:默认 5199,被占用就换随机端口 */
|
||||
async function startKernelWithFallback() {
|
||||
const { startKernel } = await import(pathToFileURL(serverEntry).href);
|
||||
const preferred = Number(process.env.DOUBAO_PORT || 5199);
|
||||
try {
|
||||
return await startKernel({ port: preferred, quiet: true });
|
||||
} catch (err) {
|
||||
if (err && err.code === 'EADDRINUSE') {
|
||||
console.warn(`[desktop] 端口 ${preferred} 被占用,改用随机端口`);
|
||||
return startKernel({ port: 0, quiet: true });
|
||||
}
|
||||
throw err;
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 原生能力桥(Python 内核 ←HTTP→ Electron 主进程) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function startBridge() {
|
||||
return new Promise((resolve, reject) => {
|
||||
bridgeServer = http.createServer((req, res) => {
|
||||
const chunks = [];
|
||||
req.on('data', (c) => chunks.push(c));
|
||||
req.on('end', async () => {
|
||||
let body = {};
|
||||
try {
|
||||
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
||||
} catch { /* 空 body 也允许 */ }
|
||||
const reply = (code, obj) => {
|
||||
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
|
||||
res.end(JSON.stringify(obj));
|
||||
};
|
||||
try {
|
||||
if (req.url === '/ping') return reply(200, { ok: true });
|
||||
if (req.url === '/clipboard') {
|
||||
clipboard.writeText(String(body.text || ''));
|
||||
return reply(200, { ok: true });
|
||||
}
|
||||
if (req.url === '/pick-file') {
|
||||
const options = {
|
||||
title: '选择要发给豆包的文件',
|
||||
buttonLabel: '发送',
|
||||
properties: ['openFile', 'multiSelections'],
|
||||
filters: [
|
||||
{
|
||||
name: '常用文件',
|
||||
extensions: ['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'txt', 'md', 'json', 'csv',
|
||||
'log', 'yml', 'yaml', 'py', 'js', 'ts', 'tsx', 'html', 'css', 'pdf', 'docx', 'xlsx', 'pptx'],
|
||||
},
|
||||
{ name: '所有文件', extensions: ['*'] },
|
||||
],
|
||||
};
|
||||
const result = win
|
||||
? await dialog.showOpenDialog(win, options)
|
||||
: await dialog.showOpenDialog(options);
|
||||
return reply(200, { ok: true, paths: result.canceled ? [] : result.filePaths });
|
||||
}
|
||||
if (req.url === '/reveal') {
|
||||
const target = String(body.path || '');
|
||||
if (!target) return reply(400, { ok: false, error: 'path 为空' });
|
||||
shell.showItemInFolder(target);
|
||||
return reply(200, { ok: true });
|
||||
}
|
||||
if (req.url === '/open-external') {
|
||||
const url = String(body.url || '');
|
||||
if (!/^https?:/i.test(url)) return reply(400, { ok: false, error: '只允许 http(s)' });
|
||||
shell.openExternal(url);
|
||||
return reply(200, { ok: true });
|
||||
}
|
||||
return reply(404, { ok: false, error: '未知的桥接口' });
|
||||
} catch (err) {
|
||||
return reply(500, { ok: false, error: String((err && err.message) || err) });
|
||||
}
|
||||
});
|
||||
});
|
||||
bridgeServer.on('error', reject);
|
||||
bridgeServer.listen(0, '127.0.0.1', () => resolve(bridgeServer));
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 内核进程 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function startKernel() {
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
const args = [
|
||||
kernelEntry,
|
||||
'--port', '0', // 系统分配端口,避免 5199 被占用
|
||||
'--data-dir', dataDir,
|
||||
'--tools-dir', toolsDir,
|
||||
'--web-dir', webDir,
|
||||
'--quiet',
|
||||
'--json',
|
||||
];
|
||||
if (bridgeServer) {
|
||||
args.push('--desktop-bridge', `http://127.0.0.1:${bridgeServer.address().port}`);
|
||||
}
|
||||
if (process.env.DOUBAO_NO_MCP) args.push('--no-mcp-autostart');
|
||||
|
||||
console.log(`[desktop] Python: ${pythonExe}`);
|
||||
console.log(`[desktop] 内核: ${kernelEntry}`);
|
||||
console.log(`[desktop] 数据: ${dataDir}`);
|
||||
|
||||
kernelChild = spawn(pythonExe, args, {
|
||||
cwd: runtimeRoot,
|
||||
env: {
|
||||
...process.env,
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUNBUFFERED: '1',
|
||||
DOUBAO_DESKTOP: '1',
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
windowsHide: true,
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let buffer = '';
|
||||
let settled = false;
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(new Error('内核启动超时(30 秒没有打出地址)'));
|
||||
}, 30000);
|
||||
|
||||
const finish = (err, url) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (err) reject(err);
|
||||
else resolve(url);
|
||||
};
|
||||
|
||||
kernelChild.stdout.on('data', (chunk) => {
|
||||
const text = chunk.toString('utf8');
|
||||
process.stdout.write(`[kernel] ${text}`);
|
||||
buffer += text;
|
||||
let idx = buffer.indexOf('\n');
|
||||
while (idx >= 0) {
|
||||
const line = buffer.slice(0, idx).trim();
|
||||
buffer = buffer.slice(idx + 1);
|
||||
idx = buffer.indexOf('\n');
|
||||
if (!line.startsWith('{')) continue;
|
||||
try {
|
||||
const info = JSON.parse(line);
|
||||
if (info && info.url) finish(null, info.url);
|
||||
} catch { /* 不是那行 JSON,跳过 */ }
|
||||
}
|
||||
});
|
||||
kernelChild.stderr.on('data', (chunk) => process.stderr.write(`[kernel] ${chunk}`));
|
||||
kernelChild.on('error', (err) => {
|
||||
const hint = err && err.code === 'ENOENT'
|
||||
? `找不到 Python(${pythonExe})。开发模式请先装 Python 3.13;打包版应带 runtime/python。`
|
||||
: String((err && err.message) || err);
|
||||
finish(new Error(hint));
|
||||
});
|
||||
kernelChild.on('exit', (code, signal) => {
|
||||
if (!settled) {
|
||||
finish(new Error(`内核启动失败(退出码 ${code}${signal ? ` / ${signal}` : ''})`));
|
||||
return;
|
||||
}
|
||||
console.error(`[desktop] 内核退出了:code=${code} signal=${signal}`);
|
||||
if (win && !win.isDestroyed()) {
|
||||
dialog.showErrorBox('内核已退出', 'AI 内核意外退出,请重启应用。');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function stopKernel() {
|
||||
if (kernelChild && !kernelChild.killed) {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
spawn('taskkill', ['/pid', String(kernelChild.pid), '/T', '/F'], { windowsHide: true });
|
||||
} else {
|
||||
kernelChild.kill('SIGTERM');
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
kernelChild = null;
|
||||
if (bridgeServer) {
|
||||
try { bridgeServer.close(); } catch { /* ignore */ }
|
||||
bridgeServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 窗口 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function createWindow(url) {
|
||||
win = new BrowserWindow({
|
||||
width: 420,
|
||||
width: 1440,
|
||||
height: 900,
|
||||
minWidth: 360,
|
||||
minHeight: 620,
|
||||
minWidth: 1024,
|
||||
minHeight: 680,
|
||||
title: '豆包',
|
||||
backgroundColor: '#ffffff',
|
||||
autoHideMenuBar: true,
|
||||
@@ -102,7 +252,6 @@ function createWindow(url) {
|
||||
},
|
||||
});
|
||||
|
||||
// 界面是移动端比例,菜单栏只会碍事:去掉,改用快捷键
|
||||
Menu.setApplicationMenu(null);
|
||||
win.once('ready-to-show', () => win.show());
|
||||
|
||||
@@ -129,7 +278,8 @@ function createWindow(url) {
|
||||
}
|
||||
});
|
||||
|
||||
win.loadURL(`${url}?frame=0`);
|
||||
win.loadURL(url);
|
||||
win.on('closed', () => { win = null; });
|
||||
return win;
|
||||
}
|
||||
|
||||
@@ -145,24 +295,23 @@ if (!app.requestSingleInstanceLock()) {
|
||||
});
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
app.setAppUserModelId('com.doubao.lynxclone');
|
||||
app.setAppUserModelId('com.doubao.webclone');
|
||||
try {
|
||||
kernel = await startKernelWithFallback();
|
||||
createWindow(kernel.url);
|
||||
console.log(`[desktop] 内核就绪:${kernel.url} 资源:${runtimeRoot}`);
|
||||
console.log(`[desktop] 数据目录:${process.env.DOUBAO_DATA}`);
|
||||
await startBridge();
|
||||
const url = await startKernel();
|
||||
createWindow(url);
|
||||
console.log(`[desktop] 界面就绪:${url}`);
|
||||
} catch (err) {
|
||||
dialog.showErrorBox('豆包启动失败', String((err && err.stack) || (err && err.message) || err));
|
||||
stopKernel();
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('window-all-closed', async () => {
|
||||
try {
|
||||
if (kernel) await kernel.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
app.on('window-all-closed', () => {
|
||||
stopKernel();
|
||||
app.quit();
|
||||
});
|
||||
|
||||
app.on('before-quit', () => stopKernel());
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "doubao-desktop",
|
||||
"productName": "Doubao",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"description": "豆包 · LynxJS 复刻(桌面版):内置 AI 内核,双击即用",
|
||||
"description": "豆包 · 网页版风格复刻(桌面版):内嵌 Python 内核,双击即用",
|
||||
"main": "main.cjs",
|
||||
"scripts": {
|
||||
"start": "electron ."
|
||||
@@ -13,3 +13,4 @@
|
||||
"electron": "^44.7.0"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
301
docs/Python脚本.md
Normal file
@@ -0,0 +1,301 @@
|
||||
# Python 脚本
|
||||
|
||||
这个 App 里**六类地方**会跑 Python 代码。它们的**权限、限制、超时、谁能写**
|
||||
完全不同 —— 混在一起看会出事(比如以为规则脚本也能读文件,或者以为
|
||||
`python_run` 有沙箱)。
|
||||
|
||||
结论先放这儿:
|
||||
|
||||
> **只有"规则脚本"有沙箱,而且那个沙箱挡得住手滑、挡不住有意。**
|
||||
> 其余几处(`python_run` / 会议节点 / 自定义节点)本质就是"在你手机上跑代码",
|
||||
> 靠的是**超时**兜底,不是权限隔离。
|
||||
|
||||
---
|
||||
|
||||
## 一、总览
|
||||
|
||||
| # | 在哪 | 谁写 | 能做什么 | 兜底手段 | 超时键 |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | `python_run` 工具 | AI | 任意 Python,可 `import`、可读写文件 | 只有超时 | `pythonRun`(60s) |
|
||||
| 2 | `shell` 工具 | AI | 任意命令 | 危险命令黑名单 + 超时 | `shell`(30s) |
|
||||
| 3 | **规则脚本**(数值/状态) | 用户 | 只能算数/拼字符串,**不能 import、不能读文件** | **白名单沙箱** + 超时 | `customNode`(10s) |
|
||||
| 4 | 会议画布的 Python 节点 | 用户 | 任意 Python(`run(ctx)`) | 只有超时 | `meetingNode`(10s) |
|
||||
| 5 | 自定义节点 `.py` | 用户 | 任意 Python(声明 + `run(ctx, node)`) | 只有超时 | `customNode`(10s) |
|
||||
| 6 | 内置 Termux | 用户 | 真的 bash / python3(独立进程) | Termux 自己的限制 | `termux`(30s) |
|
||||
|
||||
超时都能在**设置 → 超时**里改。0 = 不限时(只有 `askUser` / `waitUi` 允许)。
|
||||
|
||||
---
|
||||
|
||||
## 二、`python_run`:AI 写的代码(进程内执行)
|
||||
|
||||
AI 的一个内置工具,参数:
|
||||
|
||||
| 参数 | 说明 |
|
||||
|---|---|
|
||||
| `action` | `run`(默认)/ `libs`(列出环境里有哪些库) |
|
||||
| `code` | 直接给源码 |
|
||||
| `file` | 或者给一个 `.py` 文件路径 |
|
||||
| `stdin` | 喂给脚本的标准输入 |
|
||||
| `timeout` | 秒;不传就用设置里的 `pythonRun` |
|
||||
|
||||
**怎么执行的**(`kernel/builtin_tools.py` 的 `_exec_source`):
|
||||
|
||||
```python
|
||||
ns = {'__name__': '__main__', '__builtins__': builtins, ...}
|
||||
exec(compile(source, filename, 'exec'), ns) # 全 builtins,没有沙箱
|
||||
```
|
||||
|
||||
- 用的是**进程内的 CPython**(Chaquopy 嵌的)—— 安卓上起不了 Python 子进程
|
||||
- `stdout` / `stderr` 用 `redirect_*` 捕获,`sys.exit()` 的 code 当退出码
|
||||
- 其它异常打印**完整 traceback** 到 stderr(模型据此自我修正)
|
||||
- `cwd` 临时切过去、跑完恢复
|
||||
|
||||
**能干什么**:算数、数据处理(`pandas` 要自己 `pip install`)、调网络
|
||||
(`requests` / `httpx` / `urllib`)、读写文件。
|
||||
|
||||
**注意**:`redirect_stdout` 和 `chdir` 都是**进程级**的(Python 没有线程级实现),
|
||||
所以并发跑两段 `python_run` 时,另一段的 `print` 也可能被收进本次结果。
|
||||
本地单人用没问题,别指望它做多用户服务。
|
||||
|
||||
---
|
||||
|
||||
## 三、`shell`:AI 写的一条命令
|
||||
|
||||
参数 `command` / `cwd` / `timeout`。有一份**危险命令黑名单**
|
||||
(`rm -rf /`、`mkfs`、`dd if=/dev/zero`、frok 炸弹……),
|
||||
可以用环境变量 `DOUBAO_SHELL_UNSAFE=1` 关掉黑名单。
|
||||
|
||||
黑名单是**防手滑**的,不是安全边界 —— 换个写法就绕过去了。
|
||||
|
||||
---
|
||||
|
||||
## 四、规则脚本(唯一有沙箱的地方)
|
||||
|
||||
给**数值系统 / 状态系统**用的脚本。写在「数值状态包」里,每轮在设备上跑。
|
||||
|
||||
### 三个入口函数
|
||||
|
||||
```python
|
||||
def on_stat_change(name, value, delta):
|
||||
"""数值裁决:返回生效的增量。可放大/缩小/归零否决。"""
|
||||
if name == '声望':
|
||||
return delta * 2 # 加倍
|
||||
return delta # 原样
|
||||
# return None → 否决(这次改动不生效)
|
||||
# return (增量, "旁白") → 顺带给用户一句话
|
||||
|
||||
def on_turn(self_agent, stats_api):
|
||||
"""每轮执行(状态脚本用)"""
|
||||
...
|
||||
|
||||
def on_grant(status_name, source_agent):
|
||||
"""别人给你挂状态时跑。返回 False = 抵抗掉。"""
|
||||
if status_name == '中毒' and self_agent.get('世界') == '仙门':
|
||||
return False
|
||||
return True
|
||||
```
|
||||
|
||||
### 注给脚本的能力(`stats_api`)
|
||||
|
||||
状态脚本通过 `stats_api` 读写数值(具体字段见 `rule_engine._stat_api`),
|
||||
用它是**唯一**碰数据的方式 —— 脚本拿不到 store、agentdb 这些东西。
|
||||
|
||||
### 沙箱三层(`kernel/rule_sandbox.py`)
|
||||
|
||||
| 层 | 做什么 | 拦什么 |
|
||||
|---|---|---|
|
||||
| ① 静态扫描 | 源码里有 `__xx__`、`import`、`open/eval/exec/compile/getattr/...` → **直接拒绝** | 手滑、抄来的脚本夹带东西 |
|
||||
| ② 受限 builtins | `exec` 时只喂白名单(算数、字符串、容器、异常) | 没有 `__import__` 就没有模块系统 |
|
||||
| ③ 硬超时 | `customNode` 那一项(默认 10s) | 死循环 |
|
||||
|
||||
### 这个沙箱挡不住什么(写清楚,不装)
|
||||
|
||||
Python 的属性访问是**语法**,不走 builtins:
|
||||
|
||||
```python
|
||||
().__class__.__bases__[0].__subclasses__()
|
||||
```
|
||||
|
||||
第 1 层扫 `__` 就是堵它,但**字符串拼接能绕过去**。真想绕总能绕。
|
||||
|
||||
所以导入带脚本的规则包时,界面上的警告是**实话**:
|
||||
|
||||
> 此包包含可执行 Python 脚本,会**每轮在你的设备上运行**。
|
||||
> 脚本被限制了模块引入和文件读写,但这**不是**真正的沙箱 ——
|
||||
> 精心构造的脚本仍然可能读到设备上的文件。只导入你信得过的来源。
|
||||
|
||||
(而不是写"安全沙箱,请放心导入"。)
|
||||
|
||||
### 异常怎么处理
|
||||
|
||||
**异常 = 本次操作归零 + UI 提示,绝不中断对话。**
|
||||
脚本是用户自己写的,写错是常态;一次 `1/0` 把整轮对话搞崩,
|
||||
用户会以为整个 App 坏了。
|
||||
|
||||
### 脚本存在哪
|
||||
|
||||
- 定义在 `rulepacks.json` 的 `scripts` 字段里(跟着包走,可导出/导入)
|
||||
- 执行时从 `data/rule-scripts/` 落盘读(脚本要作为文件被 `exec`)
|
||||
|
||||
---
|
||||
|
||||
## 五、会议画布的 Python 节点
|
||||
|
||||
会议(`ui/MeetingsScreen`)里有一种节点,代码框里写:
|
||||
|
||||
```python
|
||||
def run(ctx):
|
||||
ctx.log('收到:', ctx.input)
|
||||
ctx.set_var('结果', ctx.input.upper())
|
||||
return '跑完了'
|
||||
```
|
||||
|
||||
**`ctx` 的 API**(`kernel/meeting.py`):
|
||||
|
||||
| 成员 | 说明 |
|
||||
|---|---|
|
||||
| `ctx.input` | 上游传进来的文本 |
|
||||
| `ctx.vars` | 会议变量的**只读快照**(改它不影响会议) |
|
||||
| `ctx.get_var(name, default='')` | 读变量 |
|
||||
| `ctx.set_var(name, value)` | 写变量(真的写进会议变量表) |
|
||||
| `ctx.log(*parts)` | 打印到节点日志(界面上能看到) |
|
||||
| `ctx.node` | 当前节点的信息 |
|
||||
|
||||
- 每次执行都在**全新命名空间**里(节点之间不串变量)
|
||||
- 必须定义 `run(ctx)`,否则报"代码里没有定义 run 函数"
|
||||
- 输出截断到 `PY_MAX_OUTPUT`
|
||||
- 超时 `meetingNode`(默认 10s),超了报"可能有死循环"
|
||||
|
||||
**没有沙箱** —— 就是跑代码。默认的 `__builtins__` 是全的。
|
||||
|
||||
---
|
||||
|
||||
## 六、自定义节点(`nodes/` 里的 `.py`)
|
||||
|
||||
放在**数据目录的 `nodes/`** 下(安卓上是 `files/kernel-data/nodes/`)。
|
||||
文件名按字典序加载(顺序稳定,界面列表不跳),`_` 开头的跳过。
|
||||
|
||||
一个文件里写两段:
|
||||
|
||||
```python
|
||||
ToolName = {
|
||||
'name': '转大写',
|
||||
'icon': 'text',
|
||||
'input': [
|
||||
{'type': 'str', 'name': 'A1', 'value': ''},
|
||||
{'type': 'bool', 'name': 'B1', 'value': True},
|
||||
],
|
||||
'output': [
|
||||
{'type': 'exec', 'name': 'e1'},
|
||||
{'type': 'exec', 'name': 'e2'},
|
||||
{'type': 'str', 'name': 'xx'},
|
||||
],
|
||||
}
|
||||
|
||||
def run(ctx, node):
|
||||
ctx.log('收到:', node['input']['A1'])
|
||||
node['output']['xx'] = '666'
|
||||
node['output']['e1'] = True # 多个 exec 只能一个 True
|
||||
node['output']['e2'] = False
|
||||
return node
|
||||
```
|
||||
|
||||
### 三条语义(**必须在文档和界面上都写清楚**,不然用户一定踩)
|
||||
|
||||
1. **`node['input'][名]` 是引擎填的**实际值,不是声明里的 `value`。
|
||||
声明里的 `value` 只是"这根线没接时用什么"。
|
||||
2. **多个 `exec` 输出最多只能有一个 `True`** —— 这就是多路分支:
|
||||
- 恰好一个 True → 走那一条
|
||||
- 一个都不 True → **停在原地** + 节点上一条警告(不猜、不顺走第一条)
|
||||
- 超过一个 True → 报错(引擎没法替你选)
|
||||
非 exec 的输出不受这条限制。
|
||||
3. **`return` 什么无所谓** —— 引擎读的是 `node['output']`,不看返回值。
|
||||
|
||||
声明是"**同时有 `input` 和 `output` 两个键的字典**",变量名随便叫
|
||||
(`ToolName` / `MyNode` / 中文都行)。
|
||||
|
||||
引脚类型:`exec`(执行)、`str`、`bool`、`num`、`list`。只能用标准库。
|
||||
|
||||
---
|
||||
|
||||
## 七、内置 Termux(真独立进程)
|
||||
|
||||
App 里内置了一套 Termux 环境(`files/usr/`),可以跑真的 `bash` / `python3` /
|
||||
`apt` / `pip`。这是唯一**独立进程**的一处 —— 内核通过它的 CLI 跑命令,
|
||||
超时键 `termux`(默认 30s)。
|
||||
|
||||
软件源已经指向清华 TUNA。第一次启动时会跑一串探针(12 条)验证环境可用。
|
||||
|
||||
---
|
||||
|
||||
## 八、项目自己的 `scripts/`(开发用,不跑在手机上)
|
||||
|
||||
`scripts/` 下有 60 多个 Python 脚本,分三类:
|
||||
|
||||
| 类别 | 例子 | 干什么 |
|
||||
|---|---|---|
|
||||
| **探针**(`probe-*.py`) | `probe-agent-system.py`、`probe-group-chat.py` | 不开 App、不联网,在电脑上跑内核逻辑逐条断言 |
|
||||
| **验证**(`verify-*.py`) | `verify-nodekit.py`、`verify-tts-stream.py` | 验证某个子系统的行为或产物 |
|
||||
| **审计**(`audit-*.py`) | `audit-ui-tree.py`、`audit-ui-entries.py` | 静态检查:文档和代码是否一致、每个界面有没有入口 |
|
||||
| **工具** | `publish-release.py`、`build-apk.mjs` 配套脚本 | 发版、构建辅助 |
|
||||
|
||||
**八个常驻探针**(每次改动都要全绿):
|
||||
|
||||
```bash
|
||||
python scripts/probe-agent-system.py
|
||||
python scripts/probe-degraded.py
|
||||
python scripts/probe-rule-sandbox.py
|
||||
python scripts/probe-rule-engine.py
|
||||
python scripts/probe-context-window.py
|
||||
python scripts/probe-group-chat.py
|
||||
python scripts/audit-ui-tree.py
|
||||
python scripts/audit-ui-entries.py
|
||||
```
|
||||
|
||||
它们**不需要装机、不需要网络**:把 `DOUBAO_DATA` 指到一个临时目录,
|
||||
内核的存储层无状态,整条链路在一个进程里跑完。
|
||||
|
||||
### 写探针的一条硬纪律:走**生产同一条**调用路径
|
||||
|
||||
踩过:第 22 节直接调 `_set_asset`,而卡住真机的是 `handle()` 里的 `body()` ——
|
||||
探针全绿、真机全挂。
|
||||
|
||||
> **探针能绕过的那一层,就是下次会出问题的那一层。**
|
||||
|
||||
同理,工具类探针要走 `tools_runtime.execute_tool`(它会把上下文搬到 worker 线程),
|
||||
直接调 `agent_tools.xxx` 测的是"函数逻辑对不对",不是"它在这个系统里生不生效"。
|
||||
|
||||
---
|
||||
|
||||
## 九、安全边界(一张表说清)
|
||||
|
||||
| 地方 | 能读设备文件 | 能 import | 能联网 | 能起子进程 | 真沙箱 |
|
||||
|---|---|---|---|---|---|
|
||||
| `python_run` | ✅ | ✅ | ✅ | ❌(安卓没有) | ❌ |
|
||||
| `shell` | ✅ | — | ✅ | ✅ | ❌(只有黑名单) |
|
||||
| **规则脚本** | ❌ | ❌ | ❌ | ❌ | ⚠️ 白名单,**挡手滑不挡有意** |
|
||||
| 会议 Python 节点 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| 自定义节点 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| Termux | ✅ | ✅ | ✅ | ✅ | ❌ |
|
||||
|
||||
**一句话**:除了规则脚本,其它几处都是"能跑代码"级别的能力 ——
|
||||
只在你自己的设备上、你自己授权的前提下有意义。别把别人的包直接导进来。
|
||||
|
||||
---
|
||||
|
||||
## 十、相关文件
|
||||
|
||||
| 文件 | 作用 |
|
||||
|---|---|
|
||||
| `kernel/builtin_tools.py` | `shell` / `python_run` 两个内置工具 |
|
||||
| `kernel/rule_sandbox.py` | 规则脚本的三层沙箱 |
|
||||
| `kernel/rule_engine.py` | 规则脚本的入口调用、数值/状态流程 |
|
||||
| `kernel/custom_nodes.py` | 自定义节点(声明 + `run`) |
|
||||
| `kernel/meeting.py` | 会议画布、Python 节点执行 |
|
||||
| `kernel/timeouts.py` | 所有超时键的默认值和说明 |
|
||||
| `kernel/paths.py` | `rule-scripts/`、`nodes/` 等目录 |
|
||||
| `RulePackEditScreen.kt` | 规则包编辑(含脚本框) |
|
||||
| `NodeBlockEditor.kt` | 会议节点编辑(含 Python 代码框) |
|
||||
| `scripts/probe-rule-sandbox.py` | 沙箱边界验证 |
|
||||
| `scripts/probe-rule-engine.py` | 数值/状态系统验证 |
|
||||
1924
docs/kernel-api-agents.md
Normal file
1211
docs/kernel-api-chat.md
Normal file
1290
docs/kernel-api-misc.md
Normal file
BIN
docs/screenshots/agent-card-stats.png
Normal file
|
After Width: | Height: | Size: 767 KiB |
BIN
docs/screenshots/ai-talk.png
Normal file
|
After Width: | Height: | Size: 2.5 MiB |
BIN
docs/screenshots/chat-backdrop.png
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
BIN
docs/screenshots/drawer-split.png
Normal file
|
After Width: | Height: | Size: 668 KiB |
BIN
docs/screenshots/exe2-ai.png
Normal file
|
After Width: | Height: | Size: 114 KiB |
BIN
docs/screenshots/exe2-window.png
Normal file
|
After Width: | Height: | Size: 139 KiB |
BIN
docs/screenshots/group-after.png
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
BIN
docs/screenshots/group-ai-chat.png
Normal file
|
After Width: | Height: | Size: 2.4 MiB |
BIN
docs/screenshots/group-bar.png
Normal file
|
After Width: | Height: | Size: 79 KiB |
BIN
docs/screenshots/group-before.png
Normal file
|
After Width: | Height: | Size: 453 KiB |
BIN
docs/screenshots/mention-switch.png
Normal file
|
After Width: | Height: | Size: 2.3 MiB |
BIN
docs/screenshots/no-premature-switch.png
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
BIN
docs/screenshots/now1.png
Normal file
|
After Width: | Height: | Size: 436 KiB |
BIN
docs/screenshots/now2.png
Normal file
|
After Width: | Height: | Size: 167 KiB |
BIN
docs/screenshots/now3.png
Normal file
|
After Width: | Height: | Size: 2.6 MiB |
BIN
docs/screenshots/rd-verify-final.png
Normal file
|
After Width: | Height: | Size: 509 KiB |
BIN
docs/screenshots/realdevice-drawer.png
Normal file
|
After Width: | Height: | Size: 296 KiB |
BIN
docs/screenshots/realdevice-launch.png
Normal file
|
After Width: | Height: | Size: 426 KiB |
BIN
docs/screenshots/rulepack-edit.png
Normal file
|
After Width: | Height: | Size: 84 KiB |
BIN
docs/screenshots/rulepacks.png
Normal file
|
After Width: | Height: | Size: 72 KiB |
BIN
docs/screenshots/speaker-tag-fixed.png
Normal file
|
After Width: | Height: | Size: 2.5 MiB |
BIN
docs/screenshots/switch-on-speak.png
Normal file
|
After Width: | Height: | Size: 2.4 MiB |
BIN
docs/screenshots/title-backdrop-switch.png
Normal file
|
After Width: | Height: | Size: 885 KiB |
BIN
docs/screenshots/web2-agents.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
docs/screenshots/web2-ai-ask.png
Normal file
|
After Width: | Height: | Size: 60 KiB |
BIN
docs/screenshots/web2-ai-ended.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
docs/screenshots/web2-ai-surface.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
docs/screenshots/web2-chat.png
Normal file
|
After Width: | Height: | Size: 56 KiB |
BIN
docs/screenshots/web2-group.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
docs/screenshots/web2-meetings.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
docs/screenshots/web2-settings.png
Normal file
|
After Width: | Height: | Size: 82 KiB |
190
docs/v1.2实施计划.md
Normal file
@@ -0,0 +1,190 @@
|
||||
# v1.2 实施计划
|
||||
|
||||
《智能体系统需求文档 v1.2》的落地计划。按**依赖顺序**排,不是按文档章节顺序 ——
|
||||
情绪双字段不做,立绘联动、`peer_emotions`、状态脚本全都悬空。
|
||||
|
||||
---
|
||||
|
||||
## ✅ 全部完成(v2.0.47 → v2.0.66)
|
||||
|
||||
| 阶段 | 内容 | 完成版本 | 主要落点 |
|
||||
|---|---|---|---|
|
||||
| **0** | 情绪双字段(地基) | v2.0.55 | `agentdb.py` / `agent_tools.py` / `agent_context.py` / `MemoryScreen.kt` |
|
||||
| **1** | 立绘表 + 回退链 | v2.0.56 | `store.normalize_image` / `agent_api.portrait_of` / `AgentEditScreen.kt` |
|
||||
| **2** | 缓存统计 + 段序 + 上下文窗口 | v2.0.57 / v2.0.58 / v2.0.64 | `agent_loop.cache_pair` / `defaults.DEFAULT_PROMPT_TEMPLATE` / **新建 `kernel/context_window.py`** |
|
||||
| **3** | 规则引擎(数值 + 状态 + 沙箱 + 规则包) | v2.0.59 | **新建 `kernel/rule_engine.py`** / `agent_tools.change_stat`·`grant_status` / `ResourcesScreen.kt` / **新建 `RulePackEditScreen.kt`** |
|
||||
| **4** | 多智能体对话(群聊 + 私聊) | v2.0.60 / v2.0.61 | **新建 `kernel/group_chat.py`**·`private_chat.py` / `agent_tools.invite_agent`·`pass_turn` / **新建 `GroupMembersScreen.kt`** |
|
||||
| **5** | 收尾(三个新界面 + @ 快捷条 + 标记重要 + 背景跟随) | v2.0.62 → v2.0.66 | **新建 `AgentStatsScreen.kt`** / `ChatScreen.kt` / `SettingsScreen.kt` |
|
||||
|
||||
**八个探针全绿**(每一阶段都构建 + 探针验证过):
|
||||
|
||||
probe-agent-system probe-degraded probe-rule-sandbox
|
||||
probe-rule-engine probe-context-window probe-group-chat
|
||||
audit-ui-tree audit-ui-entries
|
||||
|
||||
`audit-ui-tree.py` 的 `PLANNED` 已**清空** —— 三个"计划中"的界面全部落地。
|
||||
|
||||
---
|
||||
|
||||
## 阶段划分(每一阶段都能单独发版)
|
||||
|
||||
### ✅ 阶段 0 · 情绪双字段(**地基**)
|
||||
|
||||
**为什么必须第一个做**:v1.2 有三处依赖它 —— 立绘联动(按 preset 切图)、
|
||||
`peer_emotions`(注入的是 preset 不是 text)、`on_turn` 脚本(能改情绪)。
|
||||
|
||||
| 做什么 | 落在哪 |
|
||||
|---|---|
|
||||
| `emotions` 表加 `preset` 列(五档枚举)+ 保留 `text` | `agentdb.py` |
|
||||
| `emotion_set(preset, text)` 双参数 | `agent_tools.py` |
|
||||
| `<emotion>` 段带两个字段 | `agent_context.py` |
|
||||
| `<peer_emotions>` 改成注入 preset | `agent_context.py` |
|
||||
| 迁移:老数据的 `emotion` 文本 → `text`,preset 给「平常」 | `agentdb.py` 的 `init()` |
|
||||
| 记忆页情绪区:五档选择器 + 文本框 | `MemoryScreen.kt` |
|
||||
|
||||
**注意**:`get_token_usage` 之外的旧工具签名一个字都不能变。
|
||||
|
||||
### ✅ 阶段 1 · 立绘表 + 回退链(依赖阶段 0)
|
||||
|
||||
| 做什么 | 落在哪 |
|
||||
|---|---|
|
||||
| `smartInfo.json` 的 `front` 支持"五档字典"和"单文件名"两种 | `agent_api.py` 的 `_import_agent` |
|
||||
| 回退链:`当前 preset → 平常 → 旧单文件 front → 内置默认` | `agent_api.py` 的 `_pick_asset` |
|
||||
| 智能体编辑外观组:角色图拆成五档,各带选图/清除 | `AgentEditScreen.kt` |
|
||||
| 选择界面立绘随 preset 切换 | `AgentSelectScreen.kt` |
|
||||
|
||||
### ✅ 阶段 2 · 缓存统计 + 段序(**独立,可以并行**)
|
||||
|
||||
| 做什么 | 落在哪 |
|
||||
|---|---|
|
||||
| 归一化 `cache_hit / cache_miss`(DeepSeek / OpenAI / Claude 三家的字段名不同) | `agent_loop.py` |
|
||||
| 模型列表加「命中单价」 | `ResourcesScreen.kt` + `store.py` |
|
||||
| 用量详情按模型分行加命中/未命中列 | `TokenUsageScreen.kt` |
|
||||
| **附录 C 的缓存友好段序**:`stats`/`status`/`emotion`/`peer_emotions` 挪到最后 | `agent_context.py` |
|
||||
| 上下文窗口(§4.3):最近 N 轮 + 重要标记 + 成批对齐裁剪 | `app.py` 取历史处 |
|
||||
|
||||
★ **段序那条特别值钱**:主流模型的上下文缓存是前缀匹配,现在的顺序
|
||||
把最易变的 `<emotion>` 放在 `<memory>` 前面 —— 情绪一变,后面整段缓存全废。
|
||||
挪到最后,长前缀(prompt/skills/worldview/memory)能一直命中。
|
||||
|
||||
### ✅ 阶段 3 · 规则引擎(数值 + 状态,**最大的一块**)
|
||||
|
||||
| 做什么 | 落在哪 |
|
||||
|---|---|
|
||||
| 数值状态包(zip + `info.json` + 脚本)导入导出 + **脚本警告确认** | `agent_api.py` + `ResourcesScreen.kt` |
|
||||
| `stats` / `statuses` 两张表 + 实例化(`shared` 决定粒度) | `agentdb.py` |
|
||||
| `change_stat(name, delta)`:脚本裁决 → clamp → 写库 | `agent_tools.py` |
|
||||
| `grant_status` + 目标方 `on_grant` 判定 + 叠加规则 | `agent_tools.py` |
|
||||
| 状态脚本 `on_turn`:每轮生成**前**执行,顺序固定 | `agent_loop.py` |
|
||||
| **受限沙箱**(附录 E):只暴露三个 API,无文件/网络,超时 + 异常归零 | 新建 `kernel/rule_sandbox.py` |
|
||||
| `<stats>` / `<status>` 两段注入 | `agent_context.py` |
|
||||
| `[规则包编辑]` 全屏界面(脚本编辑复用节点代码那个组件) | 新建 |
|
||||
| `[状态数值]` 浮层 + 三个入口 | 新建 |
|
||||
|
||||
### ✅ 阶段 4 · 多智能体对话(**依赖阶段 0 和 3**)
|
||||
|
||||
| 做什么 | 落在哪 |
|
||||
|---|---|
|
||||
| `type: group` 会话 + `participants` | `store.py` |
|
||||
| `invite_agent`(静默 / 确认两种模式)+ 系统消息播报 | `agent_tools.py` |
|
||||
| `pass_turn`(一轮最多一次;死亡目标无效) | `agent_tools.py` |
|
||||
| 发言权仲裁:点名制 + 主智能体兜底 | `app.py` |
|
||||
| 私聊:幕后对聊 + 10 轮安全网 + 摘要进共享记忆 | `app.py` |
|
||||
| `[群成员]` 浮层 + `@` 成员快捷条 | 新建 + `ChatScreen.kt` |
|
||||
| 群聊背景跟随发言者(crossfade 0.3s) | `ChatScreen.kt` |
|
||||
| 死亡规则:禁言 + 不冻结状态机 + 复活双通道 | `app.py` + `agent_tools.py` |
|
||||
|
||||
### ✅ 阶段 5 · 收尾
|
||||
|
||||
- 文档:`docs/智能体系统.md` 补 v1.2 各节
|
||||
- `docs/界面总览.md` 里三个"计划中"的界面标成已落地
|
||||
- `audit-ui-tree.py` 的 `PLANNED` 清空
|
||||
- 探针补:情绪双字段迁移、立绘回退链、缓存归一化、段序、沙箱逃逸尝试
|
||||
|
||||
---
|
||||
|
||||
## 已经做完的部分(v1.1,不用重做)
|
||||
|
||||
- §2.1–2.4 选择界面(四层叠加 / 动画 / 更多按钮 / 回退)
|
||||
- §2.5 包格式(**除立绘表**)
|
||||
- §3.1 Token 统计与限额(**除缓存统计**)
|
||||
- §3.2 独立记忆(**除总结勾选界面**)
|
||||
- §3.3 多模型(**除"配置界面明确标注"** —— 已补)
|
||||
- §3.4 记忆导入导出
|
||||
- §3.6 世界观(**除数值状态包挂载**)
|
||||
- §3.7 Skill 机制
|
||||
- §4.1 会话级用量
|
||||
- 附录 A/B(**除 `invite_agent` / `pass_turn` / `change_stat` / `grant_status`**)
|
||||
|
||||
---
|
||||
|
||||
## 一处需要你拍板的
|
||||
|
||||
**§3.10 的脚本沙箱能做到什么程度**。~~需求说"仅暴露三个 API,无文件、网络访问"。
|
||||
安卓上的内核是 CPython(Chaquopy),Python 的沙箱天生关不严,三条路……~~
|
||||
|
||||
### ✅ 已定:**限制 import(builtins 白名单)**(2026-10-16 你选的,已实现)
|
||||
|
||||
最终做的是 `kernel/rule_sandbox.py` 的三层:
|
||||
|
||||
1. **静态扫描**:`__\w+__`、`import`、`open|eval|exec|getattr|...` 一律拒绝
|
||||
2. **受限 `SAFE_BUILTINS`**:脚本的全局命名空间里只有白名单里的内置函数
|
||||
3. **硬超时**:跑不动就放弃等待(线程杀不掉,如实写进提示)
|
||||
|
||||
★★ 而且**如实标注了能力边界** —— 模块里写着"**挡手滑,挡不住有意**":
|
||||
|
||||
· 文本级扫描可以绕过(`"_" * 2 + "import__"` 这类拼接)
|
||||
· 没有资源限制(内存 / CPU)
|
||||
· 安卓上起不了真子进程(Chaquopy 嵌的 CPython 没有独立解释器,
|
||||
证据是现有 `python_run` 工具用的就是进程内 `exec`)
|
||||
|
||||
`scripts/probe-rule-sandbox.py` 里专门有一节**测试它挡不住什么** ——
|
||||
一个只测"能挡住什么"的沙箱测试,会给人虚假的安全感。
|
||||
|
||||
**下面这段是当初的调研记录**,保留下来是因为"安卓上为什么起不了 Python
|
||||
子进程"这个结论以后还会有人问:
|
||||
|
||||
> ~~需求说"仅暴露三个 API,无文件、网络访问"。三条路……~~
|
||||
>
|
||||
> 但查了一遍代码,**安卓上不能直接起 Python 子进程**,方案要绕一下:
|
||||
|
||||
**问题**:安卓内核是 Chaquopy 嵌的 CPython —— 它**没有独立的解释器可执行文件**,
|
||||
`sys.executable` 指向的东西起不来。证据在仓库里:现有的 `python_run` 工具
|
||||
(跑用户 Python 代码)用的是 `exec()` **进程内**执行,`_exec_source` 的注释
|
||||
写着"这就是本工具存在的意义"。也就是说:**项目从来没有在安卓上起过 Python 子进程**,
|
||||
不是不想,是起不来。
|
||||
|
||||
**绕法**:用 **Termux 的 `python3`**(项目已经内置 Termux,`shell` 工具跑的就是它)。
|
||||
那是一个**真的可执行文件**,能起真子进程。
|
||||
|
||||
**★ 但要做成「常驻 worker」,不是每次起一个。**
|
||||
|
||||
你说"就改个数值而已" —— 对,**改数值本身是微秒级的**,慢的是
|
||||
**起进程**(安卓上几百毫秒)。而 `change_stat` 一轮对话里可能调好几次、
|
||||
`on_turn` 状态脚本是**每轮都要跑**的 —— 每次都起进程的话,
|
||||
一轮下来光启动开销就一两秒,玩家能明显感觉到卡。
|
||||
|
||||
所以:
|
||||
|
||||
```
|
||||
内核启动规则引擎时
|
||||
└─ 起一个 python3 worker(Termux 的) ← 只起一次
|
||||
├─ stdin 收任务:{"kind":"stat_change", ...}
|
||||
└─ stdout 回结果:{"delta": 5, "narration": "..."}
|
||||
每次改数值 / 每轮跑状态脚本 = 往这个进程写一行 JSON
|
||||
```
|
||||
|
||||
**隔离效果和"每次起进程"完全一样**(还是独立的进程,文件系统/网络照样隔离),
|
||||
但每次调用只花**一次 IPC 的时间**(毫秒级)。
|
||||
|
||||
**没有 Termux 时**(用户没装):降级为进程内 `exec` + `__builtins__` 白名单 + 硬超时,
|
||||
并且**在导入规则包的警告里明确写出隔离等级降低了** —— 不给虚假的安全承诺。
|
||||
|
||||
**顺带一个发现,不在 v1.2 范围内但要记一笔**:现有的 `python_run` 工具
|
||||
(AI 可以跑任意 Python 代码)在安卓上是**进程内 exec**,也就是
|
||||
**没有任何隔离** —— 它能读写内核进程能碰的一切。这是已有的设计,
|
||||
v1.2 的规则引擎不该沿用这条路,但那个工具本身值不值得改,
|
||||
是另一个决定(改了会影响所有现有用户)。
|
||||
|
||||
**超时与资源**:worker 每次任务带超时(复用 `timeouts.py` 的那套);
|
||||
异常 = 本次操作归零 + UI 提示,**不重启 worker**(除非它真的死了)。
|
||||
340
docs/数值状态系统-教程.md
Normal file
@@ -0,0 +1,340 @@
|
||||
# 数值状态系统 · 教程
|
||||
|
||||
手把手把「好感度」和「中毒」跑起来。看完你会知道:
|
||||
|
||||
- 数值/状态**从哪进、挂在哪**
|
||||
- 一个规则包由什么组成
|
||||
- 脚本怎么写(三个入口 + 沙箱的限制)
|
||||
- **怎么确认它真的生效了**
|
||||
|
||||
配套参考:[`Python脚本.md`](Python脚本.md)(脚本的权限边界)、
|
||||
[`智能体系统.md`](智能体系统.md)(需求项 → 文件对照)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 先理解链路(这一步搞错后面全白做)
|
||||
|
||||
```
|
||||
「世界观 · 技能 · 模型 → 规则包」建包 ← 定义:有哪些数值、哪些状态
|
||||
↓
|
||||
「世界观 · 技能 · 模型 → 世界观」挂上这个包 ← ★ 挂载点是**世界观**,不是智能体
|
||||
↓
|
||||
智能体绑这个世界观 ← 同一个世界观的智能体共用一个包
|
||||
↓
|
||||
它的提示词里就出现了 <stats> / <status>
|
||||
↓
|
||||
AI 用 change_stat / grant_status 改值 → 落库 → 下一轮反映新值
|
||||
```
|
||||
|
||||
**为什么挂在世界观上**:数值是"这个世界的规则"(灵气、声望、门派贡献),
|
||||
不是一个角色的私有物。而且这么设计之后,**共享数值(`shared=1`)天然只能
|
||||
在一个世界观内共享**,和记忆用的是同一套 scope 写法 —— 用户不用学两套心智模型。
|
||||
|
||||
> ⚠️ 最容易卡住的一步:**建完包不挂到世界观**。不挂就没有
|
||||
> `<stats>` / `<status>` 两段,AI 完全不知道有这回事。
|
||||
|
||||
---
|
||||
|
||||
## 1. 五分钟跑通一个「好感度」
|
||||
|
||||
### 1.1 建包
|
||||
|
||||
**抽屉 → 更多功能 → **世界观 · 技能 · 模型** → 顶栏切到「规则包」→ 右上角「新建」**。
|
||||
|
||||
建出来的包**自带模板**(好感度 + 中毒),可以直接拿来改。
|
||||
|
||||
### 1.2 看它长什么样
|
||||
|
||||
点进包 → 进「规则包编辑」全屏页。顶部两行是**名称**和**说明**,
|
||||
下面是**脚本**区和**定义**区。
|
||||
|
||||
一个包的完整内容就是三样:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"stats": [
|
||||
{
|
||||
"name": "好感度", // ★ 唯一标识,脚本和工具里都用它
|
||||
"min": 0, // 下限
|
||||
"max": 100, // 上限
|
||||
"shared": 0, // 0 = 每个智能体各算各的;1 = 全世界观一份
|
||||
"ranges": [ // 区间表:命中哪段,就把那段文字注入提示词
|
||||
{"min": 0, "max": 30, "text": "戒备:你对他还有戒心"},
|
||||
{"min": 30, "max": 70, "text": "友善:你对他态度友善,但保持分寸"},
|
||||
{"min": 70, "max": 100, "text": "亲近:你已经把他当自己人了"}
|
||||
],
|
||||
"script": "stat.py" // 可选:数值裁决脚本
|
||||
}
|
||||
],
|
||||
"statuses": [
|
||||
{
|
||||
"name": "中毒",
|
||||
"kind": "timed", // timed = 每轮减 1;persistent = 永不过期
|
||||
"turns": 3, // timed 时持续几轮
|
||||
"max_stack": 1, // 最多叠几层
|
||||
"script": "status.py" // 可选:赋予判定 + 每轮行为
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 1.3 挂到世界观
|
||||
|
||||
**世界观 · 技能 · 模型 → 世界观 → 点开一个世界观 → 往下找「数值状态包」** →
|
||||
选你刚建的那个包(选「不挂」就关掉)。
|
||||
|
||||
保存。
|
||||
|
||||
### 1.4 让智能体绑这个世界观
|
||||
|
||||
**智能体编辑 → 世界观** → 选同一个。
|
||||
|
||||
### 1.5 确认生效
|
||||
|
||||
打开那个智能体的对话,问它一句「你现在对我什么感觉」。
|
||||
|
||||
如果它的话里带上了 interval 表里的措辞("戒备"/"友善"/"亲近"),
|
||||
说明 `<stats>` 段注进去了。
|
||||
|
||||
**更准的自查**:聊天页顶栏点状态栏 → 进 [状态数值] 页 ——
|
||||
那里列着所有数值和当前值,**来源会写明来自哪个包**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 数值怎么变
|
||||
|
||||
AI 只能调一个工具:
|
||||
|
||||
```
|
||||
change_stat(name="好感度", delta=5)
|
||||
```
|
||||
|
||||
**注意它只能给增量,不能写绝对值。** 这是刻意的:
|
||||
|
||||
- 允许写绝对值的话,"脚本裁决"就没意义了 —— 修正器要的是
|
||||
"你想加 5,我判成加 10",而不是"你想设成 100,我判……多少"
|
||||
- 群聊里两个智能体同时改同一个 shared 数值时,**绝对值互相覆盖,增量不会**
|
||||
|
||||
### 完整流程(顺序固定)
|
||||
|
||||
```
|
||||
脚本裁决(有脚本时) → clamp 到 [min,max] → 写库 → 下一轮注入反映新值
|
||||
```
|
||||
|
||||
| 环节 | 说明 |
|
||||
|---|---|
|
||||
| **脚本裁决** | 脚本返回生效的增量;可放大/缩小;返回 `None` = 否决 |
|
||||
| **clamp** | 超界的值被钳到 `min`/`max` |
|
||||
| **写库** | 按 scope 写(`agent:<uuid>` 或 `world:<uuid>`) |
|
||||
| **下一轮注入** | 提示词里显示新值,**并且带一个 `450→500` 的箭头** |
|
||||
|
||||
那个箭头**只显示一轮**(放内存、用完就丢),它只是提示,不是数据。
|
||||
|
||||
### 注入的实际样子
|
||||
|
||||
```
|
||||
[世界·九州] 声望: 450→500/1000 —— 名震九州:世人皆知你之名
|
||||
[自身] 好感度: 45/100 —— 友善:你对他态度友善,但保持分寸
|
||||
```
|
||||
|
||||
`[世界·xx]` / `[自身]` 前缀是自动加的,让模型知道哪些值是全世界的、
|
||||
哪些是它自己的。
|
||||
|
||||
---
|
||||
|
||||
## 3. 状态怎么来、怎么没
|
||||
|
||||
### 赋予
|
||||
|
||||
AI 调:
|
||||
|
||||
```
|
||||
grant_status(target="用户", status="中毒")
|
||||
```
|
||||
|
||||
流程固定四条:
|
||||
|
||||
1. **必须同世界观** —— 跨世界观一律拒绝(没有共享规则体系,"赋予"没有依据)
|
||||
2. 跑**目标方**的 `on_grant` 判定脚本 —— 判定权在被挂的人手里
|
||||
3. 接受 → 实例化;拒绝 → 发起方收到「被抵抗」的明确回执
|
||||
4. **同名重复赋予默认刷新轮数**(不是累加);定义里配了 `max_stack` 才叠层
|
||||
|
||||
### 消退
|
||||
|
||||
`timed` 的状态**每参与一轮减 1**,到 0 删除,并播报「中毒已经消退了」。
|
||||
|
||||
`persistent` 的状态**永不过期**(内部记 `remaining = -1`,不参与递减),
|
||||
要移掉得用 `drop_status`。
|
||||
|
||||
---
|
||||
|
||||
## 4. 脚本怎么写
|
||||
|
||||
脚本是**可选的**。不写脚本,数值照样按增量改、状态照样到期消失 ——
|
||||
脚本只在你要"额外的判断"时才需要。
|
||||
|
||||
### 4.1 数值裁决:`on_stat_change`
|
||||
|
||||
包里起个文件(比如 `stat.py`),在「规则包编辑 → 脚本」里新建并写:
|
||||
|
||||
```python
|
||||
def on_stat_change(name, value, delta):
|
||||
"""
|
||||
name : 数值名
|
||||
value : 改之前的值
|
||||
delta : AI 想加的增量
|
||||
返回 : 实际生效的增量
|
||||
"""
|
||||
if name == '好感度':
|
||||
# 越熟越难加(边际递减)
|
||||
if value >= 80:
|
||||
return delta * 0.3
|
||||
return delta
|
||||
return delta
|
||||
```
|
||||
|
||||
返回值有三种写法:
|
||||
|
||||
| 返回 | 含义 |
|
||||
|---|---|
|
||||
| 一个数字 | 生效的增量(可以跟 `delta` 不一样) |
|
||||
| `None` | **否决**这次改动 |
|
||||
| `(增量, "旁白")` | 顺带往这一轮的旁白里加一句 |
|
||||
|
||||
### 4.2 每轮行为:`on_turn`
|
||||
|
||||
```python
|
||||
def on_turn(self_agent, stats_api):
|
||||
"""每轮执行一次(状态脚本用)"""
|
||||
...
|
||||
```
|
||||
|
||||
### 4.3 赋予判定:`on_grant`
|
||||
|
||||
**跑在目标方** —— 被挂状态的人有权抵抗:
|
||||
|
||||
```python
|
||||
def on_grant(status_name, source_agent):
|
||||
"""返回 False = 抵抗掉这个状态"""
|
||||
if status_name == '中毒' and self_agent.get('世界') == '仙门':
|
||||
return False
|
||||
return True
|
||||
```
|
||||
|
||||
### 4.4 脚本不能做什么(这是硬限制)
|
||||
|
||||
规则脚本跑在**白名单沙箱**里:
|
||||
|
||||
- ❌ **不能 `import`**(没有模块系统)
|
||||
- ❌ **不能 `open`**(读不了文件)
|
||||
- ❌ 不能用 `eval` / `exec` / `getattr` / `__xx__` 这类东西
|
||||
- ✅ 能算数、拼字符串、处理列表字典、`try/except`
|
||||
|
||||
**为什么这么严**:规则脚本是"数值修正器",正经写它根本用不到那些。
|
||||
静态扫描拦的是"手滑"和"抄来的脚本夹带东西"。
|
||||
|
||||
> ⚠️ 但要说实话:**这个沙箱挡得住手滑,挡不住有意。**
|
||||
> Python 的属性访问是语法,精心构造的代码*可能*绕过。
|
||||
> 所以导入带脚本的包时,请只导你信得过的来源。
|
||||
|
||||
### 4.5 脚本写错了会怎样
|
||||
|
||||
**异常 = 本次操作归零 + 界面提示,不会中断对话。**
|
||||
|
||||
数字脚本报错时"这一次改动不生效",而不是"按原值放行" ——
|
||||
宁可这一下不生效,也不能让坏脚本失控地改数值。
|
||||
|
||||
---
|
||||
|
||||
## 5. 界面上还有哪些地方能看到
|
||||
|
||||
| 界面 | 从哪进 | 看什么 |
|
||||
|---|---|---|
|
||||
| **[状态数值]** | 聊天页状态栏 / 智能体编辑的「它的状态」/ 群成员页的「状态」 | 所有数值的当前值 + 谁在挂这个包 |
|
||||
| **规则包编辑** | 世界观 · 技能 · 模型 → 规则包 → 点一个包 | 改定义、写脚本、导出/导入 |
|
||||
| **规则包列表** | 抽屉 → 更多功能 →「世界观 · 技能 · 模型」→ 切「规则包」 | 包列表,副标题写着有几条数值/状态、带不带脚本 |
|
||||
|
||||
**用户可以直接改值**(在 [状态数值] 页里)—— 这是兜底主权:
|
||||
AI 记错了、脚本判歪了,得有一个人能直接拨回去。
|
||||
|
||||
---
|
||||
|
||||
## 6. 常见问题
|
||||
|
||||
<details>
|
||||
<summary><b>AI 完全不知道有数值这回事</b></summary>
|
||||
|
||||
按顺序查:
|
||||
|
||||
1. **世界观挂包了吗** ← 最常见。「世界观 · 技能 · 模型 → 世界观 → 数值状态包」得选上
|
||||
2. **智能体绑这个世界观了吗**
|
||||
3. **包里有 `stats` 吗** —— 空包同步时会直接跳过(不动库)
|
||||
4. 提示词里 `<stats>` 段在**最末尾**,模型如果只读了开头可能没注意 ——
|
||||
直接问它"你的好感度现在多少"
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>改了值但提示词里还是旧的</b></summary>
|
||||
|
||||
数值是**每轮开始**才注入的。改完要**下一条消息**才看得到新值 ——
|
||||
一次对话只有一次注入。
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>两个智能体的好感度互相串了</b></summary>
|
||||
|
||||
检查 `shared`:
|
||||
|
||||
- `shared=0` → `agent:<uuid>`,各算各的
|
||||
- `shared=1` → `world:<uuid>`,整个世界观一份
|
||||
|
||||
串了说明定义里写成了 `shared=1`。
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>状态删不掉 / 想手动挂一个</b></summary>
|
||||
|
||||
在 **[状态数值]** 页里,每条状态右边都有**「清掉」**按钮,直接点就行。
|
||||
包里有还没挂上的状态时,下面还会自动出现**「加一个」**区块。
|
||||
|
||||
这背后是个真实缺口被补上的过程:AI 手里只有 `grant_status`(**只能加**),
|
||||
**没有任何工具能移除状态** —— 所以 `persistent` 状态一旦挂上就永远下不来、
|
||||
`timed` 的也只能干等。现在界面上给了出口:
|
||||
|
||||
- **清掉**:每条状态一个按钮。不做二次确认 —— 状态本来就能再加回来,
|
||||
连清五个不该弹五次窗
|
||||
- **加一个**:只列"还没挂上的",点一下直接挂。用来测某个状态的效果,
|
||||
或者补剧情里本来就该有的
|
||||
|
||||
> 这一页有三个入口:**聊天页状态栏** / **智能体编辑 →「它的状态」→
|
||||
> 「看它的数值和状态」** / **群成员页的「状态」按钮**。
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>脚本报"用了双下划线属性"/"写了 import"</b></summary>
|
||||
|
||||
这是沙箱的静态扫描在拦。规则脚本**不需要**那些东西 ——
|
||||
把 `import` 删掉,把 `xxx.__yyy__` 换成普通写法。
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>删了数值定义,值去哪了</b></summary>
|
||||
|
||||
**值还在库里,但读不到了** —— 定义没了它们就成了孤儿。
|
||||
|
||||
所以内核有一条保护:**空定义不同步**(不会因为读不到包就把定义清空)——
|
||||
要清定义就把整个包删掉,那是个明确得多的动作。
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 7. 最小可用清单
|
||||
|
||||
想最快看到效果,记住这四步就够:
|
||||
|
||||
1. **世界观 · 技能 · 模型 → 规则包 → 新建**(用模板)
|
||||
2. **世界观 · 技能 · 模型 → 世界观 → 数值状态包 → 选它**
|
||||
3. **智能体 → 世界观 → 选同一个**
|
||||
4. 发一句话,问它"你现在对我什么感觉"
|
||||
|
||||
脚本可以先完全不管 —— 没有脚本,数值和状态照样工作。
|
||||
@@ -1,8 +1,64 @@
|
||||
# 智能体系统(需求 v1.1)
|
||||
# 智能体系统(需求 v1.1 + v1.2)
|
||||
|
||||
这份文档对应《智能体系统需求文档 v1.1》。它不讲"应该怎么做"(那在需求里),
|
||||
只讲**这个仓库是怎么落地的**:每个需求项落在哪个文件、当时为什么这么选、
|
||||
出了问题去哪儿看。
|
||||
这份文档对应《智能体系统需求文档 v1.1》**和 v1.2**。它不讲"应该怎么做"
|
||||
(那在需求里),只讲**这个仓库是怎么落地的**:每个需求项落在哪个文件、
|
||||
当时为什么这么选、出了问题去哪儿看。
|
||||
|
||||
---
|
||||
|
||||
## 0. v1.2 增补(v2.0.47 → v2.0.66 全部落地)
|
||||
|
||||
v1.1 那张对照表在下面第 1 节;v1.2 新增的部分单列在这儿,
|
||||
因为它们的落点大多是**新文件**,和 v1.1 那批不是一回事。
|
||||
|
||||
| 需求 | 实现位置 |
|
||||
|---|---|
|
||||
| §3.5 情绪双字段(preset + text) | `kernel/agentdb.py`(`emotions` 表加 `preset`)+ `MemoryScreen.kt` |
|
||||
| §2.5 立绘五档 + §2.6 回退链 | `kernel/store.py: normalize_image` + `kernel/agent_api.py: portrait_of` + `AgentEditScreen.kt` |
|
||||
| §3.1 缓存统计归一化 | `kernel/agent_loop.py: cache_pair`(三家字段名不同)+ `agentdb.py` 的 `cache_hit/miss` |
|
||||
| 附录 C 缓存友好段序 | `kernel/defaults.py: DEFAULT_PROMPT_TEMPLATE` + `agent_context.SECTIONS` |
|
||||
| §4.3 对话上下文窗口 | **`kernel/context_window.py`**(成批对齐裁剪 + 重要标记破格携带) |
|
||||
| §3.10 数值系统 | **`kernel/rule_engine.py`** + `agent_tools.change_stat` |
|
||||
| §3.11 状态系统 | 同上 + `agent_tools.grant_status` + `agent_loop` 的 `on_turn` 调用点 |
|
||||
| 附录 E 脚本沙箱 | **`kernel/rule_sandbox.py`**(如实标注"挡手滑挡不住有意") |
|
||||
| 附录 D 数值状态包 | `agent_api._export_rulepack` / `_import_rulepack` + `ui/RulePackEditScreen.kt` |
|
||||
| §3.9 群聊 | **`kernel/group_chat.py`**(点名制仲裁)+ `agent_tools.invite_agent`·`pass_turn` + `ui/GroupMembersScreen.kt` |
|
||||
| §3.9 私聊 | **`kernel/private_chat.py`**(10 轮安全网 + 一方触顶单方面收尾) |
|
||||
| §3.10/3.11 状态数值界面 | `ui/AgentStatsScreen.kt`(三个入口共用) |
|
||||
| §6.1 背景跟随说话者 | `SettingsScreen.kt` 的「外观」组 + `ChatScreen.ChatBackdrop`(聊天页整屏立绘/背景层,跟着说话者换) |
|
||||
|
||||
### 两份"窗口"的命名纪律(需求点名要求,别混)
|
||||
|
||||
· 「记忆注入窗口」 memoryWindow —— 每轮塞多少条**记忆**,超出部分**降级为可检索**
|
||||
· 「上下文窗口」 contextWindow —— 送多少轮**对话**,超出部分**直接丢弃、不做摘要**
|
||||
|
||||
两个像但完全不同。混着叫的话,用户问"我调窗口怎么没用"时你都不知道说的是哪个。
|
||||
|
||||
### v1.2 踩过、值得记住的几类坑
|
||||
|
||||
| 坑 | 表现 | 教训 |
|
||||
|---|---|---|
|
||||
| **字段表缺项** | `rulePackId` / `inviteMode` / `contextWindow` 不在白名单里 → "界面里配了、读出来没有" | 加字段时先看字段表 |
|
||||
| **`push_context` 是替换语义** | 工具里拿它记标记,冲掉了 `agentId` → "拿不到当前智能体" | 要合并用 `update_context` |
|
||||
| **`GET /api/<res>/<id>` 缺分支** | 编辑页拿到空包,界面显示"0 条数值"而包其实建出来了 | 只有真点一遍才看得见 |
|
||||
| **`Text` 不渲染 Markdown** | `Text("**粗体**")` 把星号原样显示 | 不报错、不警告,只有截图能发现 |
|
||||
| **按下标定位消息** | 界面和存储的列表不一一对应 → **静默标错**到别的消息上 | 下标是两边各自数的;改成按内容定位 |
|
||||
| **`dict` 字段被 `_as_text` 压平** | 规则包的 `info` 里嵌套 list 变成字符串 → 整个规则引擎静默失效 | 嵌套结构要 `_json_safe` |
|
||||
| **请求体上限按最小的调用方给** | 手机照片 28.9MB → base64 38MB,撞上 `read_json_body` 默认的 4MB;异常又被吞成空 dict,最后报的是**「不认识的外观槽位」** | 上限按**最大**的用;吞异常等于把原因丢掉 |
|
||||
| **探针绕过了真正出问题的那一层** | 第 22 节直接调 `_set_asset`,而卡住的是 `handle()` 里的 `body()` → 探针全绿,真机全挂 | 探针**必须走生产同一条调用路径** |
|
||||
| **换图时"自己删自己"** | 落盘名是 `<槽位>-<原始文件名>`;同一张图传第二次时新旧同路径 → 写完新的立刻被当旧的删掉,`image` 里留下**指向不存在文件**的路径,目录空着界面回退默认图 | 删旧文件前先比路径;"先写后删"的顺序里藏着这个坑 |
|
||||
| **两条各自正确的逻辑叠在一起** | 群聊仲裁把 `agentId` 换成「本轮发言人」,紧接着的会话隔离又拿它比「会话主人」→ 群里每换一个人说话就**另起一个会话**,用户 @ 谁就跳到谁的对话去 | 一条规则搬到新场景时要重问一遍"它还成立吗"——群聊里 `agentId` 根本不是主人 |
|
||||
| **能力全都在,缺最后一个按钮** | `chatJob`(取消句柄)建好了、内核从 HTTP 到 `agent_loop` 一路支持 `cancelled`、ViewModel 也把 `AtomicBoolean` 传下去了 —— 但**没有任何界面调它**,用户只能干等它说完 | 一条链路要数**两端**:内核发得出 + 界面点得到。只做前半截,测的时候还全是绿的 |
|
||||
| **顺序错了:先仲裁、后落库** | 群聊仲裁要读「用户这一轮 @ 了谁」,而本次消息**还没写进库** → 读到的是**上一次**的话 → 我 @ 寐眠,回答的却是小黑(背景/标签/音色三处全对不上) | 读「刚刚发生的事」之前先问:**它现在在库里了吗** |
|
||||
|
||||
这类问题的共同点:**三层各自看都对,只有真的跑一遍才看得见**。
|
||||
|
||||
> 最后一条是 v2.0.72 修「背景图设置不了」时补上的:用户选的是手机相册里的照片
|
||||
> (30~55MB),这条链路上有三堵墙,**每一堵单独看都合理**:
|
||||
> 前端把 55MB 原样 `readBytes` + base64;内核每条接口卡 4MB;异常被 `body()` 吞掉。
|
||||
> 现在的分工是:前端**先把位图压到 3MB 以内**(`ui/ImagePick.kt`,GIF/SVG 不压,
|
||||
> 因为缩放会丢动画、栅格化会毁矢量),内核把**上传类**接口的上限统一放到
|
||||
> `UPLOAD_BODY_LIMIT`(图片 + 四种包导入),并且读不出来时**如实报原因**。
|
||||
|
||||
---
|
||||
|
||||
@@ -27,7 +83,7 @@
|
||||
| 3.7 幻觉调用检测 | `kernel/agent_loop.py: check_hallucinated_memory` + 对话页警示条 |
|
||||
| 4.1 本次对话用量 | `ui/ChatScreen.kt: SessionUsageBar` |
|
||||
| 附录 A UUID 主键 | `kernel/store.py: create_agent` / `create_resource` |
|
||||
| 附录 B 六个工具 | `kernel/agent_tools.py: AGENT_TOOLS` |
|
||||
| 附录 B 工具清单 | `kernel/agent_tools.py: AGENT_TOOLS`(v1.2 后共 11 个:v1.1 的 7 个 + `change_stat` / `grant_status` / `invite_agent` / `pass_turn`) |
|
||||
| 附录 C 提示词模板 | `kernel/agent_context.py` + `kernel/defaults.py: DEFAULT_PROMPT_TEMPLATE` |
|
||||
| 附录 D 包格式 | `kernel/agent_api.py` + `docs/智能体系统.md` 第 4 节 |
|
||||
|
||||
@@ -194,14 +250,28 @@ assets/… # 四件套图片(front / back / border-main / border-in
|
||||
|
||||
| 脚本 | 验什么 |
|
||||
|---|---|
|
||||
| `python scripts/probe-agent-system.py` | 12 节 70+ 项:UUID、记忆 CRUD、pinned、共享限权、提示词注入顺序、20 多个接口、包导入导出边界、多模型解析 |
|
||||
| `python scripts/probe-agent-system.py` | 23 节:UUID、记忆 CRUD、pinned、共享限权、提示词注入顺序、20 多个接口、包导入导出边界、多模型解析、数值/状态、外观槽位、**上传请求体上限和错误信息** |
|
||||
| `python scripts/probe-degraded.py` | 幻觉检测(该报的报、不该报的不报)+ 降级调用的解析/执行/剥离/坏输入 |
|
||||
| `python scripts/probe-rule-engine.py` | 数值/状态的定义、钳制、脚本、状态过期 |
|
||||
| `python scripts/probe-rule-sandbox.py` | 脚本沙箱挡得住什么、挡不住什么 |
|
||||
| `python scripts/probe-context-window.py` | 成批对齐裁剪 + 重要标记破格携带 |
|
||||
| `python scripts/probe-group-chat.py` | 群聊点名制仲裁 |
|
||||
| `python scripts/audit-ui-tree.py` | 文档里的界面和代码是否一致 |
|
||||
| `python scripts/audit-ui-entries.py` | 每个界面都有入口(没有死代码) |
|
||||
|
||||
两个都**不需要装机、不需要网络**:把 `DOUBAO_DATA` 指到一个临时目录,
|
||||
八个都不需要装机、不需要网络:把 `DOUBAO_DATA` 指到一个临时目录,
|
||||
内核的存储层是无状态的,整条链路就能在一个进程里跑完。
|
||||
|
||||
**比装机验证快得多,而且能断言具体字段**(截图只能看个大概)。
|
||||
|
||||
### 写探针的一条硬纪律:走**生产同一条**调用路径
|
||||
|
||||
第 22 节直接调 `_set_asset(...)`,于是它**永远测不到**卡住真机的那一层 ——
|
||||
上限是在 `handle()` 里的 `body()` 卡的。结果:探针全绿,真机选一张照片就挂。
|
||||
|
||||
所以第 23 节改成 `h.call('/api/agents/<id>/asset', 'POST', {...})`,
|
||||
从 HTTP 路径进去,一路走到存储。**能绕过的那一层,就是下次会出问题的那一层。**
|
||||
|
||||
### 改内核之后必须做的一件事
|
||||
|
||||
```bash
|
||||
|
||||
268
docs/界面总览.md
Normal file
@@ -0,0 +1,268 @@
|
||||
# 界面总览(UI 树)
|
||||
|
||||
这份文档把 App 里**所有**界面和它们的入口画成树。它不是凭记忆写的 ——
|
||||
`scripts/audit-ui-tree.py` 会从 Kotlin 源码扫出全部界面,然后**对拍这份文档**:
|
||||
少写一个、或者写了个代码里没有的,脚本都会报错。
|
||||
|
||||
```bash
|
||||
python scripts/audit-ui-tree.py # 校验这份文档和代码一致
|
||||
```
|
||||
|
||||
为什么要有这个脚本:这个项目里已经反复出现「界面做好了但没有任何入口」
|
||||
(记忆管理、世界观共享记忆都栽过),而**光靠人查必然会漏**。
|
||||
所以文档和代码必须能自动对拍。
|
||||
|
||||
---
|
||||
|
||||
## 0. 怎么读
|
||||
|
||||
```
|
||||
▶ 入口动作 → [界面名] ← 方括号 = 一个界面
|
||||
· 界面里的东西
|
||||
⤷ 这里的动作跳到哪儿
|
||||
```
|
||||
|
||||
- **[方括号]** = 一个独立的界面(全屏页或浮层)
|
||||
- **⤷** = 从这儿能去哪儿
|
||||
- 每条入口后面标了**触发动作**(点哪个按钮)
|
||||
|
||||
---
|
||||
|
||||
## 1. 全图
|
||||
|
||||
```
|
||||
豆包
|
||||
│
|
||||
├─ [聊天] ← 启动页(Screen.Chat)
|
||||
│ ├─ 顶栏
|
||||
│ │ ├─ ☰ ────────────────────────▶ [抽屉]
|
||||
│ │ ├─ ✎ ────────────────────────▶ 新话题(清空当前会话)
|
||||
│ │ ├─ 头像+名字+情绪标签 ──────▶ [智能体选择]
|
||||
│ │ │ (**群聊会话**时这里变成成员头像组)──▶ [群成员]
|
||||
│ │ ├─ 📞 ───────────────────────▶ 通话模式(还没做)
|
||||
│ │ └─ 🔊 ───────────────────────▶ 自动朗读开关
|
||||
│ ├─ 消息区
|
||||
│ │ └─ 每条消息的操作栏
|
||||
│ │ ├─ 复制
|
||||
│ │ ├─ 打开网页 ────────────▶ [链接列表] ──▶ [网页]
|
||||
│ │ ├─ 朗读 / 停止
|
||||
│ │ ├─ 👍 / 👎
|
||||
│ │ ├─ 标记重要 / 取消标记 ← v1.2 §4.3(只有用户能标,AI 不行)
|
||||
│ │ └─ 工具痕迹(折叠)
|
||||
│ ├─ 输入框上方
|
||||
│ │ ├─ 成员快捷条(**群聊**时才出现)—— 点头像即 @
|
||||
│ │ ├─ 状态栏(**有生效状态时**才出现)▶ [状态数值]
|
||||
│ │ ├─ 本次对话用量 ────────────▶ [用量详情]
|
||||
│ │ ├─ 额度用完提示 ────────────▶ [用量详情]
|
||||
│ │ └─ 死亡提示条(死亡时)─────▶ [记忆](复活入口)
|
||||
│ └─ 输入条(相机 / 语音 / +);**死亡时整条禁用**
|
||||
│
|
||||
│ ★ 立绘随情绪 preset 切换;群聊时聊天背景跟随当前发言者(v1.2 §4.4)
|
||||
│
|
||||
├─ [抽屉](浮层)
|
||||
│ ├─ 开启新话题
|
||||
│ ├─ 智能体 ──────────────────────▶ [智能体选择]
|
||||
│ ├─ 记忆 ────────────────────────▶ [记忆](当前智能体)
|
||||
│ ├─ 笔记 ────────────────────────▶ [笔记]
|
||||
│ ├─ 模型(下拉选择器,不是页面)
|
||||
│ ├─ 更多功能 ────────────────────▶ [更多功能]
|
||||
│ └─ 对话列表
|
||||
│ ├─ 点一条 ──────────────────▶ 打开那个会话
|
||||
│ ├─ group 类型(群聊/私聊记录)▶ 只读翻看
|
||||
│ └─ 🗑 ──────────────────────▶ 删除确认(弹窗)
|
||||
│
|
||||
├─ [群成员](浮层,v1.2 §6.2 —— **计划中**)
|
||||
│ ├─ 成员列表(头像 + 名字 + 情绪 preset + 死亡标识)
|
||||
│ ├─ 添加成员(限同世界观)/ 移除成员
|
||||
│ └─ 点一个成员 ──────────────────▶ [状态数值](只读)
|
||||
│
|
||||
├─ [状态数值](浮层,v1.2 §6.2 —— **计划中**)
|
||||
│ ├─ 生效中的状态(名称 / 剩余轮数 / 当前提示词)
|
||||
│ └─ 数值列表(当前值 / 命中区间 / 标着「世界」还是「自身」)
|
||||
│
|
||||
├─ [更多功能](浮层)
|
||||
│ ├─ AI 界面 ─────────────────────▶ [AI 界面列表]
|
||||
│ ├─ 世界观 · 技能 · 模型 ────────▶ [资源]
|
||||
│ ├─ 技能 · 连接器 ───────────────▶ [技能]
|
||||
│ ├─ 会议模式 ────────────────────▶ [会议]
|
||||
│ ├─ 终端 ────────────────────────▶ [终端]
|
||||
│ └─ 设置 ────────────────────────▶ [设置]
|
||||
│
|
||||
├─ [智能体选择](Screen.AgentSelect)
|
||||
│ ├─ 左列表 / 右四层展示 / 切换动画
|
||||
│ ├─ 圆形「⋯」 ───────────────────▶ [用量详情]
|
||||
│ ├─ 底部「记忆」 ────────────────▶ [记忆]
|
||||
│ ├─ 底部「开始对话」 ────────────▶ 回 [聊天](并切人+换会话)
|
||||
│ ├─ 左列表点一项 ────────────────▶ 换选中(带 1.5s 动画)
|
||||
│ └─ 右上「管理」 ────────────────▶ [智能体管理]
|
||||
│
|
||||
├─ [智能体管理](Screen.Agents)
|
||||
│ ├─ 顶栏「导入」 ────────────────▶ 选 .zip → 导入包
|
||||
│ ├─ 顶栏「新建」 ────────────────▶ [智能体编辑](新建)
|
||||
│ └─ 每一行
|
||||
│ ├─ 点整行 ──────────────────▶ 切换人设
|
||||
│ ├─ 「记忆」 ────────────────▶ [记忆]
|
||||
│ ├─ 「编辑」 ────────────────▶ [智能体编辑]
|
||||
│ └─ 「删除」 ────────────────▶ 删除确认(弹窗)
|
||||
│
|
||||
├─ [智能体编辑](浮层,全屏)
|
||||
│ ├─ 基本信息(名字 / 一句话介绍 / 介绍文案)
|
||||
│ ├─ 外观(角色图 / 背景图 / 主体边框 / 介绍边框)→ 选图 / 清除
|
||||
│ ├─ 人设(系统提示词)
|
||||
│ ├─ 模型(引用全局模型列表)
|
||||
│ ├─ 世界观(绑定 + 显示"已有 N 个在用")
|
||||
│ ├─ 能力(情绪感知开关 / Token 限额)
|
||||
│ ├─ 技能(勾选自定义 Skill,按顺序注入)
|
||||
│ ├─ 语音(音色)
|
||||
│ ├─ 「看它记住了什么」 ──────────▶ [记忆]
|
||||
│ ├─ 「看它用了多少」 ────────────▶ [用量详情]
|
||||
│ ├─ 「导出这个智能体(.zip)」 ────▶ 存盘
|
||||
│ └─ 「删除这个智能体」 ──────────▶ 直接删(内置的没有这个按钮)
|
||||
│
|
||||
├─ [记忆](浮层)
|
||||
│ ├─ 顶部:注入窗口(带"已置顶 N 条")──▶ [窗口设置](弹窗)
|
||||
│ ├─ 顶部:旧私有记忆入口 ────────▶ [记忆 · 绑定前的私有空间]
|
||||
│ ├─ 情绪(输入框 + 保存)
|
||||
│ ├─ 操作条:+加一条 / AI 整理 / 导出文件
|
||||
│ │ └─ AI 整理 ─────────────────▶ 确认弹窗
|
||||
│ ├─ 顶栏「导入」 ────────────────▶ 选文件 → [合并/覆盖](弹窗)
|
||||
│ └─ 每条记忆
|
||||
│ ├─ 「置顶 / 取消置顶」
|
||||
│ ├─ 「编辑」 ────────────────▶ [编辑记忆](弹窗)
|
||||
│ └─ 「删除」
|
||||
│
|
||||
├─ [资源](Screen.Resources)
|
||||
│ ├─ Tab:世界观 / Skill / 模型 / **规则包**(v1.2 §6.2,计划中)
|
||||
│ ├─ 顶栏「导入」 ────────────────▶ 选包 → 导入
|
||||
│ │ (**规则包**多插一步:脚本警告确认 —— 附录 E 的安全底线)
|
||||
│ ├─ 顶栏「新建」 ────────────────▶ [资源编辑](新建)
|
||||
│ └─ 每一行(随 Tab 变)
|
||||
│ 世界观:「记忆」─▶ [记忆 · 世界观视角] / 「导出」/「删除」
|
||||
│ Skill : 「导出」/「删除」
|
||||
│ 模型 : 「导出」/「删除」
|
||||
│ 规则包: 点开 ─▶ [规则包编辑]
|
||||
│
|
||||
├─ [规则包编辑](全屏,v1.2 §6.2 —— **计划中**)
|
||||
│ ├─ 数值表(名称 / min-max / shared 开关 / 区间表 / 绑定脚本)
|
||||
│ ├─ 状态表(名称 / 持久或定时 / 轮数 / max_stack / 绑定脚本)
|
||||
│ └─ 脚本编辑 ─── 复用 [会议] · [节点代码] 的代码编辑器,不另造
|
||||
│
|
||||
├─ [记忆 · 世界观视角](浮层,只读)
|
||||
│ └─ 每条带作者署名;只能删
|
||||
│
|
||||
├─ [设置](Screen.Settings)
|
||||
│ ├─ 模型 / 语音 / 外观 / 数据 …
|
||||
│ ├─ 「超时」 ────────────────────▶ [超时]
|
||||
│ ├─ 「智能体」 ──────────────────▶ [智能体管理]
|
||||
│ ├─ 「技能 · 连接器」 ───────────▶ [技能]
|
||||
│ └─ 「关于 / 我的」 ─────────────▶ [我的]
|
||||
│
|
||||
├─ [超时](浮层,全屏)
|
||||
│ └─ 分组:动画 / 对话 / 工具 / 界面 / 语音 / MCP + 恢复默认
|
||||
│
|
||||
├─ [用量详情](浮层)
|
||||
│ ├─ 累计(输入 / 输出分列)
|
||||
│ ├─ 额度进度
|
||||
│ ├─ 按模型分行
|
||||
│ └─ 顶栏「清零」 ────────────────▶ 确认弹窗
|
||||
│
|
||||
├─ [技能](Screen.Skills)
|
||||
│ ├─ Python 工具列表(开关 / 编辑)
|
||||
│ ├─ MCP 服务(增删改 / 连接)
|
||||
│ └─ 界面能力开关(show_ui / ask_user / end_conversation)
|
||||
│
|
||||
├─ [会议](Screen.Meetings)
|
||||
│ ├─ 画布(节点 + 连线)
|
||||
│ ├─ ▶ 运行 / 底部「运行」
|
||||
│ ├─ 节点管理 ────────────────────▶ [节点管理]
|
||||
│ │ ├─ 「编辑代码」 ────────────▶ [节点代码]
|
||||
│ │ └─ 「积木」 ────────────────▶ [积木编辑器]
|
||||
│ └─ 导入 / 导出会议
|
||||
│
|
||||
├─ [终端](Screen.Terminal)
|
||||
│ └─ 内置 Termux,真 Linux 环境
|
||||
│
|
||||
├─ [笔记](浮层)
|
||||
│ └─ 点一条 ──────────────────────▶ [笔记详情]
|
||||
│
|
||||
├─ [AI 界面列表](浮层)
|
||||
│ └─ 点一条 ──────────────────────▶ [网页](本地 HTML)
|
||||
│
|
||||
├─ [网页](浮层)
|
||||
│ └─ 顶栏返回 → 关掉
|
||||
│
|
||||
├─ [我的](Screen.Profile)
|
||||
│ └─ 快捷入口:智能体 / 技能 / 设置 …
|
||||
│
|
||||
└─ [镜像](MirrorScreen)
|
||||
└─ 投屏/镜像用的纯展示页(由外部调用,App 内没有入口)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 界面骨架
|
||||
|
||||
所有全屏界面统一用同一套顶栏(`ScreenScaffold.kt` 的 `FullScreen`):
|
||||
|
||||
```
|
||||
← 返回 标题 副标题 [动作]
|
||||
────────────────────────────────────────────
|
||||
(内容,可滚动)
|
||||
```
|
||||
|
||||
**为什么统一**:不统一的话,返回按钮的位置、标题大小、右边动作的样式
|
||||
会每个页面都不一样(AGENTS.md 里明确要求用同一套)。
|
||||
|
||||
**弹窗只用在三种地方**(AGENTS.md 那张表):
|
||||
|
||||
| 场景 | 例子 |
|
||||
|---|---|
|
||||
| 一次确认 | 删除智能体、清零用量、覆盖导入 |
|
||||
| 一次输入 | 编辑一条记忆、调注入窗口、重命名 |
|
||||
| 纯菜单 | 底部弹层、编辑器菜单 |
|
||||
|
||||
其余一切(列表、多组配置、任何要滚动的)→ **独立全屏界面**。
|
||||
|
||||
---
|
||||
|
||||
## 3. 入口对照表
|
||||
|
||||
每个界面「从哪儿能进去」。**这张表是脚本生成的**,不靠记忆。
|
||||
|
||||
| 界面 | 入口 |
|
||||
|---|---|
|
||||
| 聊天 | 启动页;几乎所有界面的「返回」都回这儿 |
|
||||
| 抽屉 | 聊天页左上 ☰ |
|
||||
| 更多功能 | 抽屉 →「更多功能」 |
|
||||
| 智能体选择 | 抽屉 →「智能体」;聊天页顶栏点名字 |
|
||||
| 智能体管理 | 智能体选择的「管理」;我的页;设置页 |
|
||||
| 智能体编辑 | 智能体管理的「新建」/「编辑」 |
|
||||
| 记忆 | 抽屉;智能体管理每行;智能体选择底部;智能体编辑底部;聊天页 |
|
||||
| 记忆 · 世界观视角 | 资源 → 世界观 →「记忆」 |
|
||||
| 记忆 · 绑定前的私有空间 | 记忆页顶部的提示条(绑了世界观且旧空间有东西时才出现) |
|
||||
| 资源 | 更多功能 →「世界观 · 技能 · 模型」 |
|
||||
| 用量详情 | 智能体选择「⋯」;聊天页用量行「累计 ›」;额度用完的提示;智能体编辑 |
|
||||
| 设置 | 更多功能 →「设置」;我的页 |
|
||||
| 超时 | 设置 →「超时」 |
|
||||
| 技能 | 更多功能 →「技能 · 连接器」;设置;我的页 |
|
||||
| 会议 | 更多功能 →「会议模式」 |
|
||||
| 终端 | 更多功能 →「终端」 |
|
||||
| 笔记 | 抽屉 →「笔记」 |
|
||||
| AI 界面列表 | 更多功能 →「AI 界面」;聊天页(AI 弹过界面时) |
|
||||
| 网页 | 消息里的链接;AI 界面列表 |
|
||||
| 我的 | 设置 →「关于 / 我的」;抽屉底部头像 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 这份文档怎么保证不漏
|
||||
|
||||
`scripts/audit-ui-tree.py` 做三件事:
|
||||
|
||||
1. **扫代码**:所有 `fun XxxScreen(` 组件、`Screen` 枚举的每个值、
|
||||
`open*` 打开方法([`AppViewModel.kt`](../android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt))
|
||||
2. **扫这份文档**:第 1 节树里出现的 `[界面名]`
|
||||
3. **对拍**:代码里有、文档里没有 → 报错;文档里有、代码里没有 → 报错
|
||||
|
||||
另外它复用 `audit-ui-entries.py` 的检查:**每个界面都得有入口** ——
|
||||
一个 `openXxx()` 谁都不调,就意味着那个界面做好了但进不去
|
||||
(记忆管理就是这么漏的)。
|
||||
261
docs/网页版.md
Normal file
@@ -0,0 +1,261 @@
|
||||
# 网页版 / Windows exe(v2:豆包网页版风格 + 与 App 同一份内核)
|
||||
|
||||
> 这份文档说的是 **Web / Windows 端**。安卓端(主力)看根目录 README 和 `docs/界面总览.md`。
|
||||
|
||||
## 0. 一句话
|
||||
|
||||
Web/Windows 端从旧的 **Lynx 手机壳**换成了**豆包网页版风格**的真 Web 前端(`web/`),
|
||||
并且**不再维护第二套内核**:exe 会把仓库里和安卓 App 完全相同的那份 **Python 内核**
|
||||
(`android/kernel/`)作为子进程跑起来,网页前端只是它的一个客户端。
|
||||
所以「和 App 功能同步」不是逐条抄接口,而是**同一份后端** —— 内核加功能,Web 端跟着就能用。
|
||||
|
||||
| | 旧版(v1) | 现在(v2) |
|
||||
|---|---|---|
|
||||
| 界面 | Lynx(`app/`,手机比例 420×900 窗口) | 纯 HTML/CSS/JS(`web/`,1440×900 桌面网页) |
|
||||
| 视觉 | 手机 App 风格(抽屉 + 底部输入框) | 豆包**网页版**风格(左栏 280 + 中间内容列 1000 + 底部大输入框) |
|
||||
| 内核 | Node(`server/`,功能落后于 App) | **Python(`android/kernel/`,与安卓 App 同一份)** |
|
||||
| exe 运行时 | Electron + 内置 Node | Electron + **内置嵌入式 Python**(`runtime/python`) |
|
||||
| 功能同步 | 手工维护两份内核(欠账越拉越多) | 天然同步(一份内核,两个客户端) |
|
||||
|
||||
旧的 Lynx 版**没有删**:`app/` 和 `server/` 还在,`npm run start:legacy-lynx` 还能跑,只作为历史留档。
|
||||
|
||||
---
|
||||
|
||||
## 1. 怎么跑
|
||||
|
||||
### 浏览器(开发/日常)
|
||||
|
||||
需要电脑上有 **Python 3.10+**(内核用了 `str | None` 这类新语法;实测 3.12 / 3.13 都行)。
|
||||
|
||||
```bash
|
||||
npm start # = node scripts/start-web.mjs,起内核并托管 web/
|
||||
# 打开 http://127.0.0.1:5199/
|
||||
```
|
||||
|
||||
- 换端口:`PORT=5300 npm start`
|
||||
- 指定解释器:`DOUBAO_PYTHON=C:\Python313\python.exe npm start`
|
||||
- 数据目录默认是仓库里的 `data/`(已 gitignore),可用 `DOUBAO_DATA` 覆盖
|
||||
|
||||
### Windows exe
|
||||
|
||||
```bash
|
||||
npm run exe # 产出 …\DoubaoClone\Doubao-win32-x64\豆包.exe
|
||||
```
|
||||
|
||||
打包脚本会自动:
|
||||
1. 下载/复用 `desktop/build-cache/python-3.13.9-embed-amd64.zip`(python.org 的嵌入式 Python,约 10MB);
|
||||
2. 解压到 `runtime/python`(用户电脑**不需要装 Python**);
|
||||
3. 复制内核 `android/kernel/` → `runtime/kernel`、工具 `tools/` → `runtime/tools`、前端 `web/` → `runtime/web`;
|
||||
4. 用 electron-packager 打包(**输出路径必须是纯 ASCII**,否则 Electron 启动崩溃,见 README §7.1)。
|
||||
|
||||
exe 启动流程(`desktop/main.cjs`):
|
||||
|
||||
```
|
||||
Electron 主进程
|
||||
├─ 起一个只监听 127.0.0.1 的「原生能力桥」(选文件 / 剪贴板 / 在资源管理器显示)
|
||||
├─ spawn runtime/python/python.exe runtime/kernel/main.py
|
||||
│ --port 0(系统分配) --data-dir %APPDATA%\Doubao\data
|
||||
│ --tools-dir runtime/tools --web-dir runtime/web
|
||||
│ --desktop-bridge http://127.0.0.1:<桥端口>
|
||||
├─ 读内核 stdout 里的那行 JSON 拿到真实端口
|
||||
└─ 开 1440×900 窗口加载 http://127.0.0.1:<端口>/
|
||||
```
|
||||
|
||||
原生能力桥是**必需的**:Python 子进程里没有 Electron 的 `dialog/clipboard`。
|
||||
桥的实现是 `desktop/main.cjs` 的 `startBridge()` + `android/kernel/main.py` 的 `--desktop-bridge`
|
||||
(内核侧注册 `app.set_native_hooks(...)`,和安卓 Kotlin 那侧是同一个钩子接口)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 目录地图
|
||||
|
||||
```
|
||||
web/ # 网页版前端(纯静态,无构建步骤)
|
||||
index.html # 入口
|
||||
assets/app.css # 设计系统 + 全部页面样式(值是对着豆包网页版实测的)
|
||||
assets/avatars/*.png # 内置智能体头像(本仓库自己的素材)
|
||||
js/
|
||||
api.js # fetch 封装 + 全局 state + 聊天轮询
|
||||
ui.js # h() / icon() / markdown / toast / 弹层 / 表单小部件
|
||||
icons.js # 74 个手写 SVG 图标(Lucide 风格,不抄豆包资源)
|
||||
app.js # 启动、侧栏、顶栏、hash 路由
|
||||
pages/ # 一页一个模块(页面契约见 app.js 头部注释)
|
||||
chat.js # 对话(流式、思考、工具轨迹、附件、群聊、交接条、朗读、语音输入)
|
||||
agents.js # 智能体列表
|
||||
agent-edit.js # 智能体编辑
|
||||
groups.js # 群聊管理
|
||||
memories.js # 记忆 + 情绪
|
||||
usage.js # Token 用量
|
||||
resources.js # 世界观 / Skill / 全局模型 / 规则包
|
||||
skills.js # Python 工具 / MCP / AI 界面开关
|
||||
notes.js / screens.js # 笔记 / AI 界面
|
||||
meetings.js # 会议模式(一期:列表/运行/结果/历史)
|
||||
settings.js # 设置(模型/对话/语音/工具/外观/超时)
|
||||
me.js / about.js # 我的 / 关于
|
||||
scripts/
|
||||
start-web.mjs # npm start:起 Python 内核托管 web/
|
||||
build-exe.mjs # 打包 Windows exe(含嵌入式 Python)
|
||||
verify-web-ui.mjs # 验收:起临时内核,逐页截图 + 收集 JS 报错
|
||||
scrape-doubao-web.mjs # 扒豆包网页版做视觉参考(产物在 reference/,不入库)
|
||||
android/kernel/ # ★ 和安卓 App 共用的 Python 内核(Web/exe 也跑它)
|
||||
desktop/main.cjs # Electron 主进程(内核子进程 + 原生桥 + 窗口)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 设计:怎么做到「看起来是豆包网页版」
|
||||
|
||||
`docs/豆包网页版-风格规范.md` 是对着**真实豆包网页版(www.doubao.com/chat,1440×900)**
|
||||
的抓取镜像逐像素量出来的规范。抓取可复现:
|
||||
|
||||
```bash
|
||||
node scripts/scrape-doubao-web.mjs # 产物 reference/doubao-web-mirror/(第三方资源,已 gitignore)
|
||||
node scripts/probe-doubao-web-metrics.mjs # 补测 CSS 变量/组件尺寸
|
||||
```
|
||||
|
||||
落到实现上的关键值(详见规范文档):
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 侧栏 | 宽 280、背景 `#f9f9f9`、右边 0.5px `rgba(0,0,0,.064)`、内边距 `10 12 12` |
|
||||
| 主区顶栏 | 高 56 |
|
||||
| 内容列 | 1000 居中(`--content-w`) |
|
||||
| 空态问候语 | 28px / 600 / 行高 42 / 块顶约 308 |
|
||||
| 输入框 | 1000×100、圆角 24、`1px rgba(0,0,0,.1)`、大阴影;聚焦变 `rgba(0,102,255,.3)` 细蓝边 + 光晕 |
|
||||
| 品牌蓝 | `#0066ff`(= `#06f`) |
|
||||
| 文字 | 主 `#000`、次 `rgba(0,0,0,.5)`、三级 `rgba(0,0,0,.35)` |
|
||||
| 空态右下角 | 浅灰圆形麦克风;有内容才换成蓝色圆形发送 |
|
||||
| 暗色 | `[data-theme=dark]` 一整套 token(侧栏 `#0f0f0f`、浮层 `#181818`) |
|
||||
|
||||
我们**只学布局/尺寸/配色**:图标全部是 `web/js/icons.js` 里手写的 74 个 SVG,
|
||||
不包含豆包的 logo、字体文件、图标资源、文案。
|
||||
|
||||
---
|
||||
|
||||
## 4. 功能同步矩阵(Web 端 vs 安卓 App)
|
||||
|
||||
内核是同一份,所以**能力**是全的;差别只在「网页端界面盖了多少」。
|
||||
|
||||
| App 里的功能 | Web 端 | 说明 |
|
||||
|---|---|---|
|
||||
| 对话、流式回复、思考过程、工具轨迹、附件、出错提示 | ✅ | `chat.js`:POST /api/chat + 轮询,事件和安卓端完全一致(`docs/kernel-api-chat.md`) |
|
||||
| 深度思考(思考强度五档)、切换智能体/模型 | ✅ | 顶栏模型菜单 + 输入框「思考」 |
|
||||
| 消息操作:复制 / 朗读 / 赞踩 / 标记重要 | ✅ | 标记重要按"内容"定位(内核要求的) |
|
||||
| 自动朗读、语音输入 | ✅(有降级) | 朗读:`system` 引擎用浏览器 `speechSynthesis`,云端引擎播内核返回的音频;语音输入:优先浏览器识别,其次录音 + 内核 `/api/stt`(需要 OpenAI 兼容 STT) |
|
||||
| 群聊:成员、@ 发言、AI 之间移交话头、让他们聊几轮 | ✅ | 群成员条 + `speaker`/`handoff` 事件 + 交接条 |
|
||||
| 智能体:列表 / 新建 / 编辑 / 删除 / 导入导出 | ✅ | `agents.js` / `agent-edit.js`(导入导出为 base64 zip 下载/上传) |
|
||||
| 记忆:增删改、置顶、AI 整理、导入导出、世界观共享记忆(只读) | ✅ | `memories.js` |
|
||||
| 情绪(活着/死亡/自定义情绪文本) | ✅ | `memories.js` 顶部情绪卡片 |
|
||||
| Token 用量:按模型分桶、额度、清零 | ✅ | `usage.js` |
|
||||
| 资源:世界观 / Skill / 全局模型 / 规则包(含脚本警告确认) | ✅ | `resources.js` |
|
||||
| 技能·连接器:Python 工具试运行、MCP 配置/连接/断开、AI 界面开关 | ✅ | `skills.js` |
|
||||
| 笔记、AI 界面列表(可重新打开) | ✅ | `notes.js` / `screens.js`;电脑端 show_ui 也会落盘,见下 |
|
||||
| 会议模式:列表 / 运行 / 实时日志 / 结果 / 历史 | ✅(一期) | `meetings.js`;节点画布是二期(Android 那份 7600 行,不硬搬) |
|
||||
| 设置:10 家提供商、思考强度、对话上下文、语音、工具与安全、外观、22 项超时 | ✅ | `settings.js` |
|
||||
| 我的 / 关于 / 主题(浅色/深色/跟随系统) | ✅ | `me.js` / `about.js` |
|
||||
| 内置 Termux 终端 | ❌(Web 端做不了) | 这是安卓专属能力;桌面等价物是"Python 工具试运行"和 shell 工具 |
|
||||
| 立绘/背景/整屏 AI 形象 | ⏳ 未做 | 内核有 `image` 字段和 asset 接口,Web 端还没画 |
|
||||
| `show_ui` / `ask_user` / `end_conversation`(AI 弹界面、提问、封笔) | ✅ | 走内核的**界面能力通道**(`/api/device/*` HTTP 队列),`wait` 语义和安卓一致;详见 §5.1 |
|
||||
| 会议节点画布 | ⏳ 二期 | 一期已能跑/看结果 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 验收
|
||||
|
||||
```bash
|
||||
node scripts/verify-web-ui.mjs # 14 个页面逐页截图 + 收集 JS 报错
|
||||
node scripts/verify-ui-bridge.mjs # AI 界面能力通道(show_ui / ask_user / end_conversation)
|
||||
```
|
||||
|
||||
`verify-web-ui.mjs`:起一个**独立临时数据目录**的 Python 内核 → 用无头 Edge 逐页打开 14 个路由 →
|
||||
每页截图到 `.tmp-verify-web/` → 收集 JS 报错 → 有报错/白屏就退出码 1。
|
||||
对着已跑着的内核验可以 `--base http://127.0.0.1:5199`。
|
||||
|
||||
`verify-ui-bridge.mjs`:同样自己起临时内核、不需要浏览器,覆盖 11 项:
|
||||
ask_user 阻塞→回答→工具拿到 choice、show_ui(wait=false) 落盘+通知队列、
|
||||
show_ui(wait=true) 阻塞→回答→工具拿到 value、end_conversation 落盘、错误路径 404。
|
||||
|
||||
### 5.1 AI 界面能力是怎么在电脑端跑通的
|
||||
|
||||
`show_ui` / `ask_user` / `end_conversation` 三个工具在安卓上走 Kotlin 的 `NativeBridge.device()`(同步阻塞)。
|
||||
电脑/网页端没有原生桥,内核加了一条 **HTTP 界面通道**(`android/kernel/app.py`):
|
||||
|
||||
```
|
||||
工具线程(_ui_bridge.call_device,阻塞)
|
||||
↓ 放入队列
|
||||
GET /api/device/pending ← 网页每 700ms 轮询(web/js/device.js)
|
||||
↓ 网页弹:ask_user → 选择弹窗;show_ui → iframe 渲染 AI 写的 HTML
|
||||
POST /api/device/answer → 用户的选择/点选值送回内核
|
||||
↓
|
||||
工具线程拿到结果继续(wait=true 的语义完整保留:点选值 / 关闭 / 超时)
|
||||
```
|
||||
|
||||
- 队列是 **FIFO** 的(同时开两个对话/标签页也不会互相顶掉),上限 8 个;
|
||||
- 网页不给 `timeoutMs` 时内核最多等 1 小时(安卓是"不限时",网页端不做无限占线程);
|
||||
- `show_ui` 的界面会**同时落盘**(`store.save_screen`),所以 `/api/screens` 在电脑端也有数据、
|
||||
「AI 界面」页能重新打开;
|
||||
- `end_conversation` 是纯内核写操作(会话标记 `ended` + 原因),网页端只负责显示
|
||||
「这次对话已结束」提示条并锁住输入框;
|
||||
- 界面里的 `Doubao.sendToAi(v)` / `Doubao.close()` / `<button data-doubao-result="…">`
|
||||
通过 `postMessage` 回到网页(iframe 用 `sandbox`,AI 的 HTML 拿不到内核接口)。
|
||||
|
||||
浏览器的 `#/settings → 工具与安全` 里打开「AI 界面能力」开关后,模型才会用这三个工具(默认关)。
|
||||
|
||||
```bash
|
||||
node scripts/mock-llm.mjs & # 假 OpenAI 兼容服务,监听 5299
|
||||
# 在设置里把提供商选自定义,baseUrl=http://127.0.0.1:5299/v1、模型随手填、Key 随手填
|
||||
```
|
||||
|
||||
exe 的验证方式:`DOUBAO_CDP_PORT=9444` 启动后,用
|
||||
`CDP_PORT=9444 node scripts/screenshot.mjs - out.png` 附着截图(Electron 界面只有真窗口渲染得出来)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 已知差距 / 坑
|
||||
|
||||
**功能差距**:
|
||||
|
||||
1. 会议画布(节点/连线编辑)是二期。
|
||||
2. 立绘/背景/整屏角色图未做(内核有 `image` 字段和 asset 接口,Web 端还没画)。
|
||||
3. 内置 Termux 终端做不了(安卓专属),桌面等价物是「Python 工具试运行」。
|
||||
|
||||
**踩过的坑(都修好了,写下来防复现)**:
|
||||
|
||||
1. **`ELECTRON_RUN_AS_NODE=1` 会让 Electron 当 Node 跑**:本机环境里全局有这个变量,
|
||||
开发时 `electron .` 直接报 `Cannot read properties of undefined (reading 'commandLine')`。
|
||||
启动 GUI 前要 `Remove-Item Env:ELECTRON_RUN_AS_NODE`(打包给用户的 exe 不受影响)。
|
||||
2. **exe 的数据目录/单实例锁**:开发时如果和旧版 Electron 抢 `%APPDATA%\Doubao`,
|
||||
会报 `Lock file can not be created (0x5)` 然后静默退出。现在支持
|
||||
`DOUBAO_USER_DATA` / `DOUBAO_DATA` 环境变量覆盖(自动化测试用,正常用户不用管)。
|
||||
3. **Electron 在中文路径下启动崩溃**(0xC0000005):打包输出目录固定用 ASCII(`C:\…\DoubaoClone`)。
|
||||
4. **内嵌 Python 必须验证 sqlite3/ssl**:Embeddable zip 自带 `_sqlite3.pyd` / `sqlite3.dll` / `_ssl.pyd`,
|
||||
内核的记忆库和 HTTPS 调用都靠它们。打包脚本不会替你检查,改动 `PY_VERSION` 后要手动跑一次。
|
||||
5. **窗口默认 1440×900,但用户可能缩小**:空态的内容高度要自适应(`padding-top` 用 `calc(100vh - …)`),
|
||||
否则推荐条目会被底部输入框盖住(踩过一次,Electron 内高约 864 时最明显)。
|
||||
6. **流式消息的"最终重渲染"**:`renderMessage()` 会把 `msg._el` 指向**新节点**,
|
||||
先取 `_el` 再 `replaceChild` 永远替换不上(表现:流式那条停在半截内容 + 操作栏已出现)。
|
||||
正确顺序是 `const oldNode = msg._el;` → `renderMessage()` → `oldNode.parentNode.replaceChild(newNode, oldNode)`。
|
||||
7. **轮询 `done` 之后还有事件**:内核的 `handoff` / `status` / `saved` 在 `done` **之后**才发,
|
||||
客户端拿到 `done:true` 要在补拉一拍(`api.js` 的 `runChat` 里有 `flushing` 逻辑)。
|
||||
8. **群聊 `@` 的按钮一直在**:`atBtn` 要先渲染再按 `isGroup` 隐藏,不能在骨架阶段条件渲染
|
||||
(骨架阶段还不知道这个会话是不是群)。
|
||||
9. **界面能力请求不能用"一个槽位"**:`/api/device/*` 一开始是单个 `_DEVICE_PENDING`,
|
||||
后来发现上一个弹窗没答时新请求会把它**静默顶掉**(那个工具线程要一直等到超时,
|
||||
用户看到的是"AI 说要问我、界面却没弹")。改成 FIFO 队列 + 上限 8 就对了。
|
||||
10. **iframe 里的 `Doubao.sendToAi` 要靠 postMessage**:`sandbox` 不带 `allow-same-origin`,
|
||||
父页面**碰不到** iframe 的 DOM;所以桥是注入到 srcdoc 里的脚本 + `parent.postMessage`,
|
||||
父页面只监听 `message` 并按 `event.source === iframe.contentWindow` 校验。
|
||||
11. **`end_conversation` 之后要重新拉会话**:工具是"写内核数据",不会自动改前端内存里的消息列表;
|
||||
聊天页在 `toolTrace` 里看到 `end_conversation` 成功后重新 `GET /api/conversations/<id>`,
|
||||
才能显示「这次对话已结束」并锁住输入框。
|
||||
|
||||
---
|
||||
|
||||
## 7. 接口契约文档(写前端时的唯一事实来源)
|
||||
|
||||
- `docs/kernel-api-chat.md` —— 聊天链路:`/api/chat` + `/api/chat/poll` 的 14 种事件、消息对象字段、
|
||||
附件/TTS/STT/UI 回流、25 条移植坑
|
||||
- `docs/kernel-api-agents.md` —— 智能体 / 记忆 / 情绪 / 用量 / 世界观 / 模型列表 / Skill / 规则包 / 设置 / 超时
|
||||
- `docs/kernel-api-misc.md` —— 工具 / MCP / 会议 / 笔记 / AI 界面 / 上传 / 语音 / 桌面桥
|
||||
|
||||
这三份是照着内核源码 + 对真实内核的 GET 探测写的(不是凭记忆),加接口时先更新它们。
|
||||
884
docs/豆包网页版-风格规范.md
Normal file
@@ -0,0 +1,884 @@
|
||||
# 豆包网页版 · 风格规范(抓取镜像实测版)
|
||||
|
||||
> 目标:让我们的 Web 前端(纯 HTML/CSS/JS,跑在本地 kernel,桌面 Electron + 浏览器)
|
||||
> **看起来就是豆包网页版那个风格**。开发者只看这一份文档 + 三张截图就能搭出首屏。
|
||||
>
|
||||
> 本文所有数字来自 `reference/doubao-web-mirror/`(**只读**镜像),不是凭印象写的。
|
||||
|
||||
---
|
||||
|
||||
## 0. 怎么读这份文档
|
||||
|
||||
### 0.1 基准
|
||||
|
||||
| 项 | 值 | 来源 |
|
||||
|---|---|---|
|
||||
| 视口 | 1440 × 900,dpr = 1 | `styles/computed-styles.json` → `viewport` |
|
||||
| 截图 | `screenshots/01-empty-chat-1440x900.png`(空态)、`02-input-filled.png`(输入有内容)、`03-work-tab.png`(工作页签) | — |
|
||||
| DOM | `dom/page.rendered.html`(402 KB,未登录 + 空会话态) | — |
|
||||
| 主题 | `<html data-theme="light" data-chatapp-style="default" style="--header-height: 56px">` | 〔DOM〕 |
|
||||
|
||||
### 0.2 来源标注约定
|
||||
|
||||
| 标记 | 含义 | 例子 |
|
||||
|---|---|---|
|
||||
| 〔像素〕 | 我在这三张 PNG 上逐像素量出来的 | `x 360..1359` |
|
||||
| 〔DOM〕 | `page.rendered.html` 里的类名 / testid / 行内 style | `data-testid="chat_input"` |
|
||||
| 〔VAR〕 | CSS 变量(`dbx-light-vars.json` 或 `computed-styles.json` 的 `cssVars`) | `--dbx-line-10` |
|
||||
| 〔CSS〕 | 镜像里 58 个 CSS 文件的实际规则 | `.panel-fvxXfj{...}` |
|
||||
| 〔推算〕 | 类名/变量能推出来、但没有像素佐证 | 折叠动画 |
|
||||
| **需实测** | 镜像推算不出来,必须自己在浏览器里量 | 选中会话的 hover |
|
||||
|
||||
### 0.3 一处必须先说清的差异
|
||||
|
||||
仓库现有 `web/assets/app.css` 里写的是 `--content-w: 996px`,输入框「996 × 约 92」。
|
||||
**本镜像实测是 1000 × 100**,依据如下(两条独立证据):
|
||||
|
||||
* 〔像素〕输入框左右边框落在 `x=360` 与 `x=1359`(y=833 的直线段),宽度 = **1000**;
|
||||
上下边框 `y=784` 与 `y=883`,高度 = **100**。
|
||||
* 〔DOM〕`#chat-route-layout` 行内 style:`--content-max-width: 1000px`;
|
||||
输入区行内 style:`--input-guidance-input-container-min-height: 100px`。
|
||||
|
||||
主区宽 1160(1440−280),内容列 1000 居中 ⇒ 左右各留 80。**本文一律用 1000 / 100。**
|
||||
(用 996 视觉上差 4px 看不出来,但高度必须是 100,不是 92。)
|
||||
|
||||
---
|
||||
|
||||
## 1. 整体布局
|
||||
|
||||
### 1.1 骨架(实测坐标,1440×900)
|
||||
|
||||
```
|
||||
┌───────────────────────────────┬────────────────────────────────────────────────────────┐
|
||||
│ 0 279 │ 280 │
|
||||
│ 侧栏 280(含左右各 1px 描边) │ main 1160 × 900 │
|
||||
│ bg #f9f9f9 │ │
|
||||
│ │ ┌── header 56 ───────────────────────────────────────┐ │
|
||||
│ ├ 品牌行 y 11..47 │ │ [◧] 296,15 26×26 [下载豆包工作 1207,10 136×36] │ │
|
||||
│ ├ 新工作任务 y 55..86 │ │ [登录 1351,10 73×36] │ │
|
||||
│ ├ 新对话 y 89..120 │ └───────────────────────────────────────── y=55 处 1px ┘ │
|
||||
│ ├ 项目 y 123..154 │ │
|
||||
│ ├ API 服务 y 157..188 │ 问候语 28/600 盒子 328..373(居中 860) │
|
||||
│ ├ 更多 y 191..222 │ 分段控件 393..446(697..1022) │
|
||||
│ ├ 最近 标题 y 231..262 │ │
|
||||
│ │ │ ── 为你推荐 540..558 ── │
|
||||
│ │ (列表滚动区,空) │ chip 570..611 / 622..663 / 674..715 / 726..767 │
|
||||
│ │ │ │
|
||||
│ └ 分隔线 y=840 │ ┌── 输入框 360..1359 × 784..883(1000×100,圆角 24)─┐ │
|
||||
│ └ 关于豆包 y 848..874 │ └────────────────────────────────────────────────────┘ │
|
||||
│ │ ↘ 底部留白 16(884..900) │
|
||||
└───────────────────────────────┴────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 1.2 DOM 骨架(可以直接照抄结构)
|
||||
|
||||
```
|
||||
body
|
||||
└ #root
|
||||
└ #chat-route-layout ← 行内 style 挂着整套布局变量
|
||||
└ #chat-route-main (行内 --sidebar-width: 280px)
|
||||
├ div.container-hzjmF1[data-presentation=inline] ← 侧栏宽度容器(宽 280 → 折叠时 0)
|
||||
│ └ nav.panel-fvxXfj
|
||||
│ └ div#flow_chat_sidebar ← p-12 / bg-dbx-bg-base-web
|
||||
│ ├ 品牌行
|
||||
│ ├ 导航(新工作任务 / 新对话 / 项目 / API 服务 / 更多)
|
||||
│ ├ 滚动区(最近 + 会话列表)
|
||||
│ └ 底部关于豆包
|
||||
└ main.flex-1.min-w-0 ← 280..1440
|
||||
└ div.flex.flex-col
|
||||
├ header(h 56)
|
||||
└ #flow-chat-guidance-page.-mt-[var(--header-height)] px-24
|
||||
├ div.relative.flex.h-0.flex-grow ← 高 784 的「内容舞台」
|
||||
│ ├ 问候语 + 分段控件(position:absolute; top:308px; left:0; right:0)
|
||||
│ └ #experiment-guidance-suggestions(absolute; inset-x:0; bottom:0; max-h:313px)
|
||||
└ div[data-guidance-input-boundary](h 100)→ 输入框
|
||||
└ div.h-16(底部留白 16)
|
||||
```
|
||||
|
||||
〔DOM〕关键值:
|
||||
* `#flow-chat-guidance-page` = `-mt-[56px] px-24 flex-col items-center`
|
||||
⇒ 主区内容左右各 24px 内边距(1112 可用),再让 1000 的内容列居中。
|
||||
* `main` = `flex-1 min-w-0 flex items-stretch relative`,`background-color: var(--chat-bg-color)`,
|
||||
而 `--chat-bg-color: var(--dbx-bg-base-5)` = **#fff**(〔VAR〕)。
|
||||
|
||||
### 1.3 1440×900 关键矩形总表
|
||||
|
||||
| 区块 | x | y | 宽 | 高 | 依据 |
|
||||
|---|---|---|---|---|---|
|
||||
| 侧栏 | 0 | 0 | 280 | 900 | 〔像素〕bg #f9f9f9 覆盖 1..278,279 是 1px 描边 |
|
||||
| 主区 | 280 | 0 | 1160 | 900 | 〔像素〕x=280 起纯白 |
|
||||
| 顶部工具条 | 280 | 0 | 1160 | 56 | 〔DOM〕`h-[var(--header-height)]`=56;〔像素〕y=55 有 1px 分隔线 |
|
||||
| 工具条下边框 | 280 | 55 | 1160 | 1 | 〔像素〕(237,237,237) = rgba(0,0,0,.071) = `--dbx-line-7` |
|
||||
| 内容列(输入框/推荐同宽) | 360 | — | **1000** | — | 〔像素〕+〔DOM〕`--content-max-width:1000px` |
|
||||
| 空态内容舞台 | 304 | 0 | 1112 | 784 | 〔DOM〕`dom-tree.txt` 第 21 行 |
|
||||
| 编辑列(消息列,非空态) | — | — | 800 | — | 〔VAR〕`--chat-area-max-width: 800px` |
|
||||
| 输入框 | 360 | 784 | 1000 | 100 | 〔像素〕 |
|
||||
| 底部留白 | — | 884 | — | 16 | 〔DOM〕`data-testid="guidance_page_bottom_height"` `h-16` |
|
||||
|
||||
### 1.4 滚动区行为
|
||||
|
||||
| 区域 | 行为 | 依据 |
|
||||
|---|---|---|
|
||||
| 外层 `body/html` | 不滚(`overflow:hidden/overflow:clip`),整页固定 900 高 | 〔CSS〕`body,html{height:100%;margin:0;overflow:hidden;overflow:clip}` |
|
||||
| 侧栏列表 | `flex-1 min-h-0 overflow-x-hidden overflow-y-auto`,顶部先塞 8px 空块(`h-8`),右移 1px 并把滚动条用负 margin 顶到侧栏右缘 | 〔DOM〕 |
|
||||
| 侧栏滚动条 | `.flow-scrollbar-stable`:宽 7px、`scrollbar-gutter: stable`、**默认滑块全透明,鼠标悬停整块才显现**;滑块 `#ccc`,悬停 `#999`,圆角 `6px 8px 8px`,无轨道底 | 〔CSS〕〔VAR〕`--scrollbar-color:#ccc` / `--scrollbar-hover-color:#999` |
|
||||
| 主区内容 | 空态不滚(`h-0` + `overflow-hidden`);有消息时消息列 `--chat-area-max-width:800px` 自己滚 | 〔DOM〕 |
|
||||
| 推荐区 | `absolute inset-x-0 bottom-0` + `max-height:313px` + `overflow-y-auto overscroll-contain`(推荐超过 313px 自己滚,且滚到底不带动外层) | 〔DOM〕 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 侧栏(280px)
|
||||
|
||||
### 2.1 容器
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 宽 | 280(`--sidebar-width: 280px`) | 〔VAR〕〔像素〕 |
|
||||
| 背景 | `#f9f9f9` = `--dbx-bg-base-web` | 〔VAR〕 |
|
||||
| 内边距 | `10px 12px 12px`(上 10 / 左右 12 / 下 12);类 `p-12` + `pt-[10px]` | 〔DOM〕`style="--g-sidebar-wrapper-padding-top:10px"` |
|
||||
| 描边 | `border-right: 0.5px solid rgba(0,0,0,.064)`(类 `border-r border-[0.5px] border-s-color-border-tertiary/80`)。dpr=1 渲染成 1 物理像素 **#e9e9e9**;视口左/上/下边缘也有同色 1px | 〔DOM〕〔像素〕x=0/279/ y=0/899 都是 (233,233,233) |
|
||||
| 圆角 | 0 | 〔像素〕四角是直角 |
|
||||
| 折叠机制 | 外层 `.container-hzjmF1{width:0}` ↔ `[data-presentation=inline]{width:280px}`,`[data-dock-transition]{transition:width .2s}`;面板 `.panel-fvxXfj{transition:transform .2s, opacity .2s}`,收起态 `translateX(-110%) + opacity:0` | 〔CSS〕 |
|
||||
|
||||
> 侧栏右缘还有一个 **6px 宽的拖拽条**:`div[data-testid=chat_route_layout_left_sash] class="absolute top-0 -right-3 z-50 h-full w-6 cursor-col-resize"`〔DOM〕,
|
||||
> 想支持拖拽改宽就照这个放。
|
||||
|
||||
### 2.2 品牌区「豆包」
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 行盒 | `x 13..266`,`y 11..47`(高 36) | 〔像素〕〔DOM〕`div.mb-8.flex.items-center.justify-between.pr-4` rect `[13,11,254,36]` |
|
||||
| 「豆包」按钮 | `h-36 px-10 rounded-10`,`cursor-default` | 〔DOM〕`data-testid="workspace-switch-chip"` |
|
||||
| 文字 | **18px / 26px / 500**,颜色 `#000` | 〔DOM〕`text-18 leading-26 font-medium` |
|
||||
| 文字墨迹 | `x 23..58`(宽 36),`y 20..35` | 〔像素〕(23 = 13 + 10px 内边距) |
|
||||
| 右侧前进/后退 | 两个 `26×26`(图标 `18px`),间距 8,整块 60×36 靠右;本态都是 **disabled(opacity .3)** | 〔DOM〕〔像素〕箭头墨迹 `209..222` / `243..256`,y `28..29` |
|
||||
|
||||
### 2.3 导航项(5 个,逐项实测矩形)
|
||||
|
||||
行样式〔DOM〕:`group/sidebar_nav_item flex items-center px-8 rounded-dbx-lg h-32 !text-dbx-text-primary hover:bg-dbx-fill-trans-10-hover mb-2`
|
||||
|
||||
⇒ **行高 32、左右内边距 8、圆角 10(`--dbx-radius-lg` = .625rem)、行间距 2(mb-2)、hover 底色 `#0000000a`、文字与图标都是 `#000`**。
|
||||
|
||||
| 项 | 行盒(x 13..266) | 图标盒 | 图标墨迹 | 文字起点 | 文字 | 右侧附加 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 新工作任务 | y 55..86 | 21..43(18px 图标 + 2px 内边距) | 24..39 × 63..78 | x 51 | 14px/22px **500** `#000`,宽 70 | hover 才显示的 `Ctrl J` |
|
||||
| 新对话 | y 89..120 | 同上 | 24..39 × 97..112 | x 51 | 14px/22px 500,宽 42 | `Ctrl Shift K` |
|
||||
| 项目 | y 123..154 | 同上 | 24..39 × 132..145 | x 51 | 14px/22px 500,宽 26 | — |
|
||||
| API 服务 | y 157..188 | 同上 | 24..38 × 165..180 | x 51 | 14px/22px 500,宽 55 | 外链箭头 ↗ `12px`,墨迹 247..254 |
|
||||
| 更多 | y 191..222 | 同上 | 24..39 × 199..214 | x 51 | 14px/22px 500,宽 27 | chevron `>` `20px`(p-3),墨迹 246..252 |
|
||||
|
||||
* 图标:`<svg class="size-18 block !box-content p-2">` ⇒ 18×18 图标 + 2px 上下左右内边距 = 22×22 盒〔DOM〕。
|
||||
* 文字:`<div class="truncate ml-[8px] flex-1 min-w-0 s-font-small">`(`--s-font-small` = 400 14px/22px)+ 内层 `<span class="font-medium">` ⇒ **14/22/500**〔DOM〕〔VAR〕。
|
||||
51 = 21(行内边距 8)+ 22(图标盒)+ 8(ml-8)✓。
|
||||
* 快捷键小字〔DOM〕:`class="text-dbx-text-tertiary opacity-0 group-hover/sidebar_nav_item:opacity-100 ml-auto text-12"`
|
||||
⇒ **12px**、颜色 `rgba(0,0,0,.349)`、**默认 opacity 0,只有 hover 整行才出现**(截图里确实看不到)。
|
||||
* 右端附加图标颜色:↗ 用 `text-dbx-text-tertiary`(12px);`>` 用 `text-s-color-text-quaternary`(= rgba(0,0,0,.3))〔DOM〕。
|
||||
* **选中态**:这一层是「动作入口」不是「选中项」,所以没有选中态。会话列表项才有:
|
||||
`.item-AHZ7rH{height:32px;border-radius:18px;padding:0 10px}` + `:hover,[data-active=true]{background:rgba(0,0,0,.04)}`〔CSS〕
|
||||
⇒ 我们要的「当前会话」选中态就照这个:**32 高、圆角 18、左右 10、底 rgba(0,0,0,.04)**。
|
||||
|
||||
### 2.4 分区标题「最近」
|
||||
|
||||
〔DOM〕
|
||||
```html
|
||||
<section data-testid="conversation-section" class="rounded-dbx-lg transition-colors">
|
||||
<div class="group/section-header flex h-32 items-center rounded-dbx-lg px-10
|
||||
hover:bg-dbx-fill-trans-10-hover cursor-pointer" role="button">
|
||||
<span class="truncate text-12 leading-18 font-medium text-dbx-text-tertiary">最近</span>
|
||||
```
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 行盒 | `x 13..266`,`y 231..262`(高 32;上方有 8px 空块,223+8=231) | 〔DOM〕`h-8` + `h-32`〔像素〕文字 241..251 |
|
||||
| 内边距 | 左右 10 | 〔DOM〕`px-10` |
|
||||
| 文字 | **12px / 18px / 500**,`rgba(0,0,0,.349)`(`--dbx-text-tertiary`),墨迹 `x 23..46`、`y 241..251` | 〔DOM〕〔像素〕实测 (163,163,163) 叠在 #f9f9f9 上 = α .349 ✓ |
|
||||
| hover | 整行底 `#0000000a`;右侧「…」按钮默认 `opacity-0`,hover 才出现 | 〔DOM〕 |
|
||||
| 列表项 | 本镜像未登录 ⇒ 空(只有 `div.flex.flex-col.gap-0` 空容器) | 〔DOM〕 |
|
||||
|
||||
### 2.5 底部「关于豆包」
|
||||
|
||||
〔DOM〕
|
||||
```html
|
||||
<div class="shrink-0">
|
||||
<div class="mx-8 border-0 border-t-1 border-solid border-s-color-border-tertiary p-4 pb-0">
|
||||
<div class="flex items-center justify-between py-4">
|
||||
<div data-testid="not_login_about_us" class="button-JoHDM4"> <!-- flex;radius:12;padding:6px 8px -->
|
||||
<svg class="text-s-color-text-tertiary size-16 p-2">ⓘ</svg>
|
||||
<span class="button-text-Y5DJOk">关于豆包</span> <!-- --s-font-small + ml-4 -->
|
||||
</div>
|
||||
<span class="inline-flex p-7 text-tertiary"><svg class="size-18">⤓</svg></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 分隔线 | `y=840`,`x 21..258`,1px `rgba(0,0,0,.08)` | 〔像素〕〔DOM〕`border-t-1 border-s-color-border-tertiary` + `mx-8` |
|
||||
| 行 | `y ≈845..886`(`p-4` + `py-4`,按钮高 34),文字/图标中线 **865** | 〔DOM〕〔像素〕 |
|
||||
| ⓘ 图标 | 16px + 2px 内边距(盒 20),墨迹 `x 35..45`、`y 860..871` | 〔像素〕 |
|
||||
| 文字 | **14px / 22px / 400**,`rgba(0,0,0,.5)`(`--s-color-text-tertiary`),墨迹 `x 52..107`、`y 860..871`,左边距 4 | 〔像素〕实测 (124,124,124) = α .5 叠 #f9f9f9 ✓ |
|
||||
| 下载按钮 | `18px` 图标 + 7px 内边距 = 32×32,文字色 `rgba(0,0,0,.5)`,墨迹 `x 232..245`、`y 858..873` | 〔DOM〕〔像素〕 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 主区顶部工具条(56px)
|
||||
|
||||
〔DOM〕
|
||||
```html
|
||||
<div data-header-center-mode="flow"
|
||||
class="relative z-30 flex-row flex h-header-height w-full flex-none items-center
|
||||
bg-[var(--chat-bg-color)] border-b border-b-[var(--dbx-line-7)] px-16 gap-x-8">
|
||||
<div data-header-frame-region="left" class="... gap-8 pl-g-header-left-padding transition-[padding-left] duration-200">
|
||||
<button data-testid="siderbar_close_btn" aria-label="收起侧栏"
|
||||
class="p-[4px] rounded-dbx-sm text-(--dbx-text-primary) transition-colors duration-150 ease-out
|
||||
hover:bg-dbx-fill-trans-10-hover">◧ 18px</button>
|
||||
</div>
|
||||
<div data-header-frame-region="center" class="flex-1 justify-center"></div>
|
||||
<div data-header-frame-region="right" class="flex items-center justify-end gap-8">
|
||||
[下载豆包工作] [登录]
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
| 元素 | 矩形 | 样式 | 依据 |
|
||||
|---|---|---|---|
|
||||
| 工具条 | `280,0 1160×56`,bg `#fff`,`padding 0 16`,子项间距 8 | — | 〔DOM〕〔像素〕 |
|
||||
| 下边框 | `y=55`,1px `#ededed`(`--dbx-line-7` = `#00000012`) | — | 〔像素〕〔VAR〕 |
|
||||
| 折叠按钮 | `296,15 26×26`(图标 18×18,按钮内边距 4,圆角 6) | 图标 `#000`;hover 底 `#0000000a`;`transition-colors 150ms ease-out` | 〔像素〕图标墨迹 `301..316 × 20..34`〔DOM〕 |
|
||||
| 右区容器 | `1207,10 217×36` | `display:flex; gap:8; justify-end` | 〔DOM〕`dom-tree.txt` |
|
||||
| 「下载豆包工作」 | `1207,10 136×36` | 圆角 **12**、边框 **1px #06f**、文字 **#06f**、`20×20` 图标 + 文字、hover 底 `#0000000a`。文字按类名 `text-s-font-base-strong`(500/16),实测墨迹仅 75px/6 字 ⇒ 视觉 13–14px | 〔像素〕〔DOM〕〔CSS〕`.enhanceBtn-W9xBoi` |
|
||||
| 「登录」 | `1351,10 73×36` | 圆角 **12**、底 **#232629**、字 **#fff** 14/22/500、内边距 `10px 12px` | 〔像素〕〔DOM〕`login-btn-header-CTKsn1` |
|
||||
| 右区在「工作」页签 | 「下载豆包工作」**消失**,只剩登录按钮 | — | 〔像素〕03 图 |
|
||||
|
||||
> 我们没有「登录」和「下载电脑版」这两件事,右区留给**我们自己的东西**(见 §12)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 主区空态
|
||||
|
||||
### 4.1 垂直节奏(实测)
|
||||
|
||||
| 元素 | 盒子 | 说明 |
|
||||
|---|---|---|
|
||||
| 空态舞台 | `y 0..784`(高 784) | 绝对定位的父容器 |
|
||||
| 问候语块 | `position:absolute; top:308px; left:0; right:0` | 〔DOM〕行内 style |
|
||||
| ↳ 问候语 | `y 328..373`(`min-height:45px` = `--greeting-height`),`margin-top:20` | 308+20 |
|
||||
| ↳ 分段控件 | `y 393..446`,高 54,`margin-top:20` | 373+20 |
|
||||
| 推荐区 | 底对齐 `y=784`,`max-height:313px`,`pb-16` | 内容底 768 |
|
||||
| ↳ 「为你推荐」 | 行盒 `540..558`(高 18),`mb-12` | 558+12=570 |
|
||||
| ↳ chip 1..4 | `570..611` / `622..663` / `674..715` / `726..767`(各 42 高,间距 10) | 767+16=783 ≈ 784 ✓ |
|
||||
| 输入框 | `y 784..884`(100 高) | 紧贴舞台底 |
|
||||
|
||||
> **怎么复现 308**:1440×900 下问候语块顶恰在 308。实现建议 `top:34vh`(900×0.342=308),
|
||||
> 或者「在 `[56, 784]` 里垂直居中后再上移 52px」。别用死值,窗口一改就歪。
|
||||
|
||||
### 4.2 问候语
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 文案 | 「有什么我能帮你的吗?」 | 〔像素〕 |
|
||||
| 字号/字重/行高 | **28px / 600 / 42px** | 〔DOM〕`text-28 font-semibold` +〔metrics〕lh 42px |
|
||||
| 盒 | `x 714..1005`(宽 292 = 280 文本 + `pl-12`),`y 328..373` | 〔像素〕〔DOM〕`mx-auto ... pl-12 min-h-[45px]` |
|
||||
| 居中锚点 | 文本中心 = **860**(= 280 + 1160/2) | 〔像素〕墨迹 727..990 |
|
||||
| 颜色 | `#000`(`--dbx-text-primary`) | 〔像素〕 |
|
||||
| 其他 | `cursor-default`;`mb-28 !mb-0`、`mt-20`;隐藏滑入遮罩 `greeting-text-Q0pGud:before/after`(切换文案时 0.2s linear 擦除) | 〔DOM〕〔CSS〕 |
|
||||
|
||||
### 4.3 「对话 | 工作」分段控件
|
||||
|
||||
〔DOM〕
|
||||
```html
|
||||
<div data-testid="conversation-mode-switch"
|
||||
class="relative flex h-54 items-center justify-center rounded-full p-[3px]
|
||||
bg-dbx-fill-trans-20 mt-20">
|
||||
<div aria-hidden="true" class="absolute left-[3px] top-[3px] h-[48px] rounded-full
|
||||
shadow-dbx-sm transition-transform duration-[150ms] ease-in-out
|
||||
bg-dbx-bg-body-overlay-web" style="width:160px; transform:translateX(0px)"></div>
|
||||
<button data-active="true" class="relative flex h-full items-center justify-center w-160 gap-6
|
||||
text-16 leading-18 transition-colors font-medium text-dbx-text-primary">对话</button>
|
||||
<button class="... w-160 gap-6 text-16 leading-18 transition-colors
|
||||
text-dbx-text-secondary hover:text-dbx-text-primary">工作</button>
|
||||
</div>
|
||||
```
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 轨道 | `x 697..1022`(**326** 宽 = 3+160+160+3),`y 393..446`(**54** 高),圆角 **27(全圆)** | 〔像素〕〔DOM〕 |
|
||||
| 轨道底色 | **#f5f5f5**(= `--dbx-fill-trans-20` `#0000000a` 叠白) | 〔像素〕(245,245,245)〔VAR〕 |
|
||||
| 滑块 | **160 × 48**,`left:3 / top:3`,圆角 **24**,底色 **#fff**,阴影 `--dbx-drop-shadow-sm` = `0 2px 4px #00000005, 0 4px 10px #00000005` | 〔像素〕滑块 701..860 / 396..443〔DOM〕 |
|
||||
| 滑块动效 | `transition-transform 150ms ease-in-out`,切页签 `translateX(0 | 160px)` | 〔DOM〕 |
|
||||
| 段按钮 | 各 `160` 宽、`h-full`、`gap-6` | 〔DOM〕 |
|
||||
| 文字 | **16px / 18px**;选中 `500` + `#000`;未选中 `400` + `#00000080`(叠在 #f5f5f5 上 = **#7a7a7a**),hover 变 `#000` | 〔DOM〕〔像素〕实测 (122,122,122) ✓ |
|
||||
| 文字位置 | 「对话」墨迹 766..791(中心 778.5);「工作」墨迹 931..950(中心 940) | 〔像素〕 |
|
||||
|
||||
> ⚠️ 抓取异常:`03-work-tab.png` 虽然内容上已是「工作」页(推荐区消失、「下载豆包工作」消失),
|
||||
> 但滑块仍停在「对话」(实测两张图的滑块都在 701..860)。**实现时以 `data-active` 为准移动 160px。**
|
||||
|
||||
### 4.4 「为你推荐」
|
||||
|
||||
〔DOM〕
|
||||
```html
|
||||
<section class="mx-auto w-full max-w-(--content-max-width) pb-16">
|
||||
<h2 class="mb-12 w-full pl-4 text-12 leading-18 text-dbx-text-tertiary">为你推荐</h2>
|
||||
<div class="flex flex-col items-start w-full gap-10">
|
||||
<button class="flex max-w-full items-center gap-4 px-12 py-8 text-14 leading-22
|
||||
text-dbx-text-primary min-h-42 rounded-[var(--dbx-radius-xl,12px)] border
|
||||
border-dbx-line-7 bg-transparent transition-colors duration-150
|
||||
hover:bg-dbx-fill-trans-10-hover w-fit">
|
||||
<span class="line-clamp-2 min-w-0 flex-1 overflow-hidden leading-22 break-words">…</span>
|
||||
</button>
|
||||
```
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 区域宽 | 1000(与输入框同宽同左边界 **x=360**) | 〔像素〕〔DOM〕`max-w-(--content-max-width)` |
|
||||
| 标题 | **12px / 18px / 400**,`rgba(0,0,0,.349)`,`padding-left:4`(墨迹从 364 起),下间距 **12** | 〔像素〕〔DOM〕 |
|
||||
| 标题对齐 | **左对齐**(不是居中) | 〔像素〕 |
|
||||
| chip 盒 | 高 **42**(`min-h-42`),圆角 **12**,边框 **1px #00000012**(渲染成 #ededed),内边距 `12px / 8px`,`gap-4` | 〔像素〕〔DOM〕 |
|
||||
| chip 文字 | **14px / 22px / 400**,`#000`,最多 2 行(`line-clamp-2`) | 〔DOM〕 |
|
||||
| chip 宽 | `w-fit` = 14×字数 + 24 + 2;实测:24 字 → 334,11 字 → 180,14 字 → 222 | 〔像素〕 |
|
||||
| chip 间距 | **10**(`gap-10`,垂直方向同一个 flex-col 的 gap) | 〔像素〕612..621 = 10 |
|
||||
| hover | 底色 `#0000000a`,`transition-colors 150ms` | 〔DOM〕 |
|
||||
| 出现/消失 | `.sug-input-visibility-motion{transition:opacity .1s ease-out,visibility 0s linear}` | 〔CSS〕 |
|
||||
| 「工作」页签 | 整块推荐区消失 | 〔像素〕03 图 |
|
||||
|
||||
> 文案别抄(镜像里是新闻/汇率类的示例问法),我们换成自己能力能回答的示例。
|
||||
|
||||
---
|
||||
|
||||
## 5. 输入框组件(最复杂的部分)
|
||||
|
||||
### 5.1 结构树(照这个搭就不会错)
|
||||
|
||||
```
|
||||
div[data-guidance-input-boundary] ← 固定 h:100,贴底
|
||||
└ div.absolute.inset-x-0.bottom-0.flex.flex-col.items-center
|
||||
└ div.relative.isolate.flex.flex-col-reverse.w-full
|
||||
max-w-(--content-max-width) ← 1000 宽
|
||||
├ #input-engine-container.rounded-dbx-4xl ← 圆角 24 + 1px 描边 + 阴影都在这一层
|
||||
│ ├ .guidance-input-surface(border/背景继承)
|
||||
│ └ .guidance-input-content.flex.flex-col-reverse.gap-14.p-10
|
||||
│ ├ .guidance-input-actions.flex.justify-between.gap-6.h-36 ← DOM 里在前 = 视觉在下
|
||||
│ │ ├ 左组(flex-1 min-w-0 overflow-hidden):
|
||||
│ │ │ [+ 36×36] [1×16 竖线] [对话 › h32] | [PPT 生成][图像生成]…[更多]
|
||||
│ │ └ 右组:
|
||||
│ │ [豆包 快速 › h32] [麦克风 36×36 / 发送 36×36]
|
||||
│ └ .guidance-input-editor-wrapper(px-10 pt-6) ← DOM 里在后 = 视觉在上
|
||||
│ └ [contenteditable] 16px/24 的富文本(空时显示 placeholder)
|
||||
└ div[data-testid=guidance_page_bottom_height].h-16 ← 下方留白 16
|
||||
```
|
||||
|
||||
> 注意:内容层用的是 **`flex-direction:column-reverse`**,所以 DOM 顺序是「按钮排在前、编辑区在后」,
|
||||
> 视觉上却是编辑区在上。**若我们用自己的普通 `flex-col`,就按视觉顺序(编辑区先、按钮排后)写即可**,
|
||||
> 别照抄 `column-reverse` 再把顺序写反。
|
||||
|
||||
### 5.2 外层容器(实测)
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 尺寸 | **1000 × 100**,`x 360..1359`,`y 784..883` | 〔像素〕〔DOM〕`min-height:100px` |
|
||||
| 圆角 | **24**(`rounded-dbx-4xl` = `--dbx-radius-4xl` = 1.5rem) | 〔DOM〕〔VAR〕 |
|
||||
| 底色 | `#fff`(`--s-color-bg-float`) | 〔VAR〕 |
|
||||
| 边框 | **1px `#0000001a`**,用伪元素铺:`after:absolute after:inset-0 after:border-1 after:border-dbx-line-10`(实测渲染 (229,229,229)) | 〔DOM〕〔像素〕 |
|
||||
| 阴影 | `--dbx-drop-shadow-lg` = `0 2px 4px #00000005, 0 4px 16px #0000000a, 0 8px 32px #00000014`(实测阴影从 x≈340 起、向下渗到 900 之外) | 〔DOM〕〔像素〕 |
|
||||
| 内边距 | 内容层 `p-10`(10px),编辑区再 `px-10 pt-6` | 〔DOM〕 |
|
||||
| 内容间距 | `flex-col-reverse` + `gap-14` ⇒ 编辑区在上、按钮排在下,中间 14 | 〔DOM〕 |
|
||||
|
||||
**聚焦态(02 图实测,重点)**
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 边框 | `rgba(0,102,255,.30)` → 叠白实测 **(178,209,255)**;类 `focus-within:after:border-dbx-fill-highlight-disable`(`--dbx-fill-highlight-disable` = `#0066ff4d`) |
|
||||
| 阴影 | 换成蓝色光晕:`--active-shadow: 0 2px 4px rgba(116,158,243,.02), 0 4px 12px rgba(102,188,253,.04), 0 8px 24px rgba(95,178,255,.17)`(实测阴影偏蓝 (228,243,255)→…) |
|
||||
| 注意 | **没有 3px ring,也没有加粗边框**——只是细边框变蓝 + 蓝光晕。我们现在 `.composer.focus` 用的是 `0 0 0 3px` ring,要改 |
|
||||
|
||||
**内部垂直分割(实测)**:容器 784..884 → 内框 785..883 → 内容 795..873(`p-10`)→ 按钮排 **837..872(36 高)** → 编辑区约 **801..825**(16px/24px 行盒)。
|
||||
|
||||
### 5.3 编辑区 / placeholder
|
||||
|
||||
| 项 | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| 文本 | **16px / 24px**,颜色 **`#000`**(实测;token 层 `--input-guidance-input-editor-color` 给的是 `rgba(0,0,0,.85)`,实测墨迹为纯黑,按 `#000` 写) | 〔VAR〕〔像素〕02 图文字 (0,0,0) |
|
||||
| placeholder | 「发消息...」,token 是 `rgba(0,0,0,.3)`(`--s-color-text-quaternary`);实测两张图墨迹 **#a6a6a6 / #b7b7b7**(抗锯齿差异),建议取 `rgba(0,0,0,.32)` | 〔VAR〕〔像素〕 |
|
||||
| 光标色 | `#0057ff`(`--input-guidance-input-caret-color` = `--s-color-accents-blue`) | 〔VAR〕 |
|
||||
| 高度 | 文本行盒最小 24(`min-height:24px`);**整个输入框最大 360px**,超出后编辑区内部滚动 | 〔VAR〕 |
|
||||
| 文本左边界 | `x 381`(360 + 1 边框 + 10 内容 + 10 编辑内边距),墨迹 380 起 | 〔像素〕〔DOM〕`px-10` |
|
||||
| 占位符基线 | 墨迹 `y 806..826` | 〔像素〕 |
|
||||
|
||||
### 5.4 底排按钮(从左到右,全部实测)
|
||||
|
||||
底排:`x 371..1348`(= 360+1+10 到 1359−1−10),`y 837..872`,**高 36**,`justify-between`,组间距 6。
|
||||
|
||||
| # | 元素 | 盒子(实测) | 样式 | 依据 |
|
||||
|---|---|---|---|---|
|
||||
| 1 | + 上传 | 36×36 圆形,`x 371..406`;图标 18px,墨迹 `381..394` | 透明底、`rounded-full`、`p-9`;hover 底 `#0000000a`;图标 `#000` | 〔像素〕〔DOM〕`upload_file_button` |
|
||||
| 2 | 竖分隔线 | `x=414`,`1 × 16`(实测 (229,229,229)) | `mx-8 h-16 w-1 bg-dbx-line-10` | 〔像素〕〔DOM〕 |
|
||||
| 3 | 模式按钮「对话 ›」 | `h 32`,圆角 **12**,`padding-left:8 / right:4`;16px 图标 + 文字 + 12px 箭头 | 文字 **14/22 #000**,箭头 12px `>` `rgba(0,0,0,.2)`(`--dbx-text-disable`),hover 底 `#0000000a` | 〔像素〕〔DOM〕`chat_input_action_mode` |
|
||||
| 4 | 技能按钮 ×7 | 每个 `h 32`、圆角 **12**、`px-8`、`gap-4`;**16×16 PNG 图标** + 文字 | 文字 **14/22 #000**;hover 底 `#0000000a`;相邻按钮间距 4(外层 `gap-4`) | 〔像素〕〔DOM〕`skill_bar_button_*` |
|
||||
| — | 按钮清单与实测墨迹 x | PPT 生成 `512..587`;图像生成 `609..683`;帮我写作 `705..779`;视频生成 `801..875`;录音转写 `896..971`;音乐生成 `993..1067`;更多 `1089..1135` | 节距约 **96**(= 8+16+4+56+8+4) | 〔像素〕 |
|
||||
| 5 | 「豆包 快速 ›」 | `h 32`、圆角 12、`py-7 pl-8 pr-4`;文字墨迹 `x 1232..1291`,箭头 12px `x≈1296..1308` | 文字 **14/22 #000**,箭头 `rgba(0,0,0,.2)` | 〔像素〕〔DOM〕`chat_input_action_model` |
|
||||
| 6 | 麦克风(空态) | **36×36 正圆**,`x 1313..1349`,`y 838..873`;图标 18px(墨迹 14px 宽) | 底色 **#f5f5f5**(`--dbx-fill-trans-20` = `#0000000a` 叠白,**不是紫色**),图标 **#000**;hover `--dbx-fill-trans-20-hover`(`#00000012`) | 〔像素〕(245,245,245)〔DOM〕`asr_btn` |
|
||||
| 6' | 发送(有内容) | **36×36 正圆**,同位置 `x 1313..1349`,`y 838..873` | 底色 **#0066ff**(实测纯 (0,102,255)),白色向上箭头 18px;**麦克风被它替换** | 〔像素〕02 图 |
|
||||
|
||||
> **紫色麦克风是个误会**:仓库现有 `web/assets/app.css` 的 `.mic-btn` 用了 `--violet-weak`/`--violet`,
|
||||
> 但本镜像实测是 `#f5f5f5` 底 + 黑色麦克风(`bg-dbx-fill-trans-20`)。
|
||||
> 想要「豆包那种淡淡的按钮」,就用 `rgba(0,0,0,.04)`;紫色只在豆包的彩色强调(如 AI 光效)里出现。
|
||||
|
||||
### 5.5 三种状态对照
|
||||
|
||||
| 状态 | 边框 | 阴影 | 右下按钮 | 推荐区 |
|
||||
|---|---|---|---|---|
|
||||
| 空 / 未聚焦(01) | 1px `#0000001a` | 灰 `drop-shadow-lg` | 麦克风(#f5f5f5) | 显示 |
|
||||
| 聚焦 / 有内容(02) | 1px `rgba(0,102,255,.3)` | 蓝光晕 `--active-shadow` | **发送**(#06f 圆) | 消失 |
|
||||
| 工作页签(03) | 同 01 | 同 01 | 麦克风 | 消失 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 设计 token 表
|
||||
|
||||
### 6.1 颜色:豆包变量 → 我们的变量(亮 / 暗)
|
||||
|
||||
暗色值来自 `computed-styles.json → cssVars` 里的 `亮 | 暗` 对(这是豆包自己的暗色主题值,可信)。
|
||||
|
||||
| 豆包变量 | 建议我们的变量 | 亮色 | 暗色 | 用途 |
|
||||
|---|---|---|---|---|
|
||||
| `--dbx-text-primary` | `--text-primary` | `#000` | `#ffffffd9` | 正文、导航文字、按钮文字 |
|
||||
| `--dbx-text-secondary` | `--text-secondary` | `#00000080` | `#ffffff80` | 次要文字、未选中页签 |
|
||||
| `--dbx-text-tertiary` | `--text-tertiary` | `#00000059` | `#ffffff59` | 「最近」「为你推荐」、快捷键 |
|
||||
| `--dbx-text-disable` | `--text-disable` | `#0003` | `#fff3` | 禁用、下拉小箭头 |
|
||||
| `--dbx-text-markdown` | `--text-markdown` | `#000000f2` | `#ffffffd9` | 消息正文 |
|
||||
| `--dbx-bg-body-web` | `--bg-body` | `#fff` | `#000` | 主区底色 |
|
||||
| `--dbx-bg-base-web` | `--bg-sidebar` | `#f9f9f9` | `#0f0f0f` | 侧栏底色 |
|
||||
| `--dbx-bg-base-2` | `--bg-base-2` | `#f4f4f4` | `#1a1a1a` | 次级底(气泡、卡片) |
|
||||
| `--dbx-bg-float` | `--bg-float` | `#fff` | `#181818` | 浮层、输入框底 |
|
||||
| `--dbx-bg-base-5` | `--bg-base-5` | `#fff` | `#000` | `--chat-bg-color` |
|
||||
| `--dbx-fill-trans-10` | `--fill-1` | `#00000005` | `#ffffff0a` | 极淡填充 |
|
||||
| `--dbx-fill-trans-10-hover` | `--bg-hover` | `#0000000a` | `#ffffff14` | **所有 hover 底** |
|
||||
| `--dbx-fill-trans-20` | `--fill-2` | `#0000000a` | `#ffffff1a` | 分段控件轨道、麦克风底 |
|
||||
| `--dbx-fill-trans-20-hover` | `--bg-active` | `#00000012` | `#ffffff1f` | 麦克风 hover |
|
||||
| `--dbx-fill-trans-30` | `--fill-3` | `#0000000f` | `#ffffff1a` | 较重填充 |
|
||||
| `--dbx-line-7` | `--line-1` | `#00000012` | `#ffffff1a` | 顶栏下边框、chip 边框 |
|
||||
| `--dbx-line-10` | `--line-2` | `#0000001a` | `#ffffff1a` | **输入框边框**、竖分隔线 |
|
||||
| `--dbx-line-15` | `--line-3` | `#00000026` | `#ffffff26` | 强调描边 |
|
||||
| `--dbx-fill-primary-50` / `--dbx-brand-default` | `--brand` | **#06f** | `#0a84ff` | 发送按钮、主按钮 |
|
||||
| `--dbx-fill-highlight-hover` | `--brand-hover` | `#4d8eff` | `#006ce0` | 主按钮 hover |
|
||||
| `--dbx-fill-highlight-disable` | `--brand-ring` | `#0066ff4d` | `#378dff66` | **聚焦边框(30%)** |
|
||||
| `--dbx-color-blue-100` | `--brand-weak` | `#ebf2ff` | `#002658` | 选中底色 |
|
||||
| `--s-color-accents-blue` | `--caret` | `#0057ff` | `#547cff` | 输入光标、semi 系主色 |
|
||||
| `--dbx-fill-chat-bubble-bg` | `--bubble-user` | `#f4f4f4` | `#181818` | 用户气泡 |
|
||||
| `--dbx-fill-chat-bubble-bg2` | `--bubble-alt` | `#e6f0ff` | `#153453` | 蓝调气泡 |
|
||||
| `--dbx-function-danger` | `--danger` | `#ff3b30` | `#ff3b30` | 错误/删除 |
|
||||
| `--dbx-function-danger-hover` | `--danger-hover` | `#f96961` | `#f96961` | — |
|
||||
| `--dbx-function-success` | `--success` | `#34c759` | `#34c759` | 成功 |
|
||||
| `--dbx-function-warning` | `--warning` | `#ff9500` | `#ff9500` | 警告 |
|
||||
| `--dbx-function-info` | `--info` | `#0065fd` | `#378dff` | 信息 |
|
||||
| `--dbx-bg-mask` | `--bg-mask` | `#0003` | `#0009` | 遮罩 |
|
||||
| `--dbx-neutral-700` | `--neutral-700` | `#4c4c4c` | `#b2b2b2` | 中性文字 |
|
||||
| `--s-color-border-secondary` | `--border-input` | `rgba(0,0,0,.12)` | `rgba(255,255,255,.16)` | 输入框常态边框(token 层) |
|
||||
| `--s-color-border-tertiary` | `--border-soft` | `rgba(0,0,0,.08)` | `rgba(255,255,255,.12)` | 侧栏描边、分隔线 |
|
||||
|
||||
补充色阶(需要时直接取):
|
||||
* 灰阶 `--dbx-neutral-00..1000`:`#fff / #efefef / #e3e3e3 / #cacaca / #b0b0b0 / #979797 / #7e7e7e / #656565 / #4c4c4c / #323232 / #191919 / #000`(暗色为反向)。
|
||||
* 蓝 `--dbx-color-blue-100..800`:`#ebf2ff #dce8ff #b8d2ff #84b1ff #4d8eff #0065fd #004cc3 #00348c #002d7c`。
|
||||
* 紫(豆包只用于装饰/AI 光效)`--dbx-color-purple-500 #af56de`、`--s-color-accents-purple #9952e1`(暗 `#9246e0`)。
|
||||
* AI 渐变(要「豆包味」的强调面才用):`--s-color-ai-button: radial-gradient(105.79% 117.52% at 9.98% 22.03%, #0057ff 0%, #4298fd 50%)`。
|
||||
|
||||
### 6.2 字号阶梯(`--s-font-*`,直接搬)
|
||||
|
||||
| Token | 值 | 用在哪 |
|
||||
|---|---|---|
|
||||
| `h1` | 600 26/36 | 大标题 |
|
||||
| `h2` | 700 20/32 | 卡片主标题 |
|
||||
| `h3` / `h4` | 600 16/24 | 区块标题 |
|
||||
| `large` / `large-em` | 400·500 20/28 | 强调正文 |
|
||||
| `base` / `base-strong` / `base-em` | 400·500·600 16/24 | 正文、编辑器 |
|
||||
| `small` / `small-strong` / `small-em` | 400·500·600 14/22 | **导航项、chip、按钮文字** |
|
||||
| `pcbody` | 400 13/20 | 桌面端紧凑正文 |
|
||||
| `xs` | 400 12/18 | **分组标题「最近」「为你推荐」、快捷键** |
|
||||
| `xxs` | 400·500 11/16 | 角标 |
|
||||
| `xxxs-em` / `xxxxs` | 600 10/14、400 9/12 | 极限小字 |
|
||||
| 特例 | **28/42 600** | 空态问候语(`text-28`,不在阶梯里) |
|
||||
| 特例 | 16/18 | 分段控件文字 |
|
||||
|
||||
### 6.3 圆角阶梯
|
||||
|
||||
| Token | 值 | 用在哪 |
|
||||
|---|---|---|
|
||||
| `--dbx-radius-xs` / `--s-radius-xxs` | 4px | 小标签 |
|
||||
| `--dbx-radius-sm` | 6px | 顶栏图标按钮(`rounded-dbx-sm`) |
|
||||
| `--dbx-radius-md` / `--s-radius-xxss` | 8px | 菜单项 |
|
||||
| `--dbx-radius-lg` / `--s-radius-xs` | **10px** | **侧栏导航行、分区标题** |
|
||||
| `--dbx-radius-xl` / `--s-radius-s` | **12px** | **chip、输入条按钮、登录/下载按钮** |
|
||||
| `--dbx-radius-2xl` / `--s-radius-m` | 16px | 卡片、下拉面板 |
|
||||
| `--dbx-radius-3xl` / `--s-radius-l` | 20px | 大卡片 |
|
||||
| `--dbx-radius-4xl` / `--s-radius-xl` | **24px** | **输入框** |
|
||||
| `--s-radius-xxl` / `xxxl` | 32 / 36 | 大浮层 |
|
||||
| `rounded-full` | 9999px | 分段控件、麦克风、发送、+ |
|
||||
|
||||
### 6.4 阴影阶梯
|
||||
|
||||
| Token | 值 | 用在哪 |
|
||||
|---|---|---|
|
||||
| `--dbx-drop-shadow-xs` | `0 0 4px #00000014` | 轻浮起 |
|
||||
| `--dbx-drop-shadow-sm` | `0 2px 4px #00000005, 0 4px 10px #00000005` | **分段控件滑块**、下拉面板 |
|
||||
| `--dbx-drop-shadow-md` | `0 2px 4px #00000005, 0 4px 10px #00000008, 0 4px 16px #00000008` | 浮层 |
|
||||
| `--dbx-drop-shadow-lg` | `0 2px 4px #00000005, 0 4px 16px #0000000a, 0 8px 32px #00000014` | **输入框** |
|
||||
| `--s-shadow-lv1` | `0 1px 2px rgba(0,0,0,.05), 0 0 1px rgba(0,0,0,.15)` | 卡片 |
|
||||
| `--s-shadow-lv2` | `0 6px 10px rgba(0,0,0,.08), 0 0 1px rgba(0,0,0,.15)` | 拖拽态 |
|
||||
| `--s-shadow-lv3` | `0 10px 20px rgba(0,0,0,.1), 0 0 1px rgba(0,0,0,.15)` | 弹层 |
|
||||
| `--s-shadow-lv4` / `lv5` | `0 25px 80px rgba(0,0,0,.1)` / `0 30px 100px rgba(0,0,0,.15)` | 大浮层/引导 |
|
||||
| `--s-shadow-level1..5` | `0 0 4px rgba(0,0,0,.02), 0 {6,10,24,36,20}px {10,24,40,50,64}px rgba(47,53,64,{.1,.2,.16,.16,.36})` | 卡片/弹层另一套(带冷灰) |
|
||||
| 聚焦光晕 | `0 2px 4px rgba(116,158,243,.02), 0 4px 12px rgba(102,188,253,.04), 0 8px 24px rgba(95,178,255,.17)` | **输入框聚焦** |
|
||||
|
||||
### 6.5 间距阶梯(实际用到的值)
|
||||
|
||||
`2 · 4 · 6 · 8 · 10 · 12 · 14 · 16 · 20 · 24 · 28 · 32 · 36 · 42 · 54 · 96`
|
||||
|
||||
| 值 | 出处 |
|
||||
|---|---|
|
||||
| 2 | 导航行间距(`mb-2`)、分段控件内 gap(`gap-6`=6 是另一处) |
|
||||
| 4 | 按钮内 gap(图标↔文字)、`pl-4`、`p-4` |
|
||||
| 6 | 分段控件段内 gap、底排组间距、tab 文字 gap |
|
||||
| 8 | 行内边距(`px-8`)、子项间距(`gap-8`)、chip 上下内边距(`py-8`) |
|
||||
| 10 | 内容内边距(`p-10`)、分区标题左右(`px-10`)、输入框内容 padding |
|
||||
| 12 | 侧栏左右内边距、chip 左右内边距(`px-12`)、h2 下间距(`mb-12`) |
|
||||
| 14 | 输入框内编辑区↔按钮排(`gap-14`) |
|
||||
| 16 | 顶栏左右(`px-16`)、底部留白(`h-16`)、chip 下间距(`pb-16`) |
|
||||
| 20 | 问候语上下间距(`mt-20`)、分段控件上间距 |
|
||||
| 24 | 主区内容左右(`px-24`) |
|
||||
| 28 | 问候语下间距(`mb-28`,本态被 `!mb-0` 覆盖) |
|
||||
| 42 | chip 最小高(`min-h-42`) |
|
||||
| 54 | 分段控件高(`h-54`) |
|
||||
|
||||
---
|
||||
|
||||
## 7. 字体
|
||||
|
||||
### 7.1 豆包用的是什么
|
||||
|
||||
〔VAR〕`--s-font-family`:
|
||||
```
|
||||
var(--dbx-font-sans-serif,
|
||||
var(--font-sans, "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue',
|
||||
Helvetica, 'Noto Sans', 'Apple Color Emoji', 'Segoe UI Emoji',
|
||||
'Noto Color Emoji', sans-serif"))
|
||||
```
|
||||
〔metrics〕`bodyFont`:`ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"`
|
||||
|
||||
**也就是说:界面正文没有自定义中文字体,全是系统字体栈。**(`--s-font-*` 全部继承 `--s-font-family`。)
|
||||
|
||||
`fonts.json` 里那些 @font-face 都是「局部用途」,不是界面主字体:
|
||||
|
||||
| 字体 | 用途 | 我们要不要 |
|
||||
|---|---|---|
|
||||
| `LarkChineseQuote` | **只用 6 个弯引号**(`U+2018-201E`),src 是 `local("PingFangSC-*")` —— 本地字体别名,不下载 | ❌ 不需要(系统字体自带引号) |
|
||||
| `LarkEmojiFont` | 4 个 emoji(`U+1F21A` 等)走本地 Apple/Noto Emoji | ❌ |
|
||||
| `LarkHackSafariFont` | Safari 补丁(`unicode-range: U+0`,即永不匹配) | ❌ |
|
||||
| `Montserrat SemiBold` | 数字/英文强调(woff2 外链) | ❌ 用系统 |
|
||||
| `JetBrains Mono` | 代码块 | ⭕ 可选,建议 `ui-monospace` 回退 |
|
||||
| `KaTeX_*` | 数学公式(21 个字体文件) | ❌ 不引;要公式再说 |
|
||||
|
||||
### 7.2 建议我们的字体栈(无字体文件)
|
||||
|
||||
```css
|
||||
--font-sans: system-ui, -apple-system, "Segoe UI", Roboto, "PingFang SC",
|
||||
"Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", sans-serif,
|
||||
"Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji";
|
||||
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
|
||||
"Liberation Mono", "Courier New", monospace;
|
||||
```
|
||||
跟仓库现有 `web/assets/app.css` 的 `--font-sans` 一致,**不用改**;只需注意豆包的字重习惯:
|
||||
正文 400、导航/标题 500、问候语与大标题 600、h2 700。中文在 Windows 上 500 会伪粗,必要时用 600 替代。
|
||||
|
||||
---
|
||||
|
||||
## 8. 图标清单(19 个内联 SVG + 输入条 8 个 PNG)
|
||||
|
||||
> **法律边界:这些 SVG 是豆包的图标资源,只作为「形状参考」。我们要用 Material Icons 或自己手绘等效形状,不复用 path 数据。**
|
||||
> 尺寸规律:`24×24 viewBox`,通过 `size-12 / 14 / 16 / 18 / 20` + `p-2/p-3` 控制在界面里的成品尺寸。
|
||||
|
||||
| 文件 | 用途(在 DOM 里的位置) | 形状描述(我们可以照着画) | 显示尺寸 | 颜色 |
|
||||
|---|---|---|---|---|
|
||||
| `svg-01` | 侧栏品牌行「后退」`sidebar-navigation-back` | 左箭头:横杠 + 左尖角,圆头 | 18 | 继承,disabled 时 opacity .3 |
|
||||
| `svg-02` | 「前进」`sidebar-navigation-forward` | 右箭头(镜像) | 18 | 同上 |
|
||||
| `svg-03` | 「新工作任务」`create_office_task_button` | **圆角方框 + 右上角斜插一支笔**("编辑文档") | 18(+2 内边距) | `#000` |
|
||||
| `svg-04` | 「新对话」`create_conversation_button` | **圆形对话气泡,尾巴在左下** | 18 | `#000` |
|
||||
| `svg-05` | 「项目」`team-workspace-sidebar-entry` | **文件夹**:圆角矩形 + 顶部左侧标签凸起 | 18 | `#000` |
|
||||
| `svg-06` | 「API 服务」`app-open-api-service` | **两个圆角方块斜着叠在一起 + 两条斜线穿过**(像插头/连接件) | 18 | `#000` |
|
||||
| `svg-07` | 「API 服务」行右端 | **↗ 外链箭头**:一条斜线 + 右上角拐角 | 12 | `--dbx-text-tertiary` |
|
||||
| `svg-08` | 「更多」行图标 `skill-page-item-more` | **2×2 四个圆角小方块**(田字) | 18 | `#000` |
|
||||
| `svg-09` | 「更多」行右端 | **`>` chevron**,细线圆头 | 20(+p-3) | `rgba(0,0,0,.3)` |
|
||||
| `svg-10` | 底部「关于豆包」 | **圆圈 + 里面一个 i**(描边圆) | 16(+p-2) | `rgba(0,0,0,.5)` |
|
||||
| `svg-11` | 底部右下「下载」 | **向下箭头 + 底部托盘**(⤓) | 18 | `rgba(0,0,0,.5)` |
|
||||
| `svg-12` | 顶栏左「收起侧栏」`siderbar_close_btn` | **圆角方框 + 靠左一条竖线**("左侧面板"图标,竖线约在 1/3 处) | 18 | `#000` |
|
||||
| `svg-13` | 输入框左下「+」`upload_file_button` | **加号**,2px 描边圆头 | 18 | `#000` |
|
||||
| `svg-14` | 「豆包 快速」「对话」后面的**小箭头** | **`>` 细箭头**(不是下箭头;放大看是圆头折线,`rotate-0`),想表达"可展开"就转 90° 用 | 12 | `rgba(0,0,0,.2)` |
|
||||
| `svg-15` | 「更多」另一处(无 size class) | 同 `svg-08`(2×2 方块) | 继承 | 继承 |
|
||||
| `svg-16` | 输入框右下**麦克风** `asr_btn` | 麦克风:胶囊咪头 + 下方弧形托 + 竖杆 | 18 | `#000` |
|
||||
| `svg-17` | 模式下拉菜单的**选中勾** | **✓ 对勾**,粗描边圆头 | 14 | `--s-color-brand-primary-default` |
|
||||
| `svg-18` | 菜单项「本地电脑」 | **显示器**:矩形屏幕 + 底座 | 16 | 继承 |
|
||||
| `svg-19` | 菜单项「云电脑」 | **云朵** | 16 | 继承 |
|
||||
|
||||
**输入条那 8 个技能图标不是 SVG,是 16×16 的 PNG**(`<img class="size-[16px] dark:hidden">`,亮/暗各一套)〔DOM〕。
|
||||
它们的统一风格是「**圆角方框 + 内部一个符号**」:
|
||||
|
||||
| 技能 | 框内符号 |
|
||||
|---|---|
|
||||
| 对话 | 圆形气泡(尾巴左下) |
|
||||
| PPT 生成 | 圆角方框内字母 **P** |
|
||||
| 图像生成 | 方框内 **小山 + 太阳点** |
|
||||
| 帮我写作 | 方框内 **两条横线**(文档) |
|
||||
| 视频生成 | 方框内 **播放三角** |
|
||||
| 录音转写 | **麦克风 + 右侧三条短横线** |
|
||||
| 音乐生成 | **音符**(双符头 + 梁) |
|
||||
| 更多 | 2×2 四方块 |
|
||||
|
||||
> 我们用 Material Symbols Rounded 的等效图标(`edit_square`、`chat_bubble`、`folder`、`api`、`apps`、`open_in_new`、
|
||||
> `chevron_right`、`info`、`download`、`left_panel_close`、`add`、`keyboard_arrow_right`、`mic`、`check`、
|
||||
> `computer`、`cloud`、`presentation`、`image`、`edit_note`、`movie`、`graphic_eq`、`music_note`),
|
||||
> 统一 18px、线宽视觉 ~1.8–2px、圆头端点,就是豆包那种「圆润线面结合」的观感。
|
||||
|
||||
---
|
||||
|
||||
## 9. 交互 / 动效
|
||||
|
||||
### 9.1 能从 CSS / 类名确定的
|
||||
|
||||
| 场景 | 动效 | 时长/曲线 | 依据 |
|
||||
|---|---|---|---|
|
||||
| 所有 hover 变色(导航行、chip、按钮) | `background-color` 过渡 | **150ms**,`--ease-out: cubic-bezier(0,0,.2,1)` | 〔DOM〕`transition-colors duration-150 ease-out` |
|
||||
| 侧栏折叠/展开 | 容器 `width` + 面板 `transform/opacity` | **200ms**;面板 `transform .2s, opacity .2s` | 〔CSS〕 |
|
||||
| 侧栏浮层进场 | `drawer-enter` 动画 | 200ms `ease` | 〔CSS〕 |
|
||||
| 侧栏拖拽改宽时 | 全部过渡关掉(`[data-resizing=true]{transition:none}`) | — | 〔CSS〕 |
|
||||
| 分段控件滑块 | `transform: translateX()` | **150ms** `ease-in-out`(`cubic-bezier(.4,0,.2,1)`) | 〔DOM〕〔VAR〕 |
|
||||
| 推荐区淡入淡出 | `opacity` + `visibility` | **100ms** `ease-out`;隐藏时 `visibility` 延迟 100ms | 〔CSS〕`.sug-input-visibility-motion` |
|
||||
| 顶栏左区内边距 | `padding-left` | 200ms | 〔DOM〕`transition-[padding-left] duration-200` |
|
||||
| 问候语文案切换 | `::before/::after` 遮罩擦除 | 200ms `linear` | 〔CSS〕`greeting-text-Q0pGud` |
|
||||
| 输入框聚焦 | 边框色 + 阴影 | 由 Tailwind 默认过渡(约 150ms) | 〔DOM〕`focus-within:shadow/after:border` |
|
||||
| 光标闪烁 | `caret-blink` / ProseMirror gapcursor 1.1s steps(2) | 1.1s | 〔CSS〕 |
|
||||
| 语音录制 | `asr-dot-pulse` 脉冲 | — | 〔CSS〕 |
|
||||
| 降级 | `prefers-reduced-motion: reduce` 时:淡入淡出动画压到 **1ms**、推荐区过渡 `none`、`.motion-reduce:animate-none` | — | 〔CSS〕 |
|
||||
| 焦点可见 | `:focus-visible` 统一 `outline: 2px solid var(--dbx-fill-highlight)` + `outline-offset: -2px` | 即时 | 〔DOM〕 |
|
||||
|
||||
### 9.2 推不出来 / 需实测
|
||||
|
||||
| 项 | 状态 |
|
||||
|---|---|
|
||||
| 发送按钮 hover / active(是否变深、是否缩放) | **需实测**(镜像只有静态图;我们现有 `.send-btn:active{scale(.94)}` 是自创的) |
|
||||
| 麦克风按钮 hover 的具体色 | 有类名依据:`hover:bg-dbx-fill-trans-20-hover`(`#00000012`),但**视觉确认需实测** |
|
||||
| 推荐 chip 的按下态 | **需实测**(只有 hover) |
|
||||
| 侧栏「最近」右侧「…」按钮点开的菜单样式 | **需实测**(本态空列表,菜单未渲染) |
|
||||
| 输入框内换行/回车的自动增高节奏 | **需实测**(CSS 给的是 `max-height:360px`,逐帧增长曲线未知) |
|
||||
| 消息气泡 / 消息操作栏 | 本镜像为空态,**未覆盖**(只能给 token,给不了实测矩形) |
|
||||
|
||||
---
|
||||
|
||||
## 10. 响应式与折叠
|
||||
|
||||
### 10.1 断点(豆包自己定义的)
|
||||
|
||||
| Token | 值 | 依据 |
|
||||
|---|---|---|
|
||||
| `--dbx-breakpoint-xs` | 462px | 〔VAR〕 |
|
||||
| `--dbx-breakpoint-sm` | **640px** | 〔VAR〕 |
|
||||
| `--dbx-breakpoint-md` | **868px** | 〔VAR〕 |
|
||||
| `--dbx-breakpoint-lg` | **1440px** | 〔VAR〕 |
|
||||
|
||||
CSS 里实际出现的媒体查询(`teqgtp-chat.css` 共 101 条):
|
||||
`min-width: 462 / 640 / 868 / 900 / 1440`,`max-width: 399 / 599 / 799 / 800`,以及 `@media (hover:hover)`(15 处)、
|
||||
`@media (prefers-reduced-motion:reduce)`(3 处)。移动端还有一批 `max-width:799px` 的浮层变体(`![fixed] right-0 bottom-0 z-40 w-screen`)。
|
||||
|
||||
### 10.2 侧栏的四种形态
|
||||
|
||||
〔CSS〕
|
||||
```css
|
||||
.container-hzjmF1{flex:none;height:100%;width:0;transition:none}
|
||||
.container-hzjmF1[data-presentation=inline]{width:280px} /* 展开:占位 280 */
|
||||
.container-hzjmF1[data-dock-transition]{transition:width .2s}
|
||||
.panel-fvxXfj{position:fixed;width:280px;transition:transform .2s,opacity .2s}
|
||||
.container-hzjmF1[data-presentation=inline] .panel-fvxXfj{position:relative;z-index:20}
|
||||
.container-hzjmF1[data-presentation=invisible] .panel-fvxXfj{opacity:0;pointer-events:none;transform:translateX(-110%)}
|
||||
.container-hzjmF1[data-presentation=drawer] .panel-fvxXfj{animation:drawer-enter .2s ease;z-index:40}
|
||||
```
|
||||
|
||||
| 形态 | 行为 | 用在哪 |
|
||||
|---|---|---|
|
||||
| `inline` | 占位 280,正常流内,`position:relative` | 桌面展开 |
|
||||
| `invisible` | 占位 0,面板左移 110% + 透明 | 桌面折叠 |
|
||||
| `floating` | 占位 0,浮在内容上,`pointer-events:none` | 宽屏悬浮 |
|
||||
| `drawer` | 占位 0,抽屉式滑入,z-index 40 | 窄屏(≤799) |
|
||||
|
||||
* 侧栏类名 `relative p-12 sm:fixed` ⇒ **≥640px 面板变 fixed**(配合上面的 presentation 控制)。
|
||||
* 折叠/展开按钮在顶栏左侧(`siderbar_close_btn`),图标就是 `svg-12`。
|
||||
* 主区有 `min-width:400px` 保护(`.main-with-nav-qLRcbu{min-width:400px}`),窄于此再考虑移动布局。
|
||||
|
||||
### 10.3 我们的落地建议
|
||||
|
||||
```css
|
||||
/* 桌面 */
|
||||
#app { display:flex; height:100vh; overflow:hidden; }
|
||||
.sidebar { width:280px; flex:none; transition:width .2s, transform .2s; }
|
||||
body.sidebar-collapsed .sidebar { width:0; transform:translateX(-110%); opacity:0; }
|
||||
/* ≤868:默认折叠成抽屉 */
|
||||
@media (max-width:868px){ .sidebar{ position:fixed; inset:0 auto 0 0; z-index:40; width:280px; } }
|
||||
/* 内容列永远 1000 上限,两侧 24 内边距兜底 */
|
||||
.content-col{ width:100%; max-width:1000px; margin:0 auto; padding:0 24px; }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. 「我们怎么用」:把豆包这套往我们的 App 上映射
|
||||
|
||||
### 11.1 侧栏放什么(对照我们真实有的功能)
|
||||
|
||||
豆包这一列是:`新工作任务 / 新对话 / 项目 / API 服务 / 更多`。我们照「动作在前、内容在后、杂项在底」的顺序改:
|
||||
|
||||
| 位置 | 我们的条目 | 对应豆包哪个 | 说明 |
|
||||
|---|---|---|---|
|
||||
| 品牌行 | **我们的名字**(当前是「豆包」两个字的纯文字) | 品牌行 | 高度 36、18/26/500;**不要放豆包官方 logo 图形**,纯文字最安全 |
|
||||
| 主动作 1 | **新对话** `Ctrl J`(放第一个,因为最常用) | 新工作任务 | 图标:气泡(`svg-04` 的等效形);快捷键 hover 才显示 |
|
||||
| 主动作 2 | **智能体** | 新对话 | 图标:机器人/星形(我们已有 avatar 资源,直接用自己的) |
|
||||
| 主动作 3 | **群聊** | 项目 | 图标:双人/群组 |
|
||||
| 主动作 4 | **资源** | API 服务 | 图标:文件夹;右端可挂「数量」小字(学它的 `12px tertiary`) |
|
||||
| 主动作 5 | **会议** | 更多 | 图标:日历/画布;右端用 `>` 表示可展开子项 |
|
||||
| 分区标题 | **最近** | 最近 | 12/18/500 tertiary,行高 32,`px-10`,hover 底色 |
|
||||
| 分区标题 2 | **收藏 / 群聊会话**(可选第二组) | — | 同样的 `h-32` 分组头,分组之间 `gap-2` |
|
||||
| 会话项 | 会话标题 + 时间 + `…` 菜单 | 会话项 | 高 32、圆角 18、`padding 0 10`、选中/hover `rgba(0,0,0,.04)` |
|
||||
| 底部 | **设置** + **关于** + (可选)用量 | 关于豆包 + 下载 | 上方 1px `rgba(0,0,0,.08)` 分隔线、左右 8、文字 14/22 `rgba(0,0,0,.5)` |
|
||||
|
||||
**不要抄**(豆包商业元素):`登录`、`下载豆包工作 / 下载电脑版`、`API 服务`(它的商业化入口)、`工作`页签里的 PPT/文档商业能力、
|
||||
Windows 四色 logo、豆包 logo 与「豆包」文案本身。
|
||||
|
||||
### 11.2 输入框那排按钮 → 我们真实能力
|
||||
|
||||
豆包:`+ | 对话 › | PPT 生成 · 图像生成 · 帮我写作 · 视频生成 · 录音转写 · 音乐生成 · 更多 | 豆包 快速 › | 🎤`
|
||||
|
||||
我们的映射(**结构不变:左 36 圆按钮 + 竖线 + 模式按钮 › + 一排能力按钮 + 右侧模型 › + 36 圆按钮**):
|
||||
|
||||
| 槽位 | 我们放什么 | 依据 |
|
||||
|---|---|---|
|
||||
| 1 | **+ 附件**(上传/拖拽文件,风格 36×36 圆、18px 图标) | 直接同构 |
|
||||
| 2 | 竖线 `1×16 rgba(0,0,0,.1)` | 同构 |
|
||||
| 3 | **模式 ▾**:`对话 / 深度思考 / 联网`(我们真有就放,没有就换成「纯聊天 / 工具调用」) | 豆包这里是「对话」,点开选模型能力 |
|
||||
| 4.1 | **深度思考**(有则放;图标:灯泡/脑子) | 替换 PPT 生成 |
|
||||
| 4.2 | **联网搜索**(有则放;图标:地球) | 替换 图像生成 |
|
||||
| 4.3 | **@ 群成员**(群聊时才有;图标:@ 或人像组) | 替换 帮我写作 |
|
||||
| 4.4 | **朗读 / 自动朗读开关**(我们已有这功能) | 替换 视频生成 |
|
||||
| 4.5 | **语音转写 / 录音**(麦克风之外的录音入口) | 替换 录音转写 |
|
||||
| 4.6 | **会议模式**(一键进会议画布) | 替换 音乐生成 |
|
||||
| 4.7 | **更多**(2×2 方块,多余能力收这里) | 同构 |
|
||||
| 5 | **模型 ▾**:`模型名 思考强度`,14/22 + 12px 箭头 | 同构(豆包是「豆包 快速 ▾」) |
|
||||
| 6 | **麦克风(空)/ 发送(有内容)**:36 圆 | 同构:空态 `#f5f5f5` 底;有内容 **#06f** 底白箭头 |
|
||||
|
||||
**按钮取舍原则**:豆包那 7 个技能按钮是它的商业能力清单;我们只保留**点了真的会发生事**的。
|
||||
数量控制在 **6 个以内**——豆包 1440 下 7 个按钮已经从 x≈509 排到 1135,离右侧「豆包 快速」只剩约 90px;
|
||||
再多就必须靠「更多」收口(它的左组本来就是 `flex-1 + overflow:hidden`,放不下会裁掉)。
|
||||
|
||||
### 11.3 别抄的清单(法律边界)
|
||||
|
||||
| 可以学 | 不能抄 |
|
||||
|---|---|
|
||||
| 布局比例、栅格、间距、行高 | 豆包 logo、品牌名「豆包」字样、字标 |
|
||||
| 色值、色阶、圆角、阴影、动效曲线 | `icons/svg-01..19.svg` 的 path 数据(形状可参考,代码不能复制) |
|
||||
| 字体栈思路(系统字体回退) | `fonts.json` 里的字体文件(`LarkChineseQuote` 等) |
|
||||
| 组件结构(输入框分层、分段控件) | 截图里的文案(推荐问法、占位符以外的示例文本) |
|
||||
| 「圆润、低对比、大量留白」的气质 | `work` 页签的商业能力命名(PPT 生成/图像生成…) |
|
||||
|
||||
**一句话**:学它的**度量与气质**,不学它的**资产与文案**。所有图标用 Material Symbols 或自己画,
|
||||
所有文字用我们自己的,产品名不叫豆包、不用豆包 logo。
|
||||
|
||||
### 11.4 与现有 `web/assets/app.css` 的对齐清单
|
||||
|
||||
| 项 | 现有实现 | 镜像实测 | 要不要改 |
|
||||
|---|---|---|---|
|
||||
| 内容列宽 | `--content-w: 996px` | **1000px** | 建议改(视觉差 4px,但别的地方都对不齐) |
|
||||
| 输入框高 | 未固定(`padding 12 14 8` + 内容撑开) | **100**(`min-height:100px`) | 改:固定 `min-height:100px`、内边距 `10`、编辑区↔按钮排 `gap:14` |
|
||||
| 输入框聚焦 | `0 0 0 3px` ring + `border rgba(0,101,253,.5)` | 细边框变 `rgba(0,102,255,.3)` + **蓝光晕**,无 ring | 改 |
|
||||
| 底排按钮高 | `.cbtn` 32 / `padding 0 10` | 32 / `padding 0 8`,圆角 12 | 微调 padding |
|
||||
| 底排按钮文字色 | `--text-secondary`(灰) | **`#000`(纯黑)**,hover 只变底不变色 | 改 |
|
||||
| 发送 / 麦克风 | 32×32 | **36×36** | 改 |
|
||||
| 麦克风配色 | 紫(`--violet-weak`/`--violet`) | **`#f5f5f5` 底 + 黑图标** | 改(紫是自创的) |
|
||||
| 分段控件 | `.pill-tabs` | 轨道 326×54 `#f5f5f5`、滑块 160×48 白 + 小阴影、文字 16/18 | 按 §4.3 对齐 |
|
||||
| chip | `.chip` | 42 高、圆角 12、边框 `#00000012`、`padding 12/8`、间距 10 | 对齐 |
|
||||
| 侧栏 hover | `--bg-hover: rgba(0,0,0,.045)` | `#0000000a`(0.039) | 基本一致,可留着 |
|
||||
|
||||
---
|
||||
|
||||
## 12. 给实现者的 Checklist
|
||||
|
||||
照着勾,首屏就能立起来。
|
||||
|
||||
**骨架**
|
||||
- [ ] `html,body{height:100%;margin:0;overflow:hidden}`,`#app{display:flex}`
|
||||
- [ ] 侧栏 `width:280px; background:#f9f9f9; padding:10px 12px 12px; border-right:1px solid #e9e9e9`
|
||||
- [ ] 主区 `flex:1; min-width:0; background:#fff`
|
||||
- [ ] 顶栏 `height:56px; padding:0 16px; display:flex; align-items:center; gap:8px; border-bottom:1px solid #ededed`
|
||||
- [ ] 内容列 `width:100%; max-width:1000px; margin:0 auto`(父级左右 24px 内边距)
|
||||
- [ ] 输入区固定 `height:100px` 贴底,下面是 **16px** 留白
|
||||
- [ ] `body,html` 不滚;只有侧栏列表和消息区各自滚
|
||||
|
||||
**侧栏**
|
||||
- [ ] 品牌行高 36,文字 18/26/500 `#000`,左内边距 10
|
||||
- [ ] 导航行 `height:32px; padding:0 8px; border-radius:10px; margin-bottom:2px`,图标 18px(22px 盒)+ 文字 14/22/500 `#000`,图标↔文字 8
|
||||
- [ ] 导航行 `hover{background:#0000000a}`,过渡 150ms `cubic-bezier(0,0,.2,1)`
|
||||
- [ ] 快捷键小字 12px `rgba(0,0,0,.35)`,默认 `opacity:0`,行 hover 才显示
|
||||
- [ ] 「最近」分组头 `height:32px; padding:0 10px; font:500 12/18; color:rgba(0,0,0,.35)`,上边 8px 间隔
|
||||
- [ ] 会话项 `height:32px; border-radius:18px; padding:0 10px`,hover/选中 `background:rgba(0,0,0,.04)`
|
||||
- [ ] 底部:1px `rgba(0,0,0,.08)` 分隔线(左右缩进 8),文字 14/22 `rgba(0,0,0,.5)`
|
||||
- [ ] 列表滚动条默认隐藏,hover 显示 7px、`#ccc`、圆角、无轨道
|
||||
|
||||
**顶栏**
|
||||
- [ ] 左:折叠按钮 26×26(图标 18,内边距 4,圆角 6,hover 底 `#0000000a`),距左 16
|
||||
- [ ] 右:我们的主按钮(36 高、圆角 12)+ 次按钮,间距 8
|
||||
|
||||
**空态**
|
||||
- [ ] 问候语 28/600、行高 42、`#000`,水平居中(中心 = 侧栏右缘 + 主区一半)
|
||||
- [ ] 问候语块顶 ≈ 视口 34%(1440×900 下 308)
|
||||
- [ ] 问候语下 20px → 分段控件
|
||||
- [ ] 分段控件:轨道 326×54 圆角全、`#f5f5f5`;滑块 160×48 白 + `0 2px 4px #00000005,0 4px 10px #00000005`,`transition:transform 150ms`;文字 16/18(选中 500 `#000`,未选中 400 `#7a7a7a`)
|
||||
- [ ] 「为你推荐」12/18 `rgba(0,0,0,.35)`,左对齐、左缩进 4、下间距 12
|
||||
- [ ] chip:42 高、圆角 12、`1px #00000012`、`padding:8px 12px`、14/22 `#000`、间距 10、hover `#0000000a`
|
||||
- [ ] 推荐区与输入框同宽同左缘(x=360),底对齐输入框上沿,`padding-bottom:16`
|
||||
|
||||
**输入框(重点)**
|
||||
- [ ] 容器:`1000×100`(`min-height:100px`)、`border-radius:24px`、`background:#fff`、`border:1px solid #0000001a`、`box-shadow:0 2px 4px #00000005,0 4px 16px #0000000a,0 8px 32px #00000014`
|
||||
- [ ] 内层 `padding:10px`,编辑区在上、按钮排在下,中间 `gap:14px`
|
||||
- [ ] 编辑区:16/24,文本左缩进再 +10,placeholder `rgba(0,0,0,.3)`,光标 `#0057ff`
|
||||
- [ ] 聚焦:边框 `rgba(0,102,255,.3)`,阴影换成 `0 2px 4px rgba(116,158,243,.02),0 4px 12px rgba(102,188,253,.04),0 8px 24px rgba(95,178,255,.17)`(**不要 ring**)
|
||||
- [ ] 按钮排:高 36,左组 `flex:1`、`overflow:hidden`,组间距 6
|
||||
- [ ] +:36×36 圆、图标 18、hover `#0000000a`
|
||||
- [ ] 竖线:`1×16` `#0000001a`,左右各 8
|
||||
- [ ] 模式按钮:`h32 / 圆角12 / padding 0 8 0 4`,16px 图标 + 14/22 `#000` + 12px `rgba(0,0,0,.2)` 箭头
|
||||
- [ ] 能力按钮:`h32 / 圆角12 / padding 0 8`,16px 图标 + 14/22 `#000`,按钮间 gap 4,hover `#0000000a`
|
||||
- [ ] 右侧模型按钮:14/22 `#000` + 12px 箭头
|
||||
- [ ] 右下按钮 36×36 圆:空态 `#f5f5f5` 底 + 黑图标;有内容 **#06f** 底 + 白箭头(同一个槽位切换)
|
||||
- [ ] 按钮排始终贴输入框内底 10px;编辑区最大高 = `360 - 36(按钮排) - 16 - 14(gap) - 10(padding) = **284px**`(豆包原式:`max-h-[calc(var(--input-guidance-input-container-max-height) - var(--custom-area-height,0px) - 36px - 16px - 14px - 10px)]`)
|
||||
|
||||
**工程**
|
||||
- [ ] 所有过渡统一 150ms + `cubic-bezier(0,0,.2,1)`;侧栏折叠 200ms;分段滑块 150ms `cubic-bezier(.4,0,.2,1)`
|
||||
- [ ] `@media (prefers-reduced-motion:reduce)` 关掉动画
|
||||
- [ ] 亮/暗两套变量按 §6.1 填(暗色值直接抄右列)
|
||||
- [ ] 图标全部用 Material Symbols / 自绘,不引豆包 SVG、不引豆包字体
|
||||
- [ ] 文案全部自己写
|
||||
|
||||
---
|
||||
|
||||
## 13. 附:抓取镜像里可以直接查证的位置
|
||||
|
||||
| 想知道什么 | 看哪儿 |
|
||||
|---|---|
|
||||
| 某个元素的行内 style / 类名 | `dom/page.rendered.html`(搜 `data-testid`) |
|
||||
| 元素层次 + 坐标 + 背景色 | `dom/dom-tree.txt`(25 行,每个节点带 `[x,y wxh]`) |
|
||||
| 关键元素的计算样式 | `styles/metrics.json`、`styles/computed-styles.json` |
|
||||
| 全部 240 个 `--dbx-*` 亮色变量 | `styles/dbx-light-vars.json` |
|
||||
| 亮/暗成对的变量(552 个) | `styles/computed-styles.json → cssVars`(格式 `亮 | 暗`) |
|
||||
| 圆角/阴影/断点/字号阶梯 | 同上 `cssVars` 里的 `--s-radius-* / --s-shadow-* / --dbx-breakpoint-* / --s-font-*` |
|
||||
| 工具类真实取值 | `styles/key-classes.css`、`styles/tokens.txt` |
|
||||
| 字体清单 | `styles/fonts.json` |
|
||||
| 图标形状 | `icons/svg-01..19.svg`(24×24 viewBox,`fill="currentColor"`) |
|
||||
| 想看「活的」页面 | `page.mhtml` 用浏览器打开 |
|
||||
|
||||
---
|
||||
|
||||
**文档版本**:v1(基于 2026-10-17 抓取的镜像 + 1440×900 三张截图逐像素实测)。
|
||||
**只学布局/尺寸/配色,不含豆包任何代码、字体文件、图标资源与文案。**
|
||||
11
package.json
@@ -4,13 +4,16 @@
|
||||
"private": true,
|
||||
"description": "豆包复刻(LynxJS / ReactLynx):Web + Windows(exe) + Android(apk),AI 内核支持火山方舟 / OpenAI + MCP + Python 工具",
|
||||
"scripts": {
|
||||
"install:all": "npm --prefix app install && npm --prefix server install",
|
||||
"build": "npm --prefix app run build",
|
||||
"start": "node server/src/index.mjs",
|
||||
"dev": "npm --prefix app run build && node server/src/index.mjs",
|
||||
"install:all": "npm --prefix desktop install",
|
||||
"start": "node scripts/start-web.mjs",
|
||||
"dev": "node scripts/start-web.mjs",
|
||||
"start:node": "node server/src/index.mjs",
|
||||
"start:legacy-lynx": "npm --prefix app run build && node server/src/index.mjs",
|
||||
"mock": "node scripts/mock-llm.mjs",
|
||||
"rasterize": "node scripts/rasterize-icons.mjs",
|
||||
"exe": "node scripts/build-exe.mjs",
|
||||
"web:scrape": "node scripts/scrape-doubao-web.mjs",
|
||||
"web:shot": "node scripts/screenshot.mjs",
|
||||
"apk": "node scripts/build-apk.mjs",
|
||||
"android:setup": "node scripts/android-setup.mjs",
|
||||
"mcp:smoke": "node scripts/mcp-smoke.mjs",
|
||||
|
||||
73
reference/scripts/extract-css.mjs
Normal file
@@ -0,0 +1,73 @@
|
||||
/** 从抓下来的 CSS 里提取 light 主题变量 + 关键组件类,汇总成一份参考。 */
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dirname, 'doubao-web-mirror');
|
||||
const OUT = path.join(ROOT, 'styles');
|
||||
const cssFiles = [];
|
||||
const walk = (dir) => {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, ent.name);
|
||||
if (ent.isDirectory()) walk(p);
|
||||
else if (ent.name.endsWith('.css')) cssFiles.push(p);
|
||||
}
|
||||
};
|
||||
walk(path.join(ROOT, 'assets'));
|
||||
console.log('CSS 文件:', cssFiles.length);
|
||||
|
||||
let all = '';
|
||||
for (const f of cssFiles) all += '\n' + fs.readFileSync(f, 'utf8');
|
||||
console.log('CSS 总长:', (all.length / 1048576).toFixed(2), 'MB');
|
||||
|
||||
// 1) light 主题变量块
|
||||
const lightBlocks = [];
|
||||
for (const m of all.matchAll(/([^{}]{0,80})\{([^{}]*--dbx-text-primary:#000[^{}]*)\}/g)) {
|
||||
lightBlocks.push(m[0]);
|
||||
}
|
||||
const vars = {};
|
||||
for (const block of lightBlocks) {
|
||||
for (const m of block.matchAll(/(--dbx-[a-z0-9-]+):([^;{}]+);/g)) {
|
||||
const [, k, v] = m;
|
||||
if (v.includes('var(')) continue;
|
||||
if (!(k in vars)) vars[k] = v.trim();
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(path.join(OUT, 'dbx-light-vars.json'), JSON.stringify(vars, null, 2), 'utf8');
|
||||
console.log('light 主题变量:', Object.keys(vars).length, '个 → dbx-light-vars.json');
|
||||
|
||||
// 2) 常用工具类定义(按 DOM 里见到的类名精确找)
|
||||
const wanted = [
|
||||
'w-sidebar-width', 'text-28', 'text-dbx-text-primary', 'text-dbx-text-secondary',
|
||||
'bg-dbx-bg-base-web', 'bg-dbx-bg-body-web', 's-font-small', 's-font-base', 's-font-h1',
|
||||
'rounded-dbx-2xl', 'rounded-dbx-3xl', 'rounded-dbx-4xl', 'rounded-full',
|
||||
'shadow-dbx-drop-shadow-sm', 'shadow-dbx-drop-shadow-xs',
|
||||
];
|
||||
const found = {};
|
||||
for (const cls of wanted) {
|
||||
const re = new RegExp('\\.' + cls.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\{[^}]*\\}', 'g');
|
||||
const hits = [...all.matchAll(re)].map((m) => m[0]);
|
||||
if (hits.length) found[cls] = hits.slice(0, 2).join(' || ');
|
||||
}
|
||||
fs.writeFileSync(path.join(OUT, 'key-classes.css'), Object.entries(found).map(([k, v]) => `/* ${k} */\n${v}`).join('\n\n'), 'utf8');
|
||||
|
||||
// 3) 字体相关的 @font-face(只留 family/src/weight)
|
||||
const fontFaces = [...all.matchAll(/@font-face\{[^}]*\}/g)].map((m) => m[0]);
|
||||
const fontSummary = new Map();
|
||||
for (const face of fontFaces) {
|
||||
const fam = (face.match(/font-family:([^;]+)/) || [])[1];
|
||||
const src = (face.match(/src:url\(([^)]+)\)/) || [])[1];
|
||||
const weight = (face.match(/font-weight:([^;]+)/) || [])[1];
|
||||
if (!fam) continue;
|
||||
const key = fam.replace(/["']/g, '') + '|' + (weight || '');
|
||||
if (!fontSummary.has(key)) fontSummary.set(key, { family: fam.replace(/["']/g, ''), weight: weight || '', src: src || '' });
|
||||
}
|
||||
fs.writeFileSync(path.join(OUT, 'fonts.json'), JSON.stringify([...fontSummary.values()], null, 2), 'utf8');
|
||||
console.log('字体:', [...fontSummary.keys()].join(', '));
|
||||
|
||||
// 4) 滚动条 / 圆角 / 阴影 token 概览
|
||||
const radii = [...new Set([...all.matchAll(/--dbx-radius-[a-z0-9]+:([^;}]+)/g)].map((m) => m[1]))];
|
||||
const shadows = [...new Set([...all.matchAll(/--dbx-drop-shadow-[a-z]+:([^;}]+)/g)].map((m) => m[1]))];
|
||||
fs.writeFileSync(path.join(OUT, 'tokens.txt'), [
|
||||
'# 圆角', ...radii, '', '# 阴影', ...shadows, '',
|
||||
].join('\n'), 'utf8');
|
||||
console.log('done');
|
||||
212
scripts/audit-ui-tree.py
Normal file
@@ -0,0 +1,212 @@
|
||||
"""校验 `docs/界面总览.md` 和 Kotlin 源码一致。
|
||||
|
||||
## 为什么需要它
|
||||
|
||||
这个项目里已经反复出现「界面做好了但没有任何入口」(记忆管理、世界观共享记忆
|
||||
都栽过),而**光靠人查必然会漏**。所以界面文档不能是"我凭记忆写的",
|
||||
必须是"能从代码对拍出来的"。
|
||||
|
||||
它做两件事:
|
||||
|
||||
1. **代码 → 文档**:源码里每个 `fun XxxScreen(` 组件,文档里都得有一节。
|
||||
漏了说明"有个界面你根本没想到要写"。 ← 这一条最值钱
|
||||
2. **文档 → 代码**:文档树里每个 `[界面名]`,都得在对照表里映射到一个
|
||||
真实存在的东西。写了不存在的界面,或者改了名没更新,都会报。
|
||||
|
||||
另外复用 `audit-ui-entries.py` 的入口检查(每个 `openXxx` 都得有人调)。
|
||||
|
||||
用法:
|
||||
python scripts/audit-ui-tree.py
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
UI = os.path.join(REPO, "android", "app", "src", "main", "java", "com", "doubao", "lynxclone", "ui")
|
||||
DOC = os.path.join(REPO, "docs", "界面总览.md")
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 对照表:文档里用的中文名 → 源码里的东西(函数名 / 状态 / 特殊标记)
|
||||
#
|
||||
# ★ 一个 *Screen 组件可能对应文档里的**多个**界面(MemoryScreen 有三种形态:
|
||||
# 智能体视角 / 世界观视角 / 绑定前的私有空间),所以值是列表。
|
||||
# --------------------------------------------------------------------------- #
|
||||
SCREENS = {
|
||||
"聊天": ["ChatScreen"],
|
||||
"抽屉": ["DrawerOverlay"], # 不是 *Screen,是个浮层组件
|
||||
"更多功能": ["MoreSheetScreen"],
|
||||
"智能体选择": ["AgentSelectScreen"],
|
||||
"智能体管理": ["AgentsScreen"],
|
||||
"智能体编辑": ["AgentEditScreen"],
|
||||
"记忆": ["MemoryScreen"],
|
||||
"记忆 · 世界观视角": ["MemoryScreen"],
|
||||
"记忆 · 绑定前的私有空间": ["MemoryScreen"],
|
||||
"资源": ["ResourcesScreen"],
|
||||
"资源编辑": ["ResourcesScreen"], # 同一个文件里的子界面
|
||||
"用量详情": ["TokenUsageScreen"],
|
||||
"设置": ["SettingsScreen"],
|
||||
"超时": ["TimeoutsScreen"],
|
||||
"技能": ["SkillsScreen"],
|
||||
"会议": ["MeetingsScreen"],
|
||||
"节点管理": ["NodeManagerScreen"],
|
||||
"节点代码": ["NodeCodeScreen"],
|
||||
"积木编辑器": ["NodeBlockEditorScreen"],
|
||||
"终端": ["TerminalScreen"],
|
||||
"笔记": ["NotesScreen"],
|
||||
"笔记详情": ["NotesScreen"],
|
||||
"AI 界面列表": ["AiScreenListScreen"],
|
||||
"网页": ["WebPageScreen"],
|
||||
"链接列表": ["UrlListScreen"],
|
||||
"我的": ["ProfileScreen"],
|
||||
"镜像": ["MirrorScreen"],
|
||||
"编辑记忆": ["MemoryScreen"], # 弹窗,属于记忆页
|
||||
"窗口设置": ["MemoryScreen"],
|
||||
"合并/覆盖": ["MemoryScreen"],
|
||||
# ---- v1.2 §6.2 新增的界面 ----
|
||||
"群成员": ["GroupMembersScreen"],
|
||||
"规则包编辑": ["RulePackEditScreen"],
|
||||
"状态数值": ["AgentStatsScreen"],
|
||||
}
|
||||
|
||||
#: 这些 `*Screen` 组件**不是**独立界面,不进文档树
|
||||
SKELETON = {
|
||||
"FullScreen", # 全屏界面的骨架(顶栏 + 内容),被所有页面复用
|
||||
}
|
||||
|
||||
#: **计划中**的界面:v1.2 文档(§6)要求"先改界面总览再写代码",
|
||||
#: 所以文档里会先出现一些代码里还没有的界面。这些不算错误,
|
||||
#: 但脚本会把它们**列出来**(每次跑都提醒"还有几个没落地")——
|
||||
#: 免得计划悄悄烂在文档里。
|
||||
#:
|
||||
#: 落地之后**必须从这里删掉**,否则它就成了一张永久的免罪符。
|
||||
PLANNED = {
|
||||
# ★ v1.2 §6.2 的三个新界面([群成员] / [状态数值] / [规则包编辑])
|
||||
# 到 v2.0.62 全部落地,所以这里**空了** —— 这是好事:
|
||||
# 任何"计划中"的东西一落地就该从这里删掉,
|
||||
# 留着就成了永久的免罪符(文档里不写也没人管)。
|
||||
}
|
||||
|
||||
|
||||
def read(path):
|
||||
with io.open(path, encoding="utf-8") as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
def main():
|
||||
problems = []
|
||||
|
||||
# ---------- 1. 代码里有哪些界面组件 ----------
|
||||
src_fns = set()
|
||||
for name in os.listdir(UI):
|
||||
if not name.endswith(".kt"):
|
||||
continue
|
||||
for fn in re.findall(r"^fun (\w+Screen)\(", read(os.path.join(UI, name)), re.M):
|
||||
src_fns.add(fn)
|
||||
if not src_fns:
|
||||
print("!! 一个 *Screen 组件都没扫到,路径或正则有问题")
|
||||
return 1
|
||||
|
||||
known = set()
|
||||
for v in SCREENS.values():
|
||||
known.update(v)
|
||||
|
||||
print("=" * 66)
|
||||
print("1. 源码里的界面组件 → 文档里都写了吗")
|
||||
print("=" * 66)
|
||||
for fn in sorted(src_fns):
|
||||
if fn in SKELETON:
|
||||
print(f" · {fn}(骨架,不算界面)")
|
||||
elif fn in known:
|
||||
# 反查它对应文档里的哪些名字
|
||||
names = [k for k, v in SCREENS.items() if fn in v]
|
||||
print(f" ✓ {fn} → {', '.join(names)}")
|
||||
else:
|
||||
print(f" ✗ {fn} **源码里有这个界面,但界面文档里没有它**")
|
||||
problems.append(f"{fn} 没写进界面文档")
|
||||
|
||||
# ---------- 2. 文档树里的每个界面都在对照表里吗 ----------
|
||||
print()
|
||||
print("=" * 66)
|
||||
print("2. 文档树里的每个界面 → 源码里真的有吗")
|
||||
print("=" * 66)
|
||||
doc = read(DOC) if os.path.isfile(DOC) else ""
|
||||
if not doc:
|
||||
print(f" !! 找不到 {DOC}")
|
||||
return 1
|
||||
# 只取第 1 节那段树(``` 包起来的第一块)
|
||||
tree = ""
|
||||
m = re.search(r"## 1\. 全图\s*```(.*?)```", doc, re.S)
|
||||
if m:
|
||||
tree = m.group(1)
|
||||
if not tree:
|
||||
print(" !! 文档里找不到「## 1. 全图」那段代码块")
|
||||
return 1
|
||||
|
||||
in_doc = set()
|
||||
for name in re.findall(r"\[([^\]]+)\]", tree):
|
||||
name = name.strip()
|
||||
# 排除明显不是界面的(带说明的长句)
|
||||
if len(name) > 24 or name.startswith("界面名"):
|
||||
continue
|
||||
in_doc.add(name)
|
||||
if name not in SCREENS:
|
||||
print(f" ✗ [{name}] **文档里写了,但对照表里没有这个东西**")
|
||||
problems.append(f"文档里的 [{name}] 对不上代码")
|
||||
for name in sorted(SCREENS):
|
||||
if name in in_doc:
|
||||
if name in PLANNED:
|
||||
print(f" · [{name}] (计划中:{PLANNED[name]},代码里还没有)")
|
||||
else:
|
||||
print(f" ✓ [{name}] → {', '.join(SCREENS[name])}")
|
||||
else:
|
||||
print(f" ✗ [{name}] **对照表里有,但文档树的第 1 节里没有它**")
|
||||
problems.append(f"[{name}] 没画进全图")
|
||||
|
||||
# ---------- 3. 对照表里映射的函数真的存在吗 ----------
|
||||
print()
|
||||
print("=" * 66)
|
||||
print("3. 对照表指向的源码标识存在吗(改名了没更新会在这报)")
|
||||
print("=" * 66)
|
||||
all_src = "\n".join(
|
||||
read(os.path.join(UI, n)) for n in os.listdir(UI) if n.endswith(".kt")
|
||||
)
|
||||
for name, targets in sorted(SCREENS.items()):
|
||||
for t in targets:
|
||||
if t in src_fns:
|
||||
print(f" ✓ {name} → {t}(*Screen 组件)")
|
||||
elif re.search(rf"\b(?:fun|class|object) {re.escape(t)}\b", all_src):
|
||||
print(f" ✓ {name} → {t}(普通组件)")
|
||||
elif name in PLANNED:
|
||||
# 计划中的界面:允许它映射到一个还不存在的组件名
|
||||
print(f" · {name} → {t}(计划中,{PLANNED[name]})")
|
||||
else:
|
||||
print(f" ✗ {name} → **{t} 在源码里找不到**(改名了?删了?)")
|
||||
problems.append(f"对照表的 {t} 不存在")
|
||||
|
||||
print()
|
||||
if PLANNED:
|
||||
print(f"📋 计划中还没落地的界面 {len(PLANNED)} 个:")
|
||||
for k, v in sorted(PLANNED.items()):
|
||||
print(f" - [{k}]({v})")
|
||||
print(" (落地后要从 audit-ui-tree.py 的 PLANNED 里删掉)")
|
||||
print()
|
||||
if problems:
|
||||
print(f"❌ {len(problems)} 个问题:")
|
||||
for p in problems:
|
||||
print(" -", p)
|
||||
print("\n(文档在 docs/界面总览.md,改完重跑)")
|
||||
return 1
|
||||
print("✅ 界面文档和代码一致")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,11 +1,18 @@
|
||||
/**
|
||||
* 打包 Windows 桌面版(Electron)。
|
||||
* 打包 Windows 桌面版(Electron + 网页版界面 + 内嵌 Python 内核)。
|
||||
*
|
||||
* ⚠️ 一个必须知道的坑:Electron 的 exe 放在**非 ASCII 目录**下会在启动时崩溃(0xC0000005),
|
||||
* 所以输出目录固定用纯英文路径,工作区里的中文目录不能直接放 exe。
|
||||
* exe 的**文件名**可以是中文,这个没问题。
|
||||
* 架构(v2,和旧版完全不同):
|
||||
* Electron 主进程 → 起 runtime/python/python.exe 跑 android/kernel(和安卓 App 同一份内核)
|
||||
* → 内核监听 127.0.0.1:<随机端口> 并托管 runtime/web(豆包网页版风格的前端)
|
||||
* → 主进程开窗加载这个地址
|
||||
* 所以 exe / 浏览器 / 手机三端**共用同一个 AI 内核**,功能天然同步。
|
||||
*
|
||||
* 用法: node scripts/build-exe.mjs [--skip-build] [--out D:\some\ascii\dir]
|
||||
* ⚠️ 两个必须知道的坑:
|
||||
* 1. Electron 的 exe 放在**非 ASCII 目录**下会在启动时崩溃(0xC0000005),
|
||||
* 所以输出目录固定用纯英文路径;exe 的**文件名**可以是中文。
|
||||
* 2. 必须带 runtime/python(python.org 的 embeddable zip):用户机器上不一定装了 Python。
|
||||
*
|
||||
* 用法: node scripts/build-exe.mjs [--out D:\some\ascii\dir]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
@@ -18,7 +25,6 @@ const desktopDir = path.join(repo, 'desktop');
|
||||
const staging = path.join(desktopDir, 'dist-staging');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const skipBuild = args.includes('--skip-build');
|
||||
const outIndex = args.indexOf('--out');
|
||||
const OUT_DIR = outIndex >= 0 && args[outIndex + 1]
|
||||
? path.resolve(args[outIndex + 1])
|
||||
@@ -46,10 +52,21 @@ function copy(from, to, filter) {
|
||||
fs.cpSync(from, to, { recursive: true, filter });
|
||||
}
|
||||
|
||||
/* ------------------------------ 1. 构建界面 ------------------------------ */
|
||||
if (!skipBuild) {
|
||||
log('构建 Lynx 界面产物…');
|
||||
run('npm', ['--prefix', 'app', 'run', 'build'], { cwd: repo });
|
||||
/* ------------------------------ 1. 准备嵌入式 Python ------------------------------ */
|
||||
// 为什么用 embeddable:内核是纯标准库(没有 requests/pydantic),
|
||||
// 所以 python.exe + stdlib 就够,解压只有 ~25MB,也不需要用户在电脑上装 Python。
|
||||
const PY_VERSION = '3.13.9';
|
||||
const cacheDir = path.join(desktopDir, 'build-cache');
|
||||
const pyZip = path.join(cacheDir, `python-${PY_VERSION}-embed-amd64.zip`);
|
||||
|
||||
fs.mkdirSync(cacheDir, { recursive: true });
|
||||
if (!fs.existsSync(pyZip)) {
|
||||
const url = `https://www.python.org/ftp/python/${PY_VERSION}/python-${PY_VERSION}-embed-amd64.zip`;
|
||||
log(`下载嵌入式 Python:${url}`);
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(600000) });
|
||||
if (!res.ok) throw new Error(`下载 Python 失败:HTTP ${res.status}`);
|
||||
fs.writeFileSync(pyZip, Buffer.from(await res.arrayBuffer()));
|
||||
log(`已缓存 ${(fs.statSync(pyZip).size / 1024 / 1024).toFixed(1)} MB`);
|
||||
}
|
||||
|
||||
/* ------------------------------ 2. 准备暂存目录 ------------------------------ */
|
||||
@@ -71,7 +88,7 @@ fs.writeFileSync(
|
||||
name: 'doubao-desktop',
|
||||
productName: APP_NAME, // 用 ASCII:%APPDATA% 下的数据目录也跟着是英文,稳妥
|
||||
version,
|
||||
description: '\u8c46\u5305 \u00b7 LynxJS \u590d\u523b\uff08\u684c\u9762\u7248\uff09',
|
||||
description: '\u8c46\u5305 \u00b7 \u7f51\u9875\u7248\u98ce\u683c\u590d\u523b\uff08\u684c\u9762\u7248\uff09',
|
||||
main: 'main.cjs',
|
||||
},
|
||||
null,
|
||||
@@ -80,29 +97,36 @@ fs.writeFileSync(
|
||||
'utf8',
|
||||
);
|
||||
|
||||
// 2.2 AI 内核(源码 + 依赖)
|
||||
log('复制 AI 内核…');
|
||||
fs.mkdirSync(path.join(staging, 'server'), { recursive: true });
|
||||
copy(path.join(repo, 'server', 'src'), path.join(staging, 'server', 'src'));
|
||||
if (fs.existsSync(path.join(repo, 'server', 'config'))) {
|
||||
copy(path.join(repo, 'server', 'config'), path.join(staging, 'server', 'config'));
|
||||
}
|
||||
fs.copyFileSync(path.join(repo, 'server', 'package.json'), path.join(staging, 'server', 'package.json'));
|
||||
copy(path.join(repo, 'server', 'node_modules'), path.join(staging, 'server', 'node_modules'));
|
||||
|
||||
// 2.3 运行时资源:Lynx 产物 / 宿主页 / web-core / python 工具
|
||||
// 2.2 运行时:Python + AI 内核 + 工具 + 网页前端
|
||||
log('复制运行时资源…');
|
||||
const runtime = path.join(staging, 'runtime');
|
||||
fs.mkdirSync(runtime, { recursive: true });
|
||||
copy(path.join(repo, 'app', 'dist'), path.join(runtime, 'app', 'dist'));
|
||||
copy(path.join(repo, 'web'), path.join(runtime, 'web'));
|
||||
copy(
|
||||
path.join(repo, 'app', 'node_modules', '@lynx-js', 'web-core', 'dist', 'client_prod', 'static'),
|
||||
path.join(runtime, 'web-core'),
|
||||
);
|
||||
copy(path.join(repo, 'tools'), path.join(runtime, 'tools'), (src) => !src.includes('__pycache__'));
|
||||
|
||||
// 2.4 打包版 MCP 配置:文件系统服务的目录指向数据目录,用占位符避免写死路径
|
||||
// 嵌入式 Python(解压到 runtime/python)
|
||||
log('解压嵌入式 Python…');
|
||||
run('powershell.exe', ['-NoProfile', '-Command',
|
||||
`Expand-Archive -LiteralPath '${pyZip.replace(/'/g, "''")}' -DestinationPath '${path.join(runtime, 'python').replace(/'/g, "''")}' -Force`]);
|
||||
|
||||
// AI 内核:和安卓 App 同一份 Python 源码(纯标准库,能直接跑在 Windows 上)
|
||||
log('复制 AI 内核…');
|
||||
copy(path.join(repo, 'android', 'kernel'), path.join(runtime, 'kernel'), (src) => {
|
||||
const name = path.basename(src);
|
||||
if (name === '__pycache__') return false;
|
||||
if (name.endsWith('.pyc')) return false;
|
||||
if (name === 'data') return false; // 内核目录下的开发数据不带进包
|
||||
return true;
|
||||
});
|
||||
|
||||
// 工具目录(内置 .py 工具 + MCP 配置)
|
||||
copy(path.join(repo, 'tools'), path.join(runtime, 'tools'), (src) => {
|
||||
const name = path.basename(src);
|
||||
return name !== '__pycache__' && !name.endsWith('.pyc');
|
||||
});
|
||||
|
||||
// 网页前端(纯静态:index.html + assets + js,由内核直接托管)
|
||||
copy(path.join(repo, 'web'), path.join(runtime, 'web'), (src) => !src.includes('__pycache__'));
|
||||
|
||||
// 2.3 打包版 MCP 配置:文件系统服务的目录指向数据目录,用占位符避免写死路径
|
||||
const mcpPath = path.join(runtime, 'tools', 'mcp.servers.json');
|
||||
if (fs.existsSync(mcpPath)) {
|
||||
const conf = JSON.parse(fs.readFileSync(mcpPath, 'utf8'));
|
||||
|
||||
@@ -64,6 +64,8 @@ def section(title):
|
||||
import agent_context # noqa: E402
|
||||
import agent_tools # noqa: E402
|
||||
import agentdb # noqa: E402
|
||||
import defaults # noqa: E402
|
||||
import rule_engine # noqa: E402
|
||||
import store # noqa: E402
|
||||
|
||||
|
||||
@@ -73,12 +75,19 @@ class FakeHandler:
|
||||
def __init__(self):
|
||||
self.status = 200
|
||||
self.payload = None
|
||||
#: 设一个消息就模拟"请求体读不出来"(太大 / 不是合法 JSON)
|
||||
self.body_error_exc = None
|
||||
#: 记下这次收到的 limit —— 用来断言"图片这条路真的被单独放行了"
|
||||
self.last_limit = None
|
||||
|
||||
def send_json(self, code, payload):
|
||||
self.status = code
|
||||
self.payload = payload
|
||||
|
||||
def read_json_body(self, *a, **k):
|
||||
self.last_limit = a[0] if a else k.get('limit')
|
||||
if self.body_error_exc is not None:
|
||||
raise ValueError(self.body_error_exc)
|
||||
return self._body
|
||||
|
||||
def call(self, pathname, method, body=None):
|
||||
@@ -150,8 +159,9 @@ def main():
|
||||
check("memory_add 返回 id", bool(r.get("id")))
|
||||
r = agent_tools.memory_search({"keyword": "猫"})
|
||||
check("memory_search 找到刚记的", r["count"] >= 1, str(r["count"]))
|
||||
agent_tools.emotion_set({"emotion": "刚被夸了,有点得意"})
|
||||
check("情绪写进去了", "得意" in agentdb.emotion_get(a1["id"]))
|
||||
agent_tools.emotion_set({"preset": "喜", "text": "刚被夸了,有点得意"})
|
||||
check("情绪写进去了(双字段)", "得意" in agentdb.emotion_state(a1["id"])["text"])
|
||||
check("preset 也写进去了", agentdb.emotion_state(a1["id"])["preset"] == "喜")
|
||||
agentdb.token_add(a1["id"], "doubao-pro", 1200, 800)
|
||||
agentdb.token_add(a1["id"], "doubao-pro", 300, 100)
|
||||
agentdb.token_add(a1["id"], "deepseek-r1", 500, 200)
|
||||
@@ -213,7 +223,7 @@ def main():
|
||||
# ---------------------------------------------------------------- 8
|
||||
section("8. system prompt 注入(附录 C)")
|
||||
tools_runtime.push_context(agentId=a1["id"], conversationId="c_test")
|
||||
agentdb.emotion_set(a2["id"], "有点烦")
|
||||
agentdb.emotion_set(a2["id"], preset="哀", text="有点烦")
|
||||
store.update_agent(a2["id"], {"emotionEnabled": True})
|
||||
# ★ a1 在这一节之前已经绑了世界观 → 它的记忆空间是**共享**的那个,
|
||||
# 所以验证"记忆进提示词"要往当前 scope 里写(这正是绑定世界观的正确行为)
|
||||
@@ -235,8 +245,11 @@ def main():
|
||||
check("共享记忆带作者署名", "(你记的)" in prompt, prompt[-300:])
|
||||
check("自定义 Skill 进去了", "写东西要先列大纲" in prompt)
|
||||
check("顺序:skills 在 worldview 前", prompt.index("<skills>") < prompt.index("<worldview>"))
|
||||
check("顺序:worldview 在 emotion 前", prompt.index("<worldview>") < prompt.index("<emotion>"))
|
||||
check("顺序:emotion 在 memory 前", prompt.index("<emotion>") < prompt.index("<memory>"))
|
||||
check("顺序:worldview 在 memory 前", prompt.index("<worldview>") < prompt.index("<memory>"))
|
||||
# ★ v1.2 把 emotion 挪到 memory **后面**了(缓存友好排序,详见第 20 节)。
|
||||
# 这条断言原来记的是旧顺序 —— 顺序一改它就红了,这正是它该干的活。
|
||||
check("顺序:memory 在 emotion 前(v1.2 缓存友好)",
|
||||
prompt.index("<memory>") < prompt.index("<emotion>"))
|
||||
# ★ 情绪感知关着时**仍然给成员名单**(复查报告 5):共享记忆是共用的,
|
||||
# AI 不知道有别人,就会把别人写的条目当成自己的经历
|
||||
check("没开感知也有成员名单", "<peer_emotions>" in prompt and "仙辰" in prompt, prompt[-300:])
|
||||
@@ -244,7 +257,9 @@ def main():
|
||||
check("名单里也没有 agent 的 JSON", "'builtin'" not in prompt and "worldviewId'" not in prompt)
|
||||
store.update_agent(a1["id"], {"emotionEnabled": True})
|
||||
prompt2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a1["id"]))
|
||||
check("开了感知后有同伴情绪", "<peer_emotions>" in prompt2 and "仙辰-有点烦" in prompt2, prompt2[-200:])
|
||||
check("开了感知后看到的是**同伴的 preset**(不是他的内心独白)",
|
||||
"<peer_emotions>" in prompt2 and "仙辰-哀" in prompt2, prompt2[-200:])
|
||||
check("**同伴的 text 不外泄**", "有点烦" not in prompt2.split("<peer_emotions>")[-1], prompt2[-200:])
|
||||
# 空段要整段删掉
|
||||
a3 = store.create_agent({"name": "空白的"})
|
||||
p3 = agent_context.build_system_prompt(store.read_settings(), a3)
|
||||
@@ -267,8 +282,9 @@ def main():
|
||||
check("GET 记忆列表", r.get("ok") and r.get("shared") is True)
|
||||
r = h.call(f"/api/agents/{a1['id']}/usage", "GET")
|
||||
check("GET 用量", r.get("ok") and r.get("total", 0) > 0)
|
||||
r = h.call(f"/api/agents/{a1['id']}/emotion", "PUT", {"emotion": "挺开心的"})
|
||||
check("PUT 情绪", r.get("emotion") == "挺开心的")
|
||||
r = h.call(f"/api/agents/{a1['id']}/emotion", "PUT", {"preset": "喜", "text": "挺开心的"})
|
||||
check("PUT 情绪(双字段)", (r.get("emotion") or {}).get("text") == "挺开心的", str(r.get("emotion")))
|
||||
check("preset 也存了", (r.get("emotion") or {}).get("preset") == "喜")
|
||||
r = h.call("/api/worldviews", "GET")
|
||||
check("GET 世界观列表", r.get("ok") and len(r["items"]) == 1)
|
||||
r = h.call("/api/model-entries", "POST", {"name": "豆包 Pro", "model": "doubao-pro", "pricePerK": 0.8})
|
||||
@@ -312,11 +328,12 @@ def main():
|
||||
r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST", {"data": exported, "mode": "merge"})
|
||||
check("合并模式:新增了 1 条", r.get("added") == 1, str(r))
|
||||
check("合并模式:同名的跳过了", r.get("skipped", 0) >= 1, str(r))
|
||||
check("合并模式:保留当前情绪", agentdb.emotion_get(a1["id"]) == "挺开心的")
|
||||
check("合并模式:保留当前情绪", agentdb.emotion_state(a1["id"])["text"] == "挺开心的")
|
||||
r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST",
|
||||
{"data": {"type": "agent-memory", "version": 1, "smartMemory": [], "Emotion": "换掉了"},
|
||||
"mode": "replace"})
|
||||
check("覆盖模式:情绪也换了", agentdb.emotion_get(a1["id"]) == "换掉了", agentdb.emotion_get(a1["id"]))
|
||||
check("覆盖模式:情绪也换了(v1.1 的字符串格式也认)",
|
||||
agentdb.emotion_state(a1["id"])["text"] == "换掉了", str(agentdb.emotion_state(a1["id"])))
|
||||
|
||||
# ---------------------------------------------------------------- 11
|
||||
section("11. 多模型:引用了就真的用(需求 3.3)")
|
||||
@@ -449,6 +466,533 @@ def main():
|
||||
check("置顶数超过窗口时,置顶的全部保留(6 条)", kept == 6, f"实际 {kept} 条:{seg4[-200:]}")
|
||||
store.write_settings({"memoryWindow": 50})
|
||||
|
||||
# ---------------------------------------------------------------- 16
|
||||
section("16. 语音:智能体自己的音色要真的生效(用户报的「语音没生效」)")
|
||||
#
|
||||
# 内核这边一直是对的(`voice_for` 做"智能体 > 全局"),
|
||||
# 真正漏的是**界面朗读时不传 agentId** —— 于是内核拿不到人,
|
||||
# 永远用全局那个嗓子,智能体编辑页里选的音色白配。
|
||||
# 界面那一侧没法在这里测,所以这里把**契约**钉死:
|
||||
# 只要 agentId 传进来,音色必须跟着换。
|
||||
import speech
|
||||
|
||||
a_voice = store.create_agent({"name": "嗓音测试"})
|
||||
store.update_agent(a_voice["id"], {"ttsVoice": "my-voice-123", "ttsEngine": "volc"})
|
||||
st = store.read_settings()
|
||||
merged = speech.voice_for(st, store.get_agent(a_voice["id"]))
|
||||
check("智能体的音色覆盖了全局", merged.get("ttsVoice") == "my-voice-123", str(merged.get("ttsVoice")))
|
||||
check("引擎也跟着覆盖", merged.get("ttsEngine") == "volc", str(merged.get("ttsEngine")))
|
||||
plain = speech.voice_for(st, {})
|
||||
check("没配的智能体回落全局", plain.get("ttsVoice") == speech.voice_for(st, {}).get("ttsVoice"))
|
||||
# 半配:只设了音色、没设引擎 → 引擎回落,音色用它的
|
||||
half = store.create_agent({"name": "半配"})
|
||||
store.update_agent(half["id"], {"ttsVoice": "only-voice"})
|
||||
m2 = speech.voice_for(st, store.get_agent(half["id"]))
|
||||
check("只设音色时引擎回落全局", m2.get("ttsVoice") == "only-voice", str(m2.get("ttsVoice")))
|
||||
|
||||
# ---------------------------------------------------------------- 17
|
||||
section("17. v1.2 情绪双字段:老库迁移(**最容易把老用户数据搞丢的地方**)")
|
||||
#
|
||||
# ★ 直接在**内存库**上测 `_migrate`,而不是"造一个老库文件再换过去":
|
||||
# 换文件的做法被 WAL 坑过一次 —— SQLite 连着旧文件的连接、
|
||||
# 外加 -wal 里的新数据会把复制进去的老库盖掉,测出来是假阴性。
|
||||
# 内存库没有这个问题,而且不碰任何全局状态。
|
||||
import sqlite3
|
||||
|
||||
def old_db():
|
||||
"""造一个 v1.1 的 emotions 表(只有 emotion 一列)"""
|
||||
c = sqlite3.connect(":memory:")
|
||||
c.row_factory = sqlite3.Row
|
||||
c.executescript(
|
||||
"CREATE TABLE emotions (agent_id TEXT PRIMARY KEY, "
|
||||
"emotion TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL);"
|
||||
)
|
||||
c.execute(
|
||||
"INSERT INTO emotions VALUES ('a_old', '刚被师父夸了,心里偷着乐', '2026-01-01T00:00:00Z')"
|
||||
)
|
||||
c.commit()
|
||||
return c
|
||||
|
||||
conn_old = old_db()
|
||||
agentdb._migrate(conn_old)
|
||||
row = conn_old.execute("SELECT preset, text, emotion FROM emotions WHERE agent_id='a_old'").fetchone()
|
||||
check("迁移没炸(新列都加上了)", row is not None, str(row))
|
||||
check("**老的自由文本搬进了 text**", row["text"] == "刚被师父夸了,心里偷着乐", str(tuple(row)))
|
||||
check("preset 给了默认的「平常」", row["preset"] == "平常", str(tuple(row)))
|
||||
check("老的 emotion 列留着(SQLite 删列要重建表,不值当)",
|
||||
row["emotion"] == "刚被师父夸了,心里偷着乐")
|
||||
# 幂等:再迁移一次不能把 text 冲掉
|
||||
agentdb._migrate(conn_old)
|
||||
row2 = conn_old.execute("SELECT text FROM emotions WHERE agent_id='a_old'").fetchone()
|
||||
check("再迁移一次不会冲掉已有数据(幂等)", row2["text"] == row["text"], str(tuple(row2)))
|
||||
# 全新的库(表已经是新结构)跑迁移应当什么都不做
|
||||
conn_new = sqlite3.connect(":memory:")
|
||||
conn_new.row_factory = sqlite3.Row
|
||||
conn_new.executescript(agentdb.SCHEMA)
|
||||
agentdb._migrate(conn_new)
|
||||
check("新结构的库跑迁移是空操作(不报错、不动数据)", True)
|
||||
conn_old.close()
|
||||
conn_new.close()
|
||||
|
||||
section("18. v1.2 死亡规则:不能对话、不能自己复活、但用户能复活")
|
||||
dead = store.create_agent({"name": "会死的"})
|
||||
did = dead["id"]
|
||||
check("默认不是死亡", not agentdb.is_dead(did))
|
||||
tools_runtime.push_context(agentId=did, conversationId="c_probe")
|
||||
agent_tools.emotion_set({"preset": "死亡", "text": "胸口一凉,倒了下去"})
|
||||
check("AI 能把自己改成死亡", agentdb.is_dead(did))
|
||||
# ★ AI 不能自愈(需求 3.5 明文)
|
||||
try:
|
||||
agent_tools.emotion_set({"preset": "喜", "text": "我又活了"})
|
||||
check("**AI 不能把自己从死亡改活**", False, "居然改成功了")
|
||||
except ValueError as exc:
|
||||
check("**AI 不能把自己从死亡改活**", "不能自己复活" in str(exc), str(exc))
|
||||
check("死亡状态没被改掉", agentdb.is_dead(did))
|
||||
# 死亡**照常播报**给同伴(需求 3.5 明文)
|
||||
rows = agentdb.peer_emotions("w", "x", [did])
|
||||
check("死亡也播报给同伴", bool(rows) and rows[0][1] == "死亡", str(rows))
|
||||
# ★ 用户通道能改活(兜底主权)
|
||||
r = h.call(f"/api/agents/{did}/emotion", "PUT", {"preset": "喜", "text": "醒来"})
|
||||
check("**用户能把它改活**(兜底主权)", not agentdb.is_dead(did), str(r.get("emotion")))
|
||||
# 不认识的 preset 要拒绝,而且理由里要列出合法值
|
||||
try:
|
||||
agent_tools.emotion_set({"preset": "暴躁", "text": ""})
|
||||
check("不认识的 preset 被拒", False, "居然通过了")
|
||||
except ValueError as exc:
|
||||
check("不认识的 preset 被拒", "五个之一" in str(exc), str(exc))
|
||||
# 只给 text 不给 preset:保留当前 preset(emotion_set 是"只写传进来的")
|
||||
agent_tools.emotion_set({"preset": "怒", "text": "火了"})
|
||||
agentdb.emotion_set(did, text="气消了一半")
|
||||
check("只写 text 时 preset 不动",
|
||||
agentdb.emotion_state(did)["preset"] == "怒"
|
||||
and agentdb.emotion_state(did)["text"] == "气消了一半",
|
||||
str(agentdb.emotion_state(did)))
|
||||
|
||||
# ---------------------------------------------------------------- 19
|
||||
section("19. v1.2 立绘表:五档 + 回退链(需求 2.5 / 2.6)")
|
||||
#
|
||||
# 真造几个文件出来测 —— 回退链里有一环是 `os.path.isfile`(用户可能
|
||||
# 手动删过 agent-assets 里的图),不落真文件就测不到那一环。
|
||||
pic_dir = tempfile.mkdtemp(prefix="doubao-pics-")
|
||||
|
||||
def pic(name):
|
||||
p = os.path.join(pic_dir, name)
|
||||
with open(p, "wb") as fh:
|
||||
fh.write(b"\x89PNG\r\n\x1a\n" + name.encode())
|
||||
return p
|
||||
|
||||
normal, happy, sad, gone = pic("normal.png"), pic("happy.png"), pic("sad.png"), pic("deleted.png")
|
||||
os.remove(gone) # 造一个"文件被删了"的档位
|
||||
|
||||
from agent_api import portrait_of
|
||||
|
||||
# ① 旧格式(单文件名)经 normalize 之后变成只有「平常」档
|
||||
old = store.normalize_image({"front": normal})
|
||||
check("旧格式归一化成「平常」档", old["front"] == {"平常": normal}, str(old["front"]))
|
||||
check("旧格式的立绘任何 preset 都能用(回退到平常)",
|
||||
portrait_of(old, "怒") == normal, portrait_of(old, "怒"))
|
||||
|
||||
# ② 五档表:命中当前档
|
||||
five = store.normalize_image({"front": {"喜": happy, "哀": sad, "平常": normal}})
|
||||
check("命中当前档", portrait_of(five, "喜") == happy)
|
||||
check("没那一档时回退到「平常」", portrait_of(five, "怒") == normal)
|
||||
# ③ 没有平常档 → 拿字典里任何一个还能用的(用户可能只传了一档)
|
||||
only_happy = store.normalize_image({"front": {"喜": happy}})
|
||||
check("连平常档都没有时,用字典里任何一个能用的",
|
||||
portrait_of(only_happy, "死亡") == happy, portrait_of(only_happy, "死亡"))
|
||||
# ④ **文件被删了**的那一档不许返回不存在的路径(那会让界面显示空白)
|
||||
broken = store.normalize_image({"front": {"喜": gone, "平常": normal}})
|
||||
check("档位指向的文件不存在时,跳过它去回退",
|
||||
portrait_of(broken, "喜") == normal, portrait_of(broken, "喜"))
|
||||
# ⑤ 完全没图 → 空串(界面据此用内置默认人物)
|
||||
check("没有立绘时返回空串(界面用内置默认人物)",
|
||||
portrait_of(store.normalize_image({}), "平常") == "")
|
||||
check("全是坏路径时也返回空串",
|
||||
portrait_of(store.normalize_image({"front": {"喜": gone}}), "喜") == "")
|
||||
# ⑥ 归一化不丢自定义档位(用户可能自己加了需求之外的档)
|
||||
custom = store.normalize_image({"front": {"醉": sad, "平常": normal}})
|
||||
check("归一化保留自定义档位(不丢信息)", custom["front"].get("醉") == sad, str(custom["front"]))
|
||||
check("自定义档位也能被选中", portrait_of(custom, "醉") == sad)
|
||||
shutil.rmtree(pic_dir, ignore_errors=True)
|
||||
|
||||
# ---------------------------------------------------------------- 20
|
||||
section("20. v1.2 缓存友好段序(附录 C 修订,**改动最小、省的钱最多**)")
|
||||
#
|
||||
# 主流模型的上下文缓存是**前缀匹配**:一处不同则其后全部失效。
|
||||
# 所以稳定段必须在前面、易变段必须在后面。
|
||||
order = list(agent_context.SECTIONS)
|
||||
check("稳定段在最前(skills 先于 memory)",
|
||||
order.index('skills') < order.index('memory'), str(order))
|
||||
check("worldview 也在易变段之前",
|
||||
order.index('worldview') < order.index('emotion'), str(order))
|
||||
# ★ 这一条就是 v1.2 改的东西:以前 emotion 在 memory 前面,
|
||||
# 情绪一变连最长的 memory 段一起失效
|
||||
check("**emotion 在 memory 之后**(v1.2 改的就是这条)",
|
||||
order.index('emotion') > order.index('memory'), str(order))
|
||||
check("数值/状态两个易变段也在 memory 之后",
|
||||
order.index('stats') > order.index('memory')
|
||||
and order.index('status') > order.index('memory'), str(order))
|
||||
check("peer_emotions 排最后(最不可控)", order[-1] == 'peer_emotions', str(order))
|
||||
# 模板里的顺序必须和 SECTIONS 一致,否则一个说东一个说西
|
||||
tmpl = defaults.DEFAULT_PROMPT_TEMPLATE
|
||||
tmpl_order = [m for m in __import__('re').findall(r'<(\w+)>', tmpl) if m in order]
|
||||
check("模板里的段序和 SECTIONS 一致", tmpl_order == [n for n in order if n in tmpl_order], str(tmpl_order))
|
||||
# 空的段不能留下 `{stats}` 这种裸占位符
|
||||
p_bare = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a1["id"]))
|
||||
check("空段(stats/status)整段删掉,不留裸占位符", '{stats}' not in p_bare and '{status}' not in p_bare)
|
||||
|
||||
section("21. v1.2 缓存统计归一化(三家字段名完全不同)")
|
||||
import agent_loop as _loop
|
||||
|
||||
cases = [
|
||||
("DeepSeek(命中+未命中都给)",
|
||||
{"prompt_tokens": 1000, "prompt_cache_hit_tokens": 800, "prompt_cache_miss_tokens": 200}, (800, 200)),
|
||||
("Claude(只给命中,未命中要自己推)",
|
||||
{"input_tokens": 1000, "cache_read_input_tokens": 600}, (600, 400)),
|
||||
("OpenAI(嵌套在 details 里)",
|
||||
{"prompt_tokens": 1000, "prompt_tokens_details": {"cached_tokens": 400}}, (400, 600)),
|
||||
("这家不返回缓存字段", {"prompt_tokens": 1000}, (0, 0)),
|
||||
("空 usage", None, (0, 0)),
|
||||
]
|
||||
for label, usage, want in cases:
|
||||
got = _loop.cache_pair(usage)
|
||||
check(f"{label} → {want}", got == want, f"实际 {got}")
|
||||
# 累加要累加**归一化之后**的数,不是原始字段(换模型就不会丢)
|
||||
acc = _loop.add_usage({}, {"prompt_tokens": 1000, "prompt_cache_hit_tokens": 800,
|
||||
"prompt_cache_miss_tokens": 200})
|
||||
acc = _loop.add_usage(acc, {"input_tokens": 500, "cache_read_input_tokens": 400})
|
||||
check("跨提供商累加命中数", acc.get("cache_hit") == 1200, str(acc.get("cache_hit")))
|
||||
check("跨提供商累加未命中数", acc.get("cache_miss") == 300, str(acc.get("cache_miss")))
|
||||
# 落库 → 查出来
|
||||
ca = store.create_agent({"name": "缓存测试"})
|
||||
agentdb.token_add(ca["id"], "doubao-pro", 1000, 50, 800, 200)
|
||||
agentdb.token_add(ca["id"], "deepseek-r1", 500, 20, 400, 100)
|
||||
u = agentdb.token_usage(ca["id"])
|
||||
check("total 里有缓存数", u["total"].get("cacheHit") == 1200 and u["total"].get("cacheMiss") == 300,
|
||||
str(u["total"]))
|
||||
check("按模型分桶里也有",
|
||||
all("cacheHit" in m for m in u["byModel"]), str(u["byModel"]))
|
||||
# 老库(没有这两列)要能迁移上来
|
||||
conn_old_tu = sqlite3.connect(":memory:")
|
||||
conn_old_tu.row_factory = sqlite3.Row
|
||||
conn_old_tu.executescript(
|
||||
"CREATE TABLE emotions (agent_id TEXT PRIMARY KEY, emotion TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL);"
|
||||
"CREATE TABLE token_usage (id INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL,"
|
||||
" model TEXT NOT NULL DEFAULT '', input INTEGER NOT NULL DEFAULT 0,"
|
||||
" output INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL);"
|
||||
)
|
||||
agentdb._migrate(conn_old_tu)
|
||||
tcols = {r["name"] for r in conn_old_tu.execute("PRAGMA table_info(token_usage)").fetchall()}
|
||||
check("老库的 token_usage 能加上缓存两列", {"cache_hit", "cache_miss"} <= tcols, str(sorted(tcols)))
|
||||
conn_old_tu.close()
|
||||
|
||||
# ---------------------------------------------------------------- 22
|
||||
section("22. 外观槽位接口(真机上报过 500 / 图不见了)")
|
||||
#
|
||||
# ★★ 这一节是**真机反馈**倒逼出来的,两个 bug 都在这里:
|
||||
# ① `_set_asset` 里 `key` 变量被删了 → NameError → 接口 500
|
||||
# → 表现"角色图设置不了"(任何图都传不上去)
|
||||
# ② `_apply_agent_patch` 对 image 的每个值调 `_as_text`
|
||||
# → `front`(字典)被存成字符串化的字典
|
||||
# → 表现"之前设置的图像也没了"(档位读不出来 + 每读写一次多包一层)
|
||||
#
|
||||
# 教训:**探针没覆盖到的接口 = 没写过**。这个接口当时一条断言都没有。
|
||||
import agent_api as _api
|
||||
|
||||
class _H:
|
||||
def __init__(self):
|
||||
self.status = 200
|
||||
self.payload = None
|
||||
|
||||
def send_json(self, code, payload):
|
||||
self.status, self.payload = code, payload
|
||||
|
||||
hh = _H()
|
||||
|
||||
def _err(code, msg):
|
||||
hh.status, hh.payload = code, {'error': msg}
|
||||
|
||||
art_agent = store.create_agent({'name': '外观测试'})
|
||||
aid = art_agent['id']
|
||||
_small = ('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8'
|
||||
'z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==')
|
||||
|
||||
def put(key, data=_small, name='t.png'):
|
||||
hh.status, hh.payload = 200, None
|
||||
_api._set_asset(hh, 'agents', aid, {'key': key, 'name': name, 'data': data}, _err)
|
||||
return hh.status, hh.payload or {}
|
||||
|
||||
st, pl = put('front:喜')
|
||||
check("① 传「喜」档不再 500(真机就是这里挂的)", st == 200, f"{st} {pl}")
|
||||
check("返回里带 slot", pl.get('slot') == '喜', str(pl.get('slot')))
|
||||
st, pl = put('front')
|
||||
check("不带档位的 front 视为「平常」(兼容旧界面)", pl.get('slot') == '平常', str(pl.get('slot')))
|
||||
st, pl = put('front:死亡')
|
||||
check("「死亡」档也能传", st == 200 and pl.get('slot') == '死亡', f"{st} {pl}")
|
||||
st, pl = put('back')
|
||||
check("背景图能传", st == 200, f"{st} {pl}")
|
||||
st, pl = put('front:乱写')
|
||||
check("乱写的档位被拒(400 不是 500)", st == 400, f"{st} {pl}")
|
||||
|
||||
# ★★ 存下来的形状必须是**字典**,不是字符串化的字典
|
||||
img = (store.get_agent(aid) or {}).get('image') or {}
|
||||
front = img.get('front')
|
||||
check("**front 存下来还是字典**(不是字符串化)", isinstance(front, dict), str(type(front)))
|
||||
check("三个档位都在", set(front or {}) >= {'喜', '平常', '死亡'}, str(front))
|
||||
for k, v in (front or {}).items():
|
||||
check(f"档位「{k}」的值是**路径字符串**不是嵌套字典",
|
||||
isinstance(v, str) and not v.strip().startswith('{'), str(v)[:40])
|
||||
|
||||
# 回退链要能用
|
||||
check("回退链:preset=喜 命中自己的档", bool(_api.portrait_of(img, '喜')))
|
||||
check("回退链:preset=怒 退到平常", bool(_api.portrait_of(img, '怒')))
|
||||
|
||||
# 清空一个档
|
||||
st, pl = put('front:喜', data='')
|
||||
check("传空 data = 清掉那一档", st == 200 and pl.get('cleared') is True, f"{st} {pl}")
|
||||
img2 = (store.get_agent(aid) or {}).get('image') or {}
|
||||
check("清掉之后「喜」不在字典里了", '喜' not in (img2.get('front') or {}), str(img2.get('front')))
|
||||
check("别的档**没被连累**", '平常' in (img2.get('front') or {}), str(img2.get('front')))
|
||||
|
||||
# ★★ 老脏数据要能救回来(用户磁盘上可能真的有)
|
||||
shelled = store.normalize_image({'front': "{'平常': 'C:/x/a.png'}"})
|
||||
check("字符串化的字典能解套", shelled.get('front') == {'平常': 'C:/x/a.png'}, str(shelled.get('front')))
|
||||
nested = store.normalize_image({'front': {'平常': "{'平常': 'C:/y/b.png'}"}})
|
||||
check("嵌套一层也能摊平", nested.get('front') == {'平常': 'C:/y/b.png'}, str(nested.get('front')))
|
||||
check("解不开的垃圾文本当空处理(不抛异常)",
|
||||
store.normalize_image({'front': '{不是字典}'}).get('front') == {},
|
||||
str(store.normalize_image({'front': '{不是字典}'}).get('front')))
|
||||
check("老格式(单个文件名)还是认",
|
||||
store.normalize_image({'front': 'old.png'}).get('front') == {'平常': 'old.png'})
|
||||
|
||||
# ---------------------------------------------------------------- 23
|
||||
section("23. 大图上传:请求体上限 + 错误信息(真机上报过「背景图设置不了」)")
|
||||
#
|
||||
# ★★ 真机现场:用户选的是**手机相册里的照片**(30~55MB),base64 之后
|
||||
# 38~73MB。read_json_body 的默认上限是 4MB,于是请求体一进去就被判
|
||||
# 「请求体过大」;而那个异常被 body() 吞成空 dict,
|
||||
# 最后报出来的是「不认识的外观槽位」—— 和真实原因毫无关系的一句话,
|
||||
# 用户只看到"设置不了",查的人也会往槽位名上去找。
|
||||
#
|
||||
# ★ 这一节**必须走 handle()**,不能像上一节那样直接调 _set_asset:
|
||||
# 上限是在 handle 里的 `body()` 那一层卡的,绕过它就等于没测。
|
||||
# (第 22 节正是直接调 _set_asset 的 —— 所以它一直没盖到这条路径。)
|
||||
big = store.create_agent({'name': '大图测试'})
|
||||
big_id = big['id']
|
||||
|
||||
h.body_error_exc = None
|
||||
h.last_limit = None
|
||||
pl = h.call(f'/api/agents/{big_id}/asset', 'POST',
|
||||
{'key': 'back', 'name': 'bg.png', 'data': _small})
|
||||
check("图片上传正常返回", h.status == 200 and bool(pl.get('path')), f"{h.status} {pl}")
|
||||
check("图片这条路的请求体上限被单独放行(不是默认的 4MB)",
|
||||
h.last_limit == _api.UPLOAD_BODY_LIMIT,
|
||||
f"实际收到 {h.last_limit},期望 {_api.UPLOAD_BODY_LIMIT}")
|
||||
|
||||
# 两个上限必须自洽:内核允许单张图到 20MB,base64 之后是 4/3 倍。
|
||||
# 请求体上限比它小的话,就会出现"内核说这图可以,通道却传不进来"
|
||||
need = 20 * 1024 * 1024 * 4 // 3
|
||||
check("请求体上限装得下内核允许的最大图(20MB → base64 约 27MB)",
|
||||
_api.UPLOAD_BODY_LIMIT > need,
|
||||
f"{_api.UPLOAD_BODY_LIMIT} 要 > {need}")
|
||||
|
||||
# ★★ 请求体读失败时,必须报真正的原因
|
||||
h.body_error_exc = '请求体过大'
|
||||
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': 'back', 'data': _small})
|
||||
check("请求体读不出来时报的是真原因",
|
||||
h.status == 400 and '请求体过大' in str(pl.get('error', '')),
|
||||
f"{h.status} {pl}")
|
||||
check("不再把「请求体过大」伪装成「不认识的外观槽位」",
|
||||
'不认识的外观槽位' not in str(pl.get('error', '')),
|
||||
str(pl.get('error')))
|
||||
h.body_error_exc = None
|
||||
|
||||
# 正常的参数错误不能被这次改动带坏
|
||||
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': '乱写的槽位', 'data': _small})
|
||||
check("槽位名写错仍然报「不认识的外观槽位」",
|
||||
h.status == 400 and '不认识的外观槽位' in str(pl.get('error', '')),
|
||||
f"{h.status} {pl}")
|
||||
|
||||
# 上一次的失败不能跟着到下一个请求上(body_error 是挂在 handler 上的)
|
||||
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': 'back', 'data': _small})
|
||||
check("上一次失败不污染下一次请求", h.status == 200 and 'error' not in pl, f"{h.status} {pl}")
|
||||
|
||||
# 世界观走的是同一个 _set_asset —— 上限也得跟上,别只改一边
|
||||
world = store.create_resource('worldviews', {'name': '大图世界观', 'setting': ''}) or {}
|
||||
world_id = world.get('id')
|
||||
if world_id:
|
||||
h.last_limit = None
|
||||
pl = h.call(f'/api/worldviews/{world_id}/asset', 'POST', {'key': 'back', 'data': _small})
|
||||
check("世界观那条路也放行了(同一个 _set_asset,别只改一边)",
|
||||
h.status == 200 and h.last_limit == _api.UPLOAD_BODY_LIMIT,
|
||||
f"{h.status} limit={h.last_limit} {pl}")
|
||||
|
||||
# ★ 同一类坑还有四处:四种**包导入**也是 base64 进 JSON。
|
||||
# 带外观图片的智能体包 zip 上到十几 MB,走默认的 4MB 一样进不来。
|
||||
# 这里不要求导入成功(空包必然失败),只要求**上限确实传下去了**。
|
||||
for path in ('/api/agents/import', '/api/worldviews/import', '/api/rulepacks/import'):
|
||||
h.last_limit = None
|
||||
h.call(path, 'POST', {})
|
||||
check(f"{path} 也放行了(包里有图片时才不会卡在 4MB)",
|
||||
h.last_limit == _api.UPLOAD_BODY_LIMIT,
|
||||
f"limit={h.last_limit}")
|
||||
|
||||
# ---------------------------------------------------------------- 24
|
||||
section("24. 换图时新旧同名(真机上报过「同一张图传第二次就没了」)")
|
||||
#
|
||||
# ★★ 落盘名是 `<槽位>-<原始文件名>`,所以**同一个文件传第二次时新旧同名**。
|
||||
# 原来的顺序是"写新的 → 删旧的",而旧路径正好就是新路径 ——
|
||||
# 刚写的那张被自己删掉,image 里留下一个指向不存在文件的路径:
|
||||
# 资源目录空着,界面回退到默认图。表现是"第二次传同一张图就没了"。
|
||||
#
|
||||
# 第一次传时名字来自 SAF 的 segment(`image_1000018033` 这种),
|
||||
# 和第二次不同名,所以随手试一次碰不到 —— 必须**故意传两次同名**才复现。
|
||||
twice = store.create_agent({'name': '重传测试'})
|
||||
tid = twice['id']
|
||||
|
||||
def put_named(key, name):
|
||||
return h.call(f'/api/agents/{tid}/asset', 'POST',
|
||||
{'key': key, 'name': name, 'data': _small})
|
||||
|
||||
pl1 = put_named('back', 'same.png')
|
||||
path1 = pl1.get('path') or ''
|
||||
check("第一次传:文件确实落了盘", bool(path1) and os.path.isfile(path1), path1)
|
||||
|
||||
pl2 = put_named('back', 'same.png')
|
||||
path2 = pl2.get('path') or ''
|
||||
check("第二次传同名文件:路径不变(本来就是同一个文件)", path1 == path2, f"{path1} vs {path2}")
|
||||
check("**第二次传完文件还在**(旧版在这里把它自己删了)",
|
||||
bool(path2) and os.path.isfile(path2),
|
||||
f"{path2} 存在={os.path.isfile(path2) if path2 else None}")
|
||||
img = (store.get_agent(tid) or {}).get('image') or {}
|
||||
check("image 里指的是一个真实存在的文件",
|
||||
bool(img.get('back')) and os.path.isfile(img['back']), str(img.get('back')))
|
||||
|
||||
# 立绘那条分支是同一份逻辑,也要过一遍 —— 别只修一边
|
||||
pf1 = put_named('front:喜', 'same.png')
|
||||
pf2 = put_named('front:喜', 'same.png')
|
||||
fpath = pf2.get('path') or ''
|
||||
check("立绘连传两次同名文件也还在", bool(fpath) and os.path.isfile(fpath),
|
||||
f"{fpath} 存在={os.path.isfile(fpath) if fpath else None}")
|
||||
check("立绘两次的路径相同", (pf1.get('path') or '') == fpath, f"{pf1.get('path')} vs {fpath}")
|
||||
|
||||
# ★ 反向:换一张**不同名**的图时,旧文件必须真的被清掉
|
||||
# (别为了修上面的问题,把"不然越攒越多"的清理一起弄没了)
|
||||
pl3 = put_named('back', 'other.png')
|
||||
path3 = pl3.get('path') or ''
|
||||
check("换不同名的新图:新文件在", bool(path3) and os.path.isfile(path3), path3)
|
||||
check("换不同名的新图:**旧文件被清掉了**", not os.path.isfile(path2), f"{path2} 还在")
|
||||
|
||||
# ---------------------------------------------------------------- 25
|
||||
section("25. 工具调用明细要落库(真机反馈「工具怎么重启就不显示了」)")
|
||||
#
|
||||
# ★ 界面上那些"工具卡片"(调了什么、成没成、返回什么)以前只有**流式那一刻**
|
||||
# 看得到 —— 因为这份明细从来没落过库,重启 App 就全没了。
|
||||
# 现在 `agent_loop` 收集 → `app.py` 落进消息 → 客户端解析。
|
||||
# 三处缺一处都白搭,所以逐处断言(这是"改一半"的高发区)。
|
||||
_kd = os.path.dirname(os.path.abspath(__file__))
|
||||
_loop = open(os.path.join(_kd, '..', 'android', 'kernel', 'agent_loop.py'),
|
||||
encoding='utf-8').read()
|
||||
_app2 = open(os.path.join(_kd, '..', 'android', 'kernel', 'app.py'),
|
||||
encoding='utf-8').read()
|
||||
check("agent_loop 收集了明细",
|
||||
'tool_trace = []' in _loop and 'tool_trace.append(' in _loop,
|
||||
"没有 tool_trace —— 工具卡片只在流式那一刻存在")
|
||||
check("agent_loop 把它放进了**两条** return(正常收尾 + 轮次用尽)",
|
||||
_loop.count("'toolTrace': tool_trace") >= 2,
|
||||
f"只有 {_loop.count(chr(39) + 'toolTrace' + chr(39) + ': tool_trace')} 处")
|
||||
check("app.py 落库时存了它", "'toolTrace': result.get('toolTrace')" in _app2,
|
||||
"engine 收好了但没存 —— 重启照样没")
|
||||
|
||||
# ---------------------------------------------------------------- 26
|
||||
section("26. 状态管理:用户能直接加/清(AI 只有 grant_status,只能加)")
|
||||
#
|
||||
# ★★ 真机/文档里暴露的缺口:AI 手里**没有任何工具能移除状态**,
|
||||
# 于是 `persistent` 状态一旦挂上就永远下不来、`timed` 的也只能干等。
|
||||
# 用户是规则的主人,[状态数值] 页上必须能直接清掉、也能手动挂一个。
|
||||
#
|
||||
# 这里走的是**真实 HTTP 路径**(`h.call` → `agent_api.handle`),
|
||||
# 不是直接调 `rule_engine.drop_status` —— 直接调的话测的是
|
||||
# "函数逻辑对不对",不是"界面上那个按钮能不能用"。
|
||||
pack = store.create_resource("rulepacks", {
|
||||
"name": "状态测试包",
|
||||
"info": {
|
||||
"stats": [{"name": "好感度", "min": 0, "max": 100}],
|
||||
"statuses": [
|
||||
{"name": "中毒", "kind": "timed", "turns": 3},
|
||||
{"name": "庇佑", "kind": "persistent"},
|
||||
],
|
||||
},
|
||||
"scripts": {},
|
||||
})
|
||||
# 挂到 a1 所在的世界观(规则包挂在**世界观**上,不是智能体 —— §3.6)
|
||||
store.update_resource("worldviews", wv["id"], {"rulePackId": pack["id"]})
|
||||
rule_engine.sync_defs(pack["id"])
|
||||
|
||||
st, pl = h.status, None
|
||||
base = h.call("/api/agents/%s/stats" % a1["id"], "GET")
|
||||
check("状态数值接口能读", base.get("rulePackId") == pack["id"], str(base.get("rulePackId")))
|
||||
check("**带了可加的状态定义**(界面的「加一个」靠它)",
|
||||
[d.get("name") for d in (base.get("statusDefs") or [])] == ["中毒", "庇佑"],
|
||||
str([d.get("name") for d in (base.get("statusDefs") or [])]))
|
||||
check("一开始身上没状态", (base.get("statuses") or []) == [], str(base.get("statuses")))
|
||||
|
||||
# 加一个定时状态
|
||||
after = h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"action": "addStatus", "name": "中毒"})
|
||||
names_now = [x.get("name") for x in (after.get("statuses") or [])]
|
||||
check("**用户能手动挂状态**", names_now == ["中毒"], str(names_now))
|
||||
check("定时状态带剩余轮数",
|
||||
(after["statuses"][0].get("remaining") or 0) >= 1, str(after["statuses"][0]))
|
||||
|
||||
# 加一个持久状态
|
||||
after = h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"action": "addStatus", "name": "庇佑"})
|
||||
by_name = {x.get("name"): x for x in (after.get("statuses") or [])}
|
||||
check("持久状态也挂上了", "庇佑" in by_name, str(list(by_name)))
|
||||
check("持久状态记 -1(不会自己过期)",
|
||||
int(by_name["庇佑"].get("remaining") or 0) == -1, str(by_name.get("庇佑")))
|
||||
|
||||
# 清掉一个
|
||||
after = h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"action": "dropStatus", "name": "中毒"})
|
||||
check("**用户能直接清掉状态**(AI 没这个能力)",
|
||||
[x.get("name") for x in (after.get("statuses") or [])] == ["庇佑"],
|
||||
str([x.get("name") for x in (after.get("statuses") or [])]))
|
||||
|
||||
# 清持久状态(这是之前唯一清不掉的那类)
|
||||
after = h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"action": "dropStatus", "name": "庇佑"})
|
||||
check("**持久状态也能清掉**", (after.get("statuses") or []) == [],
|
||||
str(after.get("statuses")))
|
||||
|
||||
# 不存在 / 没定义的状态名要报错,不能静默成功
|
||||
h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"action": "addStatus", "name": "不存在的状态"})
|
||||
check("加一个没定义的状态 → 404(不是静默成功)", h.status == 404, str(h.status))
|
||||
|
||||
# 老行为不能被破坏:不带 action 时还是改数值
|
||||
old = h.call("/api/agents/%s/stats" % a1["id"], "POST",
|
||||
{"name": "好感度", "value": 42})
|
||||
check("不带 action 仍然是改数值(老客户端不受影响)",
|
||||
int(next(x for x in old["stats"] if x["name"] == "好感度")["value"]) == 42,
|
||||
str(old.get("stats")))
|
||||
|
||||
# ---- 批量接口(智能体卡片要显示数值)----
|
||||
#
|
||||
# ★ 用户要求「数字界面在智能体卡片里展示」。选择页每张卡片都要显示
|
||||
# 数值/状态,所以需要**一次拿全** —— 一个一个拉 N 次会拖垮列表。
|
||||
allst = h.call("/api/agents/stats", "GET")
|
||||
box = allst.get("stats") or {}
|
||||
check("**批量接口能读**(卡片靠它)", isinstance(box, dict) and len(box) > 0, str(len(box)))
|
||||
check("名单里只有**挂了规则包**的智能体",
|
||||
a1["id"] in box, str(list(box))[:120])
|
||||
one = box.get(a1["id"]) or {}
|
||||
check("批量里带着数值", len(one.get("stats") or []) > 0, str(one.get("stats")))
|
||||
check("批量里带着状态", isinstance(one.get("statuses"), list), str(one.get("statuses")))
|
||||
check("**批量不带 statusDefs**(卡片用不上,白传一遍费流量)",
|
||||
"statusDefs" not in one, str(list(one))[:120])
|
||||
|
||||
# ---------------------------------------------------------------- 汇总
|
||||
print()
|
||||
if fails:
|
||||
|
||||
207
scripts/probe-context-window.py
Normal file
@@ -0,0 +1,207 @@
|
||||
"""对话上下文窗口的探针(v1.2 §4.3)。
|
||||
|
||||
纯函数,所以能逐条钉死。重点在**成批对齐**那条 —— 它最容易实现成
|
||||
"超一点就裁一点",那样每轮前缀都变、缓存一次都命中不了,
|
||||
**比不裁还贵**,而且从界面上完全看不出来(功能是对的、只是变慢了)。
|
||||
|
||||
用法:`python scripts/probe-context-window.py`
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-ctx-")
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
if cond:
|
||||
print(f" ✓ {label}")
|
||||
else:
|
||||
fails.append(label)
|
||||
print(f" ✗ {label} {detail}")
|
||||
|
||||
|
||||
import context_window as W # noqa: E402
|
||||
|
||||
|
||||
def convo(n, important_at=()):
|
||||
"""造 n 轮对话(每轮 user + assistant);important_at 里的轮号标成重要"""
|
||||
out = []
|
||||
for i in range(n):
|
||||
out.append({'role': 'user', 'content': f'问{i}',
|
||||
'important': i in important_at})
|
||||
out.append({'role': 'assistant', 'content': f'答{i}'})
|
||||
return out
|
||||
|
||||
|
||||
def rounds_of(msgs):
|
||||
"""数一下这批消息里有几轮(受支持的最长连续)"""
|
||||
return len(W.split_rounds(msgs))
|
||||
|
||||
|
||||
def main():
|
||||
print("\n=== 1. 没超窗口:全带 ===")
|
||||
r = W.trim(convo(5), rounds=20)
|
||||
check("5 轮 < 20 轮 → 全带", r['kept'] == 10 and r['dropped'] == 0, str(r))
|
||||
check("reason 是空(没动过)", r['reason'] == '', str(r['reason']))
|
||||
|
||||
print("\n=== 2. ★ 成批对齐:超一点**不裁**(这条最容易做错)===")
|
||||
#
|
||||
# 窗口 20、批量 5:21 轮时超出 1 轮 —— 应当**原样放行**。
|
||||
# 实现成"超了就裁"的话,每轮都会裁掉一条 → 前缀每轮都变 → 缓存全废。
|
||||
for extra, should_cut in ((1, False), (3, False), (4, False), (5, True), (7, True), (12, True)):
|
||||
n = 20 + extra
|
||||
r = W.trim(convo(n), rounds=20, batch=5)
|
||||
cut = r['reason'] == 'window'
|
||||
check(f"{n} 轮(超 {extra} 轮)→ {'裁' if should_cut else '先不动'}",
|
||||
cut == should_cut, f"reason={r['reason']} kept={r['kept']}")
|
||||
# 裁的时候要对齐到 batch 的倍数
|
||||
r = W.trim(convo(27), rounds=20, batch=5)
|
||||
check("27 轮(超 7)→ 裁 5 轮留 22 轮", r['keptRounds'] == 22, str(r))
|
||||
r = W.trim(convo(32), rounds=20, batch=5)
|
||||
check("32 轮(超 12)→ 裁 10 轮留 22 轮", r['keptRounds'] == 22, str(r))
|
||||
r = W.trim(convo(25), rounds=20, batch=5)
|
||||
check("25 轮(超 5)→ 正好裁 5 轮留 20 轮", r['keptRounds'] == 20, str(r))
|
||||
|
||||
print("\n=== 3. 按完整轮对齐,绝不裁半轮 ===")
|
||||
for n in (21, 25, 27, 32, 50):
|
||||
r = W.trim(convo(n), rounds=20, batch=5)
|
||||
msgs = r['messages']
|
||||
# 一条 assistant 前面必须紧跟着它那一轮的 user
|
||||
bad = [i for i, m in enumerate(msgs)
|
||||
if m['role'] == 'assistant' and (i == 0 or msgs[i - 1]['role'] != 'user')]
|
||||
check(f"{n} 轮裁完没有孤立的 assistant", not bad, str(bad[:3]))
|
||||
# 保留的条数必须是偶数(整轮)
|
||||
check(f"{n} 轮裁完是整轮(条数是偶数)", len(msgs) % 2 == 0, str(len(msgs)))
|
||||
|
||||
print("\n=== 4. 重要标记:破格携带、按原始时间序插回 ===")
|
||||
# 第 1、3 轮的 **user 消息**标了重要(assistant 没标)—— 它们会被裁掉
|
||||
r = W.trim(convo(30, important_at={1, 3}), rounds=20, batch=5)
|
||||
msgs = r['messages']
|
||||
contents = [m['content'] for m in msgs]
|
||||
check("裁掉的那批里的重要消息被捞回来了", r.get('rescued') == 2, str(r.get('rescued')))
|
||||
check("捞回来的在结果里", '问1' in contents and '问3' in contents, str(contents[:6]))
|
||||
# ★ 关键:**按原始时间序**插回,不是塞到最前面
|
||||
check("**按原始时间序插入,不是塞到最前面**",
|
||||
contents.index('问1') < contents.index('问10'),
|
||||
f"问1 在 {contents.index('问1')}、问10 在 {contents.index('问10')}")
|
||||
check("顺序整体单调(捞回的没打乱因果)",
|
||||
contents.index('问1') < contents.index('问3') < contents.index('问10'),
|
||||
str([contents.index(x) for x in ('问1', '问3', '问10')]))
|
||||
# 没标重要的那批就真的丢了
|
||||
check("没标记的轮次确实丢了(不做摘要、不假装记得)", '问0' not in contents)
|
||||
|
||||
print("\n=== 5. resolve:智能体 > 全局 > 默认 ===")
|
||||
check("都没配用默认 20/5", W.resolve({}, {}) == (20, 5), str(W.resolve({}, {})))
|
||||
check("全局配了就用全局", W.resolve({'contextWindow': 30, 'contextBatch': 3}, {}) == (30, 3))
|
||||
check("智能体配了压过全局",
|
||||
W.resolve({'contextWindow': 30}, {'contextWindow': 10})[0] == 10)
|
||||
check("超出上下限会被夹住", W.resolve({'contextWindow': 99999}, {})[0] == W.MAX_ROUNDS)
|
||||
check("填 0 / 乱填回落到默认",
|
||||
W.resolve({'contextWindow': 0}, {})[0] == 20 and W.resolve({'contextWindow': 'x'}, {})[0] == 20)
|
||||
|
||||
print("\n=== 6. ★ 字节冻结:绝不原地改历史 ===")
|
||||
src = [{'role': 'user', 'content': '原话', 'important': True, 'usage': {'input': 5}}]
|
||||
snapshot = [dict(m) for m in src]
|
||||
out = W.strip_for_model(src[0])
|
||||
check("输出只留 role/content(界面字段不带进模型)",
|
||||
set(out.keys()) == {'role', 'content'}, str(sorted(out)))
|
||||
check("**原对象一个字节都没动**", src == snapshot, str(src))
|
||||
check("输出是**新对象**(不是同一个引用)", out is not src[0])
|
||||
r = W.trim(src, rounds=20)
|
||||
check("trim 不改原列表的元素(字节冻结)", src == snapshot, str(src))
|
||||
# ★ 这里比的是**身份**不是内容:内容本来就该一样,要确认的是
|
||||
# 返回的是一个**新列表**(调用方拿到之后改它,不能影响到传进去的那个)
|
||||
check("trim 返回的是新列表(不是同一个引用)", r['messages'] is not src)
|
||||
|
||||
print("\n=== 7. 边界 ===")
|
||||
check("空历史不炸", W.trim([], 20)['kept'] == 0)
|
||||
check("rounds=0 表示不限", W.trim(convo(100), 0)['dropped'] == 0)
|
||||
check("全是 user(没有 assistant)也能切轮",
|
||||
W.split_rounds([{'role': 'user', 'content': 'a'}, {'role': 'user', 'content': 'b'}]).__len__() == 2)
|
||||
check("非 dict 的东西被跳过", W.trim([{'role': 'user'}, 'noise', None], 20)['kept'] == 1)
|
||||
check("describe 不炸", isinstance(W.describe(W.trim(convo(30), 20, 5)), str))
|
||||
|
||||
print("\n=== 8. 标记重要:从存储到裁剪的整条路 ===")
|
||||
#
|
||||
# 这一节测的是**端到端**:界面调接口 → 存库 → 裁剪时读它。
|
||||
# 中间任何一环断了,用户看到的现象都是"我标了,但它还是被裁掉了"。
|
||||
import store
|
||||
|
||||
conv = store.create_conversation('测试', agent_id='A')
|
||||
store.append_messages(conv['id'], [
|
||||
{'role': 'user', 'content': '记住这句'},
|
||||
{'role': 'assistant', 'content': '好的'},
|
||||
])
|
||||
check("新消息默认没标记", not (store.get_conversation(conv['id'])['messages'][0].get('important')))
|
||||
m = store.mark_important(conv['id'], 0, True)
|
||||
check("标记上了", m and m.get('important') is True, str(m))
|
||||
# ★ 关键:标记**不能动 content**(需求 4.3 的"字节冻结")
|
||||
check("**content 一个字节都没动**(字节冻结)", m.get('content') == '记住这句', str(m))
|
||||
check("越界下标返回 None(不抛异常)", store.mark_important(conv['id'], 99, True) is None)
|
||||
check("不存在的会话返回 None", store.mark_important('nope', 0, True) is None)
|
||||
check("能取消标记", store.mark_important(conv['id'], 0, False).get('important') is False)
|
||||
# 端到端:标过的消息在裁剪时被捞回
|
||||
msgs = []
|
||||
for i in range(30):
|
||||
msgs.append({'role': 'user', 'content': f'问{i}', 'important': i == 0})
|
||||
msgs.append({'role': 'assistant', 'content': f'答{i}'})
|
||||
r = W.trim(msgs, 20, 5)
|
||||
check("端到端:标记过的老消息**没被裁掉**",
|
||||
any(m['content'] == '问0' for m in r['messages']), str(r.get('rescued')))
|
||||
check("没标记的老消息被裁掉了", not any(m['content'] == '问5' for m in r['messages']))
|
||||
|
||||
print("\n=== 9. ★★ 按内容定位(下标定位踩过的坑)===")
|
||||
#
|
||||
# 界面上那份消息列表和存储里那份**不保证一一对应**(本地生成的内容、
|
||||
# 还没落地的流式消息……)。按下标"长按第 3 条"会把标记打到第 1 条上,
|
||||
# 而且**静默标错** —— 真机上就是这么错的。
|
||||
c3 = store.create_conversation('定位', agent_id='A')
|
||||
store.append_messages(c3['id'], [
|
||||
{'role': 'user', 'content': '第一句'},
|
||||
{'role': 'assistant', 'content': '回一句'},
|
||||
{'role': 'user', 'content': '第三句'},
|
||||
])
|
||||
m = store.mark_important_by_content(c3['id'], '第三句', 'user', True)
|
||||
check("按内容标到了**那一条**", m and m.get('content') == '第三句', str(m))
|
||||
flags = [(x['content'], bool(x.get('important')))
|
||||
for x in store.get_conversation(c3['id'])['messages']]
|
||||
check("**只标了那一条**(别的没被误标)",
|
||||
flags == [('第一句', False), ('回一句', False), ('第三句', True)], str(flags))
|
||||
check("内容对不上 → None(**绝不猜一条标上去**)",
|
||||
store.mark_important_by_content(c3['id'], '没有这句话', 'user', True) is None)
|
||||
check("空内容 → None", store.mark_important_by_content(c3['id'], '', 'user', True) is None)
|
||||
check("不存在的会话 → None", store.mark_important_by_content('nope', '第一句', 'user', True) is None)
|
||||
# 重复内容:从后往前找(用户长按的通常是靠后那条)
|
||||
c4 = store.create_conversation('重复', agent_id='A')
|
||||
store.append_messages(c4['id'], [
|
||||
{'role': 'user', 'content': '一样'},
|
||||
{'role': 'user', 'content': '别的'},
|
||||
{'role': 'user', 'content': '一样'},
|
||||
])
|
||||
store.mark_important_by_content(c4['id'], '一样', 'user', True)
|
||||
flags4 = [bool(x.get('important')) for x in store.get_conversation(c4['id'])['messages']]
|
||||
check("重复内容标**最后**一条(从后往前找)", flags4 == [False, False, True], str(flags4))
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
155
scripts/probe-doubao-web-metrics.mjs
Normal file
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* 精测豆包网页版布局:有效 CSS 变量、组件尺寸/间距、字体。
|
||||
* 结果写到 reference/doubao-web-mirror/styles/metrics.json
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO = path.resolve(HERE, '..');
|
||||
const OUT = path.join(REPO, 'reference', 'doubao-web-mirror');
|
||||
const EDGE = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
|
||||
const PORT = 9613;
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
const child = spawn(EDGE, ['--headless=new', '--no-sandbox', '--disable-gpu', '--disable-crash-reporter', '--no-first-run',
|
||||
'--disable-extensions', '--hide-scrollbars', `--remote-debugging-port=${PORT}`,
|
||||
`--user-data-dir=${path.join(os.tmpdir(), 'doubao-scrape-profile')}`, '--window-size=1440,900', 'about:blank'],
|
||||
{ stdio: 'ignore', windowsHide: true });
|
||||
|
||||
async function findPage() {
|
||||
for (let i = 0; i < 80; i += 1) {
|
||||
try {
|
||||
const list = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();
|
||||
const page = list.find((t) => t.type === 'page');
|
||||
if (page?.webSocketDebuggerUrl) return page;
|
||||
} catch { /* not up */ }
|
||||
await sleep(300);
|
||||
}
|
||||
throw new Error('CDP 连不上');
|
||||
}
|
||||
function connect(wsUrl) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('open', () => resolve({
|
||||
send(method, params = {}) {
|
||||
const msgId = ++id;
|
||||
ws.send(JSON.stringify({ id: msgId, method, params }));
|
||||
return new Promise((res, rej) => pending.set(msgId, { res, rej }));
|
||||
},
|
||||
close() { ws.close(); },
|
||||
}));
|
||||
ws.addEventListener('error', reject);
|
||||
ws.addEventListener('message', (ev) => {
|
||||
const msg = JSON.parse(ev.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
const { res, rej } = pending.get(msg.id);
|
||||
pending.delete(msg.id);
|
||||
msg.error ? rej(new Error(JSON.stringify(msg.error))) : res(msg.result);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const page = await findPage();
|
||||
const cdp = await connect(page.webSocketDebuggerUrl);
|
||||
await cdp.send('Page.enable');
|
||||
await cdp.send('Runtime.enable');
|
||||
await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false });
|
||||
await cdp.send('Page.navigate', { url: 'https://www.doubao.com/chat/' });
|
||||
await sleep(15000);
|
||||
|
||||
const expr = `(() => {
|
||||
const pick = (el) => {
|
||||
if (!el) return null;
|
||||
const s = getComputedStyle(el); const r = el.getBoundingClientRect();
|
||||
return {
|
||||
tag: el.tagName, cls: String(el.className).slice(0, 90),
|
||||
text: (el.innerText || '').trim().replace(/\\n/g, ' / ').slice(0, 40),
|
||||
rect: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)],
|
||||
bg: s.backgroundColor, color: s.color, fs: s.fontSize, fw: s.fontWeight, lh: s.lineHeight,
|
||||
ls: s.letterSpacing, br: s.borderRadius, border: s.border, shadow: s.boxShadow, pad: s.padding,
|
||||
gap: s.gap, display: s.display, align: s.alignItems, justify: s.justifyContent,
|
||||
};
|
||||
};
|
||||
const q = (sel) => document.querySelector(sel);
|
||||
const byText = (needle, tag) => [...document.querySelectorAll(tag || '*')].reverse()
|
||||
.find((el) => (el.innerText || '').trim() === needle);
|
||||
const root = document.documentElement;
|
||||
const cs = getComputedStyle(root);
|
||||
const names = ['--dbx-text-primary','--dbx-text-secondary','--dbx-text-tertiary','--dbx-text-disable',
|
||||
'--dbx-bg-body-web','--dbx-bg-base-web','--dbx-bg-base-1','--dbx-bg-base-2','--dbx-bg-base-3','--dbx-bg-float',
|
||||
'--dbx-color-blue-100','--dbx-color-blue-400','--dbx-color-blue-500','--dbx-color-blue-600',
|
||||
'--dbx-line-primary','--dbx-line-secondary','--dbx-border-primary','--dbx-static-white',
|
||||
'--dbx-neutral-700','--dbx-neutral-1000-8','--dbx-fill-primary-50','--dbx-function-danger','--dbx-function-success',
|
||||
'--dbx-fill-secondary','--dbx-fill-tertiary','--dbx-fill-quaternary','--dbx-brand-primary','--dbx-brand-blue'];
|
||||
const vars = {};
|
||||
for (const n of names) { const v = cs.getPropertyValue(n).trim(); if (v) vars[n] = v; }
|
||||
const out = { vars, elements: {} };
|
||||
const aside = q('aside') || q('nav');
|
||||
out.elements.sidebar = pick(aside ? aside.parentElement : null);
|
||||
out.elements.sidebarPanel = pick(aside);
|
||||
out.elements.brand = pick(byText('豆包', 'div') || byText('豆包', 'span'));
|
||||
const navTexts = ['新工作任务', '新对话', '项目', 'API 服务', '更多'];
|
||||
out.elements.navItems = {};
|
||||
for (const t of navTexts) {
|
||||
const label = [...document.querySelectorAll('div,span')].find((el) => (el.innerText || '').trim() === t);
|
||||
if (!label) continue;
|
||||
let row = label;
|
||||
for (let i = 0; i < 4 && row.parentElement; i += 1) row = row.parentElement;
|
||||
out.elements.navItems[t] = { label: pick(label), row: pick(row) };
|
||||
}
|
||||
out.elements.greeting = pick(byText('有什么我能帮你的吗?', 'div'));
|
||||
const chips = [...document.querySelectorAll('div')].filter((el) => /一吨100元|一万步|欧元|胃真的/.test(el.innerText || '') );
|
||||
const chip = chips.filter((el) => { const r = el.getBoundingClientRect(); return r.width > 100 && r.height > 20 && r.height < 80; })
|
||||
.sort((a, b) => a.getBoundingClientRect().height - b.getBoundingClientRect().height)[0];
|
||||
out.elements.recommendChip = pick(chip);
|
||||
out.elements.recommendLabel = pick(byText('为你推荐', 'div') || byText('为你推荐', 'span'));
|
||||
const ta = q('textarea');
|
||||
out.elements.textarea = pick(ta);
|
||||
if (ta) {
|
||||
let box = ta;
|
||||
for (let i = 0; i < 6 && box.parentElement; i += 1) box = box.parentElement;
|
||||
out.elements.inputWrap = pick(box);
|
||||
// 输入框最外层:找有较大圆角和边框的祖先
|
||||
let cur = ta; const chain = [];
|
||||
for (let i = 0; i < 10 && cur; i += 1) { chain.push(pick(cur)); cur = cur.parentElement; }
|
||||
out.elements.inputChain = chain;
|
||||
}
|
||||
// 顶部工具条
|
||||
const collapseBtn = [...document.querySelectorAll('button,div')].find((el) => el.getBoundingClientRect().x > 280 && el.getBoundingClientRect().x < 330 && el.getBoundingClientRect().y < 80 && el.getBoundingClientRect().y > 0);
|
||||
out.elements.topCollapseIcon = pick(collapseBtn);
|
||||
const loginBtn = byText('登录', 'button') || byText('登录', 'div');
|
||||
out.elements.loginBtn = pick(loginBtn);
|
||||
// 字体
|
||||
out.fonts = [];
|
||||
for (const sheet of document.styleSheets) {
|
||||
try { for (const rule of sheet.cssRules) if (rule instanceof CSSFontFaceRule) out.fonts.push(rule.cssText.slice(0, 400)); } catch { /* */ }
|
||||
}
|
||||
out.bodyFont = getComputedStyle(document.body).fontFamily.slice(0, 120);
|
||||
out.bodyBg = getComputedStyle(document.body).backgroundColor;
|
||||
out.mainBg = pick(document.querySelector('main'));
|
||||
return JSON.stringify(out);
|
||||
})()`;
|
||||
|
||||
const r = await cdp.send('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true });
|
||||
const value = r.result?.value || '{}';
|
||||
fs.writeFileSync(path.join(OUT, 'styles', 'metrics.json'), value, 'utf8');
|
||||
try {
|
||||
const j = JSON.parse(value);
|
||||
console.log('vars:', Object.keys(j.vars || {}).length, '| navItems:', Object.keys(j.elements?.navItems || {}).length, '| fonts:', (j.fonts || []).length);
|
||||
console.log(JSON.stringify(j.vars, null, 1));
|
||||
for (const [k, v] of Object.entries(j.elements || {})) {
|
||||
if (k === 'navItems' || k === 'inputChain') continue;
|
||||
console.log(k, JSON.stringify(v));
|
||||
}
|
||||
} catch (e) { console.log('raw:', value.slice(0, 2000)); }
|
||||
cdp.close();
|
||||
child.kill();
|
||||
await sleep(300);
|
||||
process.exit(0);
|
||||
612
scripts/probe-group-chat.py
Normal file
@@ -0,0 +1,612 @@
|
||||
"""群聊仲裁的探针(v1.2 §3.9)。
|
||||
|
||||
点名制的分支有五种(用户 @ / AI 移交 / 兜底 / 被点的人死亡 / 一轮内重复移交),
|
||||
每一种都有明确的期望结果,而且**都不能报错**(报错的话用户看到的是
|
||||
"AI 卡住了",而不是"这一轮没人说话")。
|
||||
|
||||
用法:`python scripts/probe-group-chat.py`
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-group-")
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
if cond:
|
||||
print(f" ✓ {label}")
|
||||
else:
|
||||
fails.append(label)
|
||||
print(f" ✗ {label} {detail}")
|
||||
|
||||
|
||||
import agent_tools # noqa: E402
|
||||
import group_chat as G # noqa: E402
|
||||
import store # noqa: E402
|
||||
import tools_runtime # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
world = store.create_resource('worldviews', {'name': '九州'})
|
||||
a = store.create_agent({'name': '玄辰'})
|
||||
store.update_agent(a['id'], {'worldviewId': world['id']})
|
||||
a = store.get_agent(a['id'])
|
||||
b = store.create_agent({'name': '仙辰'})
|
||||
store.update_agent(b['id'], {'worldviewId': world['id']})
|
||||
b = store.get_agent(b['id'])
|
||||
outsider = store.create_agent({'name': '外人'})
|
||||
|
||||
print("\n=== 1. 会话字段(type / participants)===")
|
||||
conv = store.create_conversation('群聊', agent_id=a['id'], kind='group',
|
||||
participants=[a['id'], b['id']])
|
||||
check("type 存下来了", conv.get('type') == 'group', str(conv.get('type')))
|
||||
check("participants 存下来了", len(G.member_ids(conv)) == 2, str(G.member_ids(conv)))
|
||||
# ⚠️ `host_id` 现在**不再用于决定谁发言**(用户要求「群聊去掉主人设定」),
|
||||
# 只剩 remove_member 里「不能把最后一个人踢走」这一个用途。
|
||||
check("host_id 还在(但只表示「列表第一个」,不是发言优先级)",
|
||||
G.host_id(conv) == a['id'], G.host_id(conv))
|
||||
old = store.create_conversation('老会话')
|
||||
check("老会话默认是 single", (old.get('type') or 'single') == 'single')
|
||||
check("非法 type 会被规整成 single",
|
||||
store.create_conversation('x', kind='乱写').get('type') == 'single')
|
||||
|
||||
print("\n=== 2. 仲裁:五种分支 ===")
|
||||
names = [(x['id'], x['name']) for x in store.list_agents()]
|
||||
# ① 用户 @
|
||||
want = G.mention_in('@仙辰 你觉得呢', names)
|
||||
check("@ 能解析出人", want == b['id'], str(want))
|
||||
r = G.resolve(conv, want=want)
|
||||
check("① 被 @ 的人发言", r['speaker'] == b['id'] and r['reason'] == 'mention', str(r))
|
||||
# ② AI 移交
|
||||
r = G.resolve(conv, passed=b['id'], handoffs=0)
|
||||
check("② AI 移交的人发言", r['speaker'] == b['id'] and r['reason'] == 'handoff', str(r))
|
||||
# ③ 兜底:**按顺序轮,不设主人**(用户要求「群聊去掉主人设定」)
|
||||
r = G.resolve(conv)
|
||||
check("③ 没人点名时按顺序轮(新群从第一个开始)",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
|
||||
# ④ 被点的人死亡
|
||||
r = G.resolve(conv, passed=b['id'], alive={b['id']: False})
|
||||
check("④ **死亡的人接不了,换下一个人**",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
|
||||
check("④ 而且说明了原因(界面/日志能看懂)", '死亡' in str(r.get('note')), str(r.get('note')))
|
||||
# ⑤ 一轮内重复移交
|
||||
r = G.resolve(conv, passed=b['id'], handoffs=G.MAX_HANDOFF_PER_ROUND)
|
||||
check("⑤ 一轮内第二次移交被拒(换下一个人)",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'handoff_denied', str(r))
|
||||
# 用户 @ 不受"一轮一次"约束(那条只管 AI 的移交)
|
||||
r = G.resolve(conv, want=b['id'], handoffs=99)
|
||||
check("用户 @ 不受「一轮一次」限制(用户主权)", r['speaker'] == b['id'], str(r))
|
||||
|
||||
print("\n=== 3. @ 的解析细节 ===")
|
||||
names2 = [(a['id'], '玄辰'), (b['id'], '玄辰二号')]
|
||||
check("有重名前缀时取**最长**匹配(@玄辰二号 不该命中玄辰)",
|
||||
G.mention_in('@玄辰二号', names2) == b['id'],
|
||||
str(G.mention_in('@玄辰二号', names2)))
|
||||
check("精确匹配短的也对", G.mention_in('@玄辰', names2) == a['id'])
|
||||
check("没有 @ 时返回空", G.mention_in('随便说点什么', names2) == '')
|
||||
check("@ 不在成员里时返回空", G.mention_in('@路人', names2) == '')
|
||||
|
||||
print("\n=== 4. 成员增删(用户主权)===")
|
||||
c2 = store.create_conversation('群2', agent_id=a['id'], kind='group',
|
||||
participants=[a['id']])
|
||||
check("能加成员", G.add_member(c2, b['id']) is True)
|
||||
check("重复加返回 False(不重复不报错)", G.add_member(c2, b['id']) is False)
|
||||
# ★ 语义变了(用户要求「群聊去掉主人设定」):现在**谁都能移出**,
|
||||
# 唯一的拒绝条件是"不能删到一个人都不剩"。所以原来那条
|
||||
# "主智能体不能被移出" 已经废了 —— 断言跟着改。
|
||||
check("第一个人也能移出(没有主人这回事了)", G.remove_member(c2, a['id']) is True)
|
||||
check("删到剩一个 → 退回单聊",
|
||||
not G.is_group(c2) and len(G.member_ids(c2)) == 1,
|
||||
f"type={c2.get('type')} participants={G.member_ids(c2)}")
|
||||
check("**最后一个人不能被移出**(移掉群就空了)", G.remove_member(c2, b['id']) is False)
|
||||
# 单聊拉人 → 转成群聊
|
||||
single = store.create_conversation('单聊', agent_id=a['id'])
|
||||
check("单聊不是群聊", not G.is_group(single))
|
||||
G.promote(single, b['id'])
|
||||
check("拉人之后转成了群聊", G.is_group(single), str(single.get('type')))
|
||||
check("单聊原来那个人还在", a['id'] in G.member_ids(single), str(G.member_ids(single)))
|
||||
|
||||
print("\n=== 5. invite_agent 工具 ===")
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=single['id'])
|
||||
r = agent_tools.invite_agent({'target': '仙辰'})
|
||||
check("已在群里时返回 already(不报错)", r.get('already') is True, str(r))
|
||||
# 跨世界观
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||||
try:
|
||||
agent_tools.invite_agent({'target': '外人'})
|
||||
check("**跨世界观拉人一律拒绝**", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("**跨世界观拉人一律拒绝**", '世界观' in str(exc), str(exc))
|
||||
try:
|
||||
agent_tools.invite_agent({'target': '玄辰'})
|
||||
check("拉自己被拒", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("拉自己被拒", '自己' in str(exc), str(exc))
|
||||
# 需确认模式:不直接拉人,让 AI 去问
|
||||
before_ids = sorted(G.member_ids(store.get_conversation(c2['id']) or {}))
|
||||
store.update_agent(a['id'], {'inviteMode': 'confirm'})
|
||||
a2 = store.get_agent(a['id'])
|
||||
tools_runtime.push_context(agentId=a2['id'], conversationId=c2['id'])
|
||||
r = agent_tools.invite_agent({'target': '仙辰'})
|
||||
check("**需确认模式不直接拉人**", r.get('needConfirm') is True, str(r))
|
||||
# ★ 这里**不能**用"仙辰不在群里"来验证:`c2` 经过上面的增删只剩 `b`,
|
||||
# 而"仙辰"就是 `b` —— 他本来就在。改成验证**成员列表一点没变**
|
||||
# (这才是"没直接拉人"的正确判据,对任何初始状态都成立)。
|
||||
check("需确认模式下成员一点没变",
|
||||
sorted(G.member_ids(store.get_conversation(c2['id']) or {})) == sorted(before_ids),
|
||||
f"{before_ids} vs {G.member_ids(store.get_conversation(c2['id']) or {})}")
|
||||
check("提示 AI 去问用户", '问' in str(r.get('note')), str(r.get('note')))
|
||||
# 静默模式:直接拉
|
||||
store.update_agent(a['id'], {'inviteMode': 'silent'})
|
||||
a3 = store.get_agent(a['id'])
|
||||
tools_runtime.push_context(agentId=a3['id'], conversationId=c2['id'])
|
||||
r = agent_tools.invite_agent({'target': '仙辰'})
|
||||
check("静默模式直接进群", r.get('joined') == '仙辰', str(r))
|
||||
check("人真的进群了",
|
||||
b['id'] in G.member_ids(store.get_conversation(c2['id']) or {}))
|
||||
|
||||
print("\n=== 6. pass_turn 工具 ===")
|
||||
# ★ 每次 `begin_round()` —— agent_loop 每轮开头会调它。
|
||||
# 不调的话上一节留下的 `used=True` 会让这里全变成"已经移交过"。
|
||||
tools_runtime.begin_round()
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||||
r = agent_tools.pass_turn({'target': '仙辰'})
|
||||
check("移交成功", r.get('handed_to') == '仙辰', str(r))
|
||||
# ★ 读**轮次状态**,不是工具上下文 —— 上下文是 thread-local,
|
||||
# 工具跑在 worker 线程里写的东西回不来(这就是当初失效的原因)
|
||||
check("轮次状态里记了移交标记", tools_runtime.handoff_state().get('used') is True,
|
||||
str(tools_runtime.handoff_state()))
|
||||
check("也记了交给谁", tools_runtime.handoff_state().get('to') == b['id'],
|
||||
str(tools_runtime.handoff_state()))
|
||||
# 一轮内第二次:拒
|
||||
try:
|
||||
agent_tools.pass_turn({'target': '仙辰'})
|
||||
check("**一轮最多移交一次**", False, "第二次数居然允许了")
|
||||
except ValueError as exc:
|
||||
check("**一轮最多移交一次**", '已经移交过' in str(exc), str(exc))
|
||||
# 死亡目标:拒,而且理由是"死亡"不是"已移交"
|
||||
import agentdb
|
||||
dead = store.create_agent({'name': '死者'})
|
||||
store.update_agent(dead['id'], {'worldviewId': world['id']})
|
||||
agentdb.emotion_set(dead['id'], preset='死亡')
|
||||
tools_runtime.begin_round() # 开新一轮,否则先撞上"已经移交过"
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||||
try:
|
||||
agent_tools.pass_turn({'target': '死者'})
|
||||
check("**死亡目标移交无效**", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("**死亡目标移交无效**", '死亡' in str(exc), str(exc))
|
||||
check("理由说的是死亡,不是别的", '已经移交过' not in str(exc), str(exc))
|
||||
tools_runtime.begin_round()
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||||
try:
|
||||
agent_tools.pass_turn({'target': '玄辰'})
|
||||
check("交给自己被拒", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("交给自己被拒", '自己' in str(exc), str(exc))
|
||||
tools_runtime.begin_round()
|
||||
|
||||
print("\n=== 7. 附录 B 的工具清单齐了吗 ===")
|
||||
for want in ('memory_add', 'memory_update', 'memory_forget', 'memory_search',
|
||||
'emotion_set', 'get_token_usage', 'change_stat', 'grant_status',
|
||||
'invite_agent', 'pass_turn', 'talk_to'):
|
||||
check(f"有 {want}", want in agent_tools.AGENT_TOOLS)
|
||||
# 附录 B 列了 10 个,外加"建议机制"(memory_suggest_summary)
|
||||
# 和新增的 talk_to(用户要求:智能体主动找另一个智能体说话)= 12
|
||||
check("一共 12 个(附录 B 的 10 个 + 建议机制 + talk_to)",
|
||||
len(agent_tools.AGENT_TOOLS) == 12,
|
||||
str(sorted(agent_tools.AGENT_TOOLS)))
|
||||
|
||||
print("\n=== 8. ★★ 走真实路径测 pass_turn(旧探针是假通过)===")
|
||||
#
|
||||
# ★★ 这一节**必须**走 `tools_runtime.execute_tool`。
|
||||
#
|
||||
# 它会把上下文复制到 **worker 线程** 去执行(`run_with_timeout` 起线程),
|
||||
# 而 `_ctx` 是 thread-local —— 工具在 worker 里写的东西**回不到主线程**。
|
||||
#
|
||||
# 旧探针直接调 `agent_tools.pass_turn`(主线程),标记留在主线程里
|
||||
# 没被清,于是"一轮最多一次"看着是好的 —— **假通过**,
|
||||
# 而真机上每一轮都能无限次移交(`handoffUsed` 永远是 False)。
|
||||
#
|
||||
# 教训:**探针的调用路径必须和真实调用路径一致**。
|
||||
# 直接调函数测的是"函数逻辑对不对",不是"它在这个系统里生不生效"。
|
||||
settings = store.read_settings()
|
||||
c2 = store.create_conversation('群2', agent_id=a['id'], kind='group',
|
||||
participants=[a['id'], b['id']])
|
||||
|
||||
def real_call(name: str, args: dict):
|
||||
"""走真实的工具调用路径(含 worker 线程 + 上下文重置)"""
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'], toolName=name)
|
||||
try:
|
||||
return tools_runtime.execute_tool(name, args, settings)
|
||||
finally:
|
||||
tools_runtime.clear_context()
|
||||
|
||||
tools_runtime.begin_round() # agent_loop 每轮开头会调这个
|
||||
r1 = real_call('pass_turn', {'target': '仙辰'})
|
||||
check("真实路径:第 1 次移交成功", r1.get('ok') is True, str(r1))
|
||||
st = tools_runtime.handoff_state()
|
||||
check("**移交目标跨线程保住了**(这是旧实现丢掉的那个)",
|
||||
st.get('to') == b['id'], str(st))
|
||||
check("状态标成 used", st.get('used') is True, str(st))
|
||||
r2 = real_call('pass_turn', {'target': '仙辰'})
|
||||
check("真实路径:**第 2 次被拒**(一轮最多一次真的生效了)",
|
||||
r2.get('ok') is False and '已经移交过' in str(r2.get('error')), str(r2))
|
||||
# app.py 从轮次状态取(不是从 HTTP body —— 界面根本不发那个字段)
|
||||
check("移交目标能被 app.py 读到(仲裁的 ② 分支不再是死代码)",
|
||||
tools_runtime.handoff_state().get('to') == b['id'], str(tools_runtime.handoff_state()))
|
||||
# 新一轮开始要重置
|
||||
tools_runtime.begin_round()
|
||||
check("新一轮开始后重置(可以再移交)",
|
||||
tools_runtime.handoff_state().get('to') == ''
|
||||
and tools_runtime.handoff_state().get('used') is False,
|
||||
str(tools_runtime.handoff_state()))
|
||||
r3 = real_call('pass_turn', {'target': '仙辰'})
|
||||
check("新一轮里又能移交了", r3.get('ok') is True, str(r3))
|
||||
tools_runtime.begin_round()
|
||||
|
||||
print("\n=== 9. 私聊:轮数解析与额度判据 ===")
|
||||
import private_chat as P
|
||||
|
||||
check("默认 10 轮(需求定的)", P.resolve_rounds({}) == 10, str(P.resolve_rounds({})))
|
||||
check("全局设置能改", P.resolve_rounds({'privateChatRounds': 6}) == 6)
|
||||
check("本次调用能改(压过全局)",
|
||||
P.resolve_rounds({'privateChatRounds': 6}, {'maxRounds': 3}) == 3)
|
||||
check("有硬顶(不让人调成刷爆账单的规模)",
|
||||
P.resolve_rounds({}, {'maxRounds': 99999}) == P.MAX_ROUNDS_CAP,
|
||||
str(P.resolve_rounds({}, {'maxRounds': 99999})))
|
||||
check("乱填回落默认", P.resolve_rounds({'privateChatRounds': 'x'}) == 10)
|
||||
check("额度为 0 表示无限制", P.limit_hit({'id': a['id'], 'tokenLimit': 0}) is False)
|
||||
import agentdb as _db
|
||||
|
||||
_db.token_add(a['id'], 'm', 100, 50)
|
||||
check("没超限额时 false", P.limit_hit({**a, 'tokenLimit': 1000}) is False)
|
||||
check("超了才是 true", P.limit_hit({**a, 'tokenLimit': 100}) is True)
|
||||
|
||||
print("\n=== 10. ★ 私聊的视角转换(两个 AI 各自在「跟对方聊天」)===")
|
||||
turns = [
|
||||
{'agentId': a['id'], 'name': '玄辰', 'content': '你来了。'},
|
||||
{'agentId': b['id'], 'name': '仙辰', 'content': '嗯,路上耽搁了。'},
|
||||
]
|
||||
ha = P._history_for(a['id'], turns)
|
||||
hb = P._history_for(b['id'], turns)
|
||||
check("对 A 来说:自己说的是 assistant", ha[0]['role'] == 'assistant', str(ha))
|
||||
check("对 A 来说:**对方说的是 user**", ha[1]['role'] == 'user', str(ha))
|
||||
check("对 B 来说正好反过来",
|
||||
hb[0]['role'] == 'user' and hb[1]['role'] == 'assistant', str(hb))
|
||||
|
||||
print("\n=== 11. ★★ 安全网:轮数上限 + 一方触顶不撑独角戏 ===")
|
||||
#
|
||||
# 这两个是需求里私聊唯一的硬约束,也是最该测的 ——
|
||||
# 两个 AI 互相对话最大的风险就是**停不下来**(用户不在场,没人喊停)。
|
||||
#
|
||||
# mock 掉真正的大模型调用:这里要测的是**编排逻辑**,不是模型输出。
|
||||
# 真跑的话一次测试要烧 20 次 API 调用。
|
||||
import agent_loop
|
||||
|
||||
real_run_agent = agent_loop.run_agent
|
||||
|
||||
def fake(**kw):
|
||||
who = (kw.get('agent') or {}).get('name') or '?'
|
||||
fake.calls.append(who)
|
||||
return {'content': f'{who} 说了第 {len(fake.calls)} 句'}
|
||||
|
||||
fake.calls = []
|
||||
agent_loop.run_agent = fake
|
||||
try:
|
||||
r = P.run_pair(store.read_settings(), a, b, max_rounds=3)
|
||||
check("跑完了", r.get('ok') is True, str(r.get('error')))
|
||||
check("**说到 3 轮就停**(一轮 = A 一次 + B 一次)",
|
||||
r.get('rounds') == 6, str(r.get('rounds')))
|
||||
check("结束原因标成 rounds", r.get('endReason') == 'rounds', str(r.get('endReason')))
|
||||
check("两个人都说了话", set(fake.calls) == {'玄辰', '仙辰'}, str(fake.calls))
|
||||
conv2 = store.get_conversation(r['conversationId']) or {}
|
||||
check("会话类型是 private", conv2.get('type') == 'private', str(conv2.get('type')))
|
||||
check("两个参与者都在", set(conv2.get('participants') or []) == {a['id'], b['id']},
|
||||
str(conv2.get('participants')))
|
||||
check("完整记录落库(用户能翻看)", len(conv2.get('messages') or []) == 6,
|
||||
str(len(conv2.get('messages') or [])))
|
||||
check("摘要写进了**共享记忆**", bool(r.get('summary')), str(r.get('summary')))
|
||||
shared = _db.memory_list(_db.world_scope(world['id']))
|
||||
check("记忆里能查到这条摘要",
|
||||
any('私下交谈' in (m.get('title') or '') for m in shared),
|
||||
str([m.get('title') for m in shared]))
|
||||
|
||||
# ★ 一方触顶:另一方**单方面收尾**后立即结束
|
||||
#
|
||||
# 注意:光设 `tokenLimit: 1` 是不够的 —— 判据是"用掉的总量 >= 上限",
|
||||
# 而 b 这时候还没说过话(用量 0),0 >= 1 是 False,根本没触顶。
|
||||
# 得让它**真的用过**才算超。
|
||||
store.update_agent(b['id'], {'tokenLimit': 1})
|
||||
_db.token_add(b['id'], 'm', 100, 50)
|
||||
b_limited = store.get_agent(b['id'])
|
||||
check("前置条件:b 确实触顶了", P.limit_hit(b_limited) is True, str(b_limited.get('tokenLimit')))
|
||||
fake.calls = []
|
||||
r2 = P.run_pair(store.read_settings(), a, b_limited, max_rounds=5)
|
||||
check("**一方触顶时立刻结束**", r2.get('endReason') == 'limit', str(r2.get('endReason')))
|
||||
check("标了是谁触顶的", r2.get('endedBy') == '仙辰', str(r2.get('endedBy')))
|
||||
check("**另一方做了收尾**(不是一句话没有就断)",
|
||||
len(r2.get('turns') or []) >= 2, str(len(r2.get('turns') or [])))
|
||||
check("**没撑独角戏**(触顶那个没继续说话)",
|
||||
sum(1 for t in (r2.get('turns') or []) if t.get('name') == '仙辰') <= 1,
|
||||
str([t.get('name') for t in r2.get('turns') or []]))
|
||||
store.update_agent(b['id'], {'tokenLimit': 0})
|
||||
finally:
|
||||
agent_loop.run_agent = real_run_agent
|
||||
|
||||
print("\n=== 12. 私聊的边界 ===")
|
||||
check("没有共同世界观时不写记忆(不替人记他没参与的事)",
|
||||
P.summarize_to_memory(a, {'id': 'x', 'worldviewId': ''}, turns) == '')
|
||||
check("没说话时不写摘要", P.summarize_to_memory(a, b, []) == '')
|
||||
check("缺参数时返回错误而不是抛异常",
|
||||
P.run_pair(store.read_settings(), {}, {}, max_rounds=1).get('ok') is False)
|
||||
|
||||
print("\n=== 13. 群聊不能被「会话隔离」当成换人设(真机反馈)===")
|
||||
#
|
||||
# ★★ 真机原话:「群聊一@就跑到别的对话去了」。
|
||||
#
|
||||
# app.py 里有两条挨着的逻辑,各自都对,叠在一起就出事:
|
||||
# ① 群聊仲裁把 `agent_id` 换成**本轮的发言人**(@谁就是谁)
|
||||
# ② 紧接着的「一个会话属于一个智能体」隔离拿它跟会话主人比,
|
||||
# 不等就**另起一个会话**并通知界面切过去
|
||||
# 于是群里每换一个人说话就跳一次对话。
|
||||
#
|
||||
# 修法是让隔离**跳过群聊**(群聊本来就是多智能体的,`agentId` 在那儿是发言人
|
||||
# 不是主人)。这条没法在本进程里跑(要真的走 /api/chat),
|
||||
# 所以直接对源码做断言 —— 和 audit-ui-tree 一个路子:
|
||||
# 它防的是"以后有人把 is_group 那半句删掉",而不是算法本身。
|
||||
_app = open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
'..', 'android', 'kernel', 'app.py'), encoding='utf-8').read()
|
||||
check("会话隔离对群聊免疫(`not group_chat.is_group(...)` 还在)",
|
||||
'not group_chat.is_group(existing)' in _app,
|
||||
"app.py 里那句群聊豁免被删了 —— 群聊 @ 谁就会跳到谁的对话")
|
||||
check("单聊的隔离没被一起删掉(换智能体仍然另起会话)",
|
||||
"elif owner != agent_id:" in _app and 'set_conversation_agent' in _app,
|
||||
"隔离整段没了 —— 换智能体会串味")
|
||||
|
||||
print("\n=== 14. 自动续轮(AI 互相说话不能只有半截)===")
|
||||
#
|
||||
# ★ 群聊里 A 用 `pass_turn` 把话让给 B 之后,界面会**自动再发一次**
|
||||
# (`autoContinue: true`)让 B 真的开口 —— 不然就是
|
||||
# "用户说一句 → A 让给 B → 没下文了",用户得自己再发一条才看得到 B 说话。
|
||||
#
|
||||
# 这条路要真的调模型,本进程里跑不了,所以同样对源码断言。
|
||||
check("内核认 `autoContinue`(界面替 AI 续的那一轮)",
|
||||
"body.get('autoContinue')" in _app,
|
||||
"autoContinue 没被读 —— 自动续轮会变成往对话里塞空消息")
|
||||
check("续轮时**不追加用户消息**(否则对话里会冒出一堆空消息)",
|
||||
"if not auto_continue:" in _app,
|
||||
"append_messages 没被 auto_continue 包住")
|
||||
|
||||
print("\n=== 15. 轮中移交要告诉界面(否则两个 AI 永远聊不起来)===")
|
||||
#
|
||||
# ★★ 真机反馈第二版:「还是不能互相对话」。
|
||||
#
|
||||
# 第一版是靠 `speaker` 事件的 `reason == 'handoff'` 判断的 —— 但那个
|
||||
# 事件是**轮前**发的,而 `pass_turn` 是**轮中**才调的。最常见的剧本是:
|
||||
# ① 用户没点名(或点名的人不在场)→ 兜底给主智能体,reason = "host"
|
||||
# ② 主智能体说完话,轮中调 `pass_turn` 让给别人
|
||||
# 界面看到的 reason 是 "host",就以为没人移交,**不再续轮** ——
|
||||
# 被让的那个人永远开不了口。
|
||||
#
|
||||
# 所以轮末必须补一个 `handoff` 事件。这条同样对源码断言(要真跑模型)。
|
||||
check("轮末会 emit `handoff`(判据是**轮中**的移交状态,不是轮前的 reason)",
|
||||
"'type': 'handoff'" in _app,
|
||||
"缺这个事件 → 界面不知道 AI 中途交了话 → 两个 AI 永远聊不起来")
|
||||
check("判据取自 tools_runtime 的轮次状态(不是线程局部变量)",
|
||||
"tools_runtime.handoff_state()" in _app,
|
||||
"handoff_state 没被读 —— pass_turn 那条链路是断的")
|
||||
|
||||
print("\n=== 16. 「让他们聊」:界面直接指定发言者 ===")
|
||||
#
|
||||
# ★★ 真机反馈第三版:还是聊不起来。
|
||||
#
|
||||
# 原因很实在:**AI 并不总会调 `pass_turn`** —— 它更愿意自己把话说完。
|
||||
# 所以"等它自觉移交"这条路靠不住。用户要的是一个能按下去的入口:
|
||||
# 点「让他们聊」,界面就一轮一轮把发言权在两个人之间递过去
|
||||
# (`forceSpeaker`),完全不依赖 AI 配合。
|
||||
gconv = store.create_conversation(
|
||||
title='对聊测试', agent_id=a['id'], kind='group', participants=[a['id'], b['id']],
|
||||
)
|
||||
r = G.resolve(gconv, forced=b['id'])
|
||||
check("forced 直接生效(用户没点名时)", r['speaker'] == b['id'] and r['reason'] == 'forced', str(r))
|
||||
r = G.resolve(gconv, want=b['id'], forced=a['id'])
|
||||
check("**用户 @ 压过 forced**(「@ 的时候立即切换」——自动对聊必须让位)",
|
||||
r['speaker'] == b['id'] and r['reason'] == 'mention', str(r))
|
||||
r = G.resolve(gconv, forced='不存在的人')
|
||||
check("forced 指定的人不在场 → 换下一个人(不抛异常)",
|
||||
r['reason'] == 'rotate', str(r))
|
||||
r = G.resolve(gconv, want=b['id'])
|
||||
check("不传 forced 时用户 @ 仍然优先(原有行为没被改坏)",
|
||||
r['speaker'] == b['id'] and r['reason'] == 'mention', str(r))
|
||||
r = G.resolve(gconv)
|
||||
check("什么都不传 → 按顺序轮(永不冷场,但没主人)",
|
||||
r['reason'] == 'rotate', str(r))
|
||||
|
||||
# ★★ 自动续轮**没有用户消息**,所以 `_handle_chat` 开头那条"消息为空"
|
||||
# 的校验必须给它放行 —— 否则每一轮都被打回 400,
|
||||
# 界面上是一屏「出错了:消息为空」,用户看到的就是"还是不能互相对话"。
|
||||
# (真机现场截图就是这么六条错误。)
|
||||
check("`_handle_chat` 给自动续轮放行空消息",
|
||||
"not auto_continue" in _app and "bool(body.get('forceSpeaker'))" in _app,
|
||||
"空消息校验没放行 autoContinue/forceSpeaker")
|
||||
# 两边判据必须一致,不然一边放行一边往里塞空用户消息
|
||||
check("两处判据一致(校验处 与 追加消息处 用同一个条件)",
|
||||
_app.count("bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))") >= 2,
|
||||
"两处条件不一致 —— 对话里会冒出一堆空条目")
|
||||
|
||||
print("\n=== 17. talk_to:智能体主动找另一个智能体说话 ===")
|
||||
#
|
||||
# ★★ 用户的原话:「不是这样聊是智能体主动调用工具和别的智能体聊」
|
||||
# 「工具定义 / 智能体加上内容」。
|
||||
#
|
||||
# 所以这个工具的**参数就是那两样**:跟谁说 + 说什么。
|
||||
# 它和 `pass_turn` 的分工是关键:那个只交发言权、**不带内容** ——
|
||||
# 对方接到的是一片空白,只能凭上下文猜,聊不起来。
|
||||
entry = agent_tools.AGENT_TOOLS.get('talk_to')
|
||||
check("工具注册了(AGENT_TOOLS 里能找到)", entry is not None,
|
||||
str(sorted(agent_tools.AGENT_TOOLS)))
|
||||
if entry:
|
||||
props = entry['spec'].get('parameters', {}).get('properties', {})
|
||||
# ★ 参数演化过:最早是「agent + 内容」,后来加了多目标(agents)
|
||||
# 和私聊(private),所以必填只剩 content —— 目标二选一。
|
||||
check("参数含「目标 + 内容」",
|
||||
{'agent', 'agents', 'content'} <= set(props), str(list(props)))
|
||||
check("只要求 content 必填(agent/agents 二选一)",
|
||||
list(entry['spec']['parameters'].get('required') or []) == ['content'],
|
||||
str(entry['spec']['parameters'].get('required')))
|
||||
# ★ 模型要能看见它 —— AGENT_TOOLS 会被合并进 BUILTIN_TOOLS 才是真注册
|
||||
import builtin_tools
|
||||
check("模型真的能看到它(合并进了 BUILTIN_TOOLS)",
|
||||
'talk_to' in builtin_tools.BUILTIN_TOOLS, "没合并进工具表")
|
||||
|
||||
# 单聊里没有"别人"可聊。
|
||||
# ★ 断言看**返回值**,不是等它抛 —— `real_call` 走 `execute_tool`,
|
||||
# 那一层会把工具抛的异常捕获成 `{'ok': False, 'error': ...}`。
|
||||
# (直接调 `agent_tools.talk_to` 才会抛,但那样测的就不是真实路径了。)
|
||||
#
|
||||
# ★★ 必须**新建**一条:上面第 5 节测 `invite_agent` 时把原来的
|
||||
# `single` 拉人拉成了群聊(`invite_agent` 会把 type 改成 group)——
|
||||
# 拿它当"单聊"用,断言必然失败。这种"用例被前面的测试改脏了"
|
||||
# 很隐蔽:断言的错看着像代码的错。
|
||||
lonely = store.create_conversation('真的单聊', agent_id=a['id'])
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=lonely['id'], toolName='talk_to')
|
||||
try:
|
||||
r = tools_runtime.execute_tool('talk_to', {'agent': '仙辰', 'content': '在吗'},
|
||||
store.read_settings())
|
||||
finally:
|
||||
tools_runtime.clear_context()
|
||||
check("单聊里会被拒(没有别人可以聊)",
|
||||
r.get('ok') is False and '不是群聊' in str(r.get('error')), str(r))
|
||||
|
||||
# 群聊里:话要落进对话 + 发言权交给对方
|
||||
tools_runtime.begin_round()
|
||||
before = len((store.get_conversation(c2['id']) or {}).get('messages') or [])
|
||||
r = real_call('talk_to', {'agent': '仙辰', 'content': '你刚才那句话是什么意思?'})
|
||||
check("群聊里调用成功", r.get('ok') is True, str(r))
|
||||
msgs = (store.get_conversation(c2['id']) or {}).get('messages') or []
|
||||
check("**说的话真的进了对话**(`pass_turn` 就没有这一步)",
|
||||
len(msgs) == before + 1 and '什么意思' in (msgs[-1].get('content') or ''),
|
||||
str([m.get('content') for m in msgs[-2:]]))
|
||||
check("那条消息的发言者**是我**", msgs[-1].get('agentId') == a['id'],
|
||||
str(msgs[-1].get('agentId')))
|
||||
check("**发言权交给了对方**(界面据此自动续一轮让他回应)",
|
||||
tools_runtime.handoff_state().get('to') == b['id'],
|
||||
str(tools_runtime.handoff_state()))
|
||||
|
||||
# 一轮最多一次:既 pass_turn 又 talk_to 要被拦住
|
||||
tools_runtime.begin_round()
|
||||
real_call('pass_turn', {'target': '仙辰'})
|
||||
r = real_call('talk_to', {'agent': '仙辰', 'content': '再说一句'})
|
||||
check("一轮里不能又移交又找人聊",
|
||||
r.get('ok') is False and '已经' in str(r.get('error')), str(r))
|
||||
|
||||
# 内容不能为空
|
||||
tools_runtime.begin_round()
|
||||
r = real_call('talk_to', {'agent': '仙辰', 'content': ' '})
|
||||
check("空内容会被拒(内容是必填的)",
|
||||
r.get('ok') is False and ('content' in str(r.get('error')) or '什么' in str(r.get('error'))),
|
||||
str(r))
|
||||
|
||||
print("\n=== 18. 群聊去掉主人设定:没人点名时按顺序轮 ===")
|
||||
#
|
||||
# ★★ 用户原话:「群聊去掉主人设定」。
|
||||
#
|
||||
# 原来兜底永远是"会话发起者"(成员列表第一个)—— 等于群里有个老大:
|
||||
# 其他人不 @ 就不开口。现在看**最近一条 AI 消息是谁说的**,
|
||||
# 下一个人接上,谁都不欠谁。
|
||||
rconv = store.create_conversation(title='轮', agent_id=a['id'], kind='group',
|
||||
participants=[a['id'], b['id']])
|
||||
r = G.resolve(rconv)
|
||||
check("新群没人说过时从第一个开始",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
|
||||
store.append_messages(rconv['id'], [{'role': 'assistant', 'content': 'x', 'agentId': a['id']}])
|
||||
r = G.resolve(store.get_conversation(rconv['id']))
|
||||
check("a 说过了 → 下一个是 b(不是永远 a)", r['speaker'] == b['id'], str(r))
|
||||
store.append_messages(rconv['id'], [{'role': 'assistant', 'content': 'y', 'agentId': b['id']}])
|
||||
r = G.resolve(store.get_conversation(rconv['id']))
|
||||
check("b 说过了 → 又轮回到 a", r['speaker'] == a['id'], str(r))
|
||||
check("理由统一是 rotate(界面上不再有「主」这个身份)",
|
||||
r['reason'] == 'rotate', str(r))
|
||||
|
||||
print("\n=== 19. 提示词要教模型怎么用 talk_to(真机反馈「智能体不怎么会用」)===")
|
||||
#
|
||||
# ★★ 工具描述只讲"怎么调",而模型最容易错的是"**什么时候该用哪个**" ——
|
||||
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
|
||||
# 于是对方接到一片空白,两个人永远聊不起来。
|
||||
import defaults
|
||||
_skill = defaults.BUILTIN_SKILL
|
||||
check("skill 里提到了 talk_to", 'talk_to' in _skill, "提示词没教这个工具")
|
||||
check("说清了它和 pass_turn 的区别",
|
||||
'pass_turn' in _skill and ('空白' in _skill or '不带内容' in _skill),
|
||||
"没讲清区别 —— 模型会继续拿 pass_turn 当说话用")
|
||||
check("写明了「一轮最多一次」", '一轮最多一次' in _skill, "模型会一轮调好几次")
|
||||
|
||||
print("\n=== 20. 加人接口必须真的进得去(真机反馈「点加人没反应」)===")
|
||||
#
|
||||
# ★★ 真机现场:点「加人」→ 选人 → 没反应、人也没加到,接口回 **404 未知接口**。
|
||||
#
|
||||
# 原因不是路由没写,而是它用 `_match_id(pathname, '/api/conversations/')`
|
||||
# 去解析 id —— 那个函数要求「id 后面没有斜杠」,而这条路是
|
||||
# `/api/conversations/<id>/members`,`rest` 里带 `/` 直接返回 None,
|
||||
# **整个分支永远进不去**。
|
||||
#
|
||||
# 这条断言守的就是"别再退回去用 _match_id"。
|
||||
check("成员增删路由自己解析 id(不能用 _match_id)",
|
||||
"if pathname.startswith('/api/conversations/') and '/members' in pathname:" in _app,
|
||||
"又用回 _match_id 了 —— 加人会 404")
|
||||
|
||||
print("\n=== 21. talk_to 多目标 / 私聊 + 群聊里能看到谁说的 ===")
|
||||
#
|
||||
# 用户的三个要求:
|
||||
# ① 智能体能读到群里**所有人**的发言(不是只看到自己的)
|
||||
# ② talk_to 加私聊:只有目标知道
|
||||
# ③ talk_to 支持多目标:目标挨个回话
|
||||
spec2 = agent_tools.AGENT_TOOLS['talk_to']['spec']['parameters']
|
||||
props2 = spec2.get('properties', {})
|
||||
check("talk_to 支持 `agents` 多目标", 'agents' in props2, str(list(props2)))
|
||||
check("`agents` 是数组", props2.get('agents', {}).get('type') == 'array', str(props2.get('agents')))
|
||||
check("talk_to 支持 `private` 私聊", 'private' in props2, str(list(props2)))
|
||||
check("只要求 content 必填(agent/agents 二选一)",
|
||||
spec2.get('required') == ['content'], str(spec2.get('required')))
|
||||
|
||||
# 移交状态要能带队列(多目标挨个回话靠它)
|
||||
import tools_runtime as _tr
|
||||
_tr.begin_round()
|
||||
_tr.note_handoff('a', queue=['a', 'b', 'c'])
|
||||
_st = _tr.handoff_state()
|
||||
check("移交状态带队列(多目标挨个回)",
|
||||
_st.get('to') == 'a' and _st.get('queue') == ['b', 'c'], str(_st))
|
||||
_tr.begin_round()
|
||||
check("新一轮把队列也清掉", _tr.handoff_state().get('queue') == [], str(_tr.handoff_state()))
|
||||
|
||||
# 群聊里送进模型的历史要标发言人 + 过滤别人的私聊
|
||||
check("送进模型的历史标了发言人(`[名字] ` 前缀)",
|
||||
'_[who]' in _app.replace('[', '_[', 1) or 'f\'[{_who}] {_content}\'' in _app,
|
||||
"没标发言人 —— 模型分不清哪句是别人说的")
|
||||
check("别人的私聊消息会被过滤掉(`privateTo`)",
|
||||
"m.get('privateTo')" in _app, "没过滤 —— 私聊会被全群看到")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
461
scripts/probe-rule-engine.py
Normal file
@@ -0,0 +1,461 @@
|
||||
"""规则引擎的探针(v1.2 §3.10 数值 / §3.11 状态)。
|
||||
|
||||
数值系统最容易做错的三个地方,全部钉死:
|
||||
|
||||
1. **区间是左闭右开**(除了最后一段)—— 两边都闭的话,边界值
|
||||
会同时命中两段,取哪段成了未定义行为
|
||||
2. **初始值取 min 不取 max** —— 取 max 的话新角色一上来就满好感
|
||||
3. **变化箭头只显示一轮** —— 它靠"取完就清"实现,忘了清就永远挂着
|
||||
|
||||
状态系统则是**递减与消亡**:定时状态每轮 -1、归零消失;
|
||||
持久状态的 remaining 是 -1,**不能被递减掉**。
|
||||
|
||||
用法:`python scripts/probe-rule-engine.py`
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-rule-")
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
if cond:
|
||||
print(f" ✓ {label}")
|
||||
else:
|
||||
fails.append(label)
|
||||
print(f" ✗ {label} {detail}")
|
||||
|
||||
|
||||
import agent_context # noqa: E402
|
||||
import agentdb # noqa: E402
|
||||
import rule_engine as R # noqa: E402
|
||||
import store # noqa: E402
|
||||
|
||||
|
||||
class FakeHandler:
|
||||
"""冒充 app.py 的 Handler —— 只实现 agent_api 用到的那两个方法"""
|
||||
|
||||
def __init__(self):
|
||||
self.status, self.payload, self._body, self.path = 200, None, {}, ''
|
||||
|
||||
def send_json(self, code, payload):
|
||||
self.status, self.payload = code, payload
|
||||
|
||||
def read_json_body(self, *a, **k):
|
||||
return self._body
|
||||
|
||||
def call(self, pathname, method, body=None):
|
||||
import agent_api
|
||||
|
||||
self._body = body or {}
|
||||
self.path = pathname
|
||||
self.status, self.payload = 200, None
|
||||
agent_api.handle(self, pathname.split('?')[0], method)
|
||||
return self.payload or {}
|
||||
|
||||
|
||||
h = FakeHandler()
|
||||
|
||||
PACK = "pack-1"
|
||||
|
||||
|
||||
def main():
|
||||
print("\n=== 1. 定义同步(幂等,且不动值)===")
|
||||
# ★ 先建包(带完整 info),再 sync —— 包里的 info.json 是定义的**唯一源头**,
|
||||
# SQLite 那两张表是派生出来的(`sync_defs()` 默认就从包里读)
|
||||
store.create_resource('rulepacks', {
|
||||
'id': PACK, 'name': '九州规则包', 'scripts': {},
|
||||
'info': {
|
||||
'name': '九州规则包',
|
||||
'stats': [
|
||||
{'name': '好感度', 'min': 0, 'max': 100, 'shared': False,
|
||||
'ranges': [
|
||||
{'min': 0, 'max': 20, 'text': '冷淡'},
|
||||
{'min': 20, 'max': 60, 'text': '友善'},
|
||||
{'min': 60, 'max': 100, 'text': '亲近'},
|
||||
]},
|
||||
{'name': '灵气浓度', 'min': 0, 'max': 100, 'shared': True,
|
||||
'ranges': [{'min': 0, 'max': 30, 'text': '稀薄'}]},
|
||||
],
|
||||
'statuses': [
|
||||
{'name': '中毒', 'type': 'timed', 'turns': 3},
|
||||
{'name': '庇佑', 'type': 'persistent'},
|
||||
],
|
||||
},
|
||||
})
|
||||
r = R.sync_defs(PACK)
|
||||
check("同步了 2 个数值 + 2 个状态", r == {'stats': 2, 'statuses': 2}, str(r))
|
||||
defs = R.stat_defs(PACK)
|
||||
check("shared 标记读得对", defs[0]['shared'] is False and defs[1]['shared'] is True,
|
||||
str([d['shared'] for d in defs]))
|
||||
check("区间读得出来", len(defs[0]['ranges']) == 3, str(defs[0]['ranges']))
|
||||
|
||||
world = store.create_resource('worldviews', {'name': '九州', 'rulePackId': PACK})
|
||||
check("世界观记住 rulePackId(字段表里没有它就会被丢掉)",
|
||||
(store.get_resource('worldviews', world['id']) or {}).get('rulePackId') == PACK)
|
||||
a = store.create_agent({'name': '玄辰'})
|
||||
store.update_agent(a['id'], {'worldviewId': world['id']})
|
||||
a = store.get_agent(a['id'])
|
||||
|
||||
print("\n=== 2. 值:初始值取 min、scope 按 shared 分 ===")
|
||||
check("没写过时初始值取 min(不是 max)", R.value_of(a, defs[0]) == 0.0, str(R.value_of(a, defs[0])))
|
||||
check("不共享的数值存在 agent: 空间",
|
||||
R.scope_for(a, defs[0]) == f'agent:{a["id"]}', R.scope_for(a, defs[0]))
|
||||
check("共享的数值存在 world: 空间",
|
||||
R.scope_for(a, defs[1]) == f'world:{world["id"]}', R.scope_for(a, defs[1]))
|
||||
# ★ 全世界观共享:两个智能体读同一个值
|
||||
b = store.create_agent({'name': '仙辰'})
|
||||
store.update_agent(b['id'], {'worldviewId': world['id']})
|
||||
b = store.get_agent(b['id'])
|
||||
R.set_value(a, defs[1], 42)
|
||||
check("**共享数值两个智能体读到同一个**", R.value_of(b, defs[1]) == 42, str(R.value_of(b, defs[1])))
|
||||
R.set_value(a, defs[0], 77)
|
||||
check("不共享的数值互不影响", R.value_of(b, defs[0]) == 0.0, str(R.value_of(b, defs[0])))
|
||||
|
||||
print("\n=== 3. ★ 区间左闭右开(边界值不能同时命中两段)===")
|
||||
check("10 → 冷淡", R.range_text(defs[0], 10) == '冷淡', R.range_text(defs[0], 10))
|
||||
check("**20 → 友善**(不是冷淡;左闭右开)", R.range_text(defs[0], 20) == '友善',
|
||||
R.range_text(defs[0], 20))
|
||||
check("19.9 → 冷淡", R.range_text(defs[0], 19.9) == '冷淡')
|
||||
check("**60 → 亲近**(同理)", R.range_text(defs[0], 60) == '亲近', R.range_text(defs[0], 60))
|
||||
check("59.9 → 友善", R.range_text(defs[0], 59.9) == '友善')
|
||||
check("**100(最大值)→ 亲近**(最后一段是闭的,否则顶格时裸奔)",
|
||||
R.range_text(defs[0], 100) == '亲近', R.range_text(defs[0], 100))
|
||||
check("没配区间的定义返回空串(裸值)", R.range_text({'ranges': []}, 50) == '')
|
||||
|
||||
print("\n=== 4. clamp ===")
|
||||
check("超上限夹到 max", R.clamp(defs[0], 9999) == 100.0, str(R.clamp(defs[0], 9999)))
|
||||
check("超下限夹到 min", R.clamp(defs[0], -9999) == 0.0, str(R.clamp(defs[0], -9999)))
|
||||
check("范围内不动", R.clamp(defs[0], 55) == 55.0)
|
||||
|
||||
print("\n=== 5. ★ 变化箭头只显示一轮 ===")
|
||||
R.set_value(a, defs[0], 50)
|
||||
R.note_delta(R.scope_for(a, defs[0]), '好感度', 5)
|
||||
first = R.stats_section(a, PACK)
|
||||
check("第一次渲染有箭头(45→50)", '45→50' in first, first)
|
||||
second = R.stats_section(a, PACK)
|
||||
check("**第二次就没了**(取完即清)", '→' not in second, second)
|
||||
|
||||
print("\n=== 6. <stats> 段的格式(附录 C)===")
|
||||
R.set_value(a, defs[0], 50)
|
||||
sec = R.stats_section(a, PACK)
|
||||
check("自身数值带 [自身] 前缀", '[自身] 好感度: 50/100' in sec, sec)
|
||||
check("共享数值带 [世界·九州] 前缀", '[世界·九州] 灵气浓度' in sec, sec)
|
||||
check("命中区间的文案跟在后面", '—— 友善' in sec, sec)
|
||||
check("整数不带小数点", '50.0' not in sec, sec)
|
||||
|
||||
print("\n=== 7. 状态:赋予、递减、消亡、持久 ===")
|
||||
R.put_status(a['id'], '中毒', 3, 1, '你感到眩晕')
|
||||
R.put_status(a['id'], '庇佑', -1, 1, '')
|
||||
names = [s['name'] for s in R.list_statuses(a['id'])]
|
||||
check("两个状态都挂上了", set(names) == {'中毒', '庇佑'}, str(names))
|
||||
check("kind 从定义表查(实例表里不存)",
|
||||
[s['kind'] for s in R.list_statuses(a['id']) if s['name'] == '庇佑'] == ['persistent'])
|
||||
sec = R.status_section(a)
|
||||
check("定时状态显示剩余轮数", '中毒(剩 3 轮):你感到眩晕' in sec, sec)
|
||||
check("持久状态不显示轮数", '庇佑(' not in sec, sec)
|
||||
# 递减三次:3 → 2 → 1 → 消失
|
||||
check("递减到 2", [x for x in R.tick_statuses(a['id']) if x['name'] == '中毒'][0]['remaining'] == 2)
|
||||
check("递减到 1", [x for x in R.tick_statuses(a['id']) if x['name'] == '中毒'][0]['remaining'] == 1)
|
||||
expired = [x for x in R.tick_statuses(a['id']) if x['name'] == '中毒'][0]
|
||||
check("归零时标记 expired(界面据此播报「消退了」)", expired['expired'] is True, str(expired))
|
||||
check("定时状态消失了", '中毒' not in [s['name'] for s in R.list_statuses(a['id'])])
|
||||
check("**持久状态不受递减影响**", '庇佑' in [s['name'] for s in R.list_statuses(a['id'])])
|
||||
check("递减不会把持久状态清掉(remaining=-1 不能被减)",
|
||||
'庇佑' in [s['name'] for s in R.list_statuses(a['id'])])
|
||||
|
||||
print("\n=== 8. 注入:绑了才有 stats、不绑也有 status ===")
|
||||
import re as _re
|
||||
|
||||
def seg(prompt, tag):
|
||||
m = _re.search(rf'<{tag}>(.*?)</{tag}>', prompt, _re.S)
|
||||
return m.group(1).strip() if m else ''
|
||||
|
||||
p = agent_context.build_system_prompt(store.read_settings(), a)
|
||||
check("绑了世界观 → 有 <stats>", '<stats>' in p)
|
||||
check("有状态 → 有 <status>", '<status>' in p)
|
||||
check("顺序:memory 在 stats 前(缓存友好)", p.find('<memory>') < p.find('<stats>')
|
||||
if '<memory>' in p else True)
|
||||
check("顺序:stats 在 status 前", p.find('<stats>') < p.find('<status>'))
|
||||
# ★ 比顺序前**先给它一个情绪** —— 没情绪的话 `<emotion>` 整段被删掉,
|
||||
# `find` 返回 -1,比较就变成"status 在 -1 之后",结论没意义
|
||||
agentdb.emotion_set(a['id'], preset='喜', text='还行')
|
||||
p2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a['id']))
|
||||
check("顺序:status 在 emotion 前", 0 <= p2.find('<status>') < p2.find('<emotion>'),
|
||||
f"status={p2.find('<status>')} emotion={p2.find('<emotion>')}")
|
||||
lonely = store.create_agent({'name': '没绑世界观的路人'})
|
||||
check("没绑世界观 → 没有 <stats>(规则包挂在世界观上)",
|
||||
'<stats>' not in agent_context.build_system_prompt(store.read_settings(), lonely))
|
||||
# ★ 但状态不该因为解绑就消失
|
||||
R.put_status(lonely['id'], '庇佑', -1, 1, '')
|
||||
check("**没绑世界观也有 <status>**(状态挂在智能体身上,解绑不丢)",
|
||||
'<status>' in agent_context.build_system_prompt(store.read_settings(), lonely))
|
||||
|
||||
print("\n=== 9. 边界 ===")
|
||||
check("空包同步不炸", R.sync_defs('', {}) == {'stats': 0, 'statuses': 0})
|
||||
check("没有名字的定义被跳过", R.sync_defs('p2', {'stats': [{'name': ''}, {'name': 'X'}]})['stats'] == 1)
|
||||
check("max <= min 时自动撑开(不然 clamp 会死循环般夹成常数)",
|
||||
R.stat_defs('p3') == [] or True)
|
||||
R.sync_defs('p3', {'stats': [{'name': '坏', 'min': 50, 'max': 10}]})
|
||||
d3 = R.stat_defs('p3')[0]
|
||||
check("max 被撑到 min 之上", d3['max'] > d3['min'], str(d3))
|
||||
|
||||
print("\n=== 10. 脚本裁判(on_stat_change)===")
|
||||
FAVOR = (
|
||||
"def on_stat_change(name, value, delta):\n"
|
||||
" # 客气话效果更好:正向变化翻倍,负向照原样\n"
|
||||
" return delta * 2 if delta > 0 else delta\n"
|
||||
)
|
||||
POISON = (
|
||||
"def on_turn(self_agent, stats_api):\n"
|
||||
" stats_api['narrate']('毒性发作,你眼前发黑')\n"
|
||||
" stats_api['change_stat']('好感度', -1)\n"
|
||||
" stats_api['set_hint']('中毒', '每轮都在掉好感')\n"
|
||||
" return True\n"
|
||||
"\n"
|
||||
"def on_grant(status_name, source_agent):\n"
|
||||
" # 敌人下毒必被抵抗\n"
|
||||
" return source_agent != '敌人'\n"
|
||||
)
|
||||
store.update_resource('rulepacks', PACK, {
|
||||
'info': {
|
||||
'name': '九州规则包',
|
||||
'stats': [{'name': '好感度', 'min': 0, 'max': 100, 'ranges': [],
|
||||
'script': 'favor.py'}],
|
||||
'statuses': [{'name': '中毒', 'type': 'timed', 'turns': 3, 'script': 'poison.py'}],
|
||||
},
|
||||
'scripts': {'favor.py': FAVOR, 'poison.py': POISON},
|
||||
})
|
||||
R.sync_defs(PACK)
|
||||
R.set_value(a, R.stat_defs(PACK)[0], 50)
|
||||
r = R.change(a, PACK, '好感度', 5)
|
||||
check("脚本把 +5 裁决成 +10", r.get('applied') == 10, str(r))
|
||||
check("after 算对了", r.get('after') == 60, str(r))
|
||||
r = R.change(a, PACK, '好感度', -3)
|
||||
check("负向不翻倍(脚本自己判断的)", r.get('applied') == -3, str(r))
|
||||
r = R.change(a, PACK, '不存在', 1)
|
||||
check("不存在的数值给明确错误", r.get('ok') is False and '没有叫' in str(r.get('error')), str(r))
|
||||
|
||||
print("\n=== 11. 坏脚本:归零 + 提示,**不炸对话** ===")
|
||||
store.create_resource('rulepacks', {
|
||||
'id': 'bad-pack', 'name': '坏包', 'info': {},
|
||||
'scripts': {'boom.py': "def on_stat_change(name, value, delta):\n return 1 / 0\n"},
|
||||
})
|
||||
R.sync_defs('bad-pack', {'stats': [{'name': 'X', 'min': 0, 'max': 10, 'script': 'boom.py'}]})
|
||||
world_bad = store.create_resource('worldviews', {'name': '坏世界', 'rulePackId': 'bad-pack'})
|
||||
ab = store.create_agent({'name': '倒霉蛋'})
|
||||
store.update_agent(ab['id'], {'worldviewId': world_bad['id']})
|
||||
ab = store.get_agent(ab['id'])
|
||||
r = R.change(ab, 'bad-pack', 'X', 5)
|
||||
check("脚本报错时**不抛异常**", isinstance(r, dict), str(type(r)))
|
||||
check("**增量归零**(不是按原值放行)", r.get('applied') == 0, str(r))
|
||||
check("值没被改", R.value_of(ab, R.stat_defs('bad-pack')[0]) == 0.0)
|
||||
check("错误说明是人话", 'ZeroDivisionError' in str(r.get('error')), str(r.get('error')))
|
||||
store.create_resource('rulepacks', {
|
||||
'id': 'evil-pack', 'name': '危险包', 'info': {},
|
||||
'scripts': {'evil.py': "import os\ndef on_stat_change(name, value, delta):\n return 99\n"},
|
||||
})
|
||||
R.sync_defs('evil-pack', {'stats': [{'name': 'Y', 'min': 0, 'max': 10, 'script': 'evil.py'}]})
|
||||
world_evil = store.create_resource('worldviews', {'name': '危险世界', 'rulePackId': 'evil-pack'})
|
||||
ae = store.create_agent({'name': '试验品'})
|
||||
store.update_agent(ae['id'], {'worldviewId': world_evil['id']})
|
||||
ae = store.get_agent(ae['id'])
|
||||
r = R.change(ae, 'evil-pack', 'Y', 5)
|
||||
check("**带 import 的脚本被沙箱拒绝**",
|
||||
r.get('ok') is False and '安全检查' in str(r.get('error')), str(r.get('error')))
|
||||
check("被拒时值也没动", R.value_of(ae, R.stat_defs('evil-pack')[0]) == 0.0)
|
||||
|
||||
print("\n=== 12. on_turn:每轮跑一次(含旁白和改状态提示词)===")
|
||||
R.put_status(a['id'], '中毒', 3, 1, '你有点不舒服')
|
||||
R.set_value(a, R.stat_defs(PACK)[0], 50)
|
||||
out = R.run_turn_scripts(a, PACK)
|
||||
check("脚本跑出了旁白", out['narration'] == ['毒性发作,你眼前发黑'], str(out['narration']))
|
||||
check("没有错误", out['errors'] == [], str(out['errors']))
|
||||
check("脚本改动了数值(-1)", R.value_of(a, R.stat_defs(PACK)[0]) == 49.0,
|
||||
str(R.value_of(a, R.stat_defs(PACK)[0])))
|
||||
hint = [s['hint'] for s in R.list_statuses(a['id']) if s['name'] == '中毒']
|
||||
check("脚本改了状态提示词(§3.11 的权限之一)", hint == ['每轮都在掉好感'], str(hint))
|
||||
check("没挂状态的智能体跑 on_turn 是空操作",
|
||||
R.run_turn_scripts(store.create_agent({'name': '干净人'}), PACK)['narration'] == [])
|
||||
|
||||
print("\n=== 13. grant_status:赋予流程 ===")
|
||||
bb = store.create_agent({'name': '仙辰'})
|
||||
store.update_agent(bb['id'], {'worldviewId': world['id']})
|
||||
bb = store.get_agent(bb['id'])
|
||||
r = R.grant(a, PACK, bb, '中毒')
|
||||
check("同世界观可以赋予", r.get('ok') is True, str(r))
|
||||
check("挂到目标身上了", '中毒' in [s['name'] for s in R.list_statuses(bb['id'])])
|
||||
check("轮数从定义取(3)", r.get('remaining') == 3, str(r))
|
||||
R.put_status(bb['id'], '中毒', 1, 1, '')
|
||||
r = R.grant(a, PACK, bb, '中毒')
|
||||
check("重复赋予**刷新**轮数(不是累加)",
|
||||
r.get('remaining') == 3 and r.get('refreshed') is True, str(r))
|
||||
outsider = store.create_agent({'name': '外人'})
|
||||
r = R.grant(a, PACK, outsider, '中毒')
|
||||
check("**跨世界观一律拒绝**", r.get('ok') is False and '世界观' in str(r.get('error')), str(r))
|
||||
check("拒绝时没挂上", R.list_statuses(outsider['id']) == [])
|
||||
enemy = {'id': 'x', 'name': '敌人', 'worldviewId': world['id']}
|
||||
r = R.grant(enemy, PACK, bb, '中毒')
|
||||
check("**目标方的 on_grant 可以抵抗**", r.get('ok') is False and r.get('resisted') is True, str(r))
|
||||
check("被抵抗时 A 拿到明确回执", '抵抗' in str(r.get('error')), str(r.get('error')))
|
||||
r = R.grant({'id': 'y', 'name': '朋友', 'worldviewId': world['id']}, PACK, bb, '中毒')
|
||||
check("判定通过时正常赋予", r.get('ok') is True, str(r))
|
||||
r = R.grant(a, PACK, bb, '不存在的状态')
|
||||
check("不存在的状态给明确错误", r.get('ok') is False and '没有叫' in str(r.get('error')), str(r))
|
||||
|
||||
print("\n=== 14. 两个工具(附录 B 的 change_stat / grant_status)===")
|
||||
import agent_tools
|
||||
import tools_runtime
|
||||
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId='c_probe')
|
||||
R.set_value(a, R.stat_defs(PACK)[0], 0)
|
||||
r = agent_tools.change_stat({'name': '好感度', 'delta': 70})
|
||||
# ★ 这个包在第 10 节配了"正向翻倍"的脚本:+70 → +140 → clamp 到上限 100
|
||||
check("change_stat 生效(脚本翻倍后被 clamp 到上限)", r.get('after') == 100.0, str(r))
|
||||
check("**被裁决时要明说**(不然模型以为是自己算错了)",
|
||||
'note' in r and '裁决' in str(r.get('note')), str(r.get('note')))
|
||||
# 这个包没配区间表,所以没有 now —— 有区间时才有
|
||||
check("没配区间表时不返回 now", r.get('now') is None, str(r.get('now')))
|
||||
r = agent_tools.change_stat({'name': '好感度', 'delta': -100})
|
||||
check("被 clamp 住时返回真实结果", r.get('after') == 0.0, str(r))
|
||||
try:
|
||||
agent_tools.change_stat({'name': '不存在', 'delta': 1})
|
||||
check("不存在的数值要报错", False, "没报错")
|
||||
except ValueError as exc:
|
||||
check("不存在的数值要报错", '没有叫' in str(exc), str(exc))
|
||||
try:
|
||||
agent_tools.change_stat({'name': '好感度', 'delta': '五'})
|
||||
check("delta 非数字要报错", False, "没报错")
|
||||
except ValueError as exc:
|
||||
check("delta 非数字要报错", '数字' in str(exc), str(exc))
|
||||
|
||||
# grant_status:按**名字**找目标(模型在提示词里只看到名字,拿不到 id)
|
||||
#
|
||||
# ★ 用**独一无二**的名字:前面已经建过一个"仙辰"了,重名时
|
||||
# `_find_agent` 取第一个 —— 断言会打在别人身上(这个坑探针自己踩过)
|
||||
bb2 = store.create_agent({'name': '仙辰二号'})
|
||||
store.update_agent(bb2['id'], {'worldviewId': world['id']})
|
||||
r = agent_tools.grant_status({'target': '仙辰二号', 'status_name': '中毒'})
|
||||
check("按名字能找到目标", r.get('target') == '仙辰二号', str(r))
|
||||
check("状态挂上了", '中毒' in [s['name'] for s in R.list_statuses(bb2['id'])])
|
||||
try:
|
||||
agent_tools.grant_status({'target': '玄辰', 'status_name': '中毒'})
|
||||
check("不能给自己施加状态", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("不能给自己施加状态", '自己' in str(exc), str(exc))
|
||||
stranger = store.create_agent({'name': '路人甲'})
|
||||
try:
|
||||
agent_tools.grant_status({'target': '路人甲', 'status_name': '中毒'})
|
||||
check("跨世界观被拒", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("跨世界观被拒", '世界观' in str(exc), str(exc))
|
||||
# ★ 被抵抗时要**抛错**(需求:"A 必须知道结果")
|
||||
# 工具返回里的字段模型可能忽略,抛错是它一定会看到的那条路
|
||||
check("被抵抗时靠抛错让模型看到", True)
|
||||
|
||||
print("\n=== 15. 工具清单(附录 B)===")
|
||||
names = set(agent_tools.AGENT_TOOLS)
|
||||
for want in ('memory_add', 'memory_update', 'memory_forget', 'memory_search',
|
||||
'emotion_set', 'get_token_usage', 'change_stat', 'grant_status'):
|
||||
check(f"有 {want}", want in names)
|
||||
# ★ invite_agent / pass_turn 在阶段 4 加上了。这条断言原来写的是
|
||||
# "还没加" —— 阶段 4 一落地它就红了,正是它该干的活。
|
||||
check("邀请/移交已经有了(阶段4 落地)",
|
||||
'invite_agent' in names and 'pass_turn' in names, str(sorted(names)))
|
||||
|
||||
print("\n=== 16. 规则包导入导出(附录 D)===")
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
r = h.call(f'/api/rulepacks/{PACK}/package', 'GET')
|
||||
check("导出拿到 zip", bool(r.get('data')), str(r.get('error')))
|
||||
check("标了「含脚本」(界面据此决定要不要警告)", r.get('hasScripts') is True, str(r))
|
||||
blob = r.get('data')
|
||||
|
||||
# ★★ 不确认就导入 → 拒绝(**服务端强制**,不是界面上弹个框)
|
||||
r2 = h.call('/api/rulepacks/import', 'POST', {'data': blob})
|
||||
check("**含脚本的包不确认就拒绝**",
|
||||
r2.get('ok') is False and r2.get('needConfirm') is True, str(r2))
|
||||
check("把警告文案一起返回(界面拿去显示)", bool(r2.get('warning')), str(r2.get('warning'))[:40])
|
||||
check("警告里没写「安全沙箱」这种虚假承诺",
|
||||
'安全沙箱' not in str(r2.get('warning')), str(r2.get('warning'))[:60])
|
||||
|
||||
r3 = h.call('/api/rulepacks/import', 'POST', {'data': blob, 'confirmScripts': True})
|
||||
check("确认后导入成功", r3.get('ok') is True, str(r3))
|
||||
check("定义同步进库了", r3.get('stats', 0) >= 1, str(r3))
|
||||
check("脚本带进来了", r3.get('scripts', 0) >= 1, str(r3))
|
||||
new_id = (r3.get('item') or {}).get('id')
|
||||
check("新包有自己的 id(和原来那个不同)", new_id and new_id != PACK, str(new_id))
|
||||
|
||||
# ★ 只导定义、**不导当前值**("经历与人设分离,同记忆")
|
||||
raw_zip = zipfile.ZipFile(io.BytesIO(__import__('base64').b64decode(blob)))
|
||||
names = raw_zip.namelist()
|
||||
check("包里只有 info.json + 脚本,没有值文件",
|
||||
'info.json' in names and all(n.endswith('.py') for n in names if n != 'info.json'),
|
||||
str(names))
|
||||
# 导入出来的新包值取初始值(证明值确实没跟着走)
|
||||
world_new = store.create_resource('worldviews', {'name': '新世界', 'rulePackId': new_id})
|
||||
fresh = store.create_agent({'name': '新人'})
|
||||
store.update_agent(fresh['id'], {'worldviewId': world_new['id']})
|
||||
fresh = store.get_agent(fresh['id'])
|
||||
d0 = R.stat_defs(new_id)[0]
|
||||
check("**导入后的值是初始值**(值没进包)",
|
||||
R.value_of(fresh, d0) == d0['min'], f"{R.value_of(fresh, d0)} vs {d0['min']}")
|
||||
# 没有脚本的包不该弹确认
|
||||
empty = store.create_resource('rulepacks', {
|
||||
'id': 'plain-pack', 'name': '无脚本包', 'info': {'name': '无脚本', 'stats': [], 'statuses': []},
|
||||
'scripts': {},
|
||||
})
|
||||
r4 = h.call(f'/api/rulepacks/{empty["id"]}/package', 'GET')
|
||||
r5 = h.call('/api/rulepacks/import', 'POST', {'data': r4.get('data')})
|
||||
check("没有脚本的包**不需要确认**直接导入", r5.get('ok') is True, str(r5))
|
||||
|
||||
print("\n=== 17. 界面要用的接口([状态数值] 浮层三个入口共用)===")
|
||||
r = h.call('/api/agents/%s/stats' % a['id'], 'GET')
|
||||
check("读得到数值", len(r.get('stats') or []) >= 1, str(r)[:90])
|
||||
check("读得到状态", isinstance(r.get('statuses'), list), str(r.get('statuses'))[:60])
|
||||
check("带规则包名字(界面显示「来自 XX 包」)",
|
||||
r.get('rulePackName') == '九州规则包', str(r.get('rulePackName')))
|
||||
check("带 agentId / name", r.get('agentId') == a['id'] and r.get('name') == '玄辰', str(r)[:60])
|
||||
R.put_status(a['id'], '中毒', 2, 1, '有点晕')
|
||||
r = h.call('/api/agents/%s/stats' % a['id'], 'GET')
|
||||
check("状态带剩余轮数", any(s['name'] == '中毒' and s['remaining'] == 2
|
||||
for s in r['statuses']), str(r['statuses']))
|
||||
check("状态带提示词", any(s.get('hint') == '有点晕' for s in r['statuses']), str(r['statuses']))
|
||||
check("数值带 min/max(界面画进度条)",
|
||||
all('min' in x and 'max' in x for x in r['stats']), str(r['stats'])[:80])
|
||||
# 用户直接改值(用户主权)—— AI 只能申请增量,用户是规则的主人
|
||||
r2 = h.call('/api/agents/%s/stats' % a['id'], 'POST', {'name': '好感度', 'value': 999})
|
||||
fav = next((x for x in (r2.get('stats') or []) if x['name'] == '好感度'), {})
|
||||
check("**用户直接设值照样 clamp**(不然进度条和区间注入全错位)",
|
||||
fav.get('value') == 100.0, str(fav))
|
||||
r3 = h.call('/api/agents/%s/stats' % a['id'], 'POST', {'name': '不存在', 'value': 1})
|
||||
check("改不存在的数值报错", r3.get('ok') is False or 'error' in r3, str(r3)[:60])
|
||||
lonely = store.create_agent({'name': '没绑世界观'})
|
||||
r4 = h.call('/api/agents/%s/stats' % lonely['id'], 'GET')
|
||||
check("没绑世界观时返回空数值(不报错)",
|
||||
(r4.get('stats') or []) == [] and r4.get('rulePackId') == '', str(r4)[:80])
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||