Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fbfd50eb56 | |||
| 5a7ed44226 | |||
| 0b80ca4830 | |||
| c1da6486a4 | |||
| f877bd6ee8 | |||
| c9e0d689c0 | |||
| cceffd77ec | |||
| 2142e119c6 | |||
| 4ad2ea8e90 | |||
| bbc32dcb46 | |||
| 778c19b088 | |||
| 7e7aea0f48 | |||
| 4effa968ac | |||
| 76d6445ed6 | |||
| b55ce63c6e | |||
| 28a2ede206 | |||
| 1a9229aa75 | |||
| e11e178810 | |||
| 6bcb5d72f8 | |||
| b693f22f61 | |||
| 6e5ea9d3b6 | |||
| 08eecb9e0a | |||
| 182c0005a4 | |||
| 9ff60e684b | |||
| f8ab075f5e | |||
| 56b15f1d19 | |||
| d3a327da26 | |||
| 4b94e3eef3 | |||
| d557dbd2e3 | |||
| a6840f383e | |||
| 9024810558 | |||
| ef42aa70ca | |||
| a87eca329a | |||
| fd72ad06a1 | |||
| 2a25cf623f | |||
| c7fed95650 | |||
| d82c3d3176 | |||
| 4850ea12af | |||
| 2c259d4270 |
128
README.md
@@ -1,4 +1,4 @@
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
@@ -322,6 +322,126 @@ mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权
|
||||
4. **通话界面**:大头像 + 声波 + 计时 + 挂断,全屏、常亮(`FLAG_KEEP_SCREEN_ON`)、
|
||||
息屏后要有前台服务,否则一锁屏就断
|
||||
|
||||
### 3.12 会议模式的节点(独立库 `:nodekit`)
|
||||
|
||||
会议编辑器是「节点 + 连线」编排多个智能体。**节点是什么形式** —— 有哪些节点、
|
||||
每个节点什么引脚、什么颜色、什么形状、卡片多高、连线从哪儿出去 ——
|
||||
这些定义全在**独立模块 [`android/nodekit/`](android/nodekit/)** 里,只有一份。
|
||||
|
||||
界面上最能看出差别的是**形状**(形状即语法,和积木编辑器同一套思路):
|
||||
|
||||
| 形状 | 含义 |
|
||||
|---|---|
|
||||
| 帽形 | 起点(开始事件) |
|
||||
| 菱形 | 一进两出(判断 / 分支) |
|
||||
| 六边形 | 会绕回来(while 循环) |
|
||||
| 胶囊 | 不执行,只提供值(读变量 / 值 / 运算 / 转换) |
|
||||
| 上边切角 | 到这里结束(最终输出) |
|
||||
| 圆角矩形 | 普通动作 |
|
||||
|
||||
「加节点」面板里每个类型前面有形状缩略图,节点卡片标题栏左边也有一个小徽标。
|
||||
|
||||
定义是**跨语言**的(界面 Kotlin、执行 Python),靠
|
||||
`python scripts/verify-nodekit.py` 逐项对拍守着 —— 节点类型、引脚类型、
|
||||
23 个算子、判断条件、转换类型、引脚方向。
|
||||
|
||||
完整说明看 **[docs/节点库.md](docs/节点库.md)**(含"怎么加一种节点"的清单)。
|
||||
|
||||
### 3.13 超时(全部可调)
|
||||
|
||||
设置页最下面那张卡片 →「超时」,**18 项全都能调**:
|
||||
|
||||

|
||||
|
||||
每一项都带一句说明(写在界面上,不用翻文档),`-` / `+` 按钮加输入框,
|
||||
右上角「恢复默认」。
|
||||
|
||||
| 分组 | 有哪些 |
|
||||
|---|---|
|
||||
| 对话 | 等模型回复、连接空闲上限、心跳间隔、本地接口请求 |
|
||||
| 工具 | 工具执行、shell 命令、跑 Python 代码、Termux 命令、会议节点、自定义节点 |
|
||||
| 界面 | AI 提问等多久、AI 界面等多久、选文件等多久 |
|
||||
| 语音 | 语音合成、语音识别 |
|
||||
| MCP | 单次请求、连接、调用工具 |
|
||||
|
||||
以前这 15 个超时**散在 10 个文件里当模块级常量**,谁也不知道一共有几个 ——
|
||||
"哪些能调、哪些不能调"这个问题根本回答不了。现在收在
|
||||
[`android/kernel/timeouts.py`](android/kernel/timeouts.py) 一份里:
|
||||
|
||||
- 界面上有哪几项、叫什么、默认多少、能填多大、说明写什么 —— **全是内核给的**
|
||||
(`GET /api/timeouts`),加一项只改那个文件,界面自动多出一行
|
||||
- 改完**立刻生效**,不用重启(各处都是现读)
|
||||
- 取值一律夹在每项的 `[min, max]` 里,填 "60秒"、空串、负数、999999 都不会出问题
|
||||
- 「改回默认」= 从配置里**删掉**这一项(不是存一个相同的值),
|
||||
这样以后调默认值时没动过的用户会跟着新默认走
|
||||
- Node 端(Web / exe)有一份对称的 [`server/src/timeouts.mjs`](server/src/timeouts.mjs),
|
||||
`python scripts/verify-timeouts.py` 会把两边**逐项对拍**
|
||||
|
||||
三个"等用户"的项(AI 提问 / AI 界面 / 工具执行)默认是 **0 = 不限时** ——
|
||||
它们的时长取决于你什么时候点,给上限等于"你想久了 AI 就自己编"。
|
||||
|
||||
> 想让 AI 别等太久?把「AI 提问等多久」填个有限值就行。但**不建议**:
|
||||
> 你去忙一会儿回来,AI 已经按自己猜的答案往下跑了,而它并不知道自己在猜。
|
||||
|
||||
---
|
||||
|
||||
### 3.14 智能体系统(记忆 / 情绪 / Token / 世界观 / 技能 / 多模型)
|
||||
|
||||
按《智能体系统需求文档 v1.1》实现。**详细文档在
|
||||
[`docs/智能体系统.md`](docs/智能体系统.md)**(需求项 → 文件对照、数据分界、踩过的坑、
|
||||
接口一览),这里只说结论。
|
||||
|
||||

|
||||
|
||||
**选择界面**:左列表 + 右侧四层叠加(背景图 / 主体边框 / 角色图 / 介绍边框),
|
||||
切换按 0.3s 出 → 0.5s 间隔 → 0.4s 换框 → 0.3s 入的四阶段走(连点立即打断、
|
||||
从眼前画面接着走)。圆形「更多」按钮进用量页。缺哪张图就走内置默认,
|
||||
**最差也是「默认人物 + 默认背景 + 方框边框」**,不会有空白展示区。
|
||||
|
||||

|
||||
|
||||
**六个能力**(都能在界面上单独关掉或不管它):
|
||||
|
||||
| | 一句话 |
|
||||
|---|---|
|
||||
| Token | 按智能体独立统计、**按模型分桶**、输入输出分开;能设上限,用满时发起前拦住并附一句告别 |
|
||||
| 记忆 | 无上限、AI 自己记,**用户能改能删**(兜底);「必须保留」的 AI 改不动 |
|
||||
| 情绪 | 每个智能体一个当前情绪,写进提示词;**绑同一世界观也不共享**(需求明确要求) |
|
||||
| 世界观 | 独立资源。绑了它的智能体**共用一份记忆**,但**只能改自己写的**那几条 |
|
||||
| 技能 | 纯文本手册,按绑定顺序注入;内置那份默认就生效 |
|
||||
| 多模型 | 全局模型列表 + UUID 引用。引用了就**整组覆盖**(地址/Key/模型一起换) |
|
||||
|
||||
**两处需要解释的设计**:
|
||||
|
||||
1. **数据分界**:记忆/情绪/Token/Skill 绑定进 SQLite(条目无上限、每轮全量读、
|
||||
要检索、要按行改删),其余仍是 JSON(量级小、要人肉可读)。
|
||||
判据写在 `android/kernel/agentdb.py` 文件头,加新数据时先按那张表判一次。
|
||||
|
||||
2. **幻觉调用检测**:模型很容易在"该记东西"的时候只在正文里说一句"我记住了"
|
||||
—— 用户当场看不出来,下次发现它完全不记得,信任就没了。所以由程序比对
|
||||
「说了什么」和「做了什么」,对不上就在那条回复下面挂一条警示。
|
||||
判宽比判窄更糟(误伤几次之后用户就不看那个警示了),所以只收明确句式。
|
||||
|
||||
**验证**(都不需要装机、不需要网络):
|
||||
|
||||
```bash
|
||||
python scripts/probe-agent-system.py # 12 节 70+ 项:UUID、记忆、限权、注入顺序、
|
||||
# 20 多个接口、包的边界、多模型解析
|
||||
python scripts/probe-degraded.py # 幻觉检测 + 不支持 function calling 的降级
|
||||
```
|
||||
|
||||
> ⚠️ **改完内核记得跑一次 `py_compile`**:Gradle 不编译 Python
|
||||
> (Chaquopy 只是把 `.py` 打进 APK),语法错误要等手机上启动内核才炸,
|
||||
> 而那时整个 App 不可用。`scripts/build-apk.mjs` 里加了这道闸,
|
||||
> 但它拦的是"打包",不是"你刚改的那一行"。
|
||||
|
||||
**全部界面和入口在哪**:[`docs/界面总览.md`](docs/界面总览.md) ——
|
||||
把 App 里所有界面画成树(含"每个界面从哪进"),而且
|
||||
`python scripts/audit-ui-tree.py` 会拿它**和源码对拍**:
|
||||
代码里有、文档没画的界面会直接报错("界面做好了但没入口"这类问题光靠人查必然会漏)。
|
||||
|
||||
**还没做的**:Node 端(Web / exe)的智能体系统仍是旧的那套 ——
|
||||
按仓库约定"引擎改了另一端必须跟上",这是欠账。
|
||||
|
||||
|
||||
---
|
||||
@@ -593,6 +713,12 @@ 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 内核对拍
|
||||
python scripts/verify-nodekit.py # 节点库与 Python 引擎逐项对拍
|
||||
python scripts/verify-timeouts.py # 超时清单:边界 + 没有硬编码 + Node 端对拍
|
||||
python scripts/verify-seed-tools.py # 内置工具的播种/覆盖规则
|
||||
python scripts/verify-ui-tools.py # interface 工具的参数与提示词
|
||||
python scripts/verify-extract-urls.py # 「打开网页」的链接抽取
|
||||
python scripts/verify-ai-webview.py # AI 界面里的 JS 桥
|
||||
node scripts/screenshot.mjs <url> <out.png> # 无头浏览器截图
|
||||
|
||||
# mock(不消耗额度)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
plugins {
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 244
|
||||
versionName = "2.0.44"
|
||||
versionCode = 263
|
||||
versionName = "2.0.63"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -20,6 +20,7 @@ import android.provider.OpenableColumns
|
||||
import com.chaquo.python.Python
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import com.doubao.lynxclone.data.AppTimeouts
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
import com.doubao.lynxclone.termux.TermuxShell
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
@@ -419,7 +420,7 @@ class NativeBridge(private val activity: Activity) {
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(LOCAL_READ_S, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
@@ -442,7 +443,7 @@ class NativeBridge(private val activity: Activity) {
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(LOCAL_READ_S, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
@@ -837,7 +838,10 @@ class NativeBridge(private val activity: Activity) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(PICK_TIMEOUT_S, TimeUnit.SECONDS)
|
||||
latch.await(
|
||||
AppTimeouts.seconds("filePicker", PICK_TIMEOUT_S.toDouble()).toLong(),
|
||||
TimeUnit.SECONDS,
|
||||
)
|
||||
pickLatch = null
|
||||
return pickedUris.mapNotNull { copyIntoCache(it) }.toTypedArray()
|
||||
}
|
||||
@@ -880,8 +884,25 @@ class NativeBridge(private val activity: Activity) {
|
||||
|
||||
companion object {
|
||||
const val REQ_PICK = 0x4D31
|
||||
|
||||
/**
|
||||
* AI 让你挑文件时等多久的**兜底值**。
|
||||
*
|
||||
* ★ 真实值从设置读(设置 → 超时 → 选文件等多久)——
|
||||
* 去相册里翻一张老照片可能不止两分钟。这里是拿不到设置时的兜底。
|
||||
*/
|
||||
private const val PICK_TIMEOUT_S = 120L
|
||||
|
||||
/**
|
||||
* 打本机内核端口([kernelPost] / [kernelPatch])的读超时。
|
||||
*
|
||||
* ★ 也做成可调的(设置 → 超时 → 本地接口请求):这些请求里有几个
|
||||
* 体积不小(读一条很长的会话、传附件),老设备上 10 秒不一定够。
|
||||
* 每次现读而不是建 client 时读一次 —— 改完立刻生效。
|
||||
*/
|
||||
private val LOCAL_READ_S: Long
|
||||
get() = AppTimeouts.seconds("kernelLocal", 10.0).toLong().coerceAtLeast(3L)
|
||||
|
||||
/** 内核起来后把 bridge 注册给 Python */
|
||||
fun register(bridge: NativeBridge) {
|
||||
val entry = Python.getInstance().getModule("doubao_entry")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.speech
|
||||
package com.doubao.lynxclone.speech
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
@@ -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)
|
||||
@@ -89,7 +99,7 @@ class SpeechController(
|
||||
// 用户看到的就是"一读语音就闪退"。
|
||||
val played = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
client.streamTts(text).use { r ->
|
||||
client.streamTts(text, agentId()).use { r ->
|
||||
val mime = r.body?.contentType().toString()
|
||||
val source = r.body?.source()
|
||||
source != null && speaker.playStream(mime, source)
|
||||
@@ -107,7 +117,7 @@ class SpeechController(
|
||||
}
|
||||
|
||||
try {
|
||||
val result = client.speak(text)
|
||||
val result = client.speak(text, agentId())
|
||||
if (!result.optBoolean("ok")) {
|
||||
// 云端失败就退回系统 TTS —— 用户点了朗读却一点动静都没有是最差的体验
|
||||
val reason = result.optString("error").ifBlank { "云端合成失败" }
|
||||
|
||||
@@ -0,0 +1,584 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
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.fillMaxSize
|
||||
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.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
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.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
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
|
||||
|
||||
/*
|
||||
* 智能体的完整编辑界面(需求 2.5 / 3.1 / 3.3 / 3.5 / 3.6 / 3.7)。
|
||||
*
|
||||
* ## ★ 为什么是全屏,而不是沿用那个弹窗
|
||||
*
|
||||
* 字段从 8 个涨到了二十多个(外观四件套、模型引用、世界观、限额、技能……)。
|
||||
* AGENTS.md 里那张表写得很清楚:「**列表 / 多组配置 / 任何要滚动的 → 独立全屏界面**」,
|
||||
* 而"节点配置 NodeConfigDialog → 全屏(字段很多)"到现在还挂在待办清单上 ——
|
||||
* 这次不再欠新账。
|
||||
*
|
||||
* ## 三处会让人困惑的地方,界面上直接说清
|
||||
*
|
||||
* ① **介绍(description)和一句话介绍(tagline)不是一回事**:
|
||||
* 前者只在选择界面的介绍框里显示,后者是列表里的摘要。
|
||||
* ② **绑了世界观 = 记忆变成共享的**(需求 3.6)—— 不写清楚,
|
||||
* 用户会以为"我给 A 记的东西怎么 B 也知道"。
|
||||
* ③ **限额 0 就是无限制**,不是"限额为 0"。
|
||||
*/
|
||||
|
||||
/** 除立绘以外的三件套(立绘是**五档**的,单独处理) */
|
||||
private val ASSET_SLOTS = listOf(
|
||||
Triple("back", "背景图", "铺在展示区最底层;缺了用内置默认背景"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区;缺了用简单方框"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本;缺了跟主体边框一个样式"),
|
||||
)
|
||||
|
||||
/** 立绘五档各档的说明 —— 每档都要写清"缺了会退回哪张",不然用户不知道该传几张 */
|
||||
private fun portraitHint(preset: String): String = when (preset) {
|
||||
"喜" -> "高兴时用这张;缺了用「平常」那张"
|
||||
"怒" -> "发怒时用这张;缺了用「平常」那张"
|
||||
"哀" -> "悲伤时用这张;缺了用「平常」那张"
|
||||
"死亡" -> "死亡时用这张(那时不能对话);缺了用「平常」那张"
|
||||
else -> "其他档都缺时兜底用这张;连它也没有就用内置默认人物"
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AgentEditScreen(
|
||||
vm: AppViewModel,
|
||||
initial: Agent?,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
val isNew = initial == null
|
||||
var draft by remember { mutableStateOf(initial ?: Agent(avatar = "custom")) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var promptDraft by remember { mutableStateOf(draft.systemPrompt) }
|
||||
var limitDraft by remember { mutableStateOf(
|
||||
if (draft.tokenLimit > 0) draft.tokenLimit.toInt().toString() else ""
|
||||
) }
|
||||
val ctx = LocalContext.current
|
||||
|
||||
// 选一张外观图 → 读字节 → base64 → 立刻上传
|
||||
// ★ 不等"保存":图片可能好几 MB,混在保存里用户会以为卡死了
|
||||
var pendingSlot by remember { mutableStateOf("") }
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
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("读不出这张图") }
|
||||
}
|
||||
|
||||
// 导出智能体包(需求 2.5):内核打包成 zip → base64 → 这里落盘。
|
||||
// ★ 包里**只有**名字/介绍/提示词/外观四件套 —— 模型引用、世界观绑定、限额
|
||||
// 一律不进包(需求 2.5 的"包的边界约定"),更不会有 API Key。
|
||||
var pendingZip by remember { mutableStateOf<String?>(null) }
|
||||
val saveZip = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.CreateDocument("application/zip"),
|
||||
) { uri ->
|
||||
val data = pendingZip
|
||||
pendingZip = null
|
||||
if (uri != null && data != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openOutputStream(uri)
|
||||
?.use { it.write(Base64.decode(data, Base64.DEFAULT)) }
|
||||
}.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") }
|
||||
}
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = if (isNew) "新建智能体" else "编辑智能体",
|
||||
subtitle = if (isNew) "保存后可以加外观图片" else draft.name,
|
||||
onBack = onDone,
|
||||
actions = {
|
||||
TopAction("保存", enabled = !saving) {
|
||||
saving = true
|
||||
vm.saveAgentFull(
|
||||
draft.copy(systemPrompt = promptDraft, tokenLimit = limitDraft.toDoubleOrNull() ?: 0.0),
|
||||
isNew,
|
||||
) { saving = false; onDone() }
|
||||
}
|
||||
},
|
||||
) {
|
||||
// 编辑中的智能体可能是**别处刚改过**的(比如刚上传完图片)——
|
||||
// vm.agents 里的那份才是最新的,这里同步一下,否则预览是旧的
|
||||
val fresh = vm.agents.firstOrNull { it.id == draft.id }
|
||||
if (!isNew && fresh != null && fresh.image != draft.image) {
|
||||
draft = draft.copy(image = fresh.image)
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
|
||||
/* ---------------- 基本信息 ---------------- */
|
||||
SectionLabel("基本信息")
|
||||
Card {
|
||||
LabeledField("名字", draft.name, "比如:玄辰") { draft = draft.copy(name = it) }
|
||||
Spacer(Modifier.height(10.dp))
|
||||
LabeledField("一句话介绍", draft.greeting, "列表里的摘要,比如:仙门大师兄") {
|
||||
draft = draft.copy(greeting = it)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("显示在智能体列表里。")
|
||||
Spacer(Modifier.height(12.dp))
|
||||
LabeledField("介绍文案", draft.description, "选择界面右边那个介绍框里显示的话") {
|
||||
draft = draft.copy(description = it)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("★ 和上面那条不一样:这条只在选择智能体时的介绍框里显示。留空就只显示名字。")
|
||||
}
|
||||
|
||||
/* ---------------- 外观 ---------------- */
|
||||
SectionLabel("外观")
|
||||
Card {
|
||||
if (isNew) {
|
||||
// ★ 图片要落到"这个智能体的资源目录"里,所以必须先在库里有一条记录
|
||||
Text(
|
||||
"先点右上角「保存」把智能体建出来,再回来加外观图片。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
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", "", "") },
|
||||
)
|
||||
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,
|
||||
desc = desc,
|
||||
path = draft.image.pathOf(key),
|
||||
onPick = { pendingSlot = key; pickImage.launch(arrayOf("image/*")) },
|
||||
onClear = { vm.uploadAgentAsset(draft.id, key, "", "") },
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Hint("支持 PNG / JPG / GIF(动图会动)。SVG 也能显示。缺哪张就用内置默认。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 人设 ---------------- */
|
||||
SectionLabel("人设(系统提示词)")
|
||||
Card {
|
||||
OutlinedTextField(
|
||||
value = promptDraft,
|
||||
onValueChange = { promptDraft = it },
|
||||
placeholder = { Text("你是一个……", fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 140.dp, max = 320.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("留空就用全局系统提示词。记忆、情绪、世界观、技能会自动拼在这后面,不用你自己写。")
|
||||
}
|
||||
|
||||
/* ---------------- 模型 ---------------- */
|
||||
SectionLabel("模型")
|
||||
Card {
|
||||
val entries = vm.state.modelEntries
|
||||
if (entries.isEmpty()) {
|
||||
Hint("还没有全局模型。去「设置 → 超时」上面的「全局模型」里加一个,就能在这里引用它。")
|
||||
} else {
|
||||
ChipRow(
|
||||
options = listOf("" to "跟随全局") + entries.map { it.id to it.name },
|
||||
active = draft.modelId,
|
||||
onPick = { draft = draft.copy(modelId = it) },
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("选了它就固定用那个模型;「跟随全局」= 用设置里当前选的那个。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 世界观 ---------------- */
|
||||
SectionLabel("世界观")
|
||||
Card {
|
||||
val worlds = vm.state.worldviews
|
||||
ChipRow(
|
||||
options = listOf("" to "不绑定") + worlds.map { it.id to it.name },
|
||||
active = draft.worldviewId,
|
||||
onPick = { draft = draft.copy(worldviewId = it) },
|
||||
)
|
||||
if (draft.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// ★ 选世界观的时候就要看到"已经有谁在"(用户问的"哪些智能体绑了它")。
|
||||
// 这是**决策依据**:如果里面已经有三个角色,加进去意味着
|
||||
// 四份记忆混在一个空间里;如果只有它一个,那基本等于私有。
|
||||
val wv = vm.state.worldviews.firstOrNull { it.id == draft.worldviewId }
|
||||
val others = (wv?.agents ?: emptyList()).filter { it.id != draft.id }
|
||||
Text(
|
||||
if (others.isEmpty()) "目前只有它用这个世界观(记忆实际上还是自己一份)"
|
||||
else "已经有 ${others.size} 个智能体在用:${others.joinToString("、") { it.name }}",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = if (others.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"★ 绑定之后:提示词里会多一段世界观设定," +
|
||||
"而且记忆会和上面这些智能体共享(它们也能看到并写入同一个空间," +
|
||||
"但只能改自己写的那几条)。\n" +
|
||||
"情绪仍然是私有的(不会共享)。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
if (worlds.isEmpty()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("还没有世界观。在「更多功能 → 世界观」里新建或导入一个。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 能力 ---------------- */
|
||||
SectionLabel("能力")
|
||||
Card {
|
||||
ToggleRow(
|
||||
title = "情绪感知",
|
||||
sub = "能看到同世界观其他智能体当前的情绪(只读,单向)",
|
||||
checked = draft.emotionEnabled,
|
||||
onChange = { draft = draft.copy(emotionEnabled = it) },
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text("Token 限额", fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = limitDraft,
|
||||
onValueChange = { s -> limitDraft = s.filter { it.isDigit() }.take(9) },
|
||||
placeholder = { Text("留空 = 无限制", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("用满之后会拦住发送,并附一句告别(那句话可以在设置里改)。留空就是无限制。")
|
||||
}
|
||||
|
||||
/* ---------------- 技能 ---------------- */
|
||||
SectionLabel("技能(Skill)")
|
||||
Card {
|
||||
val all = vm.state.skills
|
||||
if (all.isEmpty()) {
|
||||
Hint("还没有自定义 Skill。内置的记忆/情绪/用量手册默认就生效,不用在这里选。")
|
||||
} else {
|
||||
for (s in all) {
|
||||
val on = s.id in draft.skillIds
|
||||
ToggleRow(
|
||||
title = s.name.ifBlank { "未命名 Skill" },
|
||||
sub = s.content.lineSequence().firstOrNull()?.take(60) ?: "",
|
||||
checked = on,
|
||||
onChange = { v ->
|
||||
draft = draft.copy(
|
||||
// ★ 按**勾选顺序**排:需求 3.7 说"按绑定顺序拼接注入",
|
||||
// 顺序会影响模型读到的先后,所以不能是 Set
|
||||
skillIds = if (v) draft.skillIds + s.id
|
||||
else draft.skillIds.filter { it != s.id },
|
||||
)
|
||||
},
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
Hint("勾选顺序就是注入顺序(先勾的在前)。")
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 语音 ---------------- */
|
||||
SectionLabel("语音")
|
||||
Card {
|
||||
// ★ 这里**只选音色**,不选引擎 —— 引擎是"用哪套语音服务",
|
||||
// 属于全局设置(换引擎时音色名整套都不一样,混在一个界面里
|
||||
// 必然出现"选了引擎、音色还是上一家的"这种状态)。
|
||||
Hint("引擎跟随全局(在「设置 → 语音」里换)。想给这个智能体一个不同的嗓音,就在下面选音色。")
|
||||
Spacer(Modifier.height(10.dp))
|
||||
val engine = vm.state.speech.ttsEngine
|
||||
VoicePickerInline(
|
||||
engine = engine,
|
||||
voices = vm.state.speechVoices[engine] ?: emptyList(),
|
||||
voicesAll = vm.state.speechVoicesAll[engine] ?: emptyList(),
|
||||
value = draft.ttsVoice,
|
||||
onValue = { draft = draft.copy(ttsVoice = it) },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 记忆 / 用量 ---------------- */
|
||||
if (!isNew) {
|
||||
SectionLabel("它的状态")
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
BigAction("看它记住了什么") { vm.openMemories(draft.id) }
|
||||
BigAction("看它用了多少") { vm.openTokenUsage(draft.id) }
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 14.dp)) {
|
||||
Hint(
|
||||
"记忆是 AI 自己攒的(也可能记错),觉得不对就在那里改 —— " +
|
||||
"这是它记错时唯一的兜底。",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 导出 / 删除 ---------------- */
|
||||
if (!isNew) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
RowAction("导出这个智能体(.zip)") {
|
||||
vm.exportPackage("agents", draft.id) { content, _ -> pendingZip = content }
|
||||
}
|
||||
Text(
|
||||
"包里只有名字、介绍、提示词和外观图片;模型、世界观、限额不进包,更没有 API Key。",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
if (pendingZip != null) {
|
||||
LaunchedEffect(pendingZip) {
|
||||
saveZip.launch("${draft.name.ifBlank { "agent" }}.zip")
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isNew && !draft.builtin) {
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 12.dp), contentAlignment = Alignment.Center) {
|
||||
RowAction("删除这个智能体", danger = true) {
|
||||
vm.deleteAgentFull(draft.id) { onDone() }
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
private fun AgentImage.pathOf(key: String): String = when (key) {
|
||||
// v1.2:立绘是五档表,编辑界面的**预览**用内核算好的那张
|
||||
// (其他三件套还是单张)
|
||||
"front" -> portrait
|
||||
"back" -> back
|
||||
"border-main" -> borderMain
|
||||
else -> borderInfo
|
||||
}
|
||||
|
||||
// ★ `Card` / `Hint` 已经挪到 DoubaoUi.kt 变成公共组件了 ——
|
||||
// 原来它们是这个文件私有的,于是别的界面想用只能复制一份
|
||||
// ([群成员] 就要用),而"同一段逻辑抄两份"是这个仓库的老毛病。
|
||||
|
||||
/** 一行里并排的两个入口按钮(记忆 / 用量这种"跳去另一个界面"的动作) */
|
||||
@Composable
|
||||
private fun BigAction(label: String, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 13.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LabeledField(
|
||||
label: String,
|
||||
value: String,
|
||||
placeholder: String,
|
||||
onChange: (String) -> Unit,
|
||||
) {
|
||||
Text(label, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = onChange,
|
||||
placeholder = { Text(placeholder, fontSize = 13.sp) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChipRow(
|
||||
options: List<Pair<String, String>>,
|
||||
active: String,
|
||||
onPick: (String) -> Unit,
|
||||
) {
|
||||
Column {
|
||||
for (row in options.chunked(3)) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 3.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
for ((key, label) in row) {
|
||||
val on = key == active
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
color = if (on) Color.White else doubaoText(),
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { onPick(key) }
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ToggleRow(
|
||||
title: String,
|
||||
sub: String,
|
||||
checked: Boolean,
|
||||
onChange: (Boolean) -> Unit,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 14.sp, color = doubaoText())
|
||||
if (sub.isNotBlank()) {
|
||||
Text(sub, fontSize = 11.sp, lineHeight = 15.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.size(width = 44.dp, height = 26.dp)
|
||||
.clip(RoundedCornerShape(13.dp))
|
||||
.background(if (checked) Doubao.Blue else Doubao.Border)
|
||||
.clickable { onChange(!checked) },
|
||||
contentAlignment = if (checked) Alignment.CenterEnd else Alignment.CenterStart,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 3.dp)
|
||||
.size(20.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color.White),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 一个外观槽位:小预览 + 标题说明 + 选图 / 清除 */
|
||||
@Composable
|
||||
private fun AssetRow(
|
||||
title: String,
|
||||
desc: String,
|
||||
path: String,
|
||||
onPick: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(52.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
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,
|
||||
)
|
||||
} else {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 13.sp, color = doubaoText())
|
||||
Text(desc, fontSize = 10.sp, lineHeight = 14.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
RowAction("选择") { onPick() }
|
||||
if (path.isNotBlank()) RowAction("清除", danger = true) { onClear() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.LinearOutSlowInEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
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.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
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.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.R
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/*
|
||||
* 智能体选择界面(需求第二章)。
|
||||
*
|
||||
* ## 布局(需求 2.1)
|
||||
*
|
||||
* 左侧:智能体列表(纵向、当前项高亮)
|
||||
* 右侧:角色展示区,**四层叠加**:
|
||||
* ① 背景图(铺满)② 主体边框(框住展示区)③ 角色图(居中)④ 介绍边框(围住介绍文本)
|
||||
*
|
||||
* ## 切换动画(需求 2.3,定稿参数)
|
||||
*
|
||||
* ① 旧角色图渐出 + 侧移 0.3s ease-in
|
||||
* ② 间隔 0.5s
|
||||
* ③ 边框/背景/介绍 滑出滑入 0.4s ease-in-out
|
||||
* ④ 新角色图渐入 + 侧移到位 0.3s ease-out
|
||||
* 合计约 1.5s。
|
||||
*
|
||||
* **方向**:目标在当前**之下**(列表靠后)→ 向左切换;**之上** → 向右。
|
||||
*
|
||||
* **连续快速切换立即打断**:靠 `LaunchedEffect(选中的 id)` —— 换目标时
|
||||
* 上一个协程直接被取消,而 `Animatable` 会**停在当前值**,所以新动画
|
||||
* 是从眼前的画面接着走的,不会闪回。这正是需求要的"从当前视觉状态
|
||||
* 直接过渡到最新目标,不做排队"。
|
||||
*
|
||||
* ## ★ 默认资源回退(需求 2.6)
|
||||
*
|
||||
* 角色图缺 → 内置默认人物;背景缺 → 内置默认背景;边框缺 → **简单方框**。
|
||||
* 回退优先级:`smartInfo.json 指定 → 包内同名 → 内置默认`。
|
||||
* 前两级在内核导入时就落定了(存的是绝对路径),所以这里只做最后一级。
|
||||
*
|
||||
* ★ "任何智能体至少能以「默认人物 + 默认背景 + 方框边框」正常展示" ——
|
||||
* 所以**每个槽位都必须有兜底**,不能出现空白展示区。
|
||||
*/
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 动画参数(需求 2.3:所有时长收进全局配置) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/*
|
||||
* ★ 下面这四个是**兜底默认值**,真正生效的值从全局配置里读
|
||||
* (设置 →「超时」→「动画」那一组,内核 `timeouts.py` 的 SPECS)。
|
||||
*
|
||||
* 为什么不在这里写死:需求 2.3 明确要求"所有时长与缓动数值收进全局配置"。
|
||||
* 用户嫌 1.5 秒的切换太慢时,改「中间留白」就能缩到 1.0 秒。
|
||||
*
|
||||
* 复用"超时"那套数值体系(而不是在 settings 里再开一个 agentAnim 对象)
|
||||
* 的理由写在 timeouts.py 那一段注释里:再造一套就是第二份要同步的东西。
|
||||
*/
|
||||
private fun animMs(key: String, fallback: Int): Int {
|
||||
val sec = com.doubao.lynxclone.data.AppTimeouts.seconds(key, fallback / 1000.0)
|
||||
// 0 是合法的(「中间留白」调成 0 = 不停顿),所以不能拿 0 当"没配"
|
||||
return if (sec.isNaN() || sec < 0) fallback else (sec * 1000).toInt()
|
||||
}
|
||||
|
||||
private const val DEF_FRONT_OUT = 300 // ① 旧角色图出
|
||||
private const val DEF_GAP = 500 // ② 间隔
|
||||
private const val DEF_FRAME = 400 // ③ 边框/背景/介绍(滑出 + 滑入各一半)
|
||||
private const val DEF_FRONT_IN = 300 // ④ 新角色图进
|
||||
|
||||
/** 侧移幅度占展示区宽度的比例。需求只说"侧移",幅度大了像翻页、小了看不出来 */
|
||||
private const val SHIFT = 0.10f
|
||||
|
||||
@Composable
|
||||
fun AgentSelectScreen(
|
||||
agents: List<Agent>,
|
||||
activeId: String,
|
||||
/** 选中并进入它的对话界面(需求 2.1:完成选择后进入对应智能体的对话界面) */
|
||||
onEnter: (Agent) -> Unit,
|
||||
/** 「更多」→ Token 用量详情(需求 2.4) */
|
||||
onMore: (Agent) -> Unit,
|
||||
/** 「记忆」→ 看它记住了什么(记忆管理界面的主入口) */
|
||||
onMemories: (Agent) -> Unit,
|
||||
/** 管理(新建 / 编辑 / 导入导出)—— 需求文档之外,但少了它用户没法加自己的智能体 */
|
||||
onManage: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
if (agents.isEmpty()) {
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg()), verticalArrangement = Arrangement.Center) {
|
||||
Text("还没有智能体", Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = doubaoText())
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text("点右上角「管理」新建或导入一个", Modifier.fillMaxWidth(),
|
||||
textAlign = TextAlign.Center, fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
TopAction("去管理", onClick = onManage)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val startIndex = agents.indexOfFirst { it.id == activeId }.coerceAtLeast(0)
|
||||
var picked by remember(agents.size) { mutableStateOf(startIndex) }
|
||||
// `shown` 是**画面上正在显示**的那个;picked 变了之后要等动画走到第③阶段才换它
|
||||
var shown by remember(agents.size) { mutableStateOf(startIndex) }
|
||||
val shownAgent = agents.getOrNull(shown) ?: agents.first()
|
||||
val pickedAgent = agents.getOrNull(picked) ?: agents.first()
|
||||
|
||||
val frontAlpha = remember { Animatable(1f) }
|
||||
val frontShift = remember { Animatable(0f) }
|
||||
val frameAlpha = remember { Animatable(1f) }
|
||||
val frameShift = remember { Animatable(0f) }
|
||||
val listState = rememberLazyListState()
|
||||
|
||||
// 每次重组都读一遍全局配置(用户在设置里改完回来,下一次切换就是新时长)
|
||||
val tFrontOut = animMs("agentAnim.frontOut", DEF_FRONT_OUT)
|
||||
val tGap = animMs("agentAnim.gap", DEF_GAP)
|
||||
val tFrame = animMs("agentAnim.frame", DEF_FRAME)
|
||||
val tFrontIn = animMs("agentAnim.frontIn", DEF_FRONT_IN)
|
||||
|
||||
LaunchedEffect(picked, agents.size) {
|
||||
if (picked == shown) return@LaunchedEffect
|
||||
// 目标在列表靠后 = 向左切换(新内容从右边进来)
|
||||
val dir = if (picked > shown) 1f else -1f
|
||||
|
||||
// ① 旧角色图渐出 + 侧移
|
||||
launch { frontAlpha.animateTo(0f, tween(tFrontOut, easing = FastOutSlowInEasing)) }
|
||||
frontShift.animateTo(-dir * SHIFT, tween(tFrontOut, easing = FastOutSlowInEasing))
|
||||
|
||||
// ② 间隔(需求明确定义了这一段留白;调成 0 就跳过)
|
||||
if (tGap > 0) delay(tGap.toLong())
|
||||
|
||||
// ③ 边框 / 背景 / 介绍:滑出 → 换数据 → 滑入
|
||||
val half = (tFrame / 2).coerceAtLeast(1)
|
||||
launch { frameAlpha.animateTo(0f, tween(half, easing = FastOutSlowInEasing)) }
|
||||
frameShift.animateTo(-dir * SHIFT, tween(half, easing = FastOutSlowInEasing))
|
||||
shown = picked
|
||||
launch { frameAlpha.animateTo(1f, tween(half, easing = LinearOutSlowInEasing)) }
|
||||
frameShift.animateTo(0f, tween(half, easing = LinearOutSlowInEasing))
|
||||
|
||||
// ④ 新角色图渐入 + 侧移到位
|
||||
frontShift.snapTo(dir * SHIFT)
|
||||
launch { frontAlpha.animateTo(1f, tween(tFrontIn, easing = LinearOutSlowInEasing)) }
|
||||
frontShift.animateTo(0f, tween(tFrontIn, easing = LinearOutSlowInEasing))
|
||||
}
|
||||
|
||||
// 选中的那项滚进视野(列表长了之后不滚的话用户看不到自己选了谁)
|
||||
LaunchedEffect(picked) {
|
||||
runCatching { listState.animateScrollToItem(picked) }
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||
// ---------------- 顶栏 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"← 返回",
|
||||
fontSize = 14.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onBack() }.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
"选择智能体",
|
||||
fontSize = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
TopTextAction("管理", onClick = onManage)
|
||||
}
|
||||
|
||||
// ---------------- 展示区 ----------------
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f)
|
||||
.padding(horizontal = 8.dp)
|
||||
.clip(RoundedCornerShape(18.dp)),
|
||||
) {
|
||||
// ① 背景图(最底层,铺满)—— 缺就用内置默认背景
|
||||
ArtworkFill(shownAgent.image.back, R.drawable.agent_default_background)
|
||||
|
||||
// ② 左侧列表(浮在背景上)
|
||||
AgentList(
|
||||
agents = agents,
|
||||
picked = picked,
|
||||
onPick = { picked = it },
|
||||
state = listState,
|
||||
modifier = Modifier.width(96.dp).fillMaxHeight().padding(8.dp),
|
||||
)
|
||||
|
||||
// ③ 角色图(居中)。★ 它和右侧的边框/介绍一起跟着 frameShift 动
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(start = 96.dp, end = 10.dp, top = 10.dp, bottom = 10.dp),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.offset(x = (frameShift.value * 180).dp)
|
||||
.alpha(frameAlpha.value),
|
||||
) {
|
||||
// ③-1 角色图
|
||||
Box(
|
||||
Modifier.fillMaxSize().offset(x = (frontShift.value * 200).dp),
|
||||
) {
|
||||
ArtworkFill(
|
||||
shownAgent.image.portrait,
|
||||
R.drawable.agent_default_character,
|
||||
alpha = frontAlpha.value,
|
||||
scale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
|
||||
// ③-2 介绍边框 + 介绍文本(需求 2.1 的第 4 层)
|
||||
IntroCard(
|
||||
agent = shownAgent,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(end = 6.dp, bottom = 10.dp)
|
||||
.width(200.dp),
|
||||
)
|
||||
|
||||
// ③-3 主体边框(画在最上层,纯装饰)
|
||||
MainBorder(shownAgent.image.borderMain)
|
||||
}
|
||||
}
|
||||
|
||||
// ④ 「更多」按钮(需求 2.4:圆形、竖排三点、在角色图附近)→ Token 用量
|
||||
Box(
|
||||
Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(top = 10.dp, end = 12.dp)
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color(0xCC1B2430))
|
||||
.clickable { onMore(shownAgent) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.MoreVert,
|
||||
contentDescription = "用量详情",
|
||||
tint = Color(0xFFE8EAED),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 底部:进对话 / 看记忆 ----------------
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// ★「记忆」和「开始对话」并排:进对话之前顺手看一眼它记住了什么。
|
||||
// 记忆是这个功能里最需要"用户能看见"的东西 —— AI 会记错
|
||||
// (把"喜欢猫"记成"讨厌猫"很常见),看见了才能改。
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { onMemories(pickedAgent) }
|
||||
.padding(horizontal = 20.dp, vertical = 14.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("记忆", fontSize = 15.sp, color = doubaoText())
|
||||
}
|
||||
Box(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.clip(RoundedCornerShape(26.dp))
|
||||
.background(
|
||||
Brush.horizontalGradient(listOf(Color(0xFF2B7BFF), Color(0xFF5B9BFF))),
|
||||
)
|
||||
.clickable { onEnter(pickedAgent) }
|
||||
.padding(vertical = 14.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
"开始对话",
|
||||
fontSize = 16.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color.White,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 四层的具体画法 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/** 铺满一层图;没有就用内置默认(需求 2.6 的最后一级回退) */
|
||||
@Composable
|
||||
private fun ArtworkFill(
|
||||
path: String,
|
||||
fallbackRes: Int,
|
||||
alpha: Float = 1f,
|
||||
scale: ContentScale = ContentScale.Crop,
|
||||
) {
|
||||
Box(Modifier.fillMaxSize().alpha(alpha)) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = scale,
|
||||
fallback = {
|
||||
// ★ 内置默认图:**必须画出来**,不能是空白 ——
|
||||
// 需求原话"任何智能体至少能以默认人物+默认背景+方框边框正常展示"
|
||||
Image(
|
||||
painter = painterResource(fallbackRes),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = scale,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 主体边框。缺的时候用**简单方框**(纯色细线矩形)兜底 */
|
||||
@Composable
|
||||
private fun MainBorder(path: String) {
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
if (canShowImage(path)) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.FillBounds,
|
||||
fallback = { SimpleFrame(shape) },
|
||||
)
|
||||
} else {
|
||||
SimpleFrame(shape)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SimpleFrame(shape: RoundedCornerShape) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.border(1.dp, Doubao.Blue.copy(alpha = 0.45f), shape),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 介绍卡片(需求 2.1 的"介绍边框 + 介绍文本")。
|
||||
*
|
||||
* 文本来自 `description`;缺失时**只显示智能体名**(需求原文)。
|
||||
*/
|
||||
@Composable
|
||||
private fun IntroCard(agent: Agent, modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Color(0xE6FFFDF5))
|
||||
.border(1.dp, Color(0x66B9A46A), RoundedCornerShape(14.dp))
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(
|
||||
agent.name,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color(0xFF2A2419),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
val desc = agent.description.trim().ifBlank { agent.greeting.trim() }
|
||||
if (desc.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
desc,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF4A4232),
|
||||
maxLines = 6,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 左侧列表:一张卡片 = 缩略图 + 名字;当前项高亮 */
|
||||
@Composable
|
||||
private fun AgentList(
|
||||
agents: List<Agent>,
|
||||
picked: Int,
|
||||
onPick: (Int) -> Unit,
|
||||
state: androidx.compose.foundation.lazy.LazyListState,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
LazyColumn(modifier, state = state, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
itemsIndexed(agents) { index, agent ->
|
||||
val on = index == picked
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (on) Color(0xCC2B7BFF) else Color(0x99101820))
|
||||
.border(
|
||||
width = if (on) 1.5.dp else 0.5.dp,
|
||||
color = if (on) Color(0xFFFFE08A) else Color(0x33FFFFFF),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
)
|
||||
.clickable { onPick(index) }
|
||||
.padding(4.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(52.dp)
|
||||
.clip(RoundedCornerShape(9.dp))
|
||||
.background(Color(0x33FFFFFF)),
|
||||
) {
|
||||
// 缩略图:也用角色图(缺就默认人物)—— 和右侧是同一套回退。
|
||||
// ★ alignment = TopCenter:角色图是竖长的,居中裁剪只会
|
||||
// 裁出"腰到大腿",一排缩略图全是裤子
|
||||
AssetImage(
|
||||
path = agent.image.portrait,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
fallback = {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
agent.name.ifBlank { "未命名" },
|
||||
fontSize = 11.sp,
|
||||
color = Color.White,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
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) {
|
||||
StatusRow(st)
|
||||
}
|
||||
}
|
||||
Hint(
|
||||
"定时状态每参与一轮减 1,归零就消失;持久状态不会自己过期。" +
|
||||
"状态提示词会被注入到它的系统提示里。",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@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) {
|
||||
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())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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),不然看着别扭 */
|
||||
private 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.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
@@ -47,6 +47,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
@@ -72,15 +73,33 @@ import com.doubao.lynxclone.data.VoiceOption
|
||||
*/
|
||||
@Composable
|
||||
fun AgentsScreen(vm: AppViewModel) {
|
||||
var editing by remember { mutableStateOf<Agent?>(null) }
|
||||
var creating by remember { mutableStateOf(false) }
|
||||
var confirmDelete by remember { mutableStateOf<Agent?>(null) }
|
||||
|
||||
// ★ 导入智能体包(需求 2.5):zip → base64 → 内核解包。
|
||||
// 不走 Kotlin 解压是因为安卓的 `ZipInputStream` **读不出**这类 zip
|
||||
// (Termux bootstrap 那个坑,见 TermuxInstaller 的注释),
|
||||
// 而内核的 Python `zipfile` 没这个问题 —— 少踩一次已知的坑。
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
val importPackage = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
androidx.activity.result.contract.ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
}.onSuccess { bytes ->
|
||||
vm.importPackage("agents", android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP), "")
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
val activeId = vm.state.activeAgent?.id.orEmpty()
|
||||
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
ScreenHeader("智能体", onBack = { vm.screen = Screen.Chat }) {
|
||||
TextButton(onClick = { creating = true }) { Text("新建", fontSize = 13.sp) }
|
||||
TextButton(onClick = {
|
||||
importPackage.launch(arrayOf("application/zip", "application/octet-stream", "*/*"))
|
||||
}) { Text("导入", fontSize = 13.sp) }
|
||||
TextButton(onClick = { vm.openAgentEdit(null) }) { Text("新建", fontSize = 13.sp) }
|
||||
}
|
||||
|
||||
Column(
|
||||
@@ -103,8 +122,11 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
agent = agent,
|
||||
active = agent.id == activeId,
|
||||
onUse = { vm.useAgent(agent.id) },
|
||||
onEdit = { editing = agent },
|
||||
onEdit = { vm.openAgentEdit(agent) },
|
||||
onMemories = { vm.openMemories(agent.id) },
|
||||
onDelete = { confirmDelete = agent },
|
||||
worldName = vm.state.worldviews
|
||||
.firstOrNull { it.id == agent.worldviewId }?.name.orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -113,7 +135,7 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = { creating = true },
|
||||
onClick = { vm.openAgentEdit(null) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
contentPadding = PaddingValues(vertical = 12.dp),
|
||||
@@ -129,41 +151,29 @@ fun AgentsScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
/* ---------------- 新建 / 编辑 ---------------- */
|
||||
if (creating || editing != null) {
|
||||
val target = editing
|
||||
AgentEditDialog(
|
||||
agent = target,
|
||||
providers = vm.state.providers.values.toList(),
|
||||
voices = vm.state.speechVoices,
|
||||
voicesAll = vm.state.speechVoicesAll,
|
||||
globalTtsEngine = vm.state.speech.ttsEngine,
|
||||
onDismiss = { creating = false; editing = null },
|
||||
onSave = { draft ->
|
||||
vm.saveAgent(target?.id, draft) {
|
||||
creating = false
|
||||
editing = null
|
||||
}
|
||||
},
|
||||
onDelete = if (target != null && !target.builtin) {
|
||||
{ confirmDelete = target }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
//
|
||||
// ★ 编辑走的是 **AgentEditScreen(全屏)**,不是这里原来那个弹窗。
|
||||
// 字段从 8 个涨到二十多个(外观四件套 / 模型引用 / 世界观 / 限额 / 技能……),
|
||||
// 弹窗装不下 —— AGENTS.md 那张表写得很清楚。
|
||||
// 删除确认**仍然是弹窗**:它就是"一次确认",正好是弹窗该用的地方。
|
||||
|
||||
/* ---------------- 删除确认 ---------------- */
|
||||
confirmDelete?.let { agent ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDelete = null },
|
||||
title = { Text("删除智能体", fontSize = 16.sp) },
|
||||
text = { Text("确定删除「${agent.name}」吗?它的系统提示词也会一起删掉,不能撤销。", fontSize = 13.sp) },
|
||||
text = {
|
||||
Text(
|
||||
"确定删除「${agent.name}」吗?\n\n" +
|
||||
"它的系统提示词和外观会一起删掉,不能撤销。\n" +
|
||||
"**记忆会保留**(那是你攒下来的东西,删之前建议先导出)。",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
vm.deleteAgent(agent.id)
|
||||
confirmDelete = null
|
||||
// 正在编辑的就是被删的那个的话,把编辑框一起关掉,否则保存会 404
|
||||
if (editing?.id == agent.id) editing = null
|
||||
}) { Text("删除") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmDelete = null }) { Text("取消") } },
|
||||
@@ -179,7 +189,11 @@ private fun AgentRow(
|
||||
active: Boolean,
|
||||
onUse: () -> Unit,
|
||||
onEdit: () -> Unit,
|
||||
/** 看这个智能体记住了什么(记忆管理界面的入口之一) */
|
||||
onMemories: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
/** 它绑的世界观叫什么(空 = 没绑)。交互是双向的,这边也要看得见 */
|
||||
worldName: String = "",
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onUse),
|
||||
@@ -215,7 +229,23 @@ private fun AgentRow(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
// ★ 绑了哪个世界观(用户要求"互通")——
|
||||
// 重点不是"它有个世界观",而是**它和谁共用记忆**。
|
||||
// 所以文案直接写"共用记忆",而不是干巴巴一个名字。
|
||||
if (agent.worldviewId.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"世界观「${worldName.ifBlank { "已失效" }}」· 记忆与同世界的智能体共用",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
// ★「记忆」放在「编辑」**左边**:它是"看它记住了什么",
|
||||
// 属于日常动作;编辑是配置动作,用得少。
|
||||
TextButton(onClick = onMemories) { Text("记忆", fontSize = 12.sp) }
|
||||
TextButton(onClick = onEdit) { Text("编辑", fontSize = 12.sp) }
|
||||
if (!agent.builtin) {
|
||||
TextButton(onClick = onDelete) { Text("删除", fontSize = 12.sp) }
|
||||
@@ -255,185 +285,6 @@ private fun ActiveBadge() {
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun AgentEditDialog(
|
||||
agent: Agent?,
|
||||
providers: List<ProviderPreset>,
|
||||
voices: Map<String, List<VoiceOption>>,
|
||||
voicesAll: Map<String, List<VoiceOption>>,
|
||||
/** 全局当前的朗读引擎:智能体没选引擎时,音色列表要按它来给 */
|
||||
globalTtsEngine: String,
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (Agent) -> Unit,
|
||||
onDelete: (() -> Unit)?,
|
||||
) {
|
||||
// 整份草稿:加字段时只要往 Agent 里加,不用再改一遍这里的所有 var
|
||||
var draft by remember {
|
||||
mutableStateOf(
|
||||
agent ?: Agent(avatar = "doubao"),
|
||||
)
|
||||
}
|
||||
var error by remember { mutableStateOf("") }
|
||||
val name = draft.name
|
||||
val avatar = draft.avatar
|
||||
val prompt = draft.systemPrompt
|
||||
val greeting = draft.greeting
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(if (agent == null) "新建智能体" else "编辑智能体", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
FormLabel("头像")
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
AvatarKeys.forEach { key ->
|
||||
Box(Modifier.clickable { draft = draft.copy(avatar = key) }) {
|
||||
// 选中态画在 AvatarCircle 的外圈上,不改变尺寸
|
||||
AvatarCircle(name = "", avatar = key, size = 34, selected = avatar == key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("名称")
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { draft = draft.copy(name = it) },
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
placeholder = { Text("例如:翻译官", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("问候语 / 一句话介绍")
|
||||
OutlinedTextField(
|
||||
value = greeting,
|
||||
onValueChange = { draft = draft.copy(greeting = it) },
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
placeholder = { Text("显示在列表里,也用作首屏问候", fontSize = 13.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Text(
|
||||
"列表摘要会显示这句;新会话首屏也用它打招呼。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormLabel("系统提示词")
|
||||
OutlinedTextField(
|
||||
value = prompt,
|
||||
onValueChange = { draft = draft.copy(systemPrompt = it) },
|
||||
modifier = Modifier.fillMaxWidth().height(150.dp).padding(top = 6.dp),
|
||||
placeholder = { Text("这个人设、规则、说话风格…", fontSize = 13.sp) },
|
||||
textStyle = TextStyle(fontSize = 13.sp),
|
||||
)
|
||||
Text(
|
||||
"和它聊天时,这段提示词会覆盖全局系统提示词。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
/* ---------------- 模型(留空 = 跟随全局) ---------------- */
|
||||
Spacer(Modifier.height(14.dp))
|
||||
FormLabel("模型")
|
||||
Text(
|
||||
"不选就跟随「设置 → 连接与模型」里的全局配置。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
WrapChips(
|
||||
options = listOf("" to "跟随全局") +
|
||||
providers.map { it.key to it.label },
|
||||
active = draft.provider,
|
||||
) { draft = draft.copy(provider = it) }
|
||||
Spacer(Modifier.height(6.dp))
|
||||
// ★ 别把 `ifBlank{…} == "x" ? a : b` 写成一整行:Kotlin 会把那个 `?`
|
||||
// 当成安全调用开始解析,报一堆看不懂的语法错。拆成变量最稳。
|
||||
val followGlobalModel = draft.provider.isBlank()
|
||||
OutlinedTextField(
|
||||
value = draft.model,
|
||||
onValueChange = { draft = draft.copy(model = it) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
placeholder = {
|
||||
Text(
|
||||
if (followGlobalModel) "留空 = 用全局模型" else "留空 = 用这家的默认模型",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
},
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
|
||||
/* ---------------- 语音(留空 = 跟随全局) ---------------- */
|
||||
Spacer(Modifier.height(14.dp))
|
||||
FormLabel("语音")
|
||||
Text(
|
||||
"多人会议里靠它区分谁在说话 —— 几个智能体一个嗓子的话根本听不出谁在讲。",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
WrapChips(
|
||||
options = listOf("" to "跟随全局") + TtsEngineChoices,
|
||||
active = draft.ttsEngine,
|
||||
) { engine ->
|
||||
// 换引擎顺手清掉音色:音色是按引擎命名的(BVxxx / zh_xxx_bigtts),
|
||||
// 留着上一家的值一定会被判非法
|
||||
draft = draft.copy(ttsEngine = engine, ttsVoice = "")
|
||||
}
|
||||
val voiceEngine = draft.ttsEngine.ifBlank { globalTtsEngine }
|
||||
if (voiceEngine != "" && voiceEngine != "system") {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
VoicePickerInline(
|
||||
engine = voiceEngine,
|
||||
voices = voices[voiceEngine].orEmpty(),
|
||||
voicesAll = voicesAll[voiceEngine].orEmpty(),
|
||||
value = draft.ttsVoice,
|
||||
onValue = { draft = draft.copy(ttsVoice = it) },
|
||||
)
|
||||
}
|
||||
|
||||
if (error.isNotBlank()) {
|
||||
Text(error, fontSize = 12.sp, color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
if (draft.name.isBlank()) {
|
||||
error = "名称不能为空"
|
||||
} else {
|
||||
onSave(draft.copy(name = draft.name.trim(), greeting = draft.greeting.trim()))
|
||||
}
|
||||
}) { Text("保存") }
|
||||
},
|
||||
dismissButton = {
|
||||
Row {
|
||||
if (onDelete != null) {
|
||||
TextButton(onClick = onDelete) {
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline,
|
||||
null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Text("删除", color = MaterialTheme.colorScheme.error, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
TextButton(onClick = onDismiss) { Text("取消") }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** 列表里那一行摘要文案 */
|
||||
private fun agentSummary(agent: Agent): String = when {
|
||||
agent.greeting.isNotBlank() -> agent.greeting
|
||||
agent.systemPrompt.isNotBlank() -> agent.systemPrompt.lineSequence().firstOrNull { it.isNotBlank() } ?: "通用助手"
|
||||
@@ -495,7 +346,7 @@ internal fun WrapChips(
|
||||
* 拽进智能体页 —— 真要统一的话应该把它提成公共组件,那是另一件事。
|
||||
*/
|
||||
@Composable
|
||||
private fun VoicePickerInline(
|
||||
internal fun VoicePickerInline(
|
||||
engine: String,
|
||||
voices: List<VoiceOption>,
|
||||
voicesAll: List<VoiceOption>,
|
||||
|
||||
@@ -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
|
||||
@@ -72,6 +76,46 @@ fun AppRoot(
|
||||
val vm = rememberAppViewModel(client)
|
||||
LaunchedEffect(Unit) { vm.refresh() }
|
||||
|
||||
/* ---------------- 记忆的导入 / 导出(SAF)----------------
|
||||
*
|
||||
* ★ 为什么用系统的文件选择器而不是自己写路径:安卓 11+ 已经不给
|
||||
* App 随便写公共目录了,SAF 是唯一"用户想存哪就存哪"的正路
|
||||
* (会议导出、节点导出都是这条路,见 MeetingsScreen)。
|
||||
* ★ 编码固定 UTF-8:记忆里有中文,用默认编码在别的机器上会变乱码。
|
||||
*/
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
var pendingExport by remember { mutableStateOf<String?>(null) }
|
||||
// 导入记忆:文件读出来了,等用户选合并还是覆盖
|
||||
var pendingImportJson by remember { mutableStateOf<String?>(null) }
|
||||
val createMemoryDoc = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/json"),
|
||||
) { uri ->
|
||||
val text = pendingExport
|
||||
pendingExport = null
|
||||
if (uri != null && text != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openOutputStream(uri)?.use { it.write(text.toByteArray(Charsets.UTF_8)) }
|
||||
}.onFailure { vm.showHint("导出失败:${it.message ?: "写不进去"}") }
|
||||
.onSuccess { vm.showHint("记忆已导出") }
|
||||
}
|
||||
}
|
||||
val importMemoryDoc = androidx.activity.compose.rememberLauncherForActivityResult(
|
||||
androidx.activity.result.contract.ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { input ->
|
||||
input.readBytes().toString(Charsets.UTF_8)
|
||||
} ?: ""
|
||||
}.onSuccess { text ->
|
||||
// ★ 读出来先**不导**,让用户选合并还是覆盖(复查报告 4.2.4)。
|
||||
// 原来这里是"直接按合并导" —— 于是 replace 这个能力
|
||||
// 内核支持、界面上却没有入口,等于只有一半。
|
||||
if (text.isNotBlank()) pendingImportJson = text
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
// 提示条 2.5 秒后自动消失
|
||||
LaunchedEffect(vm.hint) {
|
||||
if (vm.hint.isNotBlank()) {
|
||||
@@ -104,6 +148,18 @@ fun AppRoot(
|
||||
Screen.Settings -> SettingsScreen(vm)
|
||||
Screen.Skills -> SkillsScreen(vm)
|
||||
Screen.Agents -> AgentsScreen(vm)
|
||||
// 智能体选择界面(需求第二章):左列表 + 右角色展示 + 切换动画
|
||||
Screen.AgentSelect -> AgentSelectScreen(
|
||||
agents = vm.agents,
|
||||
activeId = vm.state.settings.activeAgentId,
|
||||
onEnter = { vm.enterAgent(it.id) },
|
||||
onMore = { vm.openTokenUsage(it.id) },
|
||||
onMemories = { vm.openMemories(it.id) },
|
||||
onManage = { vm.screen = Screen.Agents },
|
||||
onBack = { vm.screen = Screen.Chat },
|
||||
)
|
||||
// 世界观 / Skill / 模型列表(需求 3.3 / 3.6 / 3.7)
|
||||
Screen.Resources -> ResourcesScreen(vm) { vm.screen = Screen.Chat }
|
||||
Screen.Meetings -> MeetingsScreen(vm)
|
||||
Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux)
|
||||
}
|
||||
@@ -156,6 +212,10 @@ fun AppRoot(
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Skills
|
||||
},
|
||||
onOpenResources = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Resources
|
||||
},
|
||||
onOpenMeetings = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Meetings
|
||||
@@ -188,6 +248,237 @@ fun AppRoot(
|
||||
)
|
||||
}
|
||||
|
||||
// 世界观的**共享记忆**(从「资源 → 世界观 → 记忆」进来)。
|
||||
//
|
||||
// ★ 它和上面那个是同一个空间(world:<uuid>)的**另一个视角**:
|
||||
// 那边问"玄辰记住了什么",这边问"这个世界里大家共同记得什么"。
|
||||
// 纯只读 —— 写入限权是按 author 判的,而这个视角没有"我"。
|
||||
AnimatedVisibility(
|
||||
visible = vm.worldMemoryId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MemoryScreen(
|
||||
space = vm.worldMemorySpace,
|
||||
agentName = vm.state.worldviews.firstOrNull { it.id == vm.worldMemoryId }?.name
|
||||
?: "世界观",
|
||||
agentId = "",
|
||||
agentNames = vm.agents.associate { it.id to it.name },
|
||||
worldMode = true,
|
||||
loading = false,
|
||||
hint = "",
|
||||
onSetEmotion = { _, _ -> },
|
||||
onAdd = { _, _ -> },
|
||||
onUpdate = { _, _, _ -> },
|
||||
// 删是可以的:限权只约束 AI,用户有权清掉任何人写的
|
||||
onDelete = { vm.deleteWorldMemory(it) },
|
||||
onTogglePin = { _, _ -> },
|
||||
onSummarize = {},
|
||||
onExport = {},
|
||||
onSetWindow = {},
|
||||
onImportClick = {},
|
||||
onOpenOwn = {},
|
||||
onBackToActive = {},
|
||||
onBack = { vm.closeWorldMemories() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「智能体编辑」—— 全屏界面(字段二十多个,弹窗装不下,见 AGENTS.md 那张表)
|
||||
AnimatedVisibility(
|
||||
visible = vm.agentEditOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
AgentEditScreen(
|
||||
vm = vm,
|
||||
initial = vm.agentEditing,
|
||||
onDone = { vm.closeAgentEdit() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「用量」详情 —— 选择界面上的「更多」按钮(需求 2.4 / 3.1)
|
||||
AnimatedVisibility(
|
||||
visible = vm.tokenUsageOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
TokenUsageScreen(
|
||||
usage = vm.tokenUsage,
|
||||
onReset = { vm.tokenUsage?.agentId?.takeIf { it.isNotBlank() }?.let { vm.resetTokenUsage(it) } },
|
||||
onBack = { vm.closeTokenUsage() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「记忆」管理(需求 3.2 的"用户手动编辑兜底")
|
||||
AnimatedVisibility(
|
||||
visible = vm.memoryAgentId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
MemoryScreen(
|
||||
space = vm.memorySpace,
|
||||
agentName = vm.agents.firstOrNull { it.id == vm.memoryAgentId }?.name ?: "",
|
||||
agentId = vm.memoryAgentId,
|
||||
agentNames = vm.agents.associate { it.id to it.name },
|
||||
loading = vm.memoryLoading,
|
||||
hint = vm.memoryHint,
|
||||
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) },
|
||||
onTogglePin = { id, p -> vm.toggleMemoryPin(id, p) },
|
||||
onSummarize = { vm.summarizeMemories() },
|
||||
onExport = { vm.exportMemories { text -> pendingExport = text } },
|
||||
onSetWindow = { vm.setMemoryWindow(it) },
|
||||
onImportClick = { importMemoryDoc.launch(arrayOf("application/json", "text/plain", "*/*")) },
|
||||
onOpenOwn = { vm.openMemories(vm.memoryAgentId, own = true) },
|
||||
onBackToActive = { vm.openMemories(vm.memoryAgentId, own = false) },
|
||||
onBack = { vm.closeMemories() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「新建群聊」:挑一个搭子(当前智能体当主角 = 主智能体)
|
||||
//
|
||||
// ★ 用对话框而不是全屏:这是**一次选择**(挑一个人就完了),
|
||||
// 智能体一般不超过十个,一屏放得下 —— 正是 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)。
|
||||
//
|
||||
// ★ 默认是合并:覆盖是破坏性的,用户点错一次就全没了。
|
||||
// 所以「覆盖」那个按钮上直接写清后果 —— 不给"确定/取消"这种看不出区别的选项。
|
||||
pendingImportJson?.let { text ->
|
||||
val count = runCatching {
|
||||
org.json.JSONObject(text).optJSONArray("smartMemory")?.length() ?: 0
|
||||
}.getOrDefault(0)
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { pendingImportJson = null },
|
||||
title = { Text("怎么导入", fontSize = 16.sp) },
|
||||
text = {
|
||||
Text(
|
||||
"这个文件里有 $count 条记忆。\n\n" +
|
||||
"合并:只加没有的(按标题判重),现有的全留着,情绪也不动。\n" +
|
||||
"覆盖:先把现在这 ${vm.memorySpace?.memories?.size ?: 0} 条全删掉," +
|
||||
"再换成文件里的,情绪也一起换掉。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { pendingImportJson = null; vm.importMemories(text, "merge") },
|
||||
) { Text("合并(推荐)") }
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { pendingImportJson = null; vm.importMemories(text, "replace") },
|
||||
) { Text("覆盖", color = androidx.compose.ui.graphics.Color(0xFFD93025)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 拿到 JSON 之后再弹存盘对话框(先有内容才能给文件名,顺序不能反)
|
||||
LaunchedEffect(pendingExport) {
|
||||
val text = pendingExport ?: return@LaunchedEffect
|
||||
if (text.isNotBlank()) {
|
||||
runCatching {
|
||||
createMemoryDoc.launch(
|
||||
"${vm.agents.firstOrNull { it.id == vm.memoryAgentId }?.name ?: "agent"}-记忆.json",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 「超时」—— 所有超时都能调(入口在设置页)
|
||||
AnimatedVisibility(
|
||||
visible = vm.timeoutsOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
TimeoutsScreen(
|
||||
state = vm.timeouts,
|
||||
saving = vm.timeoutsSaving,
|
||||
onSave = { vm.saveTimeouts(it) },
|
||||
onReset = { vm.resetTimeouts() },
|
||||
onBack = { vm.closeTimeouts() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「AI 界面」列表(用户要求"AI 写的界面可以再点开")。
|
||||
// 排在 HTML 界面之下:点一个就从列表进到界面。
|
||||
AnimatedVisibility(
|
||||
@@ -289,8 +580,24 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
// 分区标题:抽屉里两组东西(功能 / 对话)不标一下容易混在一起看
|
||||
SectionLabel("功能", Modifier.padding(horizontal = 20.dp, vertical = 6.dp))
|
||||
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||
// ★「新建群聊」(v1.2 §3.9):以前只有「[群成员] → 加人」能建群,
|
||||
// 那条路藏得太深 —— 用户想拉几个人一起聊,得先想到去成员页。
|
||||
// 放抽屉里是因为它和「开启新话题」是同一类动作(都是"开一个新的")。
|
||||
DrawerItem(Icons.Filled.Group, "新建群聊") {
|
||||
vm.drawerOpen = false
|
||||
vm.newGroupTopic()
|
||||
}
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
vm.screen = Screen.Agents; vm.drawerOpen = false
|
||||
// ★ 抽屉这一项进的是**选择界面**(需求 2.1 的入口页),
|
||||
// 管理(新建/编辑/导入导出)在那个页面的「管理」里
|
||||
vm.screen = Screen.AgentSelect; vm.drawerOpen = false
|
||||
}
|
||||
// ★「记忆」:当前这个智能体记住了什么。
|
||||
// 给它一个抽屉直达入口,因为这是**日常要看**的东西 ——
|
||||
// 你得知道它记对没记错(AI 记反了"喜欢猫/讨厌猫"这种事很常见)。
|
||||
DrawerItem(Icons.Filled.Psychology, "记忆") {
|
||||
vm.drawerOpen = false
|
||||
vm.activeAgent?.id?.let { vm.openMemories(it) }
|
||||
}
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
DrawerItem(Icons.Filled.EditNote, "笔记") {
|
||||
|
||||
226
android/app/src/main/java/com/doubao/lynxclone/ui/AssetImage.kt
Normal file
@@ -0,0 +1,226 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.ImageDecoder
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.widget.ImageView
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import java.io.File
|
||||
|
||||
/*
|
||||
* 显示智能体/世界观包里的图片资源。
|
||||
*
|
||||
* ## ★ 为什么不用 Coil / Glide
|
||||
*
|
||||
* 项目一直坚持**零第三方依赖**(安卓端构建要能离线完成、APK 也不要多几百 KB)。
|
||||
* 而这里要的东西其实很窄:显示一个已知路径的本地图片。
|
||||
* Android 原生的三套 API 正好够:
|
||||
*
|
||||
* · PNG / JPG → `BitmapFactory.decodeFile`(所有版本)
|
||||
* · GIF 动图 → `ImageDecoder.decodeDrawable`(API 28+,低版本退化成静态第一帧)
|
||||
* · SVG → 原生**解不了**,走 WebView(项目里已经大量在用 WebView)
|
||||
*
|
||||
* ## 为什么静态图不统一走 ImageView
|
||||
*
|
||||
* 因为 Compose 的 `Image(bitmap)` 在裁剪/圆角/缩放上比 `AndroidView` 包一层
|
||||
* 可控得多(`Modifier.clip` / `ContentScale` 直接生效),而 GIF 又必须用
|
||||
* `Drawable`(Compose 没有原生的动图 Painter,accompanist 是第三方)。
|
||||
* 所以按扩展名分流:常见的静态图走低成本那条,动图才付出 AndroidView 的代价。
|
||||
*
|
||||
* ## 缺失资源的回退(需求 2.6)
|
||||
*
|
||||
* 回退是**调用方**的事(`AgentArtwork` 里判的),这里只负责"路径给了就画"。
|
||||
* 给空路径、文件不存在,这里返回 false 让调用方决定显示什么。
|
||||
*/
|
||||
|
||||
private const val TAG = "DoubaoImage"
|
||||
|
||||
/** 这个文件是哪种图(按扩展名,和内核 uploads.py 一个思路) */
|
||||
private enum class ImageKind { Static, Gif, Svg, Unknown }
|
||||
|
||||
private fun kindOf(path: String): ImageKind = when (File(path).extension.lowercase()) {
|
||||
"gif" -> ImageKind.Gif
|
||||
"svg" -> ImageKind.Svg
|
||||
"png", "jpg", "jpeg", "webp", "bmp" -> ImageKind.Static
|
||||
else -> ImageKind.Unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* 画一张本地图片。
|
||||
*
|
||||
* @param path 绝对路径(内核给的就是绝对路径)
|
||||
* @param fallback 画不出来时显示什么(通常是默认图或一个占位框)
|
||||
*/
|
||||
@Composable
|
||||
fun AssetImage(
|
||||
path: String,
|
||||
modifier: Modifier = Modifier,
|
||||
contentScale: ContentScale = ContentScale.Fit,
|
||||
/**
|
||||
* 裁剪时对齐哪儿。
|
||||
*
|
||||
* ★ 缩略图必须给 `TopCenter`:角色图是**竖长**的(头在上半部分),
|
||||
* 居中对齐裁出来的是"腰到大腿"——列表里一排裤子,谁也认不出是谁。
|
||||
*/
|
||||
alignment: Alignment = Alignment.Center,
|
||||
fallback: @Composable () -> Unit = {},
|
||||
) {
|
||||
val file = remember(path) { if (path.isBlank()) null else File(path) }
|
||||
if (file == null || !file.isFile) {
|
||||
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
|
||||
return
|
||||
}
|
||||
|
||||
when (kindOf(path)) {
|
||||
ImageKind.Svg -> SvgImage(file, modifier)
|
||||
ImageKind.Gif -> DrawableImage(file, modifier, contentScale, alignment, fallback)
|
||||
else -> StaticImage(file, modifier, contentScale, alignment, fallback)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StaticImage(
|
||||
file: File,
|
||||
modifier: Modifier,
|
||||
contentScale: ContentScale,
|
||||
alignment: Alignment,
|
||||
fallback: @Composable () -> Unit,
|
||||
) {
|
||||
// ★ remember(file.path):同一张图不重复解码。列表里滚动时这一下省很多。
|
||||
val bitmap = remember(file.path) {
|
||||
runCatching { BitmapFactory.decodeFile(file.path) }.getOrNull()
|
||||
}
|
||||
if (bitmap == null) {
|
||||
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
|
||||
return
|
||||
}
|
||||
Image(
|
||||
bitmap = bitmap.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = modifier,
|
||||
contentScale = contentScale,
|
||||
alignment = alignment,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 动图(GIF)。
|
||||
*
|
||||
* ★ API 28 以下 `ImageDecoder` 不存在 —— 退回 `BitmapFactory` 拿第一帧,
|
||||
* 至少不是空白。项目 minSdk 是 24,所以这条分支真的会走到。
|
||||
*/
|
||||
@Composable
|
||||
private fun DrawableImage(
|
||||
file: File,
|
||||
modifier: Modifier,
|
||||
contentScale: ContentScale,
|
||||
alignment: Alignment,
|
||||
fallback: @Composable () -> Unit,
|
||||
) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
|
||||
StaticImage(file, modifier, contentScale, alignment, fallback)
|
||||
return
|
||||
}
|
||||
val drawable: Drawable? = remember(file.path) {
|
||||
runCatching {
|
||||
// ★ 宽度在 `info` 上(`ImageDecoder` 自己只有 setTargetSampleSize)——
|
||||
// 写成 `decoder.width` 是编译不过的
|
||||
ImageDecoder.decodeDrawable(ImageDecoder.createSource(file)) { decoder, info, _ ->
|
||||
// 缩到 1024 以内:包里的图可能很大,全尺寸解码在低端机上会 OOM
|
||||
val w = info.size.width
|
||||
if (w > 1024) decoder.setTargetSampleSize(kotlin.math.round(w / 1024f).coerceAtLeast(1f).toInt())
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
if (drawable == null) {
|
||||
Box(modifier, contentAlignment = Alignment.Center) { fallback() }
|
||||
return
|
||||
}
|
||||
AndroidView(
|
||||
modifier = modifier,
|
||||
factory = { ctx ->
|
||||
ImageView(ctx).apply {
|
||||
setImageDrawable(drawable)
|
||||
scaleType = when (contentScale) {
|
||||
ContentScale.Crop -> ImageView.ScaleType.CENTER_CROP
|
||||
ContentScale.FillBounds -> ImageView.ScaleType.FIT_XY
|
||||
else -> ImageView.ScaleType.FIT_CENTER
|
||||
}
|
||||
}
|
||||
},
|
||||
// 动图由 Drawable 自己驱动,不需要在 update 里做任何事;
|
||||
// 但路径变了要换图 —— 这个 composable 的 key 已经是路径,重建即可。
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* SVG。
|
||||
*
|
||||
* ★ 原生解不了 SVG(`BitmapFactory` 直接返回 null),而引一个 SVG 库
|
||||
* 就破了"零第三方依赖"。项目里已经有成熟的 WebView 通道
|
||||
* (AI 界面就全靠它),所以这里用 WebView 单图显示。
|
||||
*
|
||||
* ★ 关掉一切交互:它是**背景/装饰**,不能抢走列表的滑动和点击。
|
||||
*/
|
||||
@Composable
|
||||
private fun SvgImage(file: File, modifier: Modifier) {
|
||||
AndroidView(
|
||||
modifier = modifier,
|
||||
factory = { ctx ->
|
||||
android.webkit.WebView(ctx).apply {
|
||||
setBackgroundColor(android.graphics.Color.TRANSPARENT)
|
||||
settings.javaScriptEnabled = false
|
||||
settings.allowFileAccess = true
|
||||
isClickable = false
|
||||
isFocusable = false
|
||||
// 让触摸穿透到下面的列表(不然在列表里滑动会被 WebView 吃掉)
|
||||
setOnTouchListener { _, _ -> false }
|
||||
loadDataWithBaseURL(
|
||||
"file://" + file.parent + "/",
|
||||
"""<html><head><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<style>html,body{margin:0;padding:0;background:transparent;height:100%}
|
||||
img{width:100%;height:100%;object-fit:contain}</style></head>
|
||||
<body><img src="${file.name}"></body></html>""",
|
||||
"text/html", "UTF-8", null,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** 占位:没有图时显示一个淡淡的灰框 + 可选文字(需求 2.6 的"简单方框") */
|
||||
@Composable
|
||||
fun ImagePlaceholder(modifier: Modifier = Modifier, text: String = "") {
|
||||
Box(
|
||||
modifier.then(Modifier.fillMaxSize()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (text.isNotBlank()) {
|
||||
Text(text, fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 图片能不能画出来(调用方据此决定要不要回退到默认资源) */
|
||||
fun canShowImage(path: String): Boolean {
|
||||
if (path.isBlank()) return false
|
||||
val f = File(path)
|
||||
if (!f.isFile) {
|
||||
Log.w(TAG, "图片不存在:$path")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -43,6 +43,7 @@ import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
@@ -181,7 +182,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() }
|
||||
}
|
||||
@@ -328,7 +335,82 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
)
|
||||
}
|
||||
} else {
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
// 本次对话的用量(需求 4.1)跟着输入条一起显示 ——
|
||||
// 放在输入框正上方是因为它是"这次对话"的属性,而输入框就是这次对话的入口
|
||||
// ★ 群聊的成员快捷条(v1.2 §3.9):点头像 = @ 点名,被点的人这一轮一定发言
|
||||
GroupQuickBar(vm)
|
||||
SessionUsageBar(vm)
|
||||
// 额度用完被拦住了 → 给出路(复查报告 2.4)。
|
||||
// 只拦不给入口的话,用户会以为这个智能体坏了。
|
||||
if (vm.tokenLimitHit) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x1AD93025))
|
||||
.padding(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"额度用完了,这轮没发出去。",
|
||||
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 {
|
||||
vm.dismissLimitHit()
|
||||
vm.openTokenUsage(
|
||||
vm.limitAgentId.ifBlank { vm.activeAgent?.id ?: "" },
|
||||
)
|
||||
}
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
// ★★ 死亡禁言(v1.2 §6.1,需求 3.5)。
|
||||
//
|
||||
// 内核那道拦截是权威,但**界面上也要拦一道** ——
|
||||
// 让用户敲完一整句话、点发送、再被拒绝,是最差的体验。
|
||||
// 提示条点一下直达记忆页的情绪区(那就是复活入口)。
|
||||
val deadAgent = vm.activeAgent
|
||||
if (deadAgent != null && vm.state.emotions[deadAgent.id]?.dead == true) {
|
||||
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 { vm.openMemories(deadAgent.id) }
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,11 +443,15 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
HeaderIcon(Icons.Filled.Edit, "新话题") { vm.newTopic() }
|
||||
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 中间这块点开就是「模型」,和豆包一样(豆包点的是 Agent 名)
|
||||
// 中间这块点开是**智能体选择界面**(需求 2.1:它是"选择智能体的入口页")。
|
||||
//
|
||||
// ★ 以前点这里是「模型」面板 —— 但用户想"换个人聊"时点的是名字,
|
||||
// 而模型是"换脑子"、不是"换人",两者混在一个入口里说不清。
|
||||
// 模型仍然在抽屉里有独立入口(那才是它该在的地方)。
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.clickable { vm.modelPickerOpen = true }
|
||||
.clickable { vm.screen = Screen.AgentSelect }
|
||||
.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
@@ -373,10 +459,45 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
Modifier.size(24.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
|
||||
// 有自定义角色图就显示它(需求 2.5 的资源回退在内核侧已经落定,
|
||||
// 这里 path 为空就还是原来的图标)
|
||||
val art = vm.activeAgent?.image?.portrait.orEmpty()
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = art,
|
||||
modifier = Modifier.fillMaxSize().clip(CircleShape),
|
||||
contentScale = ContentScale.Crop,
|
||||
fallback = {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
|
||||
},
|
||||
)
|
||||
} else {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp))
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(agentName, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
// ★ 当前情绪(复查报告 2.6):AI 自己能改情绪,改了却看不出来,
|
||||
// 这个功能就只是个看不见的字段。放在名字旁边、字号小一半 ——
|
||||
// 它是个状态注脚,不该抢名字的注意力。
|
||||
// ★ 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(
|
||||
emoLabel.take(8),
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.padding(horizontal = 5.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
Icon(Icons.Filled.ChevronRight, null, tint = doubaoText(), modifier = Modifier.size(18.dp))
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
@@ -605,6 +726,29 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 幻觉调用检测的警示(需求 3.7):它说了"我记住了"但这一轮没调工具。
|
||||
//
|
||||
// 放在正文**下面**而不是塞进正文:这是"系统对这条回复的批注",
|
||||
// 不是 AI 说的话 —— 混进正文里,用户会以为 AI 自己在自我怀疑。
|
||||
if (msg.hallucination) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(Color(0x1AF29900))
|
||||
.padding(horizontal = 8.dp, vertical = 5.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"⚠ 它说记住了,但这一轮并没有真的调用记忆工具 —— 下次可能就不记得了。",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
modifier = Modifier.widthIn(max = 280.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (!msg.pending && msg.content.isNotBlank() && !msg.error) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -739,6 +883,51 @@ private fun AttachmentStrip(vm: AppViewModel) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 本次对话的 Token 用量(需求 4.1)。
|
||||
*
|
||||
* ## 为什么按消息加起来,而不是问内核要一个"会话总数"
|
||||
*
|
||||
* 因为用量是**按轮记在消息上的**(内核落库时就这么存的)。加起来算有两个好处:
|
||||
* · "重新生成"把上一条替换掉时,它的消耗自动消失,不会虚高
|
||||
* · 删掉某条消息、切换会话、界面刷新,都不需要额外请求
|
||||
*
|
||||
* ## 为什么没有用量时**整行不显示**
|
||||
*
|
||||
* 一条消息都还没发(或者老数据里没记用量)时显示"入 0 · 出 0"是纯噪音。
|
||||
* 需求要的是"能看到用了多少",不要求一直占一行。
|
||||
*/
|
||||
@Composable
|
||||
private fun SessionUsageBar(vm: AppViewModel) {
|
||||
val inTok = vm.messages.sumOf { it.usage?.first ?: 0L }
|
||||
val outTok = vm.messages.sumOf { it.usage?.second ?: 0L }
|
||||
if (inTok == 0L && outTok == 0L) return
|
||||
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 20.dp, end = 20.dp, bottom = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text("本次对话", fontSize = 10.sp, color = Doubao.TextTertiary)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("输入 ${fmtTokens(inTok)}", fontSize = 10.sp, color = Doubao.TextTertiary)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("输出 ${fmtTokens(outTok)}", fontSize = 10.sp, color = Doubao.TextTertiary)
|
||||
Spacer(Modifier.weight(1f))
|
||||
// 点一下看智能体的**累计**用量(那个在「更多」里,需求 3.1)
|
||||
Text(
|
||||
"累计 ›",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.clickable { vm.activeAgent?.id?.let { vm.openTokenUsage(it) } }
|
||||
.padding(horizontal = 4.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputBar(
|
||||
vm: AppViewModel,
|
||||
@@ -949,3 +1138,37 @@ private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 群聊的成员快捷条(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),
|
||||
) {
|
||||
// 主智能体标一下:没人被 @ 时由它接话,用户得知道"不点名也有话说"
|
||||
for ((i, pair) in members.withIndex()) {
|
||||
val label = if (i == 0) "${pair.second}(主)" else pair.second
|
||||
DoubaoPill(text = "@$label", onClick = { vm.draft = vm.draft + "@${pair.second} " })
|
||||
}
|
||||
RowAction("成员") { vm.openMembers(conv.id) }
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.core.*
|
||||
import androidx.compose.foundation.background
|
||||
@@ -277,3 +277,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,190 @@
|
||||
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) }
|
||||
val hostId = conv?.participants?.firstOrNull().orEmpty()
|
||||
|
||||
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()
|
||||
val candidates = vm.state.agents.filter { it.id !in inGroup }
|
||||
SectionLabel("拉谁进来")
|
||||
Card {
|
||||
if (candidates.isEmpty()) {
|
||||
Hint("所有智能体都在群里了。")
|
||||
} 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
|
||||
}.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(a, 36)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a.name, fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
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 }
|
||||
val isHost = id == hostId
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(a, 40)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
a?.name ?: "(已删除)",
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
if (isHost) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
HostBadge()
|
||||
}
|
||||
}
|
||||
Text(
|
||||
if (isHost) "没人被 @ 的时候由它接话"
|
||||
else "第 ${i + 1} 个进群的",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("状态") { onOpenStats(id) }
|
||||
if (!isHost) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
// ★ 主智能体走不到这里(上面那个 if)—— 它是兜底发言的人
|
||||
RowAction("移出") { vm.removeMember(id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint(
|
||||
"在聊天页的输入框上方点成员头像就是 @ 点名 —— " +
|
||||
"被点的人这一轮一定发言。没人被点时由主智能体兜底,不会冷场。",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 「主智能体」小标签(它和普通成员的区别只在兜底发言,用个浅色标签就够) */
|
||||
@Composable
|
||||
private fun HostBadge() {
|
||||
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),
|
||||
)
|
||||
}
|
||||
|
||||
/** 成员的小头像(有立绘用立绘,没有就用名字首字) */
|
||||
@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(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,666 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
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.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.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
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.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
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
|
||||
|
||||
/*
|
||||
* 记忆管理(需求 3.2 / 3.5)。
|
||||
*
|
||||
* ## 这个界面存在的理由
|
||||
*
|
||||
* 需求里记忆是"**混合制**":AI 通过工具自主读写,**用户手动编辑兜底**。
|
||||
* 没有这个界面,"兜底"就是空话 —— AI 记错了东西,用户只能干看着
|
||||
* (而他会记错:模型把"他喜欢猫"记成"他讨厌猫"这种事很常见)。
|
||||
*
|
||||
* 顺带把三样东西一起放进来,因为它们都是"这个智能体的内在状态":
|
||||
* · 情绪(需求 3.5:用户可手动编辑)
|
||||
* · AI 提的"该整理记忆了"建议(需求 3.2:仅提示,用户确认才执行)
|
||||
* · 导入 / 导出(需求 3.4)
|
||||
*
|
||||
* ## 共享记忆要**显式说明**
|
||||
*
|
||||
* 绑了世界观的智能体,记忆是和同世界观其他智能体**共用**的。
|
||||
* 界面上不写清楚的话,用户会以为"我给 A 记的东西怎么 B 也知道" ——
|
||||
* 所以顶部有一条明显的提示。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
fun MemoryScreen(
|
||||
space: MemorySpace?,
|
||||
agentName: String,
|
||||
/** 正在看谁的记忆 —— 用来判断"这条是不是别人写的" */
|
||||
agentId: String,
|
||||
/** 所有智能体的 id → 名字(共享记忆里显示"由某某写入") */
|
||||
agentNames: Map<String, String>,
|
||||
/**
|
||||
* **世界观视角**("这个世界里大家共同记得什么")。
|
||||
*
|
||||
* ★ 只读:增删改仍从智能体那边做。世界观视角没有"我",
|
||||
* 而共享空间的写入限权是按 author 判的(需求 3.6)——
|
||||
* 硬做一个权限含义不明的界面,只会让人误操作。
|
||||
* 情绪也藏起来:情绪是**智能体私有**的,不属于这个空间。
|
||||
*/
|
||||
worldMode: Boolean = false,
|
||||
loading: Boolean,
|
||||
hint: String,
|
||||
/** 保存情绪:preset(五档)+ text(自由一句) */
|
||||
onSetEmotion: (String, String) -> Unit,
|
||||
onAdd: (String, String) -> Unit,
|
||||
onUpdate: (String, String?, String?) -> Unit,
|
||||
onDelete: (String) -> Unit,
|
||||
onTogglePin: (String, Boolean) -> Unit,
|
||||
onSummarize: () -> Unit,
|
||||
onExport: () -> Unit,
|
||||
/** 调注入窗口(条数,0 = 不限) */
|
||||
onSetWindow: (Int) -> Unit,
|
||||
/** 由调用方弹文件选择器;选完之后的"合并/覆盖"选择也在那边做 */
|
||||
onImportClick: () -> Unit,
|
||||
/** 去看绑定世界观**之前**攒的私有记忆 */
|
||||
onOpenOwn: () -> Unit,
|
||||
/** 从旧空间回到当前生效的空间 */
|
||||
onBackToActive: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
var editing by remember { mutableStateOf<MemoryItem?>(null) }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
/** 情绪的双字段草稿(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 = 不限) */
|
||||
var editWindow by remember { mutableStateOf(false) }
|
||||
var windowDraft by remember(space?.window) { mutableStateOf((space?.window ?: 0).toString()) }
|
||||
val readingOwn = space?.own == true
|
||||
|
||||
FullScreen(
|
||||
title = "记忆",
|
||||
subtitle = buildString {
|
||||
append(agentName.ifBlank { "智能体" })
|
||||
append(" · ")
|
||||
when {
|
||||
worldMode -> append("世界观共享记忆")
|
||||
readingOwn -> append("绑定前的私有记忆")
|
||||
space == null -> append("读取中")
|
||||
space.shared -> append("世界观共享记忆")
|
||||
else -> append("私有记忆")
|
||||
}
|
||||
space?.let { append(" ${it.memories.size} 条") }
|
||||
if (loading) append(" · 处理中…")
|
||||
},
|
||||
onBack = { if (readingOwn) onBackToActive() else onBack() },
|
||||
actions = {
|
||||
// 世界观视角是纯只读(导入/导出都以"某个智能体的记忆"为单位,
|
||||
// 而这里没有"我")—— 不给按钮,而不是给一个点了没反应的按钮
|
||||
if (!worldMode && !readingOwn) TopTextAction("导入", onClick = onImportClick)
|
||||
},
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
/* ---- 空间标识(复查报告 4.1)----
|
||||
*
|
||||
* ★ 这是这个界面最重要的一段字。
|
||||
* 绑定世界观之后读写空间会从私有换成共享,列表看起来"变空了" ——
|
||||
* 记忆一条没丢,但不说明的话用户必然判定"绑定把我的记忆清了"。
|
||||
*/
|
||||
if (readingOwn) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x1AF29900))
|
||||
.clickable { onBackToActive() }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这是绑定世界观之前攒的私有记忆,现在只供查看。" +
|
||||
"AI 当前读的是共享空间那份 —— 点这里回到当前空间。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
} else if ((space?.ownCount ?: 0) > 0) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onOpenOwn() }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"绑定世界观之前你给这个智能体攒过 ${space?.ownCount} 条私有记忆,还留着。" +
|
||||
"AI 现在读的是上面那个共享空间 —— 点这里去看那些 ›",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 注入窗口(一遍看不出来"哪些真的进去了",所以直接写清)----
|
||||
if (!readingOwn && !worldMode && space != null) {
|
||||
val total = space.memories.size
|
||||
val win = space.window
|
||||
val injected = space.injected
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { windowDraft = win.toString(); editWindow = true }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Column {
|
||||
Text(
|
||||
// ★ "列表里有 300 条"和"带进去 50 条"是完全不同的两件事。
|
||||
// 不写清楚的话,用户会以为记忆全都在提示词里。
|
||||
"这一轮会带进去 $injected / $total 条",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
buildString {
|
||||
append("窗口:")
|
||||
append(if (win <= 0) "不限(全部都带)" else "最近 $win 条")
|
||||
append("。")
|
||||
// ★ "能置顶几条"必须在界面上说清:不说的话用户会默认
|
||||
// "只能有一条"(很自然的假设),而实际上标几条都行,
|
||||
// 而且它们**永远**带进去、不受窗口限制。
|
||||
append(
|
||||
if (space.pinnedCount > 0) "已置顶 ${space.pinnedCount} 条"
|
||||
else "可以置顶任意多条"
|
||||
)
|
||||
append(",置顶的永远带、不受窗口限制")
|
||||
if (injected < total) {
|
||||
append(";没带进去的没丢,AI 用 memory_search 还能搜到")
|
||||
}
|
||||
append("。 点这里调 ›")
|
||||
},
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 共享记忆提示(不写清楚用户会以为记忆串了)----
|
||||
if (worldMode) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x14F29900))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这是这个世界观里所有人共同记得的 —— 绑定了它的智能体共用这一份。\n" +
|
||||
"这里只供查看(改和删请从各自的智能体进去,那边才知道「我」是谁);" +
|
||||
"每条都标了是谁写的。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
} else if (space?.shared == true) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color(0x14F29900))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(
|
||||
"这个智能体绑定了世界观,记忆是和同世界观的其他智能体共用的。\n" +
|
||||
"它能改自己写的条目;改别人的(或删)需要你在这里手动操作。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- AI 的建议(需求 3.2:仅提示,用户确认才执行)----
|
||||
if (!space?.suggestion.isNullOrBlank()) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.08f))
|
||||
.padding(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("AI 觉得记忆该整理一下了", fontSize = 12.sp, color = Doubao.Blue)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(space?.suggestion ?: "", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Text(
|
||||
"整理",
|
||||
fontSize = 13.sp,
|
||||
color = Color.White,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Doubao.Blue)
|
||||
.clickable(enabled = !loading) { onSummarize() }
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (hint.isNotBlank()) {
|
||||
Text(
|
||||
hint,
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 情绪(世界观视角没有"自己的情绪",隐藏)----
|
||||
if (!worldMode) {
|
||||
SectionLabel("情绪")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"preset 决定系统行为(立绘换哪张、能不能对话、同伴看到什么脸色);" +
|
||||
"下面那句话只是扮演质感。AI 自己能改,你也可以在这里改。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
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 = 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(emotionPreset, emotionText.trim()) },
|
||||
enabled = emotionPreset != (space?.emotion?.preset ?: "平常") ||
|
||||
emotionText.trim() != (space?.emotion?.text ?: ""),
|
||||
) { Text("保存情绪", fontSize = 13.sp) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 操作条 ----
|
||||
SectionLabel("记忆(按时间排,最新的在下面)")
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
if (!readingOwn && !worldMode) SmallAction("+ 加一条") { adding = true }
|
||||
if (!readingOwn && !worldMode) {
|
||||
SmallAction(if (loading) "整理中…" else "AI 整理") {
|
||||
// ★ 先确认再调(复查报告 4.2.1):整理是**一次真的 LLM 调用**、
|
||||
// 会改掉现有记忆,而且用户可能刚标好了「必须保留」——
|
||||
// 让他有机会在动手前把那几条标上
|
||||
if (!loading) confirmSummarize = true
|
||||
}
|
||||
}
|
||||
SmallAction("导出文件", onClick = onExport)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
// ---- 列表 ----
|
||||
val items = space?.memories ?: emptyList()
|
||||
if (items.isEmpty()) {
|
||||
Text(
|
||||
if (loading) "读取中…" else "还没有记忆。AI 觉得有值得记住的事时会自己记下来。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 16.dp),
|
||||
)
|
||||
}
|
||||
for (m in items) {
|
||||
// ★ 共享空间里「别人写的」条目要标出来、并且**禁掉编辑和删除**
|
||||
// (复查报告 4.2.2)。不给禁用态的话,用户点了删除被后端拒绝,
|
||||
// 他会当成 bug —— 而后端拦得对(需求 3.6:只能改自己写的)。
|
||||
val author = m.authorAgent.trim()
|
||||
val mine = author.isEmpty() || author == agentId
|
||||
val authorName = if (author.isEmpty()) "" else (agentNames[author] ?: "另一个智能体")
|
||||
MemoryRow(
|
||||
item = m,
|
||||
readOnly = readingOwn,
|
||||
// 别人写的 = 界面上不给改删的入口(不是"点了才报错")
|
||||
foreign = !mine,
|
||||
authorName = if (mine) "" else authorName,
|
||||
onEdit = { editing = m },
|
||||
onDelete = { onDelete(m.id) },
|
||||
onTogglePin = { onTogglePin(m.id, !m.pinned) },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(28.dp))
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 注入窗口的调整(A 方案)----
|
||||
if (editWindow) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { editWindow = false },
|
||||
title = { Text("注入窗口", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"每轮最多把多少条记忆放进提示词。\n\n" +
|
||||
"置顶的永远带,不受这个数限制 —— 而且可以置顶任意多条" +
|
||||
"(标几条都行,它们一定都在)。\n" +
|
||||
"其余按时间取最近的。没带进去的不会丢," +
|
||||
"AI 用 memory_search 还能搜到。\n\n" +
|
||||
"填 0 = 不限(全量注入)。记忆攒到几百条时提示词会很贵," +
|
||||
"而且早期的会挤掉最近的对话上下文。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = windowDraft,
|
||||
onValueChange = { s -> windowDraft = s.filter { it.isDigit() }.take(5) },
|
||||
label = { Text("条数(0 = 不限)", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
editWindow = false
|
||||
onSetWindow(windowDraft.toIntOrNull() ?: 0)
|
||||
}) { Text("保存") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { editWindow = false }) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- AI 整理的确认(复查报告 4.2.1)----
|
||||
if (confirmSummarize) {
|
||||
val pinnedCount = space?.memories?.count { it.pinned } ?: 0
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmSummarize = false },
|
||||
title = { Text("让 AI 整理一次记忆", fontSize = 16.sp) },
|
||||
text = {
|
||||
Text(
|
||||
buildString {
|
||||
append("这会把现在这 ${space?.memories?.size ?: 0} 条零散、重复的记忆")
|
||||
append("压缩成更少、更完整的几条。\n\n")
|
||||
append("· 标了「置顶」的(现在有 $pinnedCount 条)原样不动,不参与合并\n")
|
||||
append("· 它只做合并改写,不许编造新的事实\n")
|
||||
append("· 这是一次真实的模型调用,会花 Token(但不受额度限制)\n\n")
|
||||
append("想保住哪几条,先取消对话框去标上「置顶」。")
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { confirmSummarize = false; onSummarize() }) { Text("开始整理") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmSummarize = false }) { Text("先去标几条") } },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 导入模式选择放在调用方(它管文件选择器)----
|
||||
|
||||
// ---- 编辑 / 新增 ----
|
||||
val target = editing
|
||||
if (target != null || adding) {
|
||||
MemoryEditDialog(
|
||||
initial = target,
|
||||
onDismiss = { editing = null; adding = false },
|
||||
onSave = { title, content ->
|
||||
if (target == null) onAdd(title, content) else onUpdate(target.id, title, content)
|
||||
editing = null
|
||||
adding = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SmallAction(label: String, onClick: () -> Unit) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 12.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MemoryRow(
|
||||
item: MemoryItem,
|
||||
/** 在看旧空间 → 一切都只读(那里已经不属于当前对话了,改了会让人困惑) */
|
||||
readOnly: Boolean,
|
||||
/** 这条是**别人写的**(共享空间里)→ 不给改删入口,并且标出来源 */
|
||||
foreign: Boolean,
|
||||
authorName: String,
|
||||
onEdit: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onTogglePin: () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.border(
|
||||
width = if (item.pinned) 1.dp else 0.dp,
|
||||
color = if (item.pinned) Color(0x66F29900) else Color.Transparent,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
)
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (item.pinned) {
|
||||
Text(
|
||||
"置顶",
|
||||
fontSize = 9.sp,
|
||||
color = Color(0xFF8A6100),
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Color(0x22F29900))
|
||||
.padding(horizontal = 5.dp, vertical = 2.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
// ★ 来源标注(复查报告 4.2.2):共享空间里必须看得出这条是谁写的。
|
||||
// 不标的话用户点删除会被后端拒绝,他会当成 bug —— 而后端拦得对。
|
||||
if (foreign && authorName.isNotBlank()) {
|
||||
Text(
|
||||
"由 $authorName 写入",
|
||||
fontSize = 9.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.padding(horizontal = 5.dp, vertical = 2.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
Text(
|
||||
item.title.ifBlank { "(无标题)" },
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
if (item.content.isNotBlank()) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(item.content, fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
if (readOnly) {
|
||||
Text(
|
||||
"绑定世界观之前的记忆,只供查看",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else if (foreign) {
|
||||
// 别人写的:不是"按钮点了才报错",而是**根本不给按钮**
|
||||
Text(
|
||||
"别人写的,AI 和你都改不了这一条(要删只能在这里删)",
|
||||
fontSize = 10.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
RowAction("删除", danger = true, onClick = onDelete)
|
||||
} else {
|
||||
// ★「必须保留」是**用户**的权利(需求 3.2):标上之后 AI 总结时
|
||||
// 不参与合并、AI 自己也改不动 —— 所以这个开关只在界面上给。
|
||||
// 再点一次就是**解除**(复查报告 4.2.3 担心的"解不开"不存在,
|
||||
// 但文案要写成"取消保留",不能只显示当前状态)
|
||||
RowAction(if (item.pinned) "取消置顶" else "置顶", onClick = onTogglePin)
|
||||
RowAction("编辑", onClick = onEdit)
|
||||
RowAction("删除", danger = true, onClick = onDelete)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MemoryEditDialog(
|
||||
initial: MemoryItem?,
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (String, String) -> Unit,
|
||||
) {
|
||||
var title by remember { mutableStateOf(initial?.title ?: "") }
|
||||
var content by remember { mutableStateOf(initial?.content ?: "") }
|
||||
// ★ 单条记忆的编辑用弹窗是合适的(内容量小、就是两个输入框);
|
||||
// 而"列表 / 多组配置"一律全屏 —— 见 AGENTS.md 那张表
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(if (initial == null) "加一条记忆" else "编辑记忆", fontSize = 16.sp) },
|
||||
text = {
|
||||
Column {
|
||||
OutlinedTextField(
|
||||
value = title,
|
||||
onValueChange = { title = it },
|
||||
label = { Text("标题", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = content,
|
||||
onValueChange = { content = it },
|
||||
label = { Text("内容", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 90.dp, max = 220.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = { onSave(title.trim(), content.trim()) },
|
||||
enabled = title.isNotBlank() || content.isNotBlank(),
|
||||
) { Text("保存") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
@@ -22,6 +22,7 @@ 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.Layers
|
||||
import androidx.compose.material.icons.filled.Public
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -55,6 +56,7 @@ import androidx.compose.ui.unit.sp
|
||||
fun MoreSheetScreen(
|
||||
onOpenAiScreens: () -> Unit,
|
||||
onOpenSkills: () -> Unit,
|
||||
onOpenResources: () -> Unit,
|
||||
onOpenMeetings: () -> Unit,
|
||||
onOpenTerminal: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
@@ -81,6 +83,15 @@ fun MoreSheetScreen(
|
||||
subtitle = "AI 弹过的界面都存着,点一下就能再打开",
|
||||
) { onOpenAiScreens() }
|
||||
}
|
||||
item {
|
||||
// 世界观 / Skill / 模型列表(需求 3.3 / 3.6 / 3.7)——
|
||||
// 它们是"全局资源"那一层:都被智能体引用,都是列表 + 增删改 + 导入导出
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Public,
|
||||
title = "世界观 · 技能 · 模型",
|
||||
subtitle = "共享记忆的世界、AI 的工具手册、可选模型列表",
|
||||
) { onOpenResources() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Layers,
|
||||
|
||||
@@ -0,0 +1,630 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
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.fillMaxSize
|
||||
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.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
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.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.AgentImage
|
||||
import com.doubao.lynxclone.data.ModelEntry
|
||||
import com.doubao.lynxclone.data.SkillItem
|
||||
import com.doubao.lynxclone.data.WorldviewItem
|
||||
|
||||
/*
|
||||
* 世界观 / Skill / 模型列表的管理界面(需求 3.3 / 3.6 / 3.7)。
|
||||
*
|
||||
* ## 为什么三种东西挤在一个界面里
|
||||
*
|
||||
* 它们是**同一层的东西**:都是"全局资源",都被智能体引用,都是"列表 + 增删改 +
|
||||
* 导入导出"。分开成三个入口的话,用户要记住"世界观在哪、技能在哪、模型在哪"——
|
||||
* 而它们其实是一件事("这个 App 里有哪些可复用的东西")。
|
||||
*
|
||||
* ## 表单是**字段驱动**的,不是写三份
|
||||
*
|
||||
* 三种资源的表单字段完全不同(世界观有设定文本 + 四件套;Skill 就两行;
|
||||
* 模型有地址/标识/Key/单价),但**长得一模一样** —— 都是一个 label + 一个输入框。
|
||||
* 所以用 `List<Field>` 描述,渲染只有一份。
|
||||
*
|
||||
* 写三份的话,加一个字段就要改三处,而这个仓库里"加了 list 类型但某张表没跟上"
|
||||
* 已经反复出现过(AGENTS.md 第一条就是它)。
|
||||
*/
|
||||
|
||||
/** 表单里的一个字段 */
|
||||
private data class Field(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val placeholder: String = "",
|
||||
val multiline: Boolean = false,
|
||||
val password: Boolean = false,
|
||||
val number: Boolean = false,
|
||||
/** 开关:值的约定是 `"1"` = 开、`""` = 关(不弹键盘,点一下切换) */
|
||||
val toggle: Boolean = false,
|
||||
)
|
||||
|
||||
private val WORLD_FIELDS = listOf(
|
||||
Field("name", "名字", "比如:九霄"),
|
||||
Field(
|
||||
"setting", "世界观设定",
|
||||
"这个世界的规则、背景、称呼……(绑定了它的智能体,提示词里会整段带上)",
|
||||
multiline = true,
|
||||
),
|
||||
)
|
||||
|
||||
private val SKILL_FIELDS = listOf(
|
||||
Field("name", "名字", "比如:写代码的规矩"),
|
||||
Field(
|
||||
"content", "内容",
|
||||
"告诉 AI 有哪些工具、什么时候用、用完之后不许干什么",
|
||||
multiline = true,
|
||||
),
|
||||
)
|
||||
|
||||
private val MODEL_FIELDS = listOf(
|
||||
Field("name", "显示名", "比如:豆包 Pro"),
|
||||
Field("apiBase", "API 地址", "https://ark.cn-beijing.volces.com/api/v3"),
|
||||
Field("model", "模型标识", "doubao-seed-2-1-pro-260628"),
|
||||
Field("apiKey", "API Key", "留空则用全局设置里那个", password = true),
|
||||
Field("provider", "提供商", "ark / openai / deepseek …(留空则跟随全局)"),
|
||||
Field("pricePerK", "单价(元/千 Token)", "留空 = 不显示费用估算", number = true),
|
||||
Field(
|
||||
"noTools", "不支持工具调用",
|
||||
"这个模型不会 function calling(本地小模型、老网关常见)。打开之后不再传 tools," +
|
||||
"改成让它在正文里写调用,内核执行完再剥掉 —— 记忆和情绪照常能用。",
|
||||
toggle = true,
|
||||
),
|
||||
)
|
||||
|
||||
/** 三张表:kind → (标题、字段、说明、是不是包) */
|
||||
private class Kind(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val tabLabel: String,
|
||||
val fields: List<Field>,
|
||||
val hint: String,
|
||||
/** 导入导出是 zip 包(世界观)还是单个 JSON(Skill) */
|
||||
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 = "纯文本的「工具使用手册」。内置的记忆/情绪/用量手册**默认就生效**;这里写的是你自己加的规矩。",
|
||||
),
|
||||
Kind(
|
||||
"models", "模型", "模型", MODEL_FIELDS, isZip = false,
|
||||
hint = "全局模型列表。智能体按 id 引用这里的某一项 —— 所以换 Key 只改一处," +
|
||||
"而且**导出智能体包时不会把 Key 带出去**。",
|
||||
),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
var tab by remember { mutableStateOf(0) }
|
||||
// 正在编辑的那一项(null 且 editing 为 true = 新建)
|
||||
var editing by remember { mutableStateOf<Boolean>(false) }
|
||||
var editId by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
val kind = KINDS[tab]
|
||||
val items: List<Pair<String, Triple<String, String, AgentImage>>> = when (kind.id) {
|
||||
"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):进了编辑页才知道
|
||||
// 这个模型不传 tools,等于用户永远想不起自己开过它
|
||||
it.id to Triple(
|
||||
if (it.noTools) "${it.name}(兼容模式)" else it.name,
|
||||
listOf(it.model, it.apiBase).filter { s -> s.isNotBlank() }.joinToString(" · "),
|
||||
AgentImage(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 导入导出(SAF)----------------
|
||||
* zip 走 base64(二进制没法塞进 JSON 文本),Skill 是纯 JSON 文本。
|
||||
*/
|
||||
val ctx = LocalContext.current
|
||||
var pendingExport by remember { mutableStateOf<Triple<String, String, String>?>(null) }
|
||||
val saveDoc = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("*/*")) { uri ->
|
||||
val data = pendingExport
|
||||
pendingExport = null
|
||||
if (uri != null && data != null) {
|
||||
runCatching {
|
||||
val bytes = if (data.second == "zip") Base64.decode(data.first, Base64.DEFAULT)
|
||||
else data.first.toByteArray(Charsets.UTF_8)
|
||||
ctx.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
|
||||
}.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) {
|
||||
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))
|
||||
}
|
||||
}.onFailure { vm.showHint("读不出这个文件") }
|
||||
}
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = "资源",
|
||||
subtitle = "世界观 · 规则包 · 技能 · 模型(${vm.state.agents.size} 个智能体在引用)",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("导入") {
|
||||
if (kind.isZip) openDoc.launch(arrayOf("application/zip", "application/octet-stream", "*/*"))
|
||||
else openDoc.launch(arrayOf("application/json", "text/plain", "*/*"))
|
||||
}
|
||||
},
|
||||
) {
|
||||
// ---- Tab ----
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
|
||||
for ((i, k) in KINDS.withIndex()) {
|
||||
val on = i == tab
|
||||
Text(
|
||||
k.tabLabel,
|
||||
fontSize = 13.sp,
|
||||
color = if (on) Color.White else doubaoText(),
|
||||
modifier = Modifier
|
||||
.padding(end = 8.dp)
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(if (on) Doubao.Blue else doubaoCard())
|
||||
.clickable { tab = i }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("新建") {
|
||||
// ★ 规则包**不是**"填两个字段就完事"的东西 —— 它的内容
|
||||
// (定义表 + 脚本)在独立的全屏编辑页里。
|
||||
// 所以「新建」直接建一个**带模板**的包并进去,
|
||||
// 而不是先弹"名称+说明"的表单、再让用户自己去找编辑器。
|
||||
if (kind.id == "rulepacks") { vm.createRulePackFromTemplate(); return@RowAction }
|
||||
editId = null; editing = true
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState())) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.07f))
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Text(kind.hint.replace("**", ""), fontSize = 11.sp, lineHeight = 16.sp, color = Doubao.Blue)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
if (items.isEmpty()) {
|
||||
Text(
|
||||
"还没有。点右上角「新建」,或者用「导入」拿一个现成的包。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 20.dp),
|
||||
)
|
||||
}
|
||||
|
||||
for ((id, info) in items) {
|
||||
val (name, preview, image) = info
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable {
|
||||
// ★ 规则包走**独立的全屏编辑页** —— 它的内容
|
||||
// (定义表 + 脚本)不是"label + 输入框"那套表单
|
||||
// 能表达的,硬塞进去会变成一堆看不懂的文本框
|
||||
if (kind.id == "rulepacks") { vm.openRulePackEdit(id); return@clickable }
|
||||
editId = id; editing = true
|
||||
}
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (kind.id == "worldviews") {
|
||||
Box(
|
||||
Modifier
|
||||
.size(46.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
) {
|
||||
AssetImage(
|
||||
path = image.slot("平常"),
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name.ifBlank { "未命名" }, fontSize = 14.sp, color = doubaoText())
|
||||
if (preview.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
preview.replace("\n", " ").take(70),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
// ★ 谁绑了它(用户要求)—— 反过来也得看得见:
|
||||
// 绑之前你要知道"这个世界观已经有谁在用了",
|
||||
// 空的则说明没人用它、共享记忆也没人在读写。
|
||||
if (kind.id == "worldviews") {
|
||||
val users = vm.state.worldviews.firstOrNull { it.id == id }?.agents ?: emptyList()
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
if (users.isEmpty()) "还没有智能体用它"
|
||||
else "${users.size} 个智能体在用:${users.joinToString("、") { it.name }}",
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 14.sp,
|
||||
color = if (users.isEmpty()) doubaoTextSecondary() else Doubao.Blue,
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
}
|
||||
RowAction("记忆") {
|
||||
// ★ 世界观的**共享记忆**("大家共同记得什么")——
|
||||
// 和从智能体进去看的是同一个空间、不同的视角
|
||||
vm.openWorldMemories(id)
|
||||
}
|
||||
RowAction("导出") {
|
||||
vm.exportPackage(kind.id, id) { content, ext ->
|
||||
pendingExport = Triple(content, ext, "x")
|
||||
saveDoc.launch("${name.ifBlank { "resource" }}.${if (kind.isZip) "zip" else "json"}")
|
||||
}
|
||||
}
|
||||
RowAction("删除", danger = true) { vm.deleteResource(kind.id, id) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (editing) {
|
||||
ResourceEditScreen(
|
||||
vm = vm,
|
||||
kind = kind,
|
||||
id = editId,
|
||||
onDone = { editing = false; editId = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 字段驱动的编辑表单 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@Composable
|
||||
private fun ResourceEditScreen(
|
||||
vm: AppViewModel,
|
||||
kind: Kind,
|
||||
id: String?,
|
||||
onDone: () -> Unit,
|
||||
) {
|
||||
// 三种资源的初始值从内存里那份拿(列表就是它渲染的,不会对不上)
|
||||
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)
|
||||
} ?: emptyMap()
|
||||
"skills" -> vm.state.skills.firstOrNull { it.id == id }?.let {
|
||||
mapOf("name" to it.name, "content" to it.content)
|
||||
} ?: emptyMap()
|
||||
else -> vm.state.modelEntries.firstOrNull { it.id == id }?.let {
|
||||
mapOf(
|
||||
"name" to it.name, "apiBase" to it.apiBase, "model" to it.model,
|
||||
"apiKey" to "", "provider" to it.provider,
|
||||
"pricePerK" to if (it.pricePerK > 0) it.pricePerK.toString() else "",
|
||||
"noTools" to if (it.noTools) "1" else "",
|
||||
)
|
||||
} ?: emptyMap()
|
||||
}
|
||||
}
|
||||
var values by remember(id, kind.id) { mutableStateOf(initial) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var worldImage by remember(id, kind.id) {
|
||||
mutableStateOf(vm.state.worldviews.firstOrNull { it.id == id }?.image ?: AgentImage())
|
||||
}
|
||||
val ctx = LocalContext.current
|
||||
|
||||
var pendingSlot by remember { mutableStateOf("") }
|
||||
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
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("读不出这张图") }
|
||||
}
|
||||
// 上传完 image 会变,跟着刷新预览
|
||||
vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
if (it.image != worldImage) worldImage = it.image
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = if (id == null) "新建${kind.title}" else "编辑${kind.title}",
|
||||
subtitle = values["name"].orEmpty().ifBlank { kind.title },
|
||||
onBack = onDone,
|
||||
actions = {
|
||||
TopAction("保存", enabled = !saving) {
|
||||
saving = true
|
||||
val name = values["name"].orEmpty().trim()
|
||||
val text = values[
|
||||
if (kind.id == "models") "apiBase" else if (kind.id == "skills") "content" else "setting"
|
||||
].orEmpty()
|
||||
val extra = mutableMapOf<String, Any?>()
|
||||
if (kind.id == "models") {
|
||||
extra["model"] = values["model"].orEmpty()
|
||||
extra["apiKey"] = values["apiKey"].orEmpty()
|
||||
extra["provider"] = values["provider"].orEmpty()
|
||||
extra["pricePerK"] = values["pricePerK"]?.toDoubleOrNull() ?: 0.0
|
||||
extra["noTools"] = values["noTools"] == "1"
|
||||
}
|
||||
if (kind.id == "worldviews") extra["image"] = worldImage
|
||||
vm.saveResource(kind.id, id, name, text, extra) { saving = false; onDone() }
|
||||
}
|
||||
},
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
SectionLabel("基本信息")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
for (f in kind.fields) {
|
||||
// ---- 开关型字段:点一下切换,不弹键盘 ----
|
||||
if (f.toggle) {
|
||||
val on = values[f.key] == "1"
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(f.label, fontSize = 13.sp, color = doubaoText())
|
||||
if (f.placeholder.isNotBlank()) {
|
||||
Text(
|
||||
f.placeholder,
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.size(width = 44.dp, height = 26.dp)
|
||||
.clip(RoundedCornerShape(13.dp))
|
||||
.background(if (on) Doubao.Blue else Doubao.Border)
|
||||
.clickable { values = values + (f.key to if (on) "" else "1") },
|
||||
contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart,
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 3.dp)
|
||||
.size(20.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(Color.White),
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
continue
|
||||
}
|
||||
Text(f.label, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedTextField(
|
||||
value = values[f.key].orEmpty(),
|
||||
onValueChange = { v ->
|
||||
// 单价只收数字和小数点;别的字段原样收
|
||||
values = values + (f.key to if (f.number) v.filter { c -> c.isDigit() || c == '.' } else v)
|
||||
},
|
||||
placeholder = { Text(f.placeholder, fontSize = 12.sp) },
|
||||
singleLine = !f.multiline,
|
||||
visualTransformation = if (f.password) PasswordVisualTransformation()
|
||||
else androidx.compose.ui.text.input.VisualTransformation.None,
|
||||
keyboardOptions = if (f.number) KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
else KeyboardOptions.Default,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.then(if (f.multiline) Modifier.heightIn(min = 120.dp, max = 300.dp) else Modifier),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- 世界观的四件套(需求 3.6:沿用智能体那一套)---- */
|
||||
if (kind.id == "worldviews") {
|
||||
SectionLabel("外观(四件套)")
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) {
|
||||
if (id == null) {
|
||||
Text(
|
||||
"先保存,再回来加外观图片(图片要落到这个世界观自己的目录里)。",
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
val slots = listOf(
|
||||
Triple("front", "封面 / 代表图", "智能体选择界面上用的那张"),
|
||||
Triple("back", "背景图", "铺在展示区最底层"),
|
||||
Triple("border-main", "主体边框", "框住整个展示区"),
|
||||
Triple("border-info", "介绍边框", "围住介绍文本"),
|
||||
)
|
||||
for ((key, title, desc) in slots) {
|
||||
val path = when (key) {
|
||||
"front" -> worldImage.slot("平常")
|
||||
"back" -> worldImage.back
|
||||
"border-main" -> worldImage.borderMain
|
||||
else -> worldImage.borderInfo
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(46.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(doubaoCard())
|
||||
.border(0.5.dp, Doubao.Border, RoundedCornerShape(8.dp)),
|
||||
) {
|
||||
AssetImage(
|
||||
path = path,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 13.sp, color = doubaoText())
|
||||
Text(desc, fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
RowAction("选择") {
|
||||
pendingSlot = key
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
}
|
||||
if (path.isNotBlank()) {
|
||||
RowAction("清除", danger = true) {
|
||||
vm.uploadWorldviewAsset(id, key, "", "")
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(20.dp))
|
||||
if (id != null && kind.id == "skills") {
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
TextButton(onClick = { vm.deleteResource(kind.id, id); onDone() }) {
|
||||
Text("删除这个 Skill", color = Color(0xFFD93025), fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -495,6 +495,22 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
FormHint("当前发现 Python 工具 ${vm.state.tools.size} 个 · MCP 工具 ${vm.state.mcp.sumOf { it.toolCount }} 个(在「技能·连接器」里看明细)")
|
||||
}
|
||||
|
||||
/* ---------------- 超时 ---------------- */
|
||||
// ★ 这一页**不在这个「保存设置」里** —— 超时有自己的接口
|
||||
// (/api/timeouts)和自己的全屏界面,改一项立刻生效。
|
||||
// 混进"本地草稿 + 一次性保存"反而会让用户以为要按保存。
|
||||
SettingsCard("超时") {
|
||||
NavRow(
|
||||
label = "超时设置",
|
||||
value = if (vm.timeouts.items.isEmpty()) "" else "${vm.timeouts.items.size} 项",
|
||||
onClick = { vm.openTimeouts() },
|
||||
)
|
||||
FormHint(
|
||||
"模型回复、工具执行、命令、MCP、语音、等用户回答……所有超时都能在这里调。" +
|
||||
"「等用户回答」默认是不限时。",
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 个人资料 ---------------- */
|
||||
SettingsCard("个人资料") {
|
||||
FormLabel("昵称")
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
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.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
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.focus.onFocusChanged
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.TimeoutItem
|
||||
import com.doubao.lynxclone.data.TimeoutsState
|
||||
|
||||
/*
|
||||
* 「设置 → 超时」:所有超时都能在这儿调。
|
||||
*
|
||||
* ## 为什么做成全屏界面而不是弹窗
|
||||
*
|
||||
* 见 AGENTS.md「少用弹窗,能开界面就开界面」—— 这里有 17 项、每项还带两三行说明,
|
||||
* 弹窗装不下(用户得在一个半屏高的框里滚十几屏)。
|
||||
*
|
||||
* ## ★★ 这一页**没有硬编码任何一项**
|
||||
*
|
||||
* 有哪些超时、叫什么、默认多少、能填多大、说明写什么 —— 全部来自内核
|
||||
* (`GET /api/timeouts` ← `android/kernel/timeouts.py` 的 SPECS)。
|
||||
*
|
||||
* 这么做的理由不是"架构好看",而是这个东西以前正是**反面教材**:
|
||||
* 15 个超时散在 10 个文件里当模块级常量,加一个超时要改好几处,
|
||||
* 而"到底有几个超时"这个问题谁都答不上来。现在加一项只改内核那一个文件,
|
||||
* 这一页自动多出一行。
|
||||
*
|
||||
* ## 怎么算保存
|
||||
*
|
||||
* 不做"保存按钮":点 +/- 立刻存,输入框失焦时存。
|
||||
* 每个改动都只发**改的那一项**(内核会并到当前值上),所以两项之间不会互相覆盖。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
fun TimeoutsScreen(
|
||||
state: TimeoutsState,
|
||||
saving: Boolean,
|
||||
/** 只传改过的那一项 */
|
||||
onSave: (Map<String, Double>) -> Unit,
|
||||
onReset: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
FullScreen(
|
||||
title = "超时",
|
||||
subtitle = if (saving) "保存中…" else "改完立刻生效,不用重启",
|
||||
onBack = onBack,
|
||||
actions = { TopTextAction("恢复默认", onClick = onReset) },
|
||||
) {
|
||||
if (state.items.isEmpty()) {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
if (state.error.isBlank()) "正在从内核读取…" else state.error,
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
for ((group, items) in state.groups) {
|
||||
SectionLabel(group)
|
||||
for (item in items) {
|
||||
TimeoutRow(item = item, onSave = onSave)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"说明:这些值的边界由内核把关(填超了会自动夹回去)。" +
|
||||
"「不限时」表示会一直等,不会自己放弃。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(14.dp),
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TimeoutRow(item: TimeoutItem, onSave: (Map<String, Double>) -> Unit) {
|
||||
// 输入框里的**草稿**(用户可能正在打字,这时候不能立刻拿它去保存,
|
||||
// 否则打到一半的 "18" 会被当成 18 存进去)
|
||||
var draft by remember(item.key) { mutableStateOf(fmt(item.value)) }
|
||||
var editing by remember(item.key) { mutableStateOf(false) }
|
||||
|
||||
// 值被外部改掉时(保存回来 / 恢复默认)同步草稿,但**别打断正在输入的人**
|
||||
if (!editing && draft != fmt(item.value)) draft = fmt(item.value)
|
||||
|
||||
val step = stepOf(item)
|
||||
|
||||
fun commit(raw: String) {
|
||||
val v = raw.trim().toDoubleOrNull() ?: item.value
|
||||
val clamped = v.coerceIn(item.min, item.max)
|
||||
draft = fmt(clamped)
|
||||
if (kotlin.math.abs(clamped - item.value) > 0.001) {
|
||||
onSave(mapOf(item.key to clamped))
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(item.label, fontSize = 14.sp, color = doubaoText())
|
||||
if (item.isDefault) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("默认", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
StepButton("−") {
|
||||
val next = (item.value - step).coerceAtLeast(item.min)
|
||||
draft = fmt(next)
|
||||
onSave(mapOf(item.key to next))
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = draft,
|
||||
onValueChange = { draft = it.filter { c -> c.isDigit() || c == '.' } },
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier
|
||||
.width(78.dp)
|
||||
.height(48.dp)
|
||||
.onFocusChanged { st ->
|
||||
if (st.isFocused) {
|
||||
editing = true
|
||||
} else if (editing) {
|
||||
editing = false
|
||||
commit(draft)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
StepButton("+") {
|
||||
val next = (item.value + step).coerceAtMost(item.max)
|
||||
draft = fmt(next)
|
||||
onSave(mapOf(item.key to next))
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
// 0 且允许 0 时显示"不限时",比"0 秒"清楚得多
|
||||
if (item.unlimited) "${item.zero} (${item.unit})"
|
||||
else "单位:${item.unit} 范围 ${fmt(item.min)}–${fmt(item.max)}",
|
||||
fontSize = 10.sp,
|
||||
color = if (item.unlimited) Doubao.Blue else doubaoTextSecondary(),
|
||||
fontWeight = if (item.unlimited) FontWeight.Medium else FontWeight.Normal,
|
||||
)
|
||||
}
|
||||
if (item.desc.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(item.desc, fontSize = 11.sp, lineHeight = 17.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StepButton(label: String, onClick: () -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 4.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(label, fontSize = 16.sp, fontWeight = FontWeight.Medium, color = Doubao.Blue)
|
||||
}
|
||||
}
|
||||
|
||||
/** 整秒显示,别出现 "180.0" */
|
||||
private fun fmt(v: Double): String =
|
||||
if (kotlin.math.abs(v - v.toInt()) < 0.001) v.toInt().toString() else v.toString()
|
||||
|
||||
/** 步长跟着量级走:5 秒的东西一次加 60 太难用,1800 秒的东西一次加 5 是折磨 */
|
||||
private fun stepOf(item: TimeoutItem): Double = when {
|
||||
item.max <= 60 -> 5.0
|
||||
item.max <= 300 -> 10.0
|
||||
item.max <= 900 -> 30.0
|
||||
else -> 60.0
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
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.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
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.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.TokenUsage
|
||||
|
||||
/*
|
||||
* Token 用量详情(需求 3.1 的展示入口:选择界面「更多」按钮)。
|
||||
*
|
||||
* ## 展示什么
|
||||
*
|
||||
* · 累计用量(**输入 / 输出分列**,需求明确要求不合并)
|
||||
* · 限额进度(没限额就显示"无限制")
|
||||
* · **按模型分行**(需求 3.1 的"按模型分桶",可看总数也可展开)
|
||||
* · 配了单价才显示估算费用 —— 没配就只显示 Token 数,不瞎估
|
||||
*
|
||||
* ## 不做历史曲线
|
||||
*
|
||||
* 需求原话"当前不做曲线"(时间戳只是为将来预留)。
|
||||
*
|
||||
* ## 做全屏而不是弹窗
|
||||
*
|
||||
* 见 AGENTS.md「少用弹窗」。这里要放三四行数字 + 一张可能十几行的模型表,
|
||||
* 弹窗装不下。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
fun TokenUsageScreen(
|
||||
usage: TokenUsage?,
|
||||
onReset: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
// ★ 清零是不可逆的(历史消耗数就没了),给它一次确认(复查报告 3.4)——
|
||||
// 这是"一次确认"的典型场景,弹窗正合适(AGENTS.md 那张表)
|
||||
var confirmReset by remember { mutableStateOf(false) }
|
||||
|
||||
FullScreen(
|
||||
title = "用量",
|
||||
subtitle = usage?.name?.takeIf { it.isNotBlank() }?.let { "$it · 累计" } ?: "正在读取…",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (usage != null && usage.total > 0) {
|
||||
TopTextAction("清零", danger = true) { confirmReset = true }
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (usage == null) {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Text("正在读取…", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
// ---- 总览 ----
|
||||
Card {
|
||||
Text("累计消耗", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
fmtTokens(usage.total),
|
||||
fontSize = 30.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Row {
|
||||
Metric("输入", usage.input)
|
||||
Spacer(Modifier.width(24.dp))
|
||||
Metric("输出", usage.output)
|
||||
}
|
||||
if (usage.pricePerK > 0 && usage.cost != null) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
"估算费用 ¥${"%.2f".format(usage.cost)}(按 ¥${usage.pricePerK}/千 Token)",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 限额 ----
|
||||
Card {
|
||||
if (usage.unlimited) {
|
||||
Text("额度:无限制", fontSize = 14.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"想限制他?在「管理 → 编辑」里填一个 Token 上限就行。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
} else {
|
||||
Text("额度", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Text(
|
||||
fmtTokens(usage.remaining ?: 0),
|
||||
fontSize = 22.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = if (usage.percent >= 1f) Color(0xFFD93025) else doubaoText(),
|
||||
)
|
||||
Text(
|
||||
" / ${fmtTokens(usage.limit)} 剩余",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(bottom = 3.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// 进度条自己画(项目没有 material 的 LinearProgressIndicator 用法先例,
|
||||
// 一条圆角 Box 更可控)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Border),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(usage.percent.toFloat().coerceIn(0f, 1f))
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(if (usage.percent >= 1f) Color(0xFFD93025) else Doubao.Blue),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
if (usage.percent >= 1f)
|
||||
"已经用完了 —— 下一轮会被拦住,并附一句告别。可以清零、调大限额或改成无限制。"
|
||||
else "用满之后会拦住发送(记忆整理这类操作不受影响)。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = if (usage.percent >= 1f) Color(0xFFD93025) else doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 按模型分桶 ----
|
||||
Card {
|
||||
Text("按模型", fontSize = 12.sp, color = doubaoTextSecondary())
|
||||
Spacer(Modifier.height(8.dp))
|
||||
if (usage.byModel.isEmpty()) {
|
||||
Text("还没用过", fontSize = 13.sp, color = doubaoTextSecondary())
|
||||
} else {
|
||||
for ((i, m) in usage.byModel.withIndex()) {
|
||||
if (i > 0) Spacer(Modifier.height(8.dp))
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
m.model,
|
||||
fontSize = 13.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"入 ${fmtTokens(m.input)} · 出 ${fmtTokens(m.output)}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (confirmReset) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { confirmReset = false },
|
||||
title = { Text("清零用量", fontSize = 16.sp) },
|
||||
text = {
|
||||
Text(
|
||||
"把「${usage?.name ?: ""}」的累计用量归零(当前 ${fmtTokens(usage?.total ?: 0)})。\n\n" +
|
||||
"这个数字回不来 —— 它是历史统计,不是「当前会话进度」。\n" +
|
||||
"清零之后额度也重新算,但它记得的东西、你们的对话都不受影响。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { confirmReset = false; onReset() },
|
||||
) { Text("清零") }
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(onClick = { confirmReset = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ★ 这里的私有 `Card` 删了 —— 它和 AgentEditScreen 的那个是**同一段代码**
|
||||
// 抄了两份(只有 vertical 内边距差 2dp)。现在统一用 DoubaoUi.kt 里的公共版。
|
||||
// 留着的话两个同签名函数都可见,编译器直接报"重载歧义"。
|
||||
|
||||
@Composable
|
||||
private fun Metric(label: String, value: Long) {
|
||||
Column {
|
||||
Text(label, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
Text(fmtTokens(value), fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
}
|
||||
}
|
||||
|
||||
/** 大数字加千分位:`12345` → `12,345`。Token 数动辄五六位,不加看不清量级 */
|
||||
fun fmtTokens(n: Long): String {
|
||||
val s = n.toString()
|
||||
if (s.length <= 3) return s
|
||||
val sb = StringBuilder()
|
||||
for ((i, c) in s.withIndex()) {
|
||||
if (i > 0 && (s.length - i) % 3 == 0) sb.append(',')
|
||||
sb.append(c)
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
BIN
android/app/src/main/res/drawable/agent_default_background.png
Normal file
|
After Width: | Height: | Size: 1.6 MiB |
BIN
android/app/src/main/res/drawable/agent_default_character.png
Normal file
|
After Width: | Height: | Size: 669 KiB |
1427
android/kernel/agent_api.py
Normal file
378
android/kernel/agent_context.py
Normal file
@@ -0,0 +1,378 @@
|
||||
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||||
|
||||
## 这个模块只做一件事
|
||||
|
||||
把「人设 + Skill 手册 + 世界观 + 情绪 + 记忆 + 同伴情绪」按**固定顺序**
|
||||
拼成一段 system prompt。
|
||||
|
||||
## 为什么单独一个模块,而不是写在 agent_loop 里
|
||||
|
||||
因为这里有**六种来源**,每一种都要判空、要查库/查 JSON、出错了还不能把
|
||||
整轮对话带崩。塞在 agent_loop 里会让那个函数变成两百行,而且没法单独测。
|
||||
|
||||
## 几条硬约定
|
||||
|
||||
**① 空段整段删掉。**
|
||||
绑没绑世界观、有没有情绪、记没记过东西 —— 都是常态。
|
||||
不删的话每次对话都带着一堆空的 `<worldview></worldview>`,
|
||||
模型会以为"这里本来该有内容但我没看到",反而更容易瞎编。
|
||||
|
||||
**② 顺序固定:人设 → skills → worldview → emotion → memory → peer_emotions。**
|
||||
见附录 C。顺序不是审美问题:记忆在情绪之后,模型读到"我现在有点烦"
|
||||
再看记忆,语气才连贯;反过来它会先看到一堆事实、再看到情绪,像事后补的。
|
||||
|
||||
**③ 每轮重新拼。**
|
||||
记忆和情绪随时会变(AI 自己就能改),拼一次缓存住的话,
|
||||
用户会看到"我明明让它记住了,下一句它又忘了"。
|
||||
|
||||
**④ 查库失败一律当成"这段没有"。**
|
||||
数据库被锁、文件损坏都不该让用户发不出消息。
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import rule_engine
|
||||
import store
|
||||
from defaults import (
|
||||
BUILTIN_SKILL,
|
||||
DEFAULT_MEMORY_LINE,
|
||||
DEFAULT_PROMPT_TEMPLATE,
|
||||
)
|
||||
|
||||
# 模板里的段名(顺序就是渲染顺序)。加一段要同时改 defaults.DEFAULT_PROMPT_TEMPLATE。
|
||||
#: 段落名,**顺序就是注入顺序**(需求附录 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):
|
||||
"""
|
||||
跑一个小查询,出错就当"没有"。
|
||||
|
||||
★ 单独抽出来是因为这个模式在这里出现六次:**任何一处查库失败都不该
|
||||
让整轮对话发不出去**(数据库锁了、agent.db 被删了、JSON 坏了)。
|
||||
"""
|
||||
try:
|
||||
return fn()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[agent_context] 取上下文失败,按"没有"处理:{exc}', file=__import__('sys').stderr)
|
||||
return fallback
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 各段
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def build_skills(agent: dict) -> str:
|
||||
"""
|
||||
`<skills>` 段:内置手册 + 这个智能体绑定的自定义 Skill(**按绑定顺序**)。
|
||||
|
||||
内置的那份永远在最前面 —— 它讲的是记忆/情绪这些**基础工具**怎么用,
|
||||
自定义 Skill 是额外的,放后面读起来才是"先会基本操作,再学扩展"。
|
||||
"""
|
||||
parts = [BUILTIN_SKILL.strip()] if BUILTIN_SKILL.strip() else []
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
if agent_id:
|
||||
for sid in _safe(lambda: agentdb.skills_of(agent_id), []):
|
||||
sk = _safe(lambda: store.get_resource('skills', sid), None)
|
||||
if sk and (sk.get('content') or '').strip():
|
||||
parts.append(f'【{(sk.get("name") or "Skill").strip()}】\n{sk["content"].strip()}')
|
||||
return '\n\n'.join(parts)
|
||||
|
||||
|
||||
def build_worldview(agent: dict) -> str:
|
||||
"""`<worldview>` 段:绑定的世界观设定文本(没绑就是空)"""
|
||||
wid = (agent or {}).get('worldviewId') or ''
|
||||
if not wid:
|
||||
return ''
|
||||
wv = _safe(lambda: store.get_resource('worldviews', wid), None)
|
||||
return (wv or {}).get('setting', '').strip()
|
||||
|
||||
|
||||
def memory_scope(agent: dict) -> str:
|
||||
"""这个智能体当前该读写哪个记忆空间(绑了世界观就是共享空间)"""
|
||||
agent = agent or {}
|
||||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||||
|
||||
|
||||
def build_emotion(agent: dict) -> str:
|
||||
"""
|
||||
`<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 ''
|
||||
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:
|
||||
"""
|
||||
`<memory>` 段:那个记忆空间里**会注入给模型**的条目。
|
||||
|
||||
## 注入窗口 + 置顶保护
|
||||
|
||||
"无上限 + 全量注入"这两条长期是矛盾的:攒到几百上千条时,提示词会被
|
||||
记忆撑爆(每条几十字,一千条就是几万 token),而且**越靠后越贵、
|
||||
早期记忆反而挤掉了最近的对话上下文**。
|
||||
|
||||
所以这里按**窗口**裁:
|
||||
|
||||
· **置顶的永远注入**,且排在最前面 —— 那是用户明确说了"这条重要"的
|
||||
· 其余按时间取**最近**的,凑够窗口
|
||||
· 置顶条数超过窗口时,置顶的**全部**注入(窗口是给普通记忆设的,
|
||||
不是用来否决用户明确置顶的东西)
|
||||
· 被裁掉的**没有丢**,AI 还能用 `memory_search` 检索到 ——
|
||||
也就是"降级为仅可检索"
|
||||
|
||||
窗口大小在全局设置里(`memoryWindow`),0 = 不限(退回全量注入)。
|
||||
|
||||
## 共享记忆带作者署名
|
||||
|
||||
共享空间是几个人往同一个本子上写。没有署名的时候,别人写的
|
||||
"我小时候住在海边"在模型眼里就是**它自己的经历** —— 它会当成自己的
|
||||
过去来讲,甚至在用户问起时说"我不记得有这事"。署名之后它才知道
|
||||
"这条是仙辰写的"(需求 3.6 的"交模型调和矛盾记忆"也才有前提:
|
||||
得先分得清谁写的)。
|
||||
|
||||
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
|
||||
"""
|
||||
scope = memory_scope(agent)
|
||||
items = _safe(lambda: agentdb.memory_list(scope), [])
|
||||
if not items:
|
||||
return ''
|
||||
|
||||
# ---- 窗口裁剪 ----
|
||||
settings = _safe(store.read_settings, {}) or {}
|
||||
try:
|
||||
window = int(settings.get('memoryWindow') or 0)
|
||||
except (TypeError, ValueError):
|
||||
window = 0
|
||||
total = len(items)
|
||||
trimmed = 0
|
||||
if window > 0 and total > window:
|
||||
pinned = [m for m in items if m.get('pinned')]
|
||||
rest = [m for m in items if not m.get('pinned')]
|
||||
room = max(0, window - len(pinned))
|
||||
keep = pinned + (rest[-room:] if room else [])
|
||||
# 顺序:置顶的在前(用户明确要的),其余保持时间顺序
|
||||
items = keep
|
||||
trimmed = total - len(keep)
|
||||
parts = []
|
||||
if pinned:
|
||||
parts.append(f'置顶 {len(pinned)} 条')
|
||||
if trimmed:
|
||||
parts.append(f'另有 {trimmed} 条较早的没放进来(用 memory_search 还能搜到)')
|
||||
note = '(' + ';'.join(parts) + ')' if parts else ''
|
||||
else:
|
||||
note = ''
|
||||
|
||||
tmpl = _safe(
|
||||
lambda: (store.read_settings().get('memoryLine') or DEFAULT_MEMORY_LINE),
|
||||
DEFAULT_MEMORY_LINE,
|
||||
)
|
||||
shared = scope.startswith('world:')
|
||||
names = {}
|
||||
if shared:
|
||||
names = {a.get('id'): (a.get('name') or '某人') for a in _safe(store.list_agents, [])}
|
||||
me = (agent or {}).get('id') or ''
|
||||
lines = []
|
||||
for it in items:
|
||||
title = (it.get('title') or '').strip()
|
||||
content = (it.get('content') or '').strip()
|
||||
author = (it.get('author_agent') or '').strip()
|
||||
tags = []
|
||||
if it.get('pinned'):
|
||||
tags.append('置顶')
|
||||
if shared and author:
|
||||
# 自己写的也标出来("你记的")—— 一眼能分清哪些是自己的立场
|
||||
tags.append('你记的' if author == me else f'{names.get(author) or "某人"}记的')
|
||||
if tags:
|
||||
title = f'{title}({",".join(tags)})'
|
||||
try:
|
||||
lines.append(tmpl.format(title=title, content=content))
|
||||
except (KeyError, IndexError): # 用户把模板改坏了:退回默认再试
|
||||
lines.append(DEFAULT_MEMORY_LINE.format(title=title, content=content))
|
||||
body = '\n'.join(lines)
|
||||
return f'{body}\n{note}' if note else body
|
||||
|
||||
|
||||
def build_peer_emotions(agent: dict) -> str:
|
||||
"""
|
||||
`<peer_emotions>` 段:**同世界观其他智能体**的名字(+ 情绪)(需求 3.5)。
|
||||
|
||||
★★ 分两档,不是"开关一关就什么都没有":
|
||||
|
||||
· 绑了世界观但**没开**情绪感知 → 只给**成员名单**(谁在,但看不到情绪)
|
||||
· 绑了世界观且**开了**开关 → 名单 + 各自当前的情绪
|
||||
|
||||
为什么关着也要给名单(复查报告第 5 条):
|
||||
共享记忆是**共用**的,AI 一定会看到"别人写的条目"。如果它连
|
||||
"这个空间里还有别人"都不知道,那些第三人称的条目在它眼里就是
|
||||
**自己的记忆**——它会以为"我什么时候去过九霄山?",
|
||||
于是把别人的经历当成自己的,或者在正文里跟用户说"我没记过这个"。
|
||||
名单不含情绪,所以"角色内的隐私"这条边界仍然守住了。
|
||||
|
||||
★ 情绪感知开关默认关(需求原话"默认关闭")—— 别人的**情绪**属于
|
||||
角色内的隐私,默认让 AI 看到会让它们的表现互相串味。
|
||||
"""
|
||||
agent = agent or {}
|
||||
if not agent.get('worldviewId'):
|
||||
return ''
|
||||
my_id = agent.get('id') or ''
|
||||
wid = agent.get('worldviewId') or ''
|
||||
others = [
|
||||
a for a in _safe(store.list_agents, [])
|
||||
if a.get('worldviewId') == wid and a.get('id') != my_id
|
||||
]
|
||||
if not others:
|
||||
return ''
|
||||
|
||||
by_id = {a.get('id'): a for a in others}
|
||||
names = [(by_id.get(aid) or {}).get('name') or '某人' for aid in by_id]
|
||||
|
||||
if not agent.get('emotionEnabled'):
|
||||
return ';'.join(f'{n}(不知道他此刻的情绪)' for n in names)
|
||||
|
||||
rows = _safe(
|
||||
lambda: agentdb.peer_emotions(wid, my_id, list(by_id)),
|
||||
[],
|
||||
)
|
||||
emo_by_id = {aid: (emo or '').strip() for aid, emo in rows}
|
||||
parts = []
|
||||
for aid, one in by_id.items():
|
||||
# ★ `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}(看不出什么情绪)')
|
||||
return ';'.join(parts)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 拼装
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
_RE_BLOCK = {name: re.compile(rf'<{name}>.*?</{name}>', re.S) for name in SECTIONS}
|
||||
|
||||
|
||||
def render(template: str, values: dict) -> str:
|
||||
"""
|
||||
按模板渲染,**空的段整段删掉**。
|
||||
|
||||
★ 先渲染 `{prompt}` 再处理段:人设里如果碰巧有 `<memory>` 这样的字
|
||||
(用户自己写的提示词里完全可能),会被当成段处理掉 —— 所以段的匹配
|
||||
只在**模板**上做,不在渲染结果上做。
|
||||
"""
|
||||
out = (template or DEFAULT_PROMPT_TEMPLATE).replace('{prompt}', (values.get('prompt') or '').strip())
|
||||
for name in SECTIONS:
|
||||
block = _RE_BLOCK[name].search(out)
|
||||
if not block:
|
||||
continue
|
||||
value = (values.get(name) or '').strip()
|
||||
if value:
|
||||
out = out[:block.start()] + f'<{name}>\n{value}\n</{name}>' + out[block.end():]
|
||||
else:
|
||||
out = out[:block.start()] + out[block.end():]
|
||||
# 段被删掉后会留下连续空行,压一压;别让提示词里出现四五行的空白
|
||||
out = re.sub(r'\n{3,}', '\n\n', out)
|
||||
return out.strip()
|
||||
|
||||
|
||||
def build_system_prompt(settings: dict, agent: dict) -> str:
|
||||
"""
|
||||
这一轮要用的 system prompt。
|
||||
|
||||
[settings] 里可以覆盖:`promptTemplate`(整份模板)、`memoryLine`(记忆条目排版)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
settings = settings or {}
|
||||
prompt = (agent.get('systemPrompt') or '').strip() or (settings.get('systemPrompt') or '')
|
||||
values = {
|
||||
'prompt': prompt,
|
||||
# ---- 稳定段:它们在提示词最前面,靠它们拿前缀缓存命中 ----
|
||||
'skills': build_skills(agent),
|
||||
'worldview': build_worldview(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。两种安全模式:
|
||||
@@ -10,8 +10,11 @@ Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from typing import Callable, Optional
|
||||
|
||||
import agent_context
|
||||
import store
|
||||
import tools_runtime
|
||||
from providers import stream_chat
|
||||
@@ -19,6 +22,216 @@ from providers import stream_chat
|
||||
MAX_TOOL_RESULT_CHARS = 6000
|
||||
|
||||
|
||||
def add_usage(total, one) -> dict:
|
||||
"""
|
||||
把一次调用的 usage 累加进总数。
|
||||
|
||||
★ 各家的字段名不一样(OpenAI 系是 prompt_tokens / completion_tokens,
|
||||
兼容网关有时给 input_tokens / output_tokens),**两种都认** ——
|
||||
只认一种的话换个提供商统计就静默变成 0,而"统计是 0"极难被发现。
|
||||
"""
|
||||
if not isinstance(one, dict):
|
||||
return total or {}
|
||||
out = dict(total or {})
|
||||
pairs = (
|
||||
('prompt_tokens', 'prompt_tokens'),
|
||||
('completion_tokens', 'completion_tokens'),
|
||||
('total_tokens', 'total_tokens'),
|
||||
('input_tokens', 'prompt_tokens'), # 兼容写法
|
||||
('output_tokens', 'completion_tokens'), # 兼容写法
|
||||
)
|
||||
for src, dst in pairs:
|
||||
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 {}
|
||||
return int(u.get('prompt_tokens') or 0), int(u.get('completion_tokens') or 0)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 幻觉调用检测(需求 3.7)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 「嘴上说记住了、实际没调工具」是这类有记忆的助手最常见、也最伤信任的毛病:
|
||||
# 用户当场看不出来(那句"我记住了"说得很自然),下次对话发现它完全不记得,
|
||||
# 从此就不信这个功能了。
|
||||
#
|
||||
# 而"它打算记"和"它真的记了"在**正文里看不出区别**,只能由程序比对
|
||||
# 「说了什么」和「做了什么」。所以这里做一次兜底。
|
||||
|
||||
#: 「声称记住了」的措辞。
|
||||
# ★ 宁可漏判也别误伤:误伤会让用户看到莫名其妙的警告,几次之后他就不看那个警告了
|
||||
# (比没有还糟)。所以只收明确说"我记住了"的句式,不收"我会记得的"这种客套。
|
||||
_CLAIM_RE = re.compile(
|
||||
r'我(已经)?(记住|记下|记好)了|已(经)?(记住|记下)|记到(我的)?记忆|'
|
||||
r'存(进|入)(了)?(我的)?记忆|我把它记|已经帮你记|记在小本本'
|
||||
)
|
||||
|
||||
|
||||
def detects_memory_claim(content: str) -> bool:
|
||||
"""这句话里有没有"我记住了"这类断言"""
|
||||
return bool(_CLAIM_RE.search(content or ''))
|
||||
|
||||
|
||||
def check_hallucinated_memory(content: str, tool_call_count: int, tools_available: bool) -> bool:
|
||||
"""
|
||||
这一轮该不该打「⚠ 声称记忆但未实际调用」的标记(需求 3.7)。
|
||||
|
||||
★ [tools_available] 是必须的:如果用户把 Python 工具整个关了,
|
||||
模型**想调也调不了**,那时警告它"没调用工具"是冤枉它 ——
|
||||
而且警告会一直挂着,用户会以为坏了。
|
||||
"""
|
||||
if not tools_available:
|
||||
return False
|
||||
if tool_call_count > 0:
|
||||
return False
|
||||
return detects_memory_claim(content)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 兼容降级:不支持 function calling 的模型(需求 3.3)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 有些模型(本地小模型、老网关)根本不支持 tools 参数 —— 传过去轻则被忽略、
|
||||
# 重则直接 400。而"记忆/情绪"这些能力**恰恰靠工具**,没有降级的话,
|
||||
# 用户换上这类模型之后会发现"记忆功能突然全废了",而且看不出原因。
|
||||
#
|
||||
# 降级做法:不传 tools,改成**在提示词里约定一种正文内的调用格式**,
|
||||
# 回复回来后由内核解析、执行、并从正文里剥掉。用户看到的还是干净的回答。
|
||||
#
|
||||
# ★ 为什么选"代码块里写 JSON"而不是别的:
|
||||
# · 模型对"输出 JSON"这件事训练得很充分,比自创的标记语法可靠得多
|
||||
# · 代码块有明确的边界,正则能稳稳地切出来;万一没被剥掉,
|
||||
# 用户看到的也是一段像模像样的 JSON,而不是一堆乱码
|
||||
|
||||
DEGRADED_HINT = '\n'.join([
|
||||
'',
|
||||
'【工具调用】你**不能直接调用函数**,但需要用到工具时,请在回复里单独写一段:',
|
||||
'',
|
||||
'```doubao-call',
|
||||
'{"tool": "memory_add", "args": {"title": "标题", "content": "内容"}}',
|
||||
'```',
|
||||
'',
|
||||
'可用的工具:memory_add、memory_update、memory_forget、memory_search、'
|
||||
'emotion_set、get_token_usage。',
|
||||
'这一段会被系统执行并从你的回复里**去掉**,用户看不到它。',
|
||||
'★ 需要记住什么的时候,**必须**写这一段 —— 只在正文里说"我记住了"是没用的,'
|
||||
'那样你其实什么都没记。',
|
||||
])
|
||||
|
||||
_RE_DEGRADED_CALL = re.compile(r'```doubao-call\s*\n(.*?)\n?```', re.S)
|
||||
|
||||
|
||||
def run_degraded_calls(content: str, settings: dict) -> tuple:
|
||||
"""
|
||||
执行降级模式写在正文里的结构化调用。
|
||||
|
||||
返回 `(剥掉调用块之后的正文, 执行记录)`。
|
||||
|
||||
★ 解析不了的块**原样留在正文里**:与其默默删掉(用户永远不知道它想干什么),
|
||||
不如让用户看见"它写了一段系统没认出来的东西" —— 那说明模型该换了。
|
||||
"""
|
||||
import agent_tools
|
||||
|
||||
records = []
|
||||
|
||||
def _one(match):
|
||||
raw = (match.group(1) or '').strip()
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except Exception: # noqa: BLE001 - 解析不了就留着,见 docstring
|
||||
return match.group(0)
|
||||
if not isinstance(payload, dict):
|
||||
return match.group(0)
|
||||
name = str(payload.get('tool') or '').strip()
|
||||
args = payload.get('args') if isinstance(payload.get('args'), dict) else {}
|
||||
entry = agent_tools.AGENT_TOOLS.get(name)
|
||||
rec = {
|
||||
'id': f'degraded_{len(records)}',
|
||||
'name': name or '(没写工具名)',
|
||||
'args': args,
|
||||
'ok': False,
|
||||
'result': '',
|
||||
'error': '',
|
||||
}
|
||||
if entry is None:
|
||||
rec['error'] = f'没有这个工具:{name}'
|
||||
else:
|
||||
try:
|
||||
out = entry['run'](args)
|
||||
rec['ok'] = True
|
||||
rec['result'] = json.dumps(out, ensure_ascii=False)[:2000]
|
||||
except Exception as exc: # noqa: BLE001 - 工具报错不该让整轮回答失败
|
||||
rec['error'] = str(exc)
|
||||
records.append(rec)
|
||||
return ''
|
||||
|
||||
stripped = _RE_DEGRADED_CALL.sub(_one, content or '')
|
||||
# 调用块被剥掉之后往往留下两三行空白,压一压
|
||||
stripped = re.sub(r'\n{3,}', '\n\n', stripped).strip()
|
||||
return stripped, records
|
||||
|
||||
|
||||
def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str:
|
||||
"""工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。"""
|
||||
if isinstance(text, str):
|
||||
@@ -99,7 +312,15 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
tool_defs = tools_runtime.build_tool_defs(settings)
|
||||
max_rounds = _max_rounds(settings)
|
||||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
||||
# ★★ system prompt **每轮重新拼**(需求 3.2):人设 → skills → 世界观 →
|
||||
# 情绪 → 记忆 → 同伴情绪,顺序固定(附录 C)。
|
||||
#
|
||||
# 为什么不拼一次缓存住:记忆和情绪**随时会变**,而且 AI 自己就能改它们
|
||||
# (memory_add / emotion_set)。缓存住的表现是"我明明让它记住了,
|
||||
# 下一句它又忘了"——这种 bug 用户会当成"记忆功能坏了"。
|
||||
#
|
||||
# 拼法、判空、查库失败的兜底全在 agent_context.py 里。
|
||||
system_prompt = agent_context.build_system_prompt(settings, agent or {})
|
||||
# ★★ 界面能力的用法**只在开关打开时才追加**。
|
||||
#
|
||||
# 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**,
|
||||
@@ -110,6 +331,44 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
|
||||
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 []:
|
||||
print(f'[rule] {_e}', file=sys.stderr)
|
||||
except Exception as _exc: # noqa: BLE001 - 规则引擎坏了不该让对话发不出去
|
||||
print(f'[rule] 状态脚本执行失败:{_exc}', file=sys.stderr)
|
||||
|
||||
# ★★ 兼容降级(需求 3.3):这个模型不支持 tools 参数时,换成"正文内调用约定"。
|
||||
#
|
||||
# 为什么要这么绕:记忆/情绪这些能力**全靠工具**,而本地小模型、
|
||||
# 老网关很多不支持 function calling(传 tools 过去轻则被忽略、重则 400)。
|
||||
# 不降级的话,用户换上这类模型会发现"记忆功能突然全废了",还看不出原因。
|
||||
#
|
||||
# 判定依据是**模型列表那一项上的开关**(用户在界面上打的标记),
|
||||
# 不做自动探测:各家"不支持"的报错方式五花八门,猜错的代价是
|
||||
# 把一个本来能用的模型降级掉 —— 那比不降级更糟。
|
||||
degraded = bool(provider.get('noTools'))
|
||||
if degraded:
|
||||
tool_defs = []
|
||||
system_prompt = (system_prompt + '\n' + DEGRADED_HINT).strip()
|
||||
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||||
|
||||
emit({
|
||||
@@ -171,7 +430,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
# provider 是"提供商名字"(ark/openai),已经按"智能体 > 全局"解析过了
|
||||
provider=provider_key,
|
||||
base_url=provider.get('baseUrl'),
|
||||
api_key=settings.get('apiKey') or '',
|
||||
api_key=provider.get('apiKey') or '',
|
||||
model=provider.get('model'),
|
||||
messages=convo,
|
||||
tools=tool_defs if tool_defs else None,
|
||||
@@ -192,19 +451,40 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
elif kind == 'tool_calls':
|
||||
tool_calls = event.get('toolCalls') or []
|
||||
elif kind == 'usage':
|
||||
usage = event.get('usage')
|
||||
# ★★ **累加**而不是覆盖。
|
||||
#
|
||||
# 多轮工具调用时每一轮上游都会来一个 usage,以前是直接赋值 ——
|
||||
# 只留最后一轮。而消耗的大头恰恰在前面几轮(工具结果很长,
|
||||
# 一轮就是几千 input token),丢掉之后统计出来的数字
|
||||
# 会少得离谱,用户会以为"怎么才用了这么点"。
|
||||
usage = add_usage(usage, event.get('usage'))
|
||||
|
||||
if not tool_calls:
|
||||
# 降级模式(需求 3.3):模型不会 function calling,改成让它把调用
|
||||
# **写在正文里**(```doubao-call 代码块),这里执行掉并从正文里剥掉。
|
||||
# 执行记录照常发 tool_call / tool_result 事件,所以界面上的工具痕迹、
|
||||
# 幻觉检测这些下游逻辑完全不用改。
|
||||
final = answer
|
||||
if degraded:
|
||||
final, records = run_degraded_calls(answer, settings)
|
||||
for r in records:
|
||||
emit({'type': 'tool_call', 'id': r['id'], 'name': r['name'], 'args': r.get('args')})
|
||||
emit({
|
||||
'type': 'tool_result', 'id': r['id'], 'name': r['name'],
|
||||
'ok': r['ok'], 'result': r['result'], 'error': r['error'],
|
||||
})
|
||||
if records:
|
||||
tool_call_count += len(records)
|
||||
emit({
|
||||
'type': 'done',
|
||||
'content': answer,
|
||||
'content': final,
|
||||
'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1,
|
||||
'toolCalls': tool_call_count,
|
||||
'usage': usage,
|
||||
})
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'content': final, 'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
}
|
||||
|
||||
|
||||
677
android/kernel/agent_tools.py
Normal file
@@ -0,0 +1,677 @@
|
||||
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
|
||||
|
||||
## 为什么是"内置工具"而不是 `tools/*.py`
|
||||
|
||||
`tools/` 下的工具是**用户可改的 .py 文件**(内核启动时播种到手机上的可写目录)。
|
||||
这七个不一样:
|
||||
|
||||
· 它们要读写 `agent.db`(记忆、情绪、Token 统计)—— 那是内核进程内的模块,
|
||||
电脑端的工具是**子进程**,根本 import 不到
|
||||
· 它们是系统的核心能力,不该被用户在 tools/ 里改坏(改坏了 AI 会"失忆",
|
||||
而且表现是"有时记得有时不记得",极难查)
|
||||
|
||||
所以走 `builtin_tools.BUILTIN_TOOLS` 那条路(进程内、不进 tools/、不参与播种)。
|
||||
|
||||
## 限权规则(需求 3.6,**共享记忆里最重要的一条**)
|
||||
|
||||
绑定了世界观的智能体共用一个记忆空间,于是"谁都能删"就成了问题:
|
||||
|
||||
· `memory_add` —— 任何智能体都能往共享空间写(追加优先)
|
||||
· `memory_forget` / `memory_update` —— **只能动自己写的**(按 author_agent 判定)
|
||||
· `pinned` —— 用户标记"必须保留"的条目,AI 连自己的都改不动
|
||||
|
||||
改别人的条目只能由**用户在界面上手动做**。这条不做的话,
|
||||
两个智能体互相删对方的记忆,用户会看到"记忆莫名其妙少了"。
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
import agentdb
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 拿"我现在是谁"
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _ctx() -> dict:
|
||||
"""
|
||||
当前这次工具调用的上下文(哪次对话、哪个智能体)。
|
||||
|
||||
★ 局部 import:`tools_runtime` → `builtin_tools` → 这里,顶部 import 就成环了。
|
||||
"""
|
||||
import tools_runtime
|
||||
|
||||
return tools_runtime.current_context() or {}
|
||||
|
||||
|
||||
def _me() -> dict:
|
||||
"""当前智能体(拿不到就返回空 dict —— 工具会据此报错,而不是瞎写)"""
|
||||
ctx = _ctx()
|
||||
agent = store.get_agent(ctx.get('agentId') or '') or {}
|
||||
return agent
|
||||
|
||||
|
||||
def _my_scope(agent: dict) -> str:
|
||||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||||
|
||||
|
||||
def _shared(agent: dict) -> bool:
|
||||
"""是不是在共享空间里(绑了世界观就是)"""
|
||||
return bool(agent.get('worldviewId'))
|
||||
|
||||
|
||||
def _check_editable(item: dict, agent: dict) -> None:
|
||||
"""
|
||||
能不能改/删这一条 —— 不能就抛错(**抛错而不是静默跳过**:
|
||||
静默的话模型以为改成功了,下一轮还按老样子说话)。
|
||||
"""
|
||||
if item.get('pinned'):
|
||||
raise ValueError(
|
||||
'这条记忆被用户标记为「必须保留」,你改不了也删不掉。'
|
||||
'如果它确实过时了,跟用户说一声让他自己处理。'
|
||||
)
|
||||
if _shared(agent) and (item.get('author_agent') or '') != (agent.get('id') or ''):
|
||||
raise ValueError(
|
||||
'这条是**其他智能体**写进共享记忆的,你只能改/删自己写的。'
|
||||
'需要修改它的话,跟用户说让他手动改。'
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 记忆
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
MEMORY_ADD = {
|
||||
'name': 'memory_add',
|
||||
'description': (
|
||||
'记住一件事,**跨对话保留**。用户告诉你的重要事实、偏好、约定、他的项目,'
|
||||
'都该记下来。记之前先看系统提示词里的记忆清单,已经记过的别再记一遍。'
|
||||
'返回新条目的 id(以后要改/删它需要这个 id)。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'title': {'type': 'string', 'description': '一句话标题(检索和整理时的锚点)'},
|
||||
'content': {'type': 'string', 'description': '要记住的正文'},
|
||||
},
|
||||
'required': ['title', 'content'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_add(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体,无法写记忆')
|
||||
title = str(args.get('title') or '').strip()
|
||||
content = str(args.get('content') or '').strip()
|
||||
if not title and not content:
|
||||
raise ValueError('title 和 content 至少要有一个')
|
||||
item = agentdb.memory_add(
|
||||
scope=_my_scope(agent),
|
||||
title=title,
|
||||
content=content,
|
||||
author_agent=agent.get('id') or '',
|
||||
)
|
||||
return {
|
||||
'id': item['id'],
|
||||
'title': item['title'],
|
||||
'scope': '共享记忆(世界观)' if _shared(agent) else '你自己的记忆',
|
||||
'note': '已写入。不要只在正文里说"记住了"—— 你现在已经真的记住了,正常继续就行。',
|
||||
}
|
||||
|
||||
|
||||
MEMORY_UPDATE = {
|
||||
'name': 'memory_update',
|
||||
'description': (
|
||||
'修改一条已有的记忆(只改传进来的字段)。'
|
||||
'只能改**你自己写的**、且没被用户标记为「必须保留」的条目。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'id': {'type': 'string', 'description': '记忆的 id(memory_add 返回过,或记忆清单里带的)'},
|
||||
'title': {'type': 'string', 'description': '新标题,不改就不传'},
|
||||
'content': {'type': 'string', 'description': '新正文,不改就不传'},
|
||||
},
|
||||
'required': ['id'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_update(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
mid = str(args.get('id') or '').strip()
|
||||
if not mid:
|
||||
raise ValueError('id 不能为空')
|
||||
item = agentdb.memory_get(mid)
|
||||
# ★ 只允许改**自己这个记忆空间**里的条目:不然知道 id 就能改到别人的私有记忆
|
||||
if not item or item.get('scope') != _my_scope(agent):
|
||||
raise ValueError('没找到这条记忆(id 不对,或者它不在你当前的记忆空间里)')
|
||||
_check_editable(item, agent)
|
||||
updated = agentdb.memory_update(
|
||||
mid,
|
||||
title=args.get('title') if 'title' in args else None,
|
||||
content=args.get('content') if 'content' in args else None,
|
||||
)
|
||||
return {'id': mid, 'title': (updated or {}).get('title', ''), 'note': '已更新。'}
|
||||
|
||||
|
||||
MEMORY_FORGET = {
|
||||
'name': 'memory_forget',
|
||||
'description': (
|
||||
'删掉一条记忆。只能删**你自己写的**、且没被用户标记为「必须保留」的条目。'
|
||||
'拿不准该不该删时,先问用户。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'id': {'type': 'string', 'description': '要删的记忆 id'},
|
||||
},
|
||||
'required': ['id'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_forget(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
mid = str(args.get('id') or '').strip()
|
||||
if not mid:
|
||||
raise ValueError('id 不能为空')
|
||||
item = agentdb.memory_get(mid)
|
||||
if not item or item.get('scope') != _my_scope(agent):
|
||||
raise ValueError('没找到这条记忆(id 不对,或者它不在你当前的记忆空间里)')
|
||||
_check_editable(item, agent)
|
||||
agentdb.memory_forget(mid)
|
||||
return {'id': mid, 'forgotten': True, 'note': '已删除。'}
|
||||
|
||||
|
||||
MEMORY_SEARCH = {
|
||||
'name': 'memory_search',
|
||||
'description': (
|
||||
'在自己的记忆库里检索。系统提示词里的记忆清单是**全量**的,'
|
||||
'但条数多的时候你可能只想找相关的几条 —— 用这个按关键词查。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'keyword': {'type': 'string', 'description': '关键词(标题和正文都会匹配)'},
|
||||
'limit': {'type': 'number', 'description': '最多返回几条,默认 10'},
|
||||
},
|
||||
'required': ['keyword'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_search(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
kw = str(args.get('keyword') or '').strip()
|
||||
if not kw:
|
||||
raise ValueError('keyword 不能为空')
|
||||
try:
|
||||
limit = int(float(args.get('limit') or 10))
|
||||
except (TypeError, ValueError):
|
||||
limit = 10
|
||||
rows = agentdb.memory_search(_my_scope(agent), kw, limit)
|
||||
return {
|
||||
'keyword': kw,
|
||||
'count': len(rows),
|
||||
'items': [
|
||||
{'id': r['id'], 'title': r['title'], 'content': r['content']} for r in rows
|
||||
],
|
||||
'note': '' if rows else '没有匹配的记忆。别据此说"我完全不记得"—— 换个关键词再试一次。',
|
||||
}
|
||||
|
||||
|
||||
MEMORY_SUGGEST_SUMMARY = {
|
||||
'name': 'memory_suggest_summary',
|
||||
'description': (
|
||||
'**建议**用户整理一次记忆(把零散的合并成几条)。'
|
||||
'你只负责建议,不执行 —— 用户点确认之后系统才会真的整理。'
|
||||
'什么时候用:记忆条数明显变多、或者有好几条在说同一件事。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'reason': {'type': 'string', 'description': '为什么建议整理(会显示给用户)'},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_suggest_summary(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
why = str(args.get('reason') or '').strip() or '记忆有点多了,想合并一下'
|
||||
# ★ 只挂一个"建议"标记,**不执行总结**(需求 3.2:仅提示不执行)。
|
||||
# 界面看到这个标记会给用户一个「整理记忆」按钮。
|
||||
store.add_pending_summary_suggestion(agent.get('id') or '', why)
|
||||
return {
|
||||
'suggested': True,
|
||||
'reason': why,
|
||||
'note': '已经建议了。**别再说"我整理好了"** —— 你只是提了个建议,'
|
||||
'用户点确认之后才会真的整理。正文里正常说这件事就行。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 情绪
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
EMOTION_SET = {
|
||||
'name': 'emotion_set',
|
||||
'description': (
|
||||
'更新**你自己**当前的情绪状态。两个字段都要给:\n'
|
||||
'· preset:五档之一 —— 喜 / 怒 / 哀 / 平常 / 死亡。它决定系统行为'
|
||||
'(立绘换哪张、同伴看到你什么脸色、死亡时能不能继续说话)。\n'
|
||||
'· text:一句自由描述,比如"刚被夸了,有点得意"。这只是扮演质感。\n'
|
||||
'情绪要跟着对话内容自然变化,不用每轮都改。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'preset': {
|
||||
'type': 'string',
|
||||
'enum': list(agentdb.PRESETS),
|
||||
'description': '五档情绪之一',
|
||||
},
|
||||
'text': {'type': 'string', 'description': '一句自由描述(可选)'},
|
||||
},
|
||||
'required': ['preset'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def emotion_set(args: dict) -> dict:
|
||||
"""
|
||||
写自己的情绪(需求 3.5 双字段)。
|
||||
|
||||
★★ **禁止把自己从「死亡」改活**(需求 3.5 明文)。
|
||||
|
||||
为什么:死亡是"这个角色没了"。能自己复活的话死亡就没有重量 ——
|
||||
用户会看到 AI 上一句刚咽气、下一句又活蹦乱跳,整个系统的可信度就没了。
|
||||
|
||||
复活只有两条**别的**通道,都不经过这里:
|
||||
· 用户手动改(兜底主权,在记忆页的情绪区)
|
||||
· 状态脚本改(定时复活 / 解药剧情,见 §3.11 —— 那条路走沙箱,不走工具)
|
||||
"""
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
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': '已更新你自己的情绪。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 用量
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
GET_TOKEN_USAGE = {
|
||||
'name': 'get_token_usage',
|
||||
'description': (
|
||||
'查**你自己**累计用了多少 Token、还剩多少额度。'
|
||||
'用户问"你还能说多少""用了多少"时用这个查真实数字,别猜。'
|
||||
),
|
||||
'parameters': {'type': 'object', 'properties': {}},
|
||||
}
|
||||
|
||||
|
||||
def get_token_usage(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
usage = agentdb.token_usage(agent.get('id') or '')
|
||||
limit = int(float(agent.get('tokenLimit') or 0))
|
||||
used = usage['total']['input'] + usage['total']['output']
|
||||
return {
|
||||
'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)),
|
||||
'note': '额度无限制。' if limit <= 0 else f'还剩 {max(0, limit - used)} Token。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 规则引擎(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")}」和你不在同一个世界观里,拉不进来')
|
||||
|
||||
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")}」已经在对话里了。'}
|
||||
|
||||
# 按智能体配置分流
|
||||
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'用户答应之后再调一次这个工具。'),
|
||||
}
|
||||
|
||||
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('拿不到当前智能体')
|
||||
ctx = tools_runtime.current_context()
|
||||
if ctx.get('handoffUsed'):
|
||||
# ★ 需求明文"一轮最多一次"。第二次直接拒,理由说清楚 ——
|
||||
# 不然模型会以为是"对方有问题",而不是"规则不允许"
|
||||
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")}」已经死亡,移交无效 —— 你自己接着说,或者交给别人')
|
||||
# ★ 用 update_context 而不是 push_context —— 后者是**替换**语义,
|
||||
# 会把 agentId / conversationId 一起冲掉,接着这个工具里的 _me() 就炸了
|
||||
tools_runtime.update_context(handoffTo=target['id'], handoffUsed=True)
|
||||
return {'handed_to': target.get('name'),
|
||||
'note': f'下一轮由「{target.get("name")}」接话。这一轮你不再移交了。'}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 注册
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 名字 → {'spec': TOOL, 'run': fn}(形状和 builtin_tools.BUILTIN_TOOLS 一样)
|
||||
AGENT_TOOLS = {
|
||||
'memory_add': {'spec': MEMORY_ADD, 'run': memory_add},
|
||||
'memory_update': {'spec': MEMORY_UPDATE, 'run': memory_update},
|
||||
'memory_forget': {'spec': MEMORY_FORGET, 'run': memory_forget},
|
||||
'memory_search': {'spec': MEMORY_SEARCH, 'run': memory_search},
|
||||
'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},
|
||||
}
|
||||
|
||||
|
||||
def _unused(): # pragma: no cover - 只是让 sys 的 import 不被 lint 当成没用
|
||||
return sys
|
||||
659
android/kernel/agentdb.py
Normal file
@@ -0,0 +1,659 @@
|
||||
"""智能体系统的数据层:**记忆 / 情绪 / Token 统计 / 绑定关系**。
|
||||
|
||||
## 为什么这次用 SQLite,而别处(设置/会话/智能体)还是 JSON
|
||||
|
||||
`store.py` 顶上写着"为什么用 JSON 而不是 SQLite",理由很实在:
|
||||
**数据量极小**(几条会话、几个智能体),而且用户/开发者要能直接看到、改那些文件。
|
||||
|
||||
那个理由对**智能体本身**依然成立(就几个),所以它们还在 `agents.json` 里。
|
||||
但记忆不一样,三条都指向 SQLite:
|
||||
|
||||
· 需求明确"记忆条目**无上限**",而**每轮对话都要全量注入** smartMemory ——
|
||||
几千条记忆塞进一个 JSON、每轮读盘再反序列化一遍,代价是实打实的
|
||||
· 要按关键词检索(`memory_search` 是 LIKE 查询)
|
||||
· 要"只改一条""只删自己写的"这种**行级**操作 —— 在 JSON 里就是
|
||||
读全量 → 改 → 写全量,多线程下一次并发写就可能把别人的改动盖掉
|
||||
|
||||
所以分界线是:**会持续增长、要按行操作或检索的数据 → SQLite;
|
||||
少量、要人肉可读的配置 → JSON。**
|
||||
|
||||
(另:这几张表**只属于智能体系统**,不和会话/设置混在一起 ——
|
||||
`agent.db` 单独一个文件,删了就是"重置智能体系统",不会碰到聊天记录。)
|
||||
|
||||
## 关联一律用 UUID
|
||||
|
||||
见需求附录 A。`memories.author_agent`、`agent_skills.agent_id`、
|
||||
`token_usage.agent_id` 存的都是 UUID,`name` 只是显示名(可重复、可随便改)。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 连接
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 每线程一个连接:sqlite3 的连接默认不能跨线程用,而内核是多线程的
|
||||
# (HTTP 每请求一线程 + 工具跑在又一个线程里)。
|
||||
# 用 threading.local() 而不是"一个全局连接 + 一把大锁":记忆检索可能在
|
||||
# 对话生成的过程中被调用,一把大锁会把整条链路串起来。
|
||||
_local = threading.local()
|
||||
_init_done = False
|
||||
_init_lock = threading.Lock()
|
||||
|
||||
|
||||
def db_path() -> str:
|
||||
"""数据库文件的位置(跟着数据目录走,和 settings.json 同一层)"""
|
||||
return os.path.join(os.path.dirname(paths.get().settings_file), 'agent.db')
|
||||
|
||||
|
||||
def _connect() -> sqlite3.Connection:
|
||||
conn = getattr(_local, 'conn', None)
|
||||
if conn is not None:
|
||||
return conn
|
||||
os.makedirs(os.path.dirname(db_path()), exist_ok=True)
|
||||
# check_same_thread=False 是安全的:这个连接只会被**创建它的那个线程**用到
|
||||
#
|
||||
# ★ 这个 timeout 是**锁等待**(不是查询超时):另一个线程正在写时,
|
||||
# 等多久才放弃并抛 "database is locked"。
|
||||
# 它以前写死 10 秒 —— 对拍脚本抓到的硬编码。现在复用「本地接口请求」
|
||||
# 那一项:语义最接近(都是"本机内部等一等"),而且用户调它是有意义的
|
||||
# (老设备上几千条记忆的整理会长时间占着写锁)。
|
||||
import timeouts as _timeouts
|
||||
|
||||
wait = float(_timeouts.get('kernelLocal') or 10)
|
||||
conn = sqlite3.connect(db_path(), check_same_thread=False, timeout=max(1.0, wait))
|
||||
conn.row_factory = sqlite3.Row
|
||||
# WAL:读不挡写。安卓上内核同时有"对话在写记忆"和"界面在读列表"。
|
||||
try:
|
||||
conn.execute('PRAGMA journal_mode=WAL')
|
||||
conn.execute('PRAGMA synchronous=NORMAL')
|
||||
except sqlite3.Error:
|
||||
pass # 只读文件系统之类:不致命,退化成默认模式
|
||||
_local.conn = conn
|
||||
return conn
|
||||
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS memories (
|
||||
id TEXT PRIMARY KEY,
|
||||
scope TEXT NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
pinned INTEGER NOT NULL DEFAULT 0,
|
||||
author_agent TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS emotions (
|
||||
agent_id TEXT PRIMARY KEY,
|
||||
-- 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
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS 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,
|
||||
-- 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);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS agent_skills (
|
||||
agent_id TEXT NOT NULL,
|
||||
skill_id TEXT NOT NULL,
|
||||
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)
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def init() -> None:
|
||||
"""建表(幂等)。内核启动时调一次,各处也会惰性调。"""
|
||||
global _init_done
|
||||
if _init_done:
|
||||
return
|
||||
with _init_lock:
|
||||
if _init_done:
|
||||
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
|
||||
_init_done = False
|
||||
_local.__dict__.pop('conn', None)
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
"""新实体的主键。**一律 UUID**(需求附录 A)"""
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def now_iso() -> str:
|
||||
"""和 store.now_iso() 一样的格式(前端直接拿来排序/展示)"""
|
||||
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# scope:记忆是"智能体私有"还是"世界观共享"
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 用带前缀的字符串而不是两列(agent_id / worldview_id):
|
||||
# 读的时候永远只关心"这一条属于哪个记忆空间",不需要分情况查两列;
|
||||
# 而且以后加第三种空间(比如"全局公共记忆")不用改表结构。
|
||||
|
||||
def agent_scope(agent_id: str) -> str:
|
||||
return f'agent:{agent_id or ""}'
|
||||
|
||||
|
||||
def world_scope(worldview_id: str) -> str:
|
||||
return f'world:{worldview_id or ""}'
|
||||
|
||||
|
||||
def scope_of(agent_id: str, worldview_id: str = '') -> str:
|
||||
"""
|
||||
这个智能体当前该读写哪个记忆空间。
|
||||
|
||||
绑定世界观 → 共享空间;没绑定 → 自己的私有空间(需求 3.6)。
|
||||
"""
|
||||
if worldview_id:
|
||||
return world_scope(worldview_id)
|
||||
return agent_scope(agent_id)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 记忆
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def memory_add(scope: str, title: str, content: str, author_agent: str = '') -> dict:
|
||||
"""新增一条。返回整条(带新生成的 UUID)"""
|
||||
init()
|
||||
item = {
|
||||
'id': new_id(),
|
||||
'scope': scope,
|
||||
'title': (title or '').strip(),
|
||||
'content': (content or '').strip(),
|
||||
'pinned': 0,
|
||||
'author_agent': author_agent or '',
|
||||
'created_at': now_iso(),
|
||||
}
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'INSERT INTO memories (id, scope, title, content, pinned, author_agent, created_at) '
|
||||
'VALUES (:id, :scope, :title, :content, :pinned, :author_agent, :created_at)',
|
||||
item,
|
||||
)
|
||||
conn.commit()
|
||||
return item
|
||||
|
||||
|
||||
def memory_get(memory_id: str) -> dict | None:
|
||||
init()
|
||||
row = _connect().execute('SELECT * FROM memories WHERE id = ?', (memory_id,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def memory_list(scope: str) -> list:
|
||||
"""
|
||||
一个记忆空间的全部条目(**注入 system prompt 用的就是它**)。
|
||||
|
||||
★ 顺序是**置顶的排最前**,其余按时间。
|
||||
界面和提示词注入用**同一个顺序** —— 两处各排一次的话,很容易出现
|
||||
"界面上看着在第一条、实际没进提示词"这种对不上的情况。
|
||||
"""
|
||||
init()
|
||||
rows = _connect().execute(
|
||||
'SELECT * FROM memories WHERE scope = ? ORDER BY pinned DESC, created_at ASC', (scope,),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def memory_search(scope: str, keyword: str, limit: int = 20) -> list:
|
||||
"""
|
||||
关键词检索(`memory_search` 工具)。
|
||||
|
||||
★ 用 LIKE 而不是 FTS5:FTS5 对中文要额外的分词器,而这里的关键词
|
||||
就是用户/模型给的整词,LIKE '%关键词%' 反而更符合直觉
|
||||
(搜"咖啡"能命中"喜欢喝咖啡")。条目量级(几千)下 LIKE 也够快。
|
||||
"""
|
||||
init()
|
||||
kw = (keyword or '').strip()
|
||||
if not kw:
|
||||
return []
|
||||
like = f'%{kw}%'
|
||||
rows = _connect().execute(
|
||||
'SELECT * FROM memories WHERE scope = ? AND (title LIKE ? OR content LIKE ?) '
|
||||
'ORDER BY pinned DESC, created_at DESC LIMIT ?',
|
||||
(scope, like, like, max(1, min(200, int(limit)))),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def memory_update(memory_id: str, title: str = None, content: str = None) -> dict | None:
|
||||
"""改标题/正文(只改传进来的字段)"""
|
||||
init()
|
||||
cur = memory_get(memory_id)
|
||||
if not cur:
|
||||
return None
|
||||
new_title = cur['title'] if title is None else (title or '').strip()
|
||||
new_content = cur['content'] if content is None else (content or '').strip()
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'UPDATE memories SET title = ?, content = ? WHERE id = ?',
|
||||
(new_title, new_content, memory_id),
|
||||
)
|
||||
conn.commit()
|
||||
return memory_get(memory_id)
|
||||
|
||||
|
||||
def memory_forget(memory_id: str) -> bool:
|
||||
init()
|
||||
conn = _connect()
|
||||
cur = conn.execute('DELETE FROM memories WHERE id = ?', (memory_id,))
|
||||
conn.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def memory_set_pinned(memory_id: str, pinned: bool) -> bool:
|
||||
"""用户手动标记「必须保留」(AI 改不了这个,见需求 3.2)"""
|
||||
init()
|
||||
conn = _connect()
|
||||
cur = conn.execute('UPDATE memories SET pinned = ? WHERE id = ?', (1 if pinned else 0, memory_id))
|
||||
conn.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def memory_replace_all(scope: str, items: list, keep_pinned: bool = True) -> int:
|
||||
"""
|
||||
**AI 总结**的写回:整个空间换成压缩后的那份。
|
||||
|
||||
★ `keep_pinned=True` 时 pinned 条目**原样保留**、不参与替换 ——
|
||||
这是需求 3.2 里"pinned 保护"的落地:用户标了"必须保留"的东西,
|
||||
不能被一次总结合并掉。
|
||||
|
||||
返回写回了多少条。
|
||||
"""
|
||||
init()
|
||||
conn = _connect()
|
||||
kept = []
|
||||
if keep_pinned:
|
||||
kept = [dict(r) for r in conn.execute(
|
||||
'SELECT * FROM memories WHERE scope = ? AND pinned = 1', (scope,),
|
||||
).fetchall()]
|
||||
conn.execute('DELETE FROM memories WHERE scope = ?' + (' AND pinned = 0' if keep_pinned else ''),
|
||||
(scope,))
|
||||
n = 0
|
||||
for it in items or []:
|
||||
title = str((it or {}).get('title') or '').strip()
|
||||
content = str((it or {}).get('content') or '').strip()
|
||||
if not title and not content:
|
||||
continue
|
||||
conn.execute(
|
||||
'INSERT INTO memories (id, scope, title, content, pinned, author_agent, created_at) '
|
||||
'VALUES (?, ?, ?, ?, 0, ?, ?)',
|
||||
(new_id(), scope, title, content, str(it.get('author_agent') or ''), now_iso()),
|
||||
)
|
||||
n += 1
|
||||
conn.commit()
|
||||
return n + len(kept)
|
||||
|
||||
|
||||
def memory_titles(scope: str) -> list:
|
||||
"""只要标题清单(注入时先拼标题,正文按需检索 —— 见注入模板)"""
|
||||
init()
|
||||
rows = _connect().execute(
|
||||
'SELECT title FROM memories WHERE scope = ? ORDER BY pinned DESC, created_at ASC', (scope,),
|
||||
).fetchall()
|
||||
return [r['title'] for r in rows if r['title']]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 情绪(始终按智能体私有,即使绑定了世界观 —— 需求 3.5)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def emotion_state(agent_id: str) -> dict:
|
||||
"""
|
||||
读一个智能体的情绪 → `{'preset': ..., 'text': ...}`(需求 3.5 双字段)。
|
||||
|
||||
★ 没记过情绪时返回默认值(「平常」+ 空文本),而不是空 —— 调用方
|
||||
(注入模板、界面)就不用各自处理 None 了。
|
||||
"""
|
||||
init()
|
||||
row = _connect().execute(
|
||||
'SELECT preset, text FROM emotions WHERE agent_id = ?', (agent_id or '',),
|
||||
).fetchone()
|
||||
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, 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, 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 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, preset)]。
|
||||
"""
|
||||
init()
|
||||
out = []
|
||||
for aid in agent_ids or []:
|
||||
if not aid or aid == exclude_agent:
|
||||
continue
|
||||
out.append((aid, emotion_state(aid)['preset']))
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Token 统计
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
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, 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()
|
||||
|
||||
|
||||
def token_usage(agent_id: str) -> dict:
|
||||
"""
|
||||
这个智能体的累计用量。
|
||||
|
||||
返回 `{'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, '
|
||||
'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),
|
||||
'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,
|
||||
}
|
||||
|
||||
|
||||
def token_reset(agent_id: str) -> int:
|
||||
"""按智能体清零(需求 3.1 的"管理操作")。返回清掉了几行"""
|
||||
init()
|
||||
conn = _connect()
|
||||
cur = conn.execute('DELETE FROM token_usage WHERE agent_id = ?', (agent_id or '',))
|
||||
conn.commit()
|
||||
return cur.rowcount
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Skill 绑定
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def skills_of(agent_id: str) -> list:
|
||||
"""这个智能体绑定的自定义 Skill id(**按绑定顺序** —— 注入要按顺序拼)"""
|
||||
init()
|
||||
rows = _connect().execute(
|
||||
'SELECT skill_id FROM agent_skills WHERE agent_id = ? ORDER BY ord ASC, skill_id ASC',
|
||||
(agent_id or '',),
|
||||
).fetchall()
|
||||
return [r['skill_id'] for r in rows]
|
||||
|
||||
|
||||
def bind_skills(agent_id: str, skill_ids: list) -> None:
|
||||
"""整体替换绑定关系(界面上的"勾选"就是一次整体替换,不用做增删接口)"""
|
||||
init()
|
||||
conn = _connect()
|
||||
conn.execute('DELETE FROM agent_skills WHERE agent_id = ?', (agent_id or '',))
|
||||
for i, sid in enumerate(skill_ids or []):
|
||||
if not sid:
|
||||
continue
|
||||
conn.execute(
|
||||
'INSERT OR REPLACE INTO agent_skills (agent_id, skill_id, ord) VALUES (?, ?, ?)',
|
||||
(agent_id or '', sid, i),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def unbind_agent(agent_id: str) -> None:
|
||||
"""智能体被删掉时的清理(记忆**不删** —— 那是用户的数据,删了他会心疼)"""
|
||||
init()
|
||||
conn = _connect()
|
||||
conn.execute('DELETE FROM agent_skills WHERE agent_id = ?', (agent_id or '',))
|
||||
conn.execute('DELETE FROM emotions WHERE agent_id = ?', (agent_id or '',))
|
||||
conn.commit()
|
||||
@@ -38,6 +38,13 @@ import paths
|
||||
import providers
|
||||
import speech
|
||||
import store
|
||||
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
|
||||
@@ -245,8 +252,15 @@ class SseChannel:
|
||||
|
||||
def _ping_loop(self) -> None:
|
||||
while not self.closed:
|
||||
# 用 Event.wait 代替 sleep,结束时会立刻退出,不用等满 15 秒
|
||||
if self._stop_event.wait(15):
|
||||
# ★ 心跳间隔可调(设置 → 超时 → 心跳间隔)。
|
||||
# 它必须**明显小于**客户端的读超时(sseRead),否则客户端会先
|
||||
# 判定"连接死了"再断开 —— 等用户回答的那种场景会因此白等。
|
||||
try:
|
||||
gap = float(timeouts.get('heartbeat'))
|
||||
except Exception: # noqa: BLE001
|
||||
gap = 15.0
|
||||
# 用 Event.wait 代替 sleep,结束时会立刻退出,不用等满
|
||||
if self._stop_event.wait(gap):
|
||||
return
|
||||
if self.closed:
|
||||
return
|
||||
@@ -570,7 +584,50 @@ 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 的回退链:
|
||||
# 当前 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'): 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 '')
|
||||
for a in store.list_agents()
|
||||
if store.peek_summary_suggestion(a.get('id') or '')
|
||||
},
|
||||
'toolNames': tool_names,
|
||||
'suggestedAllow': tools_runtime.suggest_allowlist(tool_names),
|
||||
# 前端用它挑终端里的预设命令(安卓的 getprop / Windows 的 dir 不通用)
|
||||
@@ -585,6 +642,36 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200, {'ok': True, 'settings': store.mask_settings(nxt)})
|
||||
return True
|
||||
|
||||
# ---------------------------------------------------------------- #
|
||||
# 超时(设置 → 超时)
|
||||
#
|
||||
# ★ 清单由内核给,**界面不硬编码这些项目** —— 加一项超时只改 timeouts.py,
|
||||
# 界面自动多出一行(连说明文字都是这里带过去的)。
|
||||
# ★ 写的时候是**整体替换**而不是深合并:默认值在 timeouts.py 里,
|
||||
# "改回默认"等于"从设置文件里删掉这一项",深合并会让它删不掉。
|
||||
# ---------------------------------------------------------------- #
|
||||
if pathname == '/api/timeouts' and method == 'GET':
|
||||
self.send_json(200, {
|
||||
'ok': True,
|
||||
'items': timeouts.catalog(),
|
||||
'values': timeouts.resolved(),
|
||||
})
|
||||
return True
|
||||
|
||||
if pathname == '/api/timeouts' and method in ('PUT', 'POST'):
|
||||
body = self.read_json_body()
|
||||
if body.get('reset'):
|
||||
next_values = timeouts.reset()
|
||||
else:
|
||||
next_values = timeouts.patch(body.get('values') or body)
|
||||
store.write_settings({'timeouts': next_values})
|
||||
self.send_json(200, {
|
||||
'ok': True,
|
||||
'items': timeouts.catalog(),
|
||||
'values': timeouts.resolved(),
|
||||
})
|
||||
return True
|
||||
|
||||
if pathname == '/api/models' and method == 'GET':
|
||||
settings = store.read_settings()
|
||||
try:
|
||||
@@ -869,8 +956,58 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
self.send_json(200, {'conversation': store.create_conversation(body.get('title') or '新对话')})
|
||||
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:"用户手动增删成员无条件")----
|
||||
#
|
||||
# ★ "无条件"是需求原话:不加"只有主智能体能加人""要对方同意"这类
|
||||
# 限制 —— 会话是用户的,他想拉谁就拉谁。
|
||||
# 唯一的例外是主智能体不能移出(移掉就没有兜底发言的人了)。
|
||||
member_id = self._match_id(pathname, '/api/conversations/')
|
||||
if member_id is not None and '/members' in pathname:
|
||||
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':
|
||||
@@ -1219,27 +1356,15 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200, {'ok': True})
|
||||
return True
|
||||
|
||||
# 智能体
|
||||
if pathname == '/api/agents' and method == 'GET':
|
||||
self.send_json(200, {'agents': store.list_agents()})
|
||||
# 智能体系统的接口(记忆 / 情绪 / Token / 世界观 / 模型列表 / Skill / 导入导出)
|
||||
#
|
||||
# ★ 全部集中在 agent_api.py 里 —— app.py 已经 1800 行,二十多个新接口
|
||||
# 塞进来会让这个文件彻底没法看。
|
||||
# ★ 老的 /api/agents 那三个路由**删掉了**(原来在下面),由这里统一处理:
|
||||
# 留着就是两份实现,而新那份多了"内置智能体不能删"的保护 ——
|
||||
# 两份并存的话,哪份生效取决于顺序,这种 bug 最难查。
|
||||
if agent_api.handle(self, pathname, method):
|
||||
return True
|
||||
if pathname == '/api/agents' and method == 'POST':
|
||||
body = self.read_json_body()
|
||||
self.send_json(200, {'agent': store.create_agent(body)})
|
||||
return True
|
||||
agent_id = self._match_id(pathname, '/api/agents/')
|
||||
if agent_id is not None:
|
||||
if method in ('PATCH', 'PUT'):
|
||||
body = self.read_json_body()
|
||||
agent = store.update_agent(agent_id, body)
|
||||
if agent:
|
||||
self.send_json(200, {'agent': agent})
|
||||
else:
|
||||
self.send_json(404, {'error': '智能体不存在'})
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
self.send_json(200 if store.delete_agent(agent_id) else 404, {'ok': True})
|
||||
return True
|
||||
|
||||
# 附件
|
||||
if pathname == '/api/upload' and method == 'POST':
|
||||
@@ -1388,7 +1513,19 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
)
|
||||
merged_agent = {'systemPrompt': sys_prompt, 'id': '', 'name': '判断器'}
|
||||
else:
|
||||
base = (agent or {}).get('systemPrompt') or cfg.get('systemPrompt') or ''
|
||||
# ★ 会议节点也走**同一套** system prompt 拼装(需求附录 C)。
|
||||
#
|
||||
# 以前这里是自己拼的(`agent.systemPrompt or cfg.systemPrompt`),
|
||||
# 于是同一个智能体在聊天里有记忆/情绪/世界观、在会议节点里没有 ——
|
||||
# "引擎改了另一端必须跟上"这条在这个仓库里踩过好几次,
|
||||
# 所以这次直接复用 agent_context,别再抄一份。
|
||||
#
|
||||
# ★ 节点的额外要求 / 输出要求 / 变量说明仍然**追加在后面**:
|
||||
# 它们是"这一轮的任务约束",比人设更具体,放最后模型才看得重。
|
||||
if agent:
|
||||
base = agent_context.build_system_prompt(store.read_settings(), agent)
|
||||
else:
|
||||
base = cfg.get('systemPrompt') or ''
|
||||
parts = [base] if base.strip() else []
|
||||
if extra:
|
||||
parts.append('【本次任务的额外要求】\n' + extra)
|
||||
@@ -1572,9 +1709,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')
|
||||
]
|
||||
|
||||
@@ -1600,6 +1738,133 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
has_image = any(p.get('type') == 'image_url' for p in parts)
|
||||
user_content = parts if (has_image or len(parts) > 1) else text
|
||||
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]
|
||||
# 用户这一轮 @ 了谁:从**最后一条用户消息**里找
|
||||
last_user = ''
|
||||
for m in reversed(raw_history):
|
||||
if m.get('role') == 'user':
|
||||
last_user = str(m.get('content') or '')
|
||||
break
|
||||
pick = group_chat.resolve(
|
||||
conv0,
|
||||
want=group_chat.mention_in(last_user, names),
|
||||
passed=str(body.get('handoffTo') 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)
|
||||
|
||||
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
|
||||
#
|
||||
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
|
||||
# 还在同一个会话里接着聊 —— 历史消息是上一个角色说的,
|
||||
# 而 system prompt 已经换成新角色的了。新角色**会把别人的话
|
||||
# 当成自己说的**(用户的原话:"智能体怎么串味了")。
|
||||
#
|
||||
# 处理:主人不一致就**另起一个会话**,并通知界面换 id。
|
||||
# · 老会话(本次改动之前建的)没有 agentId —— 那种**认领**它,
|
||||
# 而不是也另起一个,否则所有历史会话第一次聊天都会跳走。
|
||||
owner = (existing.get('agentId') or '').strip()
|
||||
if existing and agent_id:
|
||||
if not owner:
|
||||
store.set_conversation_agent(conversation_id, agent_id)
|
||||
elif owner != agent_id:
|
||||
conversation_id = store.create_conversation(agent_id=agent_id)['id']
|
||||
existing = store.get_conversation(conversation_id) or {}
|
||||
# 界面据此把当前会话切过去(不然它会往老 id 上继续追加)
|
||||
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)。
|
||||
#
|
||||
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
||||
# **已经攒下来的**用量,超了就根本不发这一轮。
|
||||
#
|
||||
# ★ 拦在"写用户消息之前":拦住了还把用户那句话落库的话,
|
||||
# 他会看到自己发的消息挂在那儿、AI 永远不回,以为卡住了。
|
||||
#
|
||||
# ★ 豁免:记忆整理、导出这些**非对话生成**的操作不走这里
|
||||
# (它们有自己的接口),所以不会被限额挡住。
|
||||
try:
|
||||
limit = int(float((agent or {}).get('tokenLimit') or 0))
|
||||
except (TypeError, ValueError):
|
||||
limit = 0
|
||||
if limit > 0 and agent_id:
|
||||
used = sum(agentdb.token_usage(agent_id)['total'].values())
|
||||
if used >= limit:
|
||||
farewell = (settings.get('tokenLimitFarewell') or '我没力气再说话了……').strip()
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'assistant',
|
||||
'content': farewell,
|
||||
'agentId': agent_id,
|
||||
# ★ 标一下"这不是模型生成的":界面据此把它显示成提示样式,
|
||||
# 而且重新生成时不会被当成一条正常的 AI 回复
|
||||
'limitNotice': True,
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
emit({
|
||||
'type': 'error',
|
||||
'code': 'token_limit',
|
||||
'message': f'{(agent or {}).get("name") or "这个智能体"}的 Token 额度用完了',
|
||||
'used': used,
|
||||
'limit': limit,
|
||||
'farewell': farewell,
|
||||
'hint': '可以清零重新开始,或者把限额调大 / 改成无限制。',
|
||||
})
|
||||
return
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'user',
|
||||
@@ -1623,14 +1888,61 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
send_depth=send_depth,
|
||||
)
|
||||
|
||||
# ★ 这一轮的 Token 用量(需求 4.1:对话界面显示"本次对话"的用量)。
|
||||
# 按轮记在消息上,会话级用量是**加起来**算的 —— 这样"重新生成"
|
||||
# 把上一条替换掉时,它的消耗也跟着消失,不会虚高。
|
||||
in_tok, out_tok = agent_loop.usage_pair(result.get('usage'))
|
||||
model_name = (store.provider_info(settings, agent) or {}).get('model') or ''
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'assistant',
|
||||
'content': result.get('content', ''),
|
||||
# 思维链也要落库,否则一刷新「思考过程」就没了
|
||||
'reasoning': result.get('reasoning', '') or '',
|
||||
'agentId': (agent or {}).get('id') or '',
|
||||
'agentId': agent_id,
|
||||
'usage': {'input': in_tok, 'output': out_tok},
|
||||
# ★ 幻觉调用检测(需求 3.7):嘴上说记住了、实际没调工具。
|
||||
# 界面据此显示一个 ⚠ 标记 —— 用户当场看不出来,
|
||||
# 但下次发现它"完全不记得"时就晚了。
|
||||
'hallucination': agent_loop.check_hallucinated_memory(
|
||||
result.get('content') or '',
|
||||
int(result.get('toolCalls') or 0),
|
||||
bool((settings.get('tools') or {}).get('python', True)),
|
||||
),
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
|
||||
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
|
||||
if agent_id and (in_tok or out_tok):
|
||||
try:
|
||||
# ★ 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 事件收尾,前端才知道停了
|
||||
|
||||
@@ -26,6 +26,7 @@ import time
|
||||
import traceback
|
||||
|
||||
import paths
|
||||
import timeouts
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 工具定义(与 tools/shell.py、tools/python_run.py 的 TOOL 完全一致,
|
||||
@@ -43,7 +44,10 @@ SHELL_TOOL = {
|
||||
'properties': {
|
||||
'command': {'type': 'string', 'description': '要执行的命令,例如 ls -la 或 python --version'},
|
||||
'cwd': {'type': 'string', 'description': '工作目录,可留空'},
|
||||
'timeout': {'type': 'number', 'description': '超时秒数,默认 30,最大 300'},
|
||||
'timeout': {
|
||||
'type': 'number',
|
||||
'description': '超时秒数。不传就用设置里「超时 → shell 命令」那个值',
|
||||
},
|
||||
},
|
||||
'required': ['command'],
|
||||
},
|
||||
@@ -67,7 +71,10 @@ PYTHON_RUN_TOOL = {
|
||||
'code': {'type': 'string', 'description': '要执行的 Python 代码(action=run 时二选一)'},
|
||||
'file': {'type': 'string', 'description': '要执行的 .py 文件路径(action=run 时二选一)'},
|
||||
'stdin': {'type': 'string', 'description': '传给脚本的标准输入,可留空'},
|
||||
'timeout': {'type': 'number', 'description': '超时秒数,默认 60,最大 600'},
|
||||
'timeout': {
|
||||
'type': 'number',
|
||||
'description': '超时秒数。不传就用设置里「超时 → 跑 Python 代码」那个值',
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -125,7 +132,8 @@ def shell_run(args: dict) -> dict:
|
||||
if bad in lowered:
|
||||
raise ValueError(f'命令命中黑名单({bad}),已拒绝执行。确实需要请设置 DOUBAO_SHELL_UNSAFE=1')
|
||||
|
||||
timeout = max(1, min(300, int(args.get('timeout') or 30)))
|
||||
# 超时:模型传了就用它的,没传就用设置里的(设置 → 超时 → shell 命令)
|
||||
timeout = timeouts.budget(args, 'shell')
|
||||
cwd = args.get('cwd') or None
|
||||
if cwd and not os.path.isdir(cwd):
|
||||
raise ValueError(f'工作目录不存在:{cwd}')
|
||||
@@ -248,6 +256,17 @@ def run_with_timeout(fn, timeout_s: float):
|
||||
而且 CPython 根本杀不掉一个正在跑的线程。超时后我们只能"放弃等待",
|
||||
被放弃的线程会继续在后台跑完(daemon 线程,不阻塞进程退出)。
|
||||
这个取舍必须让用户知道,所以超时消息里写清楚。
|
||||
|
||||
★★ `timeout_s <= 0` = **不限时**(一直等到它跑完)。
|
||||
|
||||
给"停下来等用户"的那类工具用(`ask_user` / `show_ui` 的 wait 模式)——
|
||||
它们的耗时**完全取决于用户什么时候点**,60 秒的上限只会造成:
|
||||
弹窗还开着、用户 5 分钟后才选,而模型早就收到"工具执行超时"、
|
||||
于是按自己猜的答案往下写了。
|
||||
|
||||
为什么默认仍然是 60 秒:这是"工具里写了死循环"的安全网
|
||||
(不让整个内核跟着卡死)。会等用户的工具属于**设计上就该慢**,
|
||||
由工具自己声明 `WAIT_FOR_USER = True` 来豁免,见 tools_runtime。
|
||||
"""
|
||||
box = {}
|
||||
|
||||
@@ -259,9 +278,13 @@ def run_with_timeout(fn, timeout_s: float):
|
||||
|
||||
thread = threading.Thread(target=worker, name='doubao-python-run', daemon=True)
|
||||
thread.start()
|
||||
thread.join(timeout_s)
|
||||
if thread.is_alive():
|
||||
return None
|
||||
if timeout_s and timeout_s > 0:
|
||||
thread.join(timeout_s)
|
||||
if thread.is_alive():
|
||||
return None
|
||||
else:
|
||||
# 不限时:join() 不带参数就是一直等
|
||||
thread.join()
|
||||
if 'error' in box:
|
||||
raise box['error']
|
||||
return box.get('value')
|
||||
@@ -278,7 +301,7 @@ def python_run(args: dict) -> dict:
|
||||
if not code and not file_path:
|
||||
raise ValueError('code 和 file 至少要给一个')
|
||||
|
||||
timeout = max(1, min(600, int(args.get('timeout') or 60)))
|
||||
timeout = timeouts.budget(args, 'pythonRun')
|
||||
stdin_text = args.get('stdin') or ''
|
||||
|
||||
if file_path:
|
||||
@@ -321,3 +344,13 @@ BUILTIN_TOOLS = {
|
||||
'shell': {'spec': SHELL_TOOL, 'run': shell_run},
|
||||
'python_run': {'spec': PYTHON_RUN_TOOL, 'run': python_run},
|
||||
}
|
||||
|
||||
# 智能体系统的工具(记忆 / 情绪 / 用量)也走**进程内**实现 —— 它们要读写
|
||||
# `agent.db`,而电脑端的文件工具是子进程,根本 import 不到内核模块。
|
||||
#
|
||||
# ★ 合并进这一个字典而不是让 tools_runtime 从两处取:
|
||||
# 发现工具、找入口、判"要不要豁免超时"全都只认 BUILTIN_TOOLS,
|
||||
# 多一个来源就多一处"忘了查"的机会(加进来之后自动全部生效)。
|
||||
from agent_tools import AGENT_TOOLS # noqa: E402
|
||||
|
||||
BUILTIN_TOOLS.update(AGENT_TOOLS)
|
||||
|
||||
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',
|
||||
]
|
||||
@@ -67,8 +67,10 @@ import sys
|
||||
import threading
|
||||
import traceback
|
||||
|
||||
# 单个自定义节点最多跑多久(和会议里的 Python 节点同一套兜底)
|
||||
RUN_TIMEOUT = 10
|
||||
import timeouts
|
||||
|
||||
# ★ 单个自定义节点的超时**不在这里** —— 见 timeouts.py 的 'customNode'
|
||||
# (设置 → 超时 → 自定义节点)。和会议里的 Python 节点是同一套兜底。
|
||||
|
||||
# 引脚类型:exec 是执行引脚,其余是数据引脚
|
||||
PIN_KINDS = ('exec', 'str', 'bool', 'num', 'list')
|
||||
@@ -344,9 +346,10 @@ def run_custom(defn: dict, inputs: dict, variables: dict, node: dict,
|
||||
|
||||
th = threading.Thread(target=work, daemon=True)
|
||||
th.start()
|
||||
th.join(RUN_TIMEOUT)
|
||||
budget = timeouts.get('customNode')
|
||||
th.join(budget)
|
||||
if th.is_alive():
|
||||
return {}, f'超过 {RUN_TIMEOUT} 秒还没跑完(可能有死循环)'
|
||||
return {}, f'超过 {budget:g} 秒还没跑完(可能有死循环,可在设置里调)'
|
||||
return result['outs'], result['err']
|
||||
|
||||
|
||||
|
||||
@@ -166,6 +166,15 @@ for _key, _url in PROVIDER_CONSOLE_URLS.items():
|
||||
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
# 记忆注入窗口(条数):每轮最多把多少条记忆放进提示词。
|
||||
#
|
||||
# ★ "记忆无上限"和"每轮全量注入"这两条长期是矛盾的 —— 攒到几百上千条时
|
||||
# 提示词会被记忆撑爆(一千条 × 几十字 ≈ 几万 token),而且**越靠后的
|
||||
# 记忆越贵、反而把最近的对话上下文挤掉**。
|
||||
# 所以给一个窗口:置顶的永远注入,其余取最近的。
|
||||
# 被裁掉的没丢,AI 还能用 memory_search 检索到("降级为仅可检索")。
|
||||
# 0 = 不限(退回全量注入)。
|
||||
'memoryWindow': 50,
|
||||
'provider': 'ark',
|
||||
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
||||
@@ -206,6 +215,13 @@ DEFAULT_SETTINGS = {
|
||||
},
|
||||
# 安全模式:open 全部放行 / restricted 只放 allow 白名单
|
||||
'security': {'mode': 'open', 'allow': []},
|
||||
# 超时。**这里故意是空的** —— 默认值全在 timeouts.py 的 DEFAULT 里,
|
||||
# 只有用户改过的项才会出现在这儿(和默认一样就删掉,见 timeouts.patch)。
|
||||
#
|
||||
# 为什么这么做:以后调整某个默认值时,没动过那一项的用户会跟着新默认走。
|
||||
# 如果把默认值也存进设置文件,老用户会被永久钉在旧的默认上,
|
||||
# 而且"我明明改的是代码里的默认值,怎么没生效"这种问题极难查。
|
||||
'timeouts': {},
|
||||
# Node 版用它指定解释器;Python 内核在进程内执行工具,这个字段只为兼容而保留
|
||||
'pythonBin': '',
|
||||
'nickname': '我',
|
||||
@@ -215,6 +231,99 @@ DEFAULT_SETTINGS = {
|
||||
|
||||
SECRET_KEYS = {'apiKey'}
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 智能体系统(需求 v1.1)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# 内置 Skill:记忆 / 情绪 / 检索 / 用量这几个工具的**使用手册**(需求 3.7)。
|
||||
#
|
||||
# ★ 为什么不把这些写进工具自己的 description:
|
||||
# 工具的 description 只讲"这个工具怎么调",而 Skill 讲的是
|
||||
# "**什么时候该用、用完之后不许干什么**"—— 后者才是模型最容易犯错的地方
|
||||
# (最典型的是"只在嘴上说记住了、根本没调工具")。
|
||||
# 放在 <skills> 段里,每个智能体都能看到;自定义 Skill 按同样的方式追加。
|
||||
BUILTIN_SKILL = '\n'.join([
|
||||
'【记忆】你有自己的记忆库,**跨对话保留**:',
|
||||
'· 用户说了值得长期记住的事(称呼、偏好、重要事实、约定、他的项目),用 memory_add 记下来。',
|
||||
'· 记之前先看上面的记忆清单 —— 已经记过的不要再记一遍,否则清单会越来越乱。',
|
||||
'· 记错了/过时了用 memory_update 改;确实不该留的用 memory_forget 删(只能删你自己写的)。',
|
||||
'· 清单里只有标题,需要正文细节时用 memory_search 检索。',
|
||||
'★★ 绝对不要只在回复里说"我记住了"却不调用 memory_add。',
|
||||
' 说了要记就必须真的调工具;没调就别说这句话 —— 用户会当场发现你在骗他。',
|
||||
'',
|
||||
'【情绪】emotion_set 改的是**你自己**的情绪状态,下次对话还在。',
|
||||
' 情绪要跟着对话内容自然变化;别每轮都改,也别一直用同一个词。',
|
||||
'',
|
||||
'【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。',
|
||||
])
|
||||
|
||||
# system prompt 的注入模板(需求附录 C,v1.2 修订了段序)。
|
||||
#
|
||||
# ★★ **缓存友好排序**(附录 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}',
|
||||
'',
|
||||
'<skills>',
|
||||
'{skills}',
|
||||
'</skills>',
|
||||
'',
|
||||
'<worldview>',
|
||||
'{worldview}',
|
||||
'</worldview>',
|
||||
'',
|
||||
'<memory>',
|
||||
'{memory}',
|
||||
'</memory>',
|
||||
'',
|
||||
# ---- 以下是易变段,放最后 ----
|
||||
'<stats>',
|
||||
'{stats}',
|
||||
'</stats>',
|
||||
'',
|
||||
'<status>',
|
||||
'{status}',
|
||||
'</status>',
|
||||
'',
|
||||
'<emotion>',
|
||||
'{emotion}',
|
||||
'</emotion>',
|
||||
'',
|
||||
'<peer_emotions>',
|
||||
'{peer_emotions}',
|
||||
'</peer_emotions>',
|
||||
])
|
||||
|
||||
# 记忆注入时的条目模板(附录 C 的 `【标题1】内容1`)。
|
||||
#
|
||||
# ★ 是**全量注入**(标题 + 正文都进去)—— 需求 3.2 的"主动记忆:smartMemory
|
||||
# 全量注入 system prompt"。正文不进的话模型只知道"我记过这件事",
|
||||
# 每次要用都得再检索一次,白花一轮。
|
||||
DEFAULT_MEMORY_LINE = '【{title}】{content}'
|
||||
|
||||
|
||||
# 内置智能体(前端有同名头像,靠 avatar 字段对应)
|
||||
DEFAULT_AGENTS = [
|
||||
{
|
||||
|
||||
@@ -18,6 +18,10 @@ import shutil
|
||||
import sys
|
||||
import threading
|
||||
|
||||
# 超时全部收在 timeouts.py 里(用户可在「设置 → 超时」调)。
|
||||
# 它读不到设置时会回落默认值,所以在启动早期 import 也是安全的。
|
||||
import timeouts
|
||||
|
||||
# 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录)
|
||||
BUNDLED_TOOL_FILES = [
|
||||
'_protocol.py',
|
||||
@@ -40,6 +44,11 @@ BUNDLED_TOOL_FILES = [
|
||||
'notifications.py',
|
||||
'apps.py',
|
||||
'volume.py',
|
||||
# ★ web_search.py 以前漏在清单外(对拍脚本抓出来的)。
|
||||
# 它其实**照样会被播种**(构建脚本遍历整个 tools/ 目录,
|
||||
# _seed_tools 又用那份源码整体补齐),所以功能上没缺 ——
|
||||
# 但清单是"内置工具一览"的文档,和现实不一致就会误导下一个人。
|
||||
'web_search.py',
|
||||
'_mcp_python_example.py',
|
||||
]
|
||||
|
||||
@@ -148,7 +157,10 @@ SHELL_TOOL_SPEC = {
|
||||
'properties': {
|
||||
'command': {'type': 'string', 'description': '要执行的命令'},
|
||||
'cwd': {'type': 'string', 'description': '工作目录,可留空'},
|
||||
'timeout': {'type': 'number', 'description': '超时秒数,默认 30,最大 300'},
|
||||
'timeout': {
|
||||
'type': 'number',
|
||||
'description': '超时秒数。不传就用设置里「超时 → Termux 命令」那个值',
|
||||
},
|
||||
},
|
||||
'required': ['command'],
|
||||
},
|
||||
@@ -223,7 +235,7 @@ def shell_run(args: dict) -> dict:
|
||||
if not command or _android is None:
|
||||
return fallback_shell(args)
|
||||
|
||||
timeout = max(1, min(300, int(args.get('timeout', 30) or 30)))
|
||||
timeout = timeouts.budget(args, 'termux')
|
||||
hit = _try_termux(command, str(args.get('cwd') or ''), timeout)
|
||||
if hit is not None:
|
||||
return {
|
||||
|
||||
175
android/kernel/group_chat.py
Normal file
@@ -0,0 +1,175 @@
|
||||
"""群聊的发言权仲裁(需求 v1.2 §3.9)。
|
||||
|
||||
## 点名制
|
||||
|
||||
需求原话:
|
||||
|
||||
> **发言权仲裁:点名制**。被 @ 者发言;AI 可通过 `pass_turn` 指定下一位
|
||||
> 发言者,**一轮最多一次移交**;无人被点名时由主智能体(会话发起者)兜底,
|
||||
> **永不冷场**。
|
||||
|
||||
翻译成优先级(从高到低):
|
||||
|
||||
① 用户 @ 的人 用户主权,最高
|
||||
② AI 上一轮 pass_turn 的人 一轮最多一次
|
||||
③ 主智能体(participants[0])兜底,永不冷场
|
||||
|
||||
## 死亡的人不能接
|
||||
|
||||
> 死亡智能体被点名时移交无效,发言权回主智能体。
|
||||
|
||||
这条单独写出来,是因为"移交无效"有三种可能的处置:
|
||||
报错、随机选一个、回主智能体 —— 需求选了第三种。
|
||||
**回主智能体**也对:它会接着把话头圆下去,用户不会看到"没人应"。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
仲裁是**纯逻辑**(给一群人和几个标记,返回谁说话),没有 IO。
|
||||
放在 `app.py` 的对话循环里就没法逐条测 —— 而它的分支(点名/移交/
|
||||
兜底/死亡/不在场)有五种,正是最该测的那种。
|
||||
"""
|
||||
|
||||
#: 一轮最多移交一次。需求明文,所以做成一个常量而不是散在代码里的布尔。
|
||||
MAX_HANDOFF_PER_ROUND = 1
|
||||
|
||||
|
||||
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:
|
||||
"""主智能体 = 会话发起者 = 成员列表的第一个(需求:"发起者")"""
|
||||
ids = member_ids(conv)
|
||||
return ids[0] if ids else (conv or {}).get('agentId') or ''
|
||||
|
||||
|
||||
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) -> dict:
|
||||
"""
|
||||
决定这一轮谁发言。
|
||||
|
||||
[want] 用户 @ 出来的人(`mention_in` 的结果)
|
||||
[passed] AI 上一轮 `pass_turn` 指定的人
|
||||
[alive] `{agent_id: bool}`,缺省视为活着
|
||||
[handoffs] 这一轮已经移交过几次(用于"一轮最多一次")
|
||||
|
||||
返回 `{'speaker': id, 'reason': 'mention'|'handoff'|'host'|'handoff_denied', 'note': ''}`。
|
||||
"""
|
||||
conv = conv or {}
|
||||
alive = alive or {}
|
||||
ids = member_ids(conv)
|
||||
host = host_id(conv)
|
||||
|
||||
def ok(aid: str) -> bool:
|
||||
return bool(aid) and aid in ids and alive.get(aid, True)
|
||||
|
||||
# ① 用户 @ 的人(用户主权,不受"一轮一次"约束 —— 那条只管 AI 的移交)
|
||||
if want:
|
||||
if ok(want):
|
||||
return {'speaker': want, 'reason': 'mention', 'note': ''}
|
||||
# 被 @ 的人死了或不在场:回主智能体,而不是报错
|
||||
return {'speaker': host, 'reason': 'host',
|
||||
'note': '被点的人不在场或已死亡,发言权回主智能体'}
|
||||
|
||||
# ② AI 的移交(一轮最多一次)
|
||||
if passed:
|
||||
if handoffs >= MAX_HANDOFF_PER_ROUND:
|
||||
return {'speaker': host, 'reason': 'handoff_denied',
|
||||
'note': '这一轮已经移交过了,不再移交'}
|
||||
if ok(passed):
|
||||
return {'speaker': passed, 'reason': 'handoff', 'note': ''}
|
||||
# ★ 死亡的人被点名时**移交无效**,发言权回主智能体(需求明文)
|
||||
return {'speaker': host, 'reason': 'host',
|
||||
'note': f'「{passed}」已死亡或不在场,移交无效,发言权回主智能体'}
|
||||
|
||||
# ③ 兜底:永不冷场
|
||||
return {'speaker': host, 'reason': 'host', 'note': ''}
|
||||
|
||||
|
||||
def add_member(conv: dict, agent_id: str) -> bool:
|
||||
"""
|
||||
加一个成员(用户手动增删**无条件允许** —— 用户主权)。
|
||||
|
||||
★ 加完**自动升级成 group**:成员超过一个时 `type` 必须是 `group`,
|
||||
不然成员列表里有人、仲裁逻辑还按单聊跑 ——
|
||||
表现是"我把人拉进来了,但他从来不说话"。
|
||||
这条收在这里而不是让调用方自己补,是因为"忘记补"的代价不对称:
|
||||
补错了只是类型不对,忘补了就是功能整个不生效。
|
||||
|
||||
★ 单聊要拉人 → 那个会话**就地转成群聊**,而不是偷偷往
|
||||
`participants` 里塞一个 id 却把 `type` 留着。
|
||||
"""
|
||||
c = conv or {}
|
||||
aid = str(agent_id or '').strip()
|
||||
if not aid:
|
||||
return False
|
||||
ids = member_ids(c)
|
||||
if aid in ids:
|
||||
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:
|
||||
"""
|
||||
移出一个成员。**主智能体不能被移出**(需求说发言权兜底靠它 ——
|
||||
移掉的话这个群聊就没有兜底了,会冷场)。
|
||||
"""
|
||||
c = conv or {}
|
||||
aid = str(agent_id or '').strip()
|
||||
ids = member_ids(c)
|
||||
if aid not in ids or aid == host_id(c):
|
||||
return False
|
||||
ids.remove(aid)
|
||||
c['participants'] = ids
|
||||
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
|
||||
@@ -29,10 +29,37 @@ import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import paths
|
||||
import timeouts
|
||||
|
||||
PROTOCOL_VERSION = '2024-11-05'
|
||||
CLIENT_INFO = {'name': 'doubao-kernel-py', 'version': '0.1.0'}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 超时
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ★ 这三个超时**不写死在这里** —— 它们在 timeouts.py 里,用户可以在
|
||||
# 「设置 → 超时 → MCP」那一组里调。
|
||||
#
|
||||
# ★ 为什么是函数而不是默认参数值:Python 的默认参数**只在函数定义时求值一次**,
|
||||
# 写成 `def request(self, message, timeout=timeouts.get('mcpRequest'))`
|
||||
# 会把第一次读到的值永久钉住 —— 用户在设置里改完发现没生效,
|
||||
# 而且这种 bug 光看代码看不出来(写法看起来很合理)。
|
||||
# 所以默认值一律写 None,真正取值在这里做。
|
||||
|
||||
def _span_timeout(value, key: str, fallback: float) -> float:
|
||||
if value:
|
||||
return float(value)
|
||||
try:
|
||||
return float(timeouts.get(key))
|
||||
except Exception: # noqa: BLE001 - 设置读不出来也不能让 MCP 用不了
|
||||
return fallback
|
||||
|
||||
|
||||
def _req_timeout(value) -> float:
|
||||
"""单次请求的超时"""
|
||||
return _span_timeout(value, 'mcpRequest', 60.0)
|
||||
|
||||
_clients: dict = {} # serverName -> {'spec','client','tools','error'}
|
||||
_lock = threading.RLock()
|
||||
|
||||
@@ -204,7 +231,8 @@ class _HttpTransport:
|
||||
self.session_id = sid
|
||||
return resp
|
||||
|
||||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||
def request(self, message: dict, timeout: float = None) -> dict:
|
||||
timeout = _req_timeout(timeout)
|
||||
resp = self._post(message, timeout)
|
||||
try:
|
||||
status = getattr(resp, 'status', 200)
|
||||
@@ -575,7 +603,8 @@ class _StdioTransport:
|
||||
self._closed = True
|
||||
self._cv.notify_all()
|
||||
|
||||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||
def request(self, message: dict, timeout: float = None) -> dict:
|
||||
timeout = _req_timeout(timeout)
|
||||
with self._cv:
|
||||
if self._closed:
|
||||
raise McpError('MCP 服务进程已退出')
|
||||
@@ -704,7 +733,8 @@ class _InprocTransport:
|
||||
self._closed = True
|
||||
self._cv.notify_all()
|
||||
|
||||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||
def request(self, message: dict, timeout: float = None) -> dict:
|
||||
timeout = _req_timeout(timeout)
|
||||
req_id = message.get('id')
|
||||
with self._cv:
|
||||
if self._closed:
|
||||
@@ -805,7 +835,8 @@ class McpClient:
|
||||
raise McpError(f'{method} 失败:{detail}')
|
||||
return response.get('result')
|
||||
|
||||
def connect(self, timeout: float = 180) -> 'McpClient':
|
||||
def connect(self, timeout: float = None) -> 'McpClient':
|
||||
timeout = _span_timeout(timeout, 'mcpConnect', 180.0)
|
||||
# initialize 允许失败:inproc 的最小实现可能只认 tools/list、tools/call
|
||||
self._request(
|
||||
'initialize',
|
||||
@@ -818,11 +849,12 @@ class McpClient:
|
||||
tolerate_error=True,
|
||||
)
|
||||
self.transport.notify({'jsonrpc': '2.0', 'method': 'notifications/initialized', 'params': {}})
|
||||
listed = self._request('tools/list', {}, 60) or {}
|
||||
listed = self._request('tools/list', {}, _req_timeout(None)) or {}
|
||||
self.tools = listed.get('tools') or []
|
||||
return self
|
||||
|
||||
def call_tool(self, name: str, arguments: dict, timeout: float = 120) -> dict:
|
||||
def call_tool(self, name: str, arguments: dict, timeout: float = None) -> dict:
|
||||
timeout = _span_timeout(timeout, 'mcpTool', 120.0)
|
||||
result = self._request('tools/call', {'name': name, 'arguments': arguments or {}}, timeout)
|
||||
return result or {}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
import timeouts
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
@@ -74,7 +75,8 @@ NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar', 'while', 'valu
|
||||
# 但**必须**做两件事:超时(死循环不能把 App 卡死)和异常兜底
|
||||
# (报错要显示在哪一步,而不是整场会议崩掉)。
|
||||
|
||||
PY_TIMEOUT = 10 # 单个 Python 节点最多跑多少秒
|
||||
# ★ 单个 Python 节点的超时**不在这里** —— 见 timeouts.py 的 'meetingNode'
|
||||
# (设置 → 超时 → 会议节点)。以前写死 10 秒,跑个稍重的计算就会被判死循环。
|
||||
PY_MAX_OUTPUT = 20000 # 输出最多留多少字符
|
||||
|
||||
|
||||
@@ -131,9 +133,10 @@ def run_py_node(code: str, input_text: str, variables: dict,
|
||||
|
||||
th = threading.Thread(target=work, daemon=True)
|
||||
th.start()
|
||||
th.join(PY_TIMEOUT)
|
||||
budget = timeouts.get('meetingNode')
|
||||
th.join(budget)
|
||||
if th.is_alive():
|
||||
return (result['out'] or '')[:PY_MAX_OUTPUT], f'超过 {PY_TIMEOUT} 秒还没跑完(可能有死循环)'
|
||||
return (result['out'] or '')[:PY_MAX_OUTPUT], f'超过 {budget:g} 秒还没跑完(可能有死循环,可在设置里调)'
|
||||
|
||||
for k, v in writes.items():
|
||||
variables[k] = v
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
运行期路径与平台判断。
|
||||
|
||||
为什么单独一个模块:
|
||||
@@ -86,6 +86,25 @@ class Paths:
|
||||
self.conversations_file = os.path.join(self.data_dir, 'conversations.json')
|
||||
self.agents_file = os.path.join(self.data_dir, 'agents.json')
|
||||
self.mcp_file = os.path.join(self.data_dir, 'mcp.servers.json')
|
||||
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
||||
#
|
||||
# ★ 和 agents.json 一样是 JSON、一人一个文件:它们的量级也是"几个到几十个",
|
||||
# 而且要人肉可读(用户会想直接看自己建的世界观写成什么样)。
|
||||
# 会**持续增长**的那些(记忆 / 情绪 / Token 统计)在 agent.db 里,
|
||||
# 分界线见 agentdb.py 的文件头。
|
||||
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 时落到这儿)
|
||||
self.agent_assets_dir = os.path.join(self.data_dir, 'agent-assets')
|
||||
|
||||
@staticmethod
|
||||
def _resolve_web_core(explicit: str | None) -> str:
|
||||
@@ -103,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.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
|
||||
@@ -20,11 +20,20 @@ import urllib.request
|
||||
from typing import Callable, Iterator, Optional
|
||||
|
||||
from defaults import PROVIDER_PRESETS
|
||||
import timeouts
|
||||
|
||||
# 推理模型(o 系列 / gpt-5 系)不接受 temperature 等采样参数
|
||||
REASONING_MODEL_RE = re.compile(r'^(o1|o3|o4|gpt-5|gpt-6)', re.IGNORECASE)
|
||||
|
||||
DEFAULT_TIMEOUT_MS = 180000
|
||||
# ★ 模型请求的超时**不在这里** —— 它和别的超时一起收在 timeouts.py 里
|
||||
# (设置 → 超时 → 等模型回复)。以前这里是 `DEFAULT_TIMEOUT_MS = 180000`,
|
||||
# 用户改不了;现在每次请求现读,改了立刻生效、不用重启。
|
||||
def model_timeout_s() -> float:
|
||||
"""等模型返回的秒数(读设置,出错时回落 180 秒)"""
|
||||
try:
|
||||
return float(timeouts.get('model'))
|
||||
except Exception: # noqa: BLE001 - 设置读不出来也不能让请求发不出去
|
||||
return 180.0
|
||||
|
||||
|
||||
def join_url(base_url: str, suffix: str) -> str:
|
||||
@@ -109,7 +118,7 @@ def _request(url: str, api_key: str, body: dict | None = None, method: str = 'PO
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
# 不用 urlopen 的 with:流式响应要留给调用方边读边消费
|
||||
return urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_MS / 1000)
|
||||
return urllib.request.urlopen(req, timeout=model_timeout_s())
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
try:
|
||||
@@ -263,7 +272,7 @@ def list_models(*, base_url: str, api_key: str) -> list:
|
||||
url = join_url(base_url, '/models')
|
||||
req = urllib.request.Request(url, headers={'Authorization': f'Bearer {api_key}'}, method='GET')
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_MS / 1000)
|
||||
resp = urllib.request.urlopen(req, timeout=model_timeout_s())
|
||||
except urllib.error.HTTPError as exc:
|
||||
raise UpstreamError(f'上游 {exc.code}') from exc
|
||||
except urllib.error.URLError as exc:
|
||||
|
||||
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'
|
||||
'只导入你信得过的来源。'
|
||||
)
|
||||
@@ -28,8 +28,28 @@ import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
DEFAULT_TIMEOUT_TTS = 60
|
||||
DEFAULT_TIMEOUT_STT = 120
|
||||
import timeouts
|
||||
|
||||
# ★ 语音的超时也收在 timeouts.py 里(设置 → 超时 → 语音合成 / 语音识别)。
|
||||
# 以前这里是 `DEFAULT_TIMEOUT_TTS = 60` / `DEFAULT_TIMEOUT_STT = 120` 两个常量,
|
||||
# 网络慢或者回复长的时候用户只能忍着。现在是函数 —— 每次现读,改完立刻生效。
|
||||
|
||||
|
||||
def tts_timeout() -> float:
|
||||
"""语音合成等多久(出错回落 60 秒)"""
|
||||
try:
|
||||
return float(timeouts.get('tts'))
|
||||
except Exception: # noqa: BLE001
|
||||
return 60.0
|
||||
|
||||
|
||||
def stt_timeout() -> float:
|
||||
"""语音识别等多久(出错回落 120 秒)"""
|
||||
try:
|
||||
return float(timeouts.get('stt'))
|
||||
except Exception: # noqa: BLE001
|
||||
return 120.0
|
||||
|
||||
|
||||
# 允许用环境变量覆盖:自测时把火山接口指到本地 mock,就能验证"我们到底发了什么"
|
||||
# (鉴权头那个分号、body 的层级,光看代码容易自我说服,实测才算数)
|
||||
@@ -267,7 +287,7 @@ def _synthesize_volc_v3(text: str, speech: dict, speed: float) -> dict:
|
||||
req.add_header('X-Control-Require-Usage-Tokens-Return', '*')
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp:
|
||||
with urllib.request.urlopen(req, timeout=tts_timeout()) as resp:
|
||||
raw = resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
@@ -342,7 +362,7 @@ def _synthesize_volc(text: str, speech: dict, speed: float) -> dict:
|
||||
'operation': 'query',
|
||||
},
|
||||
}
|
||||
result = _post_json(VOLC_TTS_URL, body, {'Authorization': f'Bearer;{token}'}, DEFAULT_TIMEOUT_TTS)
|
||||
result = _post_json(VOLC_TTS_URL, body, {'Authorization': f'Bearer;{token}'}, tts_timeout())
|
||||
|
||||
code = result.get('code')
|
||||
if code != 3000:
|
||||
@@ -374,7 +394,7 @@ def _synthesize_openai(text: str, settings: dict, speech: dict, speed: float) ->
|
||||
req.add_header('Authorization', f'Bearer {api_key}')
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp:
|
||||
with urllib.request.urlopen(req, timeout=tts_timeout()) as resp:
|
||||
raw = resp.read()
|
||||
ctype = resp.headers.get('Content-Type') or 'audio/mpeg'
|
||||
except urllib.error.HTTPError as exc:
|
||||
@@ -429,7 +449,7 @@ def transcribe(audio: bytes, filename: str, content_type: str, settings: dict) -
|
||||
req.add_header('Authorization', f'Bearer {api_key}')
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_STT) as resp:
|
||||
with urllib.request.urlopen(req, timeout=stt_timeout()) as resp:
|
||||
raw = resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
@@ -564,7 +584,7 @@ def _stream_volc_v3(text: str, speech: dict, speed: float):
|
||||
|
||||
mime = VOLC_MIME.get(fmt, 'audio/L16')
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS)
|
||||
resp = urllib.request.urlopen(req, timeout=tts_timeout())
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
try:
|
||||
|
||||
@@ -21,6 +21,7 @@ import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
import agentdb
|
||||
from defaults import DEFAULT_AGENTS, DEFAULT_SETTINGS, PROVIDER_PRESETS
|
||||
|
||||
_lock = threading.RLock()
|
||||
@@ -40,6 +41,42 @@ 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" 这种情况也不会被冲掉。
|
||||
|
||||
归一化**不丢信息**:字典里多出来的档位原样保留(用户可能自己加了「醉」这种)。
|
||||
"""
|
||||
img = dict(image or {})
|
||||
front = img.get('front')
|
||||
if isinstance(front, str):
|
||||
# v1.1 的单文件名 → 只有「平常」档
|
||||
img['front'] = {'平常': front} if front.strip() else {}
|
||||
elif isinstance(front, dict):
|
||||
img['front'] = {
|
||||
str(k): str(v) for k, v in front.items()
|
||||
if str(v or '').strip()
|
||||
}
|
||||
else:
|
||||
img['front'] = {}
|
||||
for key in ('back', 'border-main', 'border-info'):
|
||||
img[key] = str(img.get(key) or '')
|
||||
return img
|
||||
|
||||
|
||||
def _read_json(file_path: str):
|
||||
"""读 JSON;文件不存在或坏掉都返回 None(调用方决定怎么兜底)。"""
|
||||
if not os.path.isfile(file_path):
|
||||
@@ -135,6 +172,11 @@ def read_settings() -> dict:
|
||||
# ({"speech":"{autoRead=true}"}),存进去之后**每一次**读配置都会抛
|
||||
# TypeError,/api/state 从此一直 500 —— 一个坏字段把整个 App 弄成空白。
|
||||
# 所以:读的时候发现不是字典就回落默认值(自愈),写的时候也不让非字典覆盖。
|
||||
#
|
||||
# ★ timeouts **刻意不在这个列表里**:它的默认值是空 dict(真正的默认值在
|
||||
# timeouts.py 里),深合并会让"改回默认 = 删掉这一项"永远删不掉 ——
|
||||
# 旧值残留在设置文件里,用户会看到"我明明恢复默认了怎么还是 30 秒"。
|
||||
# 所以它走**整体替换**:写进来的就是全部,没写到的等于用默认值。
|
||||
for key in ('tools', 'security', 'speech'):
|
||||
defaults = DEFAULT_SETTINGS.get(key) or {}
|
||||
raw = stored.get(key)
|
||||
@@ -202,6 +244,16 @@ def write_settings(patch: dict) -> dict:
|
||||
else:
|
||||
nxt[key] = current.get(key) or {}
|
||||
print(f'[config] 补丁里的 {key} 不是对象({type(patch[key]).__name__}),已忽略', file=sys.stderr, flush=True)
|
||||
# ★ timeouts 是**整体替换**,不深合并 —— 默认值在 timeouts.py 里,
|
||||
# 深合并会让"改回默认 = 从设置里删掉这一项"永远删不掉。
|
||||
# 调用方(/api/timeouts)传进来的就是**完整的非默认集合**。
|
||||
if 'timeouts' in patch:
|
||||
raw_t = patch['timeouts']
|
||||
if isinstance(raw_t, dict):
|
||||
nxt['timeouts'] = raw_t
|
||||
else:
|
||||
nxt['timeouts'] = current.get('timeouts') or {}
|
||||
print(f'[config] 补丁里的 timeouts 不是对象({type(raw_t).__name__}),已忽略', file=sys.stderr, flush=True)
|
||||
if patch.get('apiKey') == '••••••••':
|
||||
nxt['apiKey'] = current.get('apiKey', '')
|
||||
# ★ 掩码回写保护:界面读到的是 '••••••••',用户不改语音设置直接保存时,
|
||||
@@ -229,13 +281,52 @@ def write_settings(patch: dict) -> dict:
|
||||
|
||||
def provider_info(settings: dict, agent: dict = None) -> dict:
|
||||
"""
|
||||
当前提供商的完整信息(预设 + 生效的 baseUrl/model)。
|
||||
当前提供商的完整信息(预设 + 生效的 baseUrl/model/apiKey)。
|
||||
|
||||
★ agent 不为空时,智能体自己的 provider/model/baseUrl **优先**,留空则继承全局。
|
||||
这样"某个智能体用 DeepSeek、其它还用方舟"是改一个智能体的事,
|
||||
不用来回切全局设置 —— 而全局设置仍然是没配过的智能体的默认值。
|
||||
|
||||
★★ v1.1 新增一层:智能体可以**引用全局模型列表里的一项**(`modelId`,需求 3.3)。
|
||||
优先级是:
|
||||
|
||||
模型列表那一项(地址/Key/模型标识都从它来,**整组覆盖**)
|
||||
↓ 没引用
|
||||
智能体自己的 provider/model/baseUrl
|
||||
↓ 留空
|
||||
全局设置
|
||||
↓ 还没填
|
||||
提供商预设
|
||||
|
||||
「整组覆盖」是刻意的:模型列表存在的意义就是"配一次到处用、
|
||||
改 Key 只改一处"。如果只覆盖 model 而 Key 还用全局的,
|
||||
就会出现"选了 DeepSeek 的模型、却拿方舟的 Key 去调"这种必然 401 的组合。
|
||||
"""
|
||||
agent = agent or {}
|
||||
entry = None
|
||||
model_id = (agent.get('modelId') or '').strip()
|
||||
if model_id:
|
||||
try:
|
||||
entry = get_resource('models', model_id)
|
||||
except Exception: # noqa: BLE001 - 列表坏了不该让对话发不出去
|
||||
entry = None
|
||||
|
||||
if entry:
|
||||
provider_key = (entry.get('provider') or '').strip() or settings.get('provider')
|
||||
preset = PROVIDER_PRESETS.get(provider_key) or _preset_of(settings)
|
||||
return {
|
||||
**preset,
|
||||
'provider': provider_key,
|
||||
'baseUrl': (entry.get('apiBase') or '').strip() or preset.get('baseUrl', ''),
|
||||
'model': (entry.get('model') or '').strip() or preset.get('defaultModel', ''),
|
||||
# ★ Key 也从那一项来(留空才回落全局)——
|
||||
# "只覆盖 model 不覆盖 Key"必然 401,见上面的注释
|
||||
'apiKey': (entry.get('apiKey') or '').strip() or settings.get('apiKey') or '',
|
||||
'modelEntryId': model_id,
|
||||
# ★ 兼容降级(需求 3.3):这个模型不支持 tools 参数
|
||||
'noTools': bool(entry.get('noTools')),
|
||||
}
|
||||
|
||||
provider_key = (agent.get('provider') or '').strip() or settings.get('provider')
|
||||
preset = PROVIDER_PRESETS.get(provider_key) or _preset_of(settings)
|
||||
return {
|
||||
@@ -244,6 +335,7 @@ def provider_info(settings: dict, agent: dict = None) -> dict:
|
||||
# baseUrl 也是三层:智能体 > 全局 > 预设
|
||||
'baseUrl': (agent.get('baseUrl') or '').strip() or settings.get('baseUrl') or preset.get('baseUrl', ''),
|
||||
'model': (agent.get('model') or '').strip() or settings.get('model') or preset.get('defaultModel', ''),
|
||||
'apiKey': settings.get('apiKey') or '',
|
||||
}
|
||||
|
||||
|
||||
@@ -802,11 +894,59 @@ def clear_pending_ui(conv_id: str) -> None:
|
||||
_pending_ui.pop(conv_id, None)
|
||||
|
||||
|
||||
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 「建议整理记忆」的待处理队列
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# AI 用 memory_suggest_summary 提的建议 —— **只提示不执行**(需求 3.2)。
|
||||
# 界面读到之后给用户一个「整理记忆」按钮,用户点了才真的跑总结。
|
||||
#
|
||||
# ★ 为什么放内存而不是落库:它是一次性的提示,用户处理完就该消失。
|
||||
# 落库的话重启一次 App 会看到三天前那条建议,莫名其妙。
|
||||
# ★ 按智能体存(不是按会话):建议是"你的记忆该整理了",跟哪个会话无关。
|
||||
_pending_summary: dict = {}
|
||||
|
||||
|
||||
def add_pending_summary_suggestion(agent_id: str, reason: str) -> None:
|
||||
"""同一个人后来的建议**覆盖**前面的 —— 说两遍没有意义"""
|
||||
if not agent_id:
|
||||
return
|
||||
with _lock:
|
||||
_pending_summary[agent_id] = (reason or '').strip()
|
||||
|
||||
|
||||
def peek_summary_suggestion(agent_id: str) -> str:
|
||||
with _lock:
|
||||
return _pending_summary.get(agent_id or '', '')
|
||||
|
||||
|
||||
def take_summary_suggestion(agent_id: str) -> str:
|
||||
"""取走(取完就没了)"""
|
||||
with _lock:
|
||||
return _pending_summary.pop(agent_id or '', '')
|
||||
|
||||
|
||||
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(),
|
||||
@@ -844,6 +984,26 @@ def delete_conversation(conv_id: str) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def set_conversation_agent(conv_id: str, agent_id: str) -> None:
|
||||
"""
|
||||
把会话**认领**给一个智能体(只用于没有主人的老会话)。
|
||||
|
||||
★ 只认领、不"改嫁":已经在别人名下的会话不由这里动 ——
|
||||
那会让历史消息和提示词对不上(用户报的"串味"就是这么来的)。
|
||||
★ 走 `_load_conversations` / `_persist_conversations` 这一对,
|
||||
不要自己 `_read_json`+`_write_json`:会话有一份**内存缓存**,
|
||||
绕过它写文件的话,紧接着的 `get_conversation` 读到的还是旧的缓存
|
||||
(这个错误在探针里被抓到过)。
|
||||
"""
|
||||
with _lock:
|
||||
data = _load_conversations()
|
||||
for c in data.get('conversations') or []:
|
||||
if c.get('id') == conv_id and not (c.get('agentId') or '').strip():
|
||||
c['agentId'] = agent_id
|
||||
_persist_conversations()
|
||||
return
|
||||
|
||||
|
||||
def append_messages(conv_id: str, messages: list):
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
@@ -884,31 +1044,108 @@ def store_file_path() -> str:
|
||||
# 提成常量是为了 create / update 两边不会漂移:
|
||||
# 之前这两个函数各写一份硬编码白名单,加字段时漏改一处,
|
||||
# 表现就是"界面上填了、保存后再打开又变空了"。
|
||||
AGENT_FIELDS = (
|
||||
#
|
||||
# ★ v1.1 新增(《智能体系统需求文档》),字段按类型分开,见下面的 _apply_agent_patch:
|
||||
# description 选择界面上展示的介绍文案(2.1)
|
||||
# image 外观四件套 front / back / border-main / border-info(2.5)
|
||||
# modelId 引用全局模型列表里的一个(3.3 多模型)
|
||||
# worldviewId 绑定的世界观(3.6)
|
||||
# emotionEnabled 情绪感知开关(3.5)
|
||||
# tokenLimit Token 限额,0 = 无限制(3.1)
|
||||
# skillIds 绑定的自定义 Skill(3.7;真正的绑定关系在 agent.db)
|
||||
AGENT_TEXT_FIELDS = (
|
||||
'name', 'avatar', 'tagline', 'description', 'systemPrompt',
|
||||
'provider', # 走哪家(留空 = 全局)
|
||||
'model', # 用哪个模型
|
||||
'baseUrl', # 自定义网关地址
|
||||
'ttsEngine', # 朗读引擎:system / volcv3 / volc / openai
|
||||
'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',)
|
||||
AGENT_DICT_FIELDS = ('image',)
|
||||
|
||||
#: 能被 patch 改的全部字段(界面上"这个智能体有哪些可配"就看它)
|
||||
AGENT_FIELDS = (
|
||||
AGENT_TEXT_FIELDS + AGENT_NUM_FIELDS + AGENT_BOOL_FIELDS
|
||||
+ AGENT_LIST_FIELDS + AGENT_DICT_FIELDS
|
||||
)
|
||||
|
||||
|
||||
def _rid_agent() -> str:
|
||||
return f'a_{_ts36()}_{_rand36(4)}'
|
||||
def _apply_agent_patch(agent: dict, patch: dict) -> dict:
|
||||
"""
|
||||
把 patch 里的字段规整进 agent。
|
||||
|
||||
★ **create 和 update 共用这一份** —— 它们以前各写一份白名单,
|
||||
加字段漏改一处就是"界面上填了、保存后再打开又变空了"这种查半天的 bug。
|
||||
★ 类型规整也在这里:从 HTTP 来的东西可能是字符串(`"true"`、`"3"`),
|
||||
直接存进去会让界面读到时类型不对(勾选框永远是空的)。
|
||||
"""
|
||||
patch = patch or {}
|
||||
for key in AGENT_TEXT_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
agent[key] = _as_text(patch[key])
|
||||
for key in AGENT_NUM_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
try:
|
||||
agent[key] = float(patch[key])
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
for key in AGENT_BOOL_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
agent[key] = bool(patch[key])
|
||||
for key in AGENT_LIST_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
raw = patch[key]
|
||||
agent[key] = [str(x) for x in raw] if isinstance(raw, list) else []
|
||||
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 {}
|
||||
)
|
||||
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):
|
||||
@@ -923,19 +1160,19 @@ def get_agent(agent_id: str | None):
|
||||
def create_agent(payload: dict) -> dict:
|
||||
payload = payload or {}
|
||||
state = {'agents': list_agents()}
|
||||
# ★ id 一律 UUID(需求附录 A):`name` 只是显示名,允许重复、允许随便改,
|
||||
# 所有关联(记忆作者、Token 统计、Skill 绑定)都挂在这个 id 上。
|
||||
# 老数据里的 `a_doubao` 这种短 id **保留不动** —— 会话语料引用着它们。
|
||||
agent = {
|
||||
'id': _rid_agent(),
|
||||
'id': agentdb.new_id(),
|
||||
'name': _as_text(payload.get('name') or '新智能体')[:24],
|
||||
'avatar': payload.get('avatar') or 'custom',
|
||||
'avatar': _as_text(payload.get('avatar') or 'custom'),
|
||||
'tagline': _as_text(payload.get('tagline'))[:40],
|
||||
'systemPrompt': _as_text(payload.get('systemPrompt')),
|
||||
'builtin': False,
|
||||
'createdAt': now_iso(),
|
||||
}
|
||||
# 智能体自己的模型/语音(留空 = 继承全局)
|
||||
for key in AGENT_FIELDS:
|
||||
if payload.get(key) is not None:
|
||||
agent[key] = _as_text(payload.get(key))
|
||||
_apply_agent_patch(agent, payload)
|
||||
state['agents'].append(agent)
|
||||
_write_json(paths.get().agents_file, state)
|
||||
return agent
|
||||
@@ -946,10 +1183,7 @@ def update_agent(agent_id: str, patch: dict):
|
||||
agent = next((a for a in state['agents'] if a.get('id') == agent_id), None)
|
||||
if not agent:
|
||||
return None
|
||||
patch = patch or {}
|
||||
for key in ('name', 'avatar', 'tagline', 'systemPrompt', *AGENT_FIELDS):
|
||||
if patch.get(key) is not None:
|
||||
agent[key] = patch[key]
|
||||
_apply_agent_patch(agent, patch)
|
||||
_write_json(paths.get().agents_file, state)
|
||||
return agent
|
||||
|
||||
@@ -961,6 +1195,191 @@ def delete_agent(agent_id: str) -> bool:
|
||||
return False
|
||||
state['agents'].pop(index)
|
||||
_write_json(paths.get().agents_file, state)
|
||||
# 清掉它在数据库里的绑定关系和情绪;**记忆不删** —— 那是用户的数据,
|
||||
# 删智能体顺手把他攒了几个月的记忆抹掉,他会心疼(而且没法恢复)
|
||||
try:
|
||||
agentdb.unbind_agent(agent_id)
|
||||
except Exception as exc: # noqa: BLE001 - 清理失败不该让删除失败
|
||||
print(f'[store] 清理 {agent_id} 的绑定关系失败:{exc}', file=sys.stderr)
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 通用资源表:世界观 / 全局模型 / Skill
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 三者的 CRUD 完全一样(列表 + 增 + 改 + 删 + UUID 主键),所以**只写一份** ——
|
||||
# 区别只是"有哪些字段",那部分在 RESOURCES 里声明。
|
||||
#
|
||||
# ★ 为什么不放 agent.db(SQLite):它们的量级和 agents.json 一样是"几个到几十个"
|
||||
# (用户自己会去数),而且要人肉可读。分界线见 agentdb.py 的文件头。
|
||||
|
||||
RESOURCES = {
|
||||
# 世界观(需求 3.6):名字 + 设定文本 + 外观四件套
|
||||
'worldviews': {
|
||||
'file': lambda: paths.get().worldviews_file,
|
||||
'key': 'worldviews',
|
||||
# ★ 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 = 不显示费用估算
|
||||
# ★ noTools:这个模型不支持 function calling(需求 3.3 的兼容降级)。
|
||||
# 打开之后不传 tools、改成正文内的调用约定 —— 见 agent_loop.DEGRADED_HINT。
|
||||
'bool': ('noTools',),
|
||||
'label': '模型',
|
||||
},
|
||||
# Skill(需求 3.7):纯文本的"工具使用手册"
|
||||
'skills': {
|
||||
'file': lambda: paths.get().skills_file,
|
||||
'key': 'skills',
|
||||
'text': ('name', 'content'),
|
||||
'bool': ('builtin',),
|
||||
'label': 'Skill',
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _res(name: str) -> dict:
|
||||
cfg = RESOURCES.get(name)
|
||||
if not cfg:
|
||||
raise KeyError(f'没有这种资源:{name}')
|
||||
return cfg
|
||||
|
||||
|
||||
def list_resource(name: str) -> list:
|
||||
cfg = _res(name)
|
||||
file_path = cfg['file']()
|
||||
data = _read_json(file_path)
|
||||
if not isinstance(data, dict) or not isinstance(data.get(cfg['key']), list):
|
||||
return []
|
||||
return data[cfg['key']]
|
||||
|
||||
|
||||
def _write_resource(name: str, items: list) -> None:
|
||||
cfg = _res(name)
|
||||
_write_json(cfg['file'](), {cfg['key']: items})
|
||||
|
||||
|
||||
def get_resource(name: str, rid: str):
|
||||
if not rid:
|
||||
return None
|
||||
for item in list_resource(name):
|
||||
if item.get('id') == rid:
|
||||
return item
|
||||
return None
|
||||
|
||||
|
||||
def _apply_resource_patch(name: str, item: dict, patch: dict) -> dict:
|
||||
cfg = _res(name)
|
||||
patch = patch or {}
|
||||
for key in cfg.get('text', ()):
|
||||
if patch.get(key) is not None:
|
||||
item[key] = _as_text(patch[key])
|
||||
for key in cfg.get('num', ()):
|
||||
if patch.get(key) is not None:
|
||||
try:
|
||||
item[key] = float(patch[key])
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
for key in cfg.get('bool', ()):
|
||||
if patch.get(key) is not None:
|
||||
item[key] = bool(patch[key])
|
||||
for key in cfg.get('dict', ()):
|
||||
if patch.get(key) is not None:
|
||||
raw = patch[key]
|
||||
# ★★ **不要对每个值调 `_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': want_id or agentdb.new_id(), # ★ UUID(需求附录 A)
|
||||
'name': _as_text((payload or {}).get('name'))[:40],
|
||||
'builtin': False,
|
||||
'createdAt': now_iso(),
|
||||
}
|
||||
_apply_resource_patch(name, item, payload)
|
||||
# 重名不拦(需求 2.5:重名由用户自己区分),但界面要能看出来,
|
||||
# 所以这里不做任何"自动改名" —— 显示时加序号是界面的事
|
||||
items.append(item)
|
||||
_write_resource(name, items)
|
||||
return item
|
||||
|
||||
|
||||
def update_resource(name: str, rid: str, patch: dict):
|
||||
items = list_resource(name)
|
||||
item = next((x for x in items if x.get('id') == rid), None)
|
||||
if not item:
|
||||
return None
|
||||
_apply_resource_patch(name, item, patch)
|
||||
_write_resource(name, items)
|
||||
return item
|
||||
|
||||
|
||||
def delete_resource(name: str, rid: str) -> bool:
|
||||
items = list_resource(name)
|
||||
left = [x for x in items if x.get('id') != rid]
|
||||
if len(left) == len(items):
|
||||
return False
|
||||
_write_resource(name, left)
|
||||
return True
|
||||
|
||||
|
||||
|
||||
352
android/kernel/timeouts.py
Normal file
@@ -0,0 +1,352 @@
|
||||
"""**所有超时的唯一一份定义**,以及读取它们的入口。
|
||||
|
||||
## 为什么要收成一份
|
||||
|
||||
改造前,15 个超时散在 10 个文件里,全是模块级常量,谁也说不清一共有几个:
|
||||
|
||||
tools_runtime.py TOOL_TIMEOUT_S = 60 工具执行
|
||||
builtin_tools.py shell 工具 30 / python 60 命令执行(还各自夹了上限)
|
||||
doubao_entry.py termux 命令 30
|
||||
providers.py DEFAULT_TIMEOUT_MS = 180000 模型请求
|
||||
speech.py TTS 60 / STT 120
|
||||
mcp_client.py 请求 60 / 连接 180 / 工具 120
|
||||
meeting.py PY_TIMEOUT = 10 会议里的 Python 节点
|
||||
custom_nodes.py RUN_TIMEOUT = 10
|
||||
tools/ask_user.py TIMEOUT_S = 0 / MAX 3600
|
||||
tools/show_ui.py MIN 5 / MAX 3600
|
||||
KernelClient.kt connect 5s / read 120s
|
||||
|
||||
后果和"节点定义写 6 遍"是同一类:**想调一个超时要先找到它在哪**,
|
||||
而且改了一处不知道还有没有别处也在卡同一个东西。
|
||||
|
||||
## 用户要"全部可调",所以这里同时是**界面数据的来源**
|
||||
|
||||
界面不硬编码这些项目 —— 它读 `GET /api/timeouts`,那个接口返回的就是 [SPECS]。
|
||||
所以**加一项超时只改这个文件**(加 [DEFAULT] 一条 + [SPECS] 一条),
|
||||
内核各处 `timeouts.get('名字')`,界面自动多出一行。
|
||||
|
||||
## 边界
|
||||
|
||||
每项都带 `min` / `max`,取值时**一律夹进去**([get] 里做的)。
|
||||
不是"相信用户不会填错":填 0 会让 curl 永远不超时、填 999999 会让内核线程
|
||||
挂到天荒地老。夹取是这一层唯一该做的"业务判断",所以放在这里而不是各调用点。
|
||||
|
||||
`min = 0` 表示这一项**允许"不限时"**(只有"等用户"这类才该允许)。
|
||||
"""
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 默认值
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 这里只放**数字**。每一项都必须能在 SPECS 里找到同名条目 ——
|
||||
# `scripts/verify-timeouts.py` 会检查两边对得上(少一条就报错)。
|
||||
|
||||
DEFAULT = {
|
||||
# ---- 智能体切换动画(需求 2.3)----
|
||||
'agentAnim.frontOut': 0.3,
|
||||
'agentAnim.gap': 0.5,
|
||||
'agentAnim.frame': 0.4,
|
||||
'agentAnim.frontIn': 0.3,
|
||||
# ---- 对话 ----
|
||||
'model': 180, # 等模型返回
|
||||
'sseRead': 120, # 客户端读 SSE 的间隔上限(内核只负责告诉客户端)
|
||||
'heartbeat': 15, # SSE 心跳间隔
|
||||
'kernelLocal': 10, # 客户端调内核本地接口(安卓侧用)
|
||||
|
||||
# ---- 工具 ----
|
||||
'tool': 60, # 任意 Python 工具执行
|
||||
'shell': 30, # 安卓 shell 命令(builtin)
|
||||
'pythonRun': 60, # 跑一段 Python 代码(builtin)
|
||||
'termux': 30, # 内置 Termux 里跑命令
|
||||
'meetingNode': 10, # 会议里的 Python / 自定义节点
|
||||
'customNode': 10, # 自定义节点(nodes/ 里的)
|
||||
|
||||
# ---- 界面(等用户)----
|
||||
'askUser': 0, # ask_user 等用户选,0 = 不限时
|
||||
'waitUi': 0, # show_ui 的 wait 模式等用户,0 = 不限时
|
||||
'filePicker': 120, # AI 让你选文件时等你多久
|
||||
|
||||
# ---- 语音 ----
|
||||
'tts': 60,
|
||||
'stt': 120,
|
||||
|
||||
# ---- MCP ----
|
||||
'mcpRequest': 60,
|
||||
'mcpConnect': 180,
|
||||
'mcpTool': 120,
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 每一项的说明(界面直接用这些文字)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# group 决定界面上分到哪一组;unit 目前全是"秒"(毫秒的东西一律在调用点换算)。
|
||||
|
||||
SPECS = [
|
||||
# ---------------- 智能体切换动画(需求 2.3)----------------
|
||||
#
|
||||
# ★ 这几项严格说**不是超时**,但它们和超时是同一类东西:
|
||||
# 一个"全局可调的时间数值"。需求 2.3 原话是"所有时长与缓动数值收进全局配置"。
|
||||
#
|
||||
# 为什么不单独造一套(settings 里加个 agentAnim 对象 + 再写一个配置界面):
|
||||
# 那就是**第二份要同步的东西** —— 加一项要改两处、界面要写两遍,
|
||||
# 而这个仓库里"同一逻辑抄成两份、改的时候只改一份"已经反复出现过。
|
||||
# 复用它唯一的代价是分组标题要写清楚(界面上这一组的说明就是这么写的)。
|
||||
{
|
||||
'key': 'agentAnim.frontOut', 'group': '动画', 'label': '角色图出场',
|
||||
'default': 0.3, 'min': 0.05, 'max': 3, 'unit': '秒',
|
||||
'desc': '切换智能体时,**旧**角色图淡出 + 侧移的时长(需求定的 0.3s)。',
|
||||
},
|
||||
{
|
||||
'key': 'agentAnim.gap', 'group': '动画', 'label': '中间留白',
|
||||
'default': 0.5, 'min': 0, 'max': 5, 'unit': '秒', 'zero': '不停顿',
|
||||
'desc': '两个阶段之间的停顿(需求定的 0.5s)。调成 0 就是"出场完立刻换框",'
|
||||
'整个切换会从 1.5 秒缩到 1.0 秒 —— 嫌切换慢就改这个。',
|
||||
},
|
||||
{
|
||||
'key': 'agentAnim.frame', 'group': '动画', 'label': '边框背景切换',
|
||||
'default': 0.4, 'min': 0.05, 'max': 4, 'unit': '秒',
|
||||
'desc': '背景图 / 主体边框 / 介绍框滑出滑入的**总**时长(需求定的 0.4s,'
|
||||
'实际拆成滑出一半、滑入一半)。',
|
||||
},
|
||||
{
|
||||
'key': 'agentAnim.frontIn', 'group': '动画', 'label': '角色图入场',
|
||||
'default': 0.3, 'min': 0.05, 'max': 3, 'unit': '秒',
|
||||
'desc': '**新**角色图淡入 + 侧移到位的时长(需求定的 0.3s)。',
|
||||
},
|
||||
|
||||
# ---------------- 对话 ----------------
|
||||
{
|
||||
'key': 'model', 'group': '对话', 'label': '等模型回复',
|
||||
'default': 180, 'min': 10, 'max': 1800, 'unit': '秒',
|
||||
'desc': '发出去到开始收到第一个字的最长等待。深度思考的模型(R1 这类)'
|
||||
'经常要想一分钟以上,调小了会频繁断在半路;本地小模型可以调大。',
|
||||
},
|
||||
{
|
||||
'key': 'sseRead', 'group': '对话', 'label': '连接空闲上限',
|
||||
'default': 120, 'min': 20, 'max': 3600, 'unit': '秒',
|
||||
'desc': '手机上"多久没收到任何数据就断开"。内核每【心跳间隔】秒发一次心跳,'
|
||||
'所以这个值必须比心跳间隔大不少 —— 内核发的就是心跳间隔那项。'
|
||||
'弱网/代理会悄悄掐长连接,可以把两个都调小一点,断得早反而好重连。',
|
||||
},
|
||||
{
|
||||
'key': 'heartbeat', 'group': '对话', 'label': '心跳间隔',
|
||||
'default': 15, 'min': 5, 'max': 300, 'unit': '秒',
|
||||
'desc': '对话过程中内核每隔这么久发一个空包,证明连接还活着。'
|
||||
'调大了在弱网下容易被中间设备当成死连接掐掉;调小了费电。',
|
||||
},
|
||||
{
|
||||
'key': 'kernelLocal', 'group': '对话', 'label': '本地接口请求',
|
||||
'default': 10, 'min': 3, 'max': 300, 'unit': '秒',
|
||||
'desc': '界面调内核的普通接口(读会话、存设置、拉笔记)等多久。'
|
||||
'只有老设备 + 会话特别长时才会顶到这个值。',
|
||||
},
|
||||
|
||||
# ---------------- 工具 ----------------
|
||||
{
|
||||
'key': 'tool', 'group': '工具', 'label': '工具执行',
|
||||
'default': 60, 'min': 0, 'max': 3600, 'unit': '秒', 'zero': '不限时',
|
||||
'desc': '任意一个 Python 工具最多跑多久。这是"工具里写了死循环"的安全网。\n'
|
||||
'填 0 = 不限时。注意:会停下来等你的工具(AI 提问、AI 界面等待)'
|
||||
'本来就不受这一项限制 —— 它们的时长取决于你什么时候点。',
|
||||
},
|
||||
{
|
||||
'key': 'shell', 'group': '工具', 'label': 'shell 命令',
|
||||
'default': 30, 'min': 1, 'max': 3600, 'unit': '秒',
|
||||
'desc': 'AI 调用内置 shell 工具跑一条命令的最长时间。'
|
||||
'装包(pkg install / pip install)这类会超过 30 秒,那时可以让 AI 自己传更长的值。',
|
||||
},
|
||||
{
|
||||
'key': 'pythonRun', 'group': '工具', 'label': '跑 Python 代码',
|
||||
'default': 60, 'min': 1, 'max': 3600, 'unit': '秒',
|
||||
'desc': 'AI 写一段 Python 交给内核执行的最长时间。算得久(循环、大文件)就调大。',
|
||||
},
|
||||
{
|
||||
'key': 'termux', 'group': '工具', 'label': 'Termux 命令',
|
||||
'default': 30, 'min': 1, 'max': 3600, 'unit': '秒',
|
||||
'desc': '在内置 Termux 环境里跑命令的最长时间。',
|
||||
},
|
||||
{
|
||||
'key': 'meetingNode', 'group': '工具', 'label': '会议节点',
|
||||
'default': 10, 'min': 1, 'max': 600, 'unit': '秒',
|
||||
'desc': '会议里一个 Python 节点 / 自定义节点最多跑多久。'
|
||||
'这是防死循环的 —— 调太大会让整个会议卡住,建议别超过 60。',
|
||||
},
|
||||
{
|
||||
'key': 'customNode', 'group': '工具', 'label': '自定义节点',
|
||||
'default': 10, 'min': 1, 'max': 600, 'unit': '秒',
|
||||
'desc': 'nodes/ 目录里自己写的节点,执行一次的最长时间。',
|
||||
},
|
||||
|
||||
# ---------------- 界面 ----------------
|
||||
{
|
||||
'key': 'askUser', 'group': '界面', 'label': 'AI 提问等多久',
|
||||
'default': 0, 'min': 0, 'max': 3600, 'unit': '秒', 'zero': '不限时',
|
||||
'desc': 'AI 弹选择框问你时,等多久算"你没空"。**默认 0 = 一直等**。\n'
|
||||
'不建议改:设成有限值后,你去忙一会儿回来,AI 已经按它自己猜的答案'
|
||||
'往下写了,而它并不知道自己在猜。',
|
||||
},
|
||||
{
|
||||
'key': 'waitUi', 'group': '界面', 'label': 'AI 界面等多久',
|
||||
'default': 0, 'min': 0, 'max': 3600, 'unit': '秒', 'zero': '不限时',
|
||||
'desc': 'AI 弹的界面在 wait 模式下等你点按钮的时长。**默认 0 = 一直等**。',
|
||||
},
|
||||
{
|
||||
'key': 'filePicker', 'group': '界面', 'label': '选文件等多久',
|
||||
'default': 120, 'min': 10, 'max': 3600, 'unit': '秒',
|
||||
'desc': 'AI 让你挑一个文件时,等你挑完的时长。'
|
||||
'去相册里翻一张老照片可能不止两分钟,可以调大。',
|
||||
},
|
||||
|
||||
# ---------------- 语音 ----------------
|
||||
{
|
||||
'key': 'tts', 'group': '语音', 'label': '语音合成',
|
||||
'default': 60, 'min': 5, 'max': 600, 'unit': '秒',
|
||||
'desc': '把回复转成语音的最长等待。长回复、网络慢时要更久。',
|
||||
},
|
||||
{
|
||||
'key': 'stt', 'group': '语音', 'label': '语音识别',
|
||||
'default': 120, 'min': 5, 'max': 600, 'unit': '秒',
|
||||
'desc': '把录音转成文字的最长等待。录音越长越久。',
|
||||
},
|
||||
|
||||
# ---------------- MCP ----------------
|
||||
{
|
||||
'key': 'mcpRequest', 'group': 'MCP', 'label': '单次请求',
|
||||
'default': 60, 'min': 5, 'max': 600, 'unit': '秒',
|
||||
'desc': '和 MCP 服务说话时,单次请求等多久。',
|
||||
},
|
||||
{
|
||||
'key': 'mcpConnect', 'group': 'MCP', 'label': '连接',
|
||||
'default': 180, 'min': 5, 'max': 900, 'unit': '秒',
|
||||
'desc': '启动 MCP 服务(npx / uvx 第一次要下载)的最长等待。'
|
||||
'第一次装包经常要几分钟,这也是默认给到 180 秒的原因。',
|
||||
},
|
||||
{
|
||||
'key': 'mcpTool', 'group': 'MCP', 'label': '调用工具',
|
||||
'default': 120, 'min': 5, 'max': 900, 'unit': '秒',
|
||||
'desc': '调用 MCP 服务里某个工具的最长等待。',
|
||||
},
|
||||
]
|
||||
|
||||
BY_KEY = {s['key']: s for s in SPECS}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 读取
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _stored() -> dict:
|
||||
"""用户改过的那部分(没改过就是空的)"""
|
||||
try:
|
||||
import store # 局部导入:store 依赖 paths,放顶部会把导入顺序弄难读
|
||||
raw = (store.read_settings() or {}).get('timeouts')
|
||||
except Exception: # noqa: BLE001 - 设置读不出来时一律用默认值,别让业务挂掉
|
||||
return {}
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def coerce(key: str, raw) -> float:
|
||||
"""
|
||||
把用户填的东西变成一个合法的秒数。
|
||||
|
||||
★ 容错是必须的:界面上是输入框,用户可能填 "60秒"、空串、负数、
|
||||
或者一个巨大的数。任何一种都不该让调用它的地方炸掉。
|
||||
"""
|
||||
spec = BY_KEY.get(key)
|
||||
if spec is None:
|
||||
raise KeyError(f'没有这个超时项:{key}')
|
||||
value = spec['default']
|
||||
if raw is not None and raw != '':
|
||||
try:
|
||||
value = float(str(raw).strip().rstrip('秒sS'))
|
||||
except (TypeError, ValueError):
|
||||
value = spec['default']
|
||||
lo, hi = spec['min'], spec['max']
|
||||
if value < lo:
|
||||
value = lo
|
||||
if value > hi:
|
||||
value = hi
|
||||
return value
|
||||
|
||||
|
||||
def get(key: str) -> float:
|
||||
"""读一项当前的超时(秒)。0 = 不限时(只有允许的项才会是 0)。"""
|
||||
return coerce(key, _stored().get(key))
|
||||
|
||||
|
||||
def ms(key: str) -> int:
|
||||
"""要毫秒的地方用这个(别在每个调用点自己写 * 1000)"""
|
||||
return int(get(key) * 1000)
|
||||
|
||||
|
||||
def resolved() -> dict:
|
||||
"""当前生效的全部值(默认 + 用户改的),给界面和诊断用"""
|
||||
stored = _stored()
|
||||
return {s['key']: coerce(s['key'], stored.get(s['key'])) for s in SPECS}
|
||||
|
||||
|
||||
def catalog() -> list:
|
||||
"""
|
||||
给界面的清单:每一项的说明 + 默认值 + 边界 + 现在是多少。
|
||||
|
||||
★ 界面**不硬编码**这些项目,它读这个。加一项超时只改本文件。
|
||||
"""
|
||||
stored = _stored()
|
||||
out = []
|
||||
for s in SPECS:
|
||||
item = dict(s)
|
||||
item['value'] = coerce(s['key'], stored.get(s['key']))
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def patch(values: dict) -> dict:
|
||||
"""
|
||||
算出"要存下来的那部分"(只含和默认值不同的项)。
|
||||
|
||||
★ 只存"和默认值不同的":这样以后改了默认值,没动过的项会跟着新默认走
|
||||
(如果一律存下来,老用户会被永久钉在旧默认上)。
|
||||
和默认一样就**删掉**这个键,不是存一个相同的值。
|
||||
"""
|
||||
current = dict(_stored())
|
||||
if not isinstance(values, dict):
|
||||
return resolved()
|
||||
for key, raw in values.items():
|
||||
if key not in BY_KEY:
|
||||
continue
|
||||
value = coerce(key, raw)
|
||||
if abs(value - float(BY_KEY[key]['default'])) < 1e-9:
|
||||
current.pop(key, None)
|
||||
else:
|
||||
# 存成 int 更好看(都是整秒),带小数的也不丢
|
||||
current[key] = int(value) if float(value).is_integer() else value
|
||||
return current
|
||||
|
||||
|
||||
def reset() -> dict:
|
||||
"""全部恢复默认"""
|
||||
return {}
|
||||
|
||||
|
||||
def budget(args: dict, key: str) -> int:
|
||||
"""
|
||||
算一次工具执行的超时:**工具参数优先,否则用设置里的值**,一律夹在该项边界内。
|
||||
|
||||
给 shell / python_run / termux 这几个"模型自己可以传 timeout"的工具用:
|
||||
|
||||
· 模型传了就用它的(它知道自己要跑多久:装个包当然比 ls 久)
|
||||
· 没传就用设置里的默认值(用户可能在设置里统一调大了)
|
||||
· 不管谁给的都夹在 [min, max] 里 —— 模型传 999999 也不能真的等那么久
|
||||
"""
|
||||
spec = BY_KEY.get(key)
|
||||
if spec is None:
|
||||
raise KeyError(f'没有这个超时项:{key}')
|
||||
raw = (args or {}).get('timeout')
|
||||
if raw in (None, ''):
|
||||
return int(get(key))
|
||||
try:
|
||||
value = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
return int(get(key))
|
||||
return int(max(spec['min'], min(spec['max'], value)))
|
||||
@@ -24,6 +24,7 @@ import threading
|
||||
|
||||
import mcp_client
|
||||
import paths
|
||||
import timeouts
|
||||
from builtin_tools import BUILTIN_TOOLS, run_with_timeout
|
||||
|
||||
# 文件工具的缓存:path -> {'mtime':..., 'spec':..., 'error':...}
|
||||
@@ -32,9 +33,73 @@ _cache_lock = threading.Lock()
|
||||
# 已经 import 过的模块名(重载时要先从 sys.modules 里摘掉)
|
||||
_loaded_modules: dict = {}
|
||||
|
||||
TOOL_TIMEOUT_S = 60
|
||||
# ★ 工具的默认执行超时**不在这里** —— 它和别的 15 个超时一起收在
|
||||
# `timeouts.py` 里,用户可以在「设置 → 超时」里调。这里以前写死 `TOOL_TIMEOUT_S = 60`,
|
||||
# 现在一律 `timeouts.get('tool')`。
|
||||
BUILTIN_FILE_LABEL = '<内置>'
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 会"停下来等用户"的工具:执行超时对它们不适用
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★★ 这个坑很隐蔽,记下来:
|
||||
#
|
||||
# 用户要求"AI 询问界面不要限时",我把弹窗那侧改成了无限等(`AiSurface.ask`),
|
||||
# 实测弹窗确实 135 秒还在 —— **但工具调用在 60 秒时就被内核判超时了**,
|
||||
# 模型收到的是"工具执行超时(60s)",用户五分钟后点的那个选项**根本回不到
|
||||
# 模型手里**。表现就是"弹窗还在、但 AI 已经自己往下写了"。
|
||||
#
|
||||
# 所以"不限时"必须**三处一起改**才算数:
|
||||
# ① 界面侧等多久(AiSurface)
|
||||
# ② 内核侧给工具多少时间(这里)
|
||||
# ③ 工具自己声明的 timeout(tools/ask_user.py、tools/show_ui.py)
|
||||
#
|
||||
# 判定方式:工具模块里声明 `WAIT_FOR_USER = True`。
|
||||
# 放在工具文件里而不是在这个列表里硬编码 —— 加新工具时不会漏(写工具的人
|
||||
# 自己知道它会不会等用户)。
|
||||
def _waits_for_user(name: str, spec: dict, module) -> bool:
|
||||
"""这个工具会不会停下来等用户交互"""
|
||||
if spec.get('_builtin'):
|
||||
return bool((BUILTIN_TOOLS.get(name) or {}).get('WAIT_FOR_USER'))
|
||||
return bool(getattr(module, 'WAIT_FOR_USER', False))
|
||||
|
||||
|
||||
def _with_default_timeouts(name: str, spec: dict, module, payload: dict) -> dict:
|
||||
"""
|
||||
把设置里的默认超时**注入**给声明了要的工具。
|
||||
|
||||
## 工具是这么声明的
|
||||
|
||||
# tools/ask_user.py
|
||||
TIMEOUT_KEYS = {'timeout': 'askUser'}
|
||||
|
||||
意思是:"我这个 `timeout` 参数如果模型没给,就用设置里 `askUser` 那一项的值。"
|
||||
|
||||
## 为什么要走这条路,而不是让工具自己 import timeouts
|
||||
|
||||
因为工具**不一定跑在内核进程里**:安卓端是进程内 import(能读),
|
||||
电脑端是 `python tool.py` 起子进程(读不到内核的模块)。而工具是要跨端复用的,
|
||||
所以不能让它们依赖内核的模块。
|
||||
|
||||
内核在**调用前**把值塞进参数里,工具照常从自己的参数读 —— 两端行为一致,
|
||||
工具本身也不用知道"设置"这回事(单独跑、自测时用自己文件里的兜底默认值)。
|
||||
"""
|
||||
keys = getattr(module, 'TIMEOUT_KEYS', None)
|
||||
if not isinstance(keys, dict) or not keys:
|
||||
return payload
|
||||
out = dict(payload)
|
||||
for arg_name, key in keys.items():
|
||||
# 模型给了就不覆盖(模型知道自己要等多久);给 0 也当"没给",
|
||||
# 因为 0 是"不限时"的合法值,但默认参数里它和"没填"是同一个意思
|
||||
if out.get(arg_name) in (None, '', 0, '0'):
|
||||
try:
|
||||
out[arg_name] = timeouts.get(key)
|
||||
except Exception: # noqa: BLE001 - 设置读不出来就用工具自己的兜底
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 界面工具的开关
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -67,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
|
||||
|
||||
@@ -301,6 +386,8 @@ def run_python_tool(name: str, args: dict) -> dict:
|
||||
runner = getattr(module, 'run')
|
||||
|
||||
payload = args if isinstance(args, dict) else {}
|
||||
# ★ 设置里的默认超时注入给声明了 TIMEOUT_KEYS 的工具(ask_user / show_ui)
|
||||
payload = _with_default_timeouts(name, spec, module, payload)
|
||||
# ★★★ **先抓住当前线程的上下文**,因为 run_with_timeout 会在**另一个线程**里
|
||||
# 跑工具,而 threading.local() 是**不跨线程继承**的 —— 不搬过去的话,
|
||||
# 工作线程里 current_context() 永远是空的。
|
||||
@@ -320,14 +407,22 @@ def run_python_tool(name: str, args: dict) -> dict:
|
||||
_ctx.value = None
|
||||
|
||||
try:
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
|
||||
outcome = run_with_timeout(_invoke, TOOL_TIMEOUT_S)
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死。
|
||||
# ★ 会等用户的工具(ask_user / show_ui 的 wait 模式)**不限时** ——
|
||||
# 它们的耗时取决于用户什么时候点,给上限等于"用户想久了 AI 就自己编"。
|
||||
# 见 _waits_for_user 的注释。
|
||||
# ★ 预算是**设置里可调**的(设置 → 超时 → 工具执行),不是写死的 60。
|
||||
if _waits_for_user(name, spec, module):
|
||||
budget = 0
|
||||
else:
|
||||
budget = timeouts.get('tool')
|
||||
outcome = run_with_timeout(_invoke, budget)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500
|
||||
# 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"},
|
||||
# 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。
|
||||
return {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||
if outcome is None:
|
||||
return {'ok': False, 'error': f'工具执行超时({TOOL_TIMEOUT_S}s)'}
|
||||
return {'ok': False, 'error': f'工具执行超时({budget:g}s,可在设置里调)'}
|
||||
result = outcome
|
||||
# 工具可以像 _protocol 那样返回 {"ok":..,"result":..},也可以直接返回业务结果
|
||||
if isinstance(result, dict) and 'ok' in result:
|
||||
|
||||
@@ -25,11 +25,49 @@
|
||||
| 工具 | 阻不阻塞 | 为什么 |
|
||||
|---|---|---|
|
||||
| `show_ui` | **不阻塞** | 展示语义。用户可能盯着看很久,把内核线程占住没意义 |
|
||||
| `ask_user` | **阻塞**(最多 120s) | 问询语义。拿不到答案就没法继续 |
|
||||
| `ask_user` | **阻塞**(默认**不限时**,见下) | 问询语义。拿不到答案就没法继续 |
|
||||
| `end_conversation` | 立刻返回 | 它只改状态(落盘 + 界面收输入框) |
|
||||
|
||||
超时是**必须**的:用户可能锁屏就走了。不设的话内核的工作线程永远挂着,
|
||||
而 HTTP 是每请求一线程,挂一个少一个。
|
||||
### ★★ 不限时(v2.0.45 起):要三处一起改才算数
|
||||
|
||||
原来是 120 秒上限,用户明确要求去掉:"AI 询问界面不要限时"。理由很实在:
|
||||
|
||||
> 用户看到选项、去翻了下手机算个数、回来弹窗没了;模型收到 `timeout=true`,
|
||||
> 理解成"用户不想理我",于是**按自己猜的答案往下写** —— 这一轮整个废掉。
|
||||
|
||||
现在的默认是**一直等**,放行出口是:点任意选项 / 点「取消」/ 关掉 App。
|
||||
模型真想限时得自己传 `timeout`(`ask_user` 1~3600 秒,`show_ui` 5~3600 秒)。
|
||||
|
||||
**这个值现在也是可调的**:设置 → 超时 → 「AI 提问等多久」/「AI 界面等多久」
|
||||
(默认 0 = 不限时)。内核在调用工具前把它注入到 `timeout` 参数里,
|
||||
见 `tools_runtime._with_default_timeouts`。
|
||||
|
||||
**这个改动必须同时改三处**,只改一两处的表现是"看起来改了其实没生效":
|
||||
|
||||
| # | 改哪儿 | 不改的后果 |
|
||||
|---|---|---|
|
||||
| ① | `AiSurface.ask` / `showScreen`(界面侧等多久) | 弹窗到点自己消失 |
|
||||
| ② | `timeouts.py` 的 `tool` 那一项(内核给工具多少时间) | 弹窗还开着,但内核 60 秒就把这次调用判超时、把结果丢了 |
|
||||
| ③ | 工具自己声明的 `timeout`(现在由设置注入) | 工具主动提前放弃 |
|
||||
|
||||
②最隐蔽:`TOOL_TIMEOUT_S = 60` 是"工具里写了死循环"的安全网,
|
||||
而等用户的工具**设计上就该慢**。所以它们在自己的文件里声明
|
||||
`WAIT_FOR_USER = True`,内核据此把超时预算设成 0(不限时)。
|
||||
|
||||
> 实测记录:只改 ①③ 时,弹窗 135 秒确实还在,但工具在 **60.0 秒**返回了
|
||||
> `{"ok":false,"error":"工具执行超时(60s)"}` —— 用户后来点的选项根本回不到
|
||||
> 模型手里。补上 ② 之后同一个探针在 **66.2 秒**返回
|
||||
> `{"choice":"B","timeout":false}`。
|
||||
> 探针:`scripts/probe-ask-user-forever.py`;守门:`scripts/verify-ui-tools.py`。
|
||||
|
||||
### 客户端那条长连接为什么不会断
|
||||
|
||||
对话是 SSE 长连接,等待期间可能几分钟没有正常数据。两端都不会断:
|
||||
|
||||
- 内核每 **15 秒**发一个 `: ping` 心跳(`app.py` 的 `_ping_loop`)
|
||||
- 客户端 `readTimeout` 是 **120 秒**(`KernelClient`)—— 它管的是"两次数据之间的最大间隔",不是总时长
|
||||
|
||||
所以心跳只要 < 120 秒就安全。
|
||||
|
||||
---
|
||||
|
||||
@@ -38,7 +76,7 @@
|
||||
| 用法 | 行为 | 适合 |
|
||||
|---|---|---|
|
||||
| `wait` 不传(默认) | 弹出就返回,不等 | 图表、报告这类"给用户看"的 |
|
||||
| `wait=true` | **等用户点回传按钮或关掉界面**,最多 `timeout` 秒(默认 120,上限 600) | "弹几个选项让用户挑,然后我接着干" |
|
||||
| `wait=true` | **等用户点回传按钮或关掉界面**(默认**不限时**;显式传 `timeout` 则 5~3600 秒) | "弹几个选项让用户挑,然后我接着干" |
|
||||
| 不调用 | 纯文字回答 | —— |
|
||||
|
||||
等待模式下用户点的值**立刻**作为工具返回值给模型,**同一个回合里**就能接着处理:
|
||||
@@ -48,7 +86,7 @@ wait=true → 阻塞 9.3s → {"waited":true,"timeout":false,"value":"方案丙
|
||||
```
|
||||
|
||||
- 用户直接关掉界面(没点任何按钮)→ `value=""` + `closed=true`
|
||||
- 超时 → `timeout=true`,提示词里明确要求**别反复重弹**
|
||||
- 只有显式设了 `timeout` 才可能 `timeout=true`,提示词里要求**别反复重弹**
|
||||
|
||||
### ★ 实现上的一个竞态
|
||||
|
||||
|
||||
BIN
docs/screenshots/agent-edit.png
Normal file
|
After Width: | Height: | Size: 99 KiB |
BIN
docs/screenshots/agent-memory.png
Normal file
|
After Width: | Height: | Size: 72 KiB |
BIN
docs/screenshots/agent-resources.png
Normal file
|
After Width: | Height: | Size: 58 KiB |
BIN
docs/screenshots/agent-select-switched.png
Normal file
|
After Width: | Height: | Size: 785 KiB |
BIN
docs/screenshots/agent-select.png
Normal file
|
After Width: | Height: | Size: 779 KiB |
BIN
docs/screenshots/markdown-table.png
Normal file
|
After Width: | Height: | Size: 123 KiB |
BIN
docs/screenshots/nodekit-node-shapes.png
Normal file
|
After Width: | Height: | Size: 98 KiB |
BIN
docs/screenshots/timeouts.png
Normal file
|
After Width: | Height: | Size: 169 KiB |
148
docs/v1.2实施计划.md
Normal file
@@ -0,0 +1,148 @@
|
||||
# v1.2 实施计划
|
||||
|
||||
《智能体系统需求文档 v1.2》的落地计划。按**依赖顺序**排,不是按文档章节顺序 ——
|
||||
情绪双字段不做,立绘联动、`peer_emotions`、状态脚本全都悬空。
|
||||
|
||||
---
|
||||
|
||||
## 阶段划分(每一阶段都能单独发版)
|
||||
|
||||
### 阶段 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 的沙箱天生关不严,三条路……~~
|
||||
|
||||
### ✅ 已定:子进程 + 资源限制(2026-10-16 你选的)
|
||||
|
||||
但查了一遍代码,**安卓上不能直接起 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**(除非它真的死了)。
|
||||
261
docs/智能体系统.md
Normal file
@@ -0,0 +1,261 @@
|
||||
# 智能体系统(需求 v1.1)
|
||||
|
||||
这份文档对应《智能体系统需求文档 v1.1》。它不讲"应该怎么做"(那在需求里),
|
||||
只讲**这个仓库是怎么落地的**:每个需求项落在哪个文件、当时为什么这么选、
|
||||
出了问题去哪儿看。
|
||||
|
||||
---
|
||||
|
||||
## 1. 需求 → 实现对照
|
||||
|
||||
| 需求 | 实现位置 |
|
||||
|---|---|
|
||||
| 2.1 选择界面(左列表 + 右四层展示) | `ui/AgentSelectScreen.kt` |
|
||||
| 2.2 资源格式(GIF/SVG/PNG/JPG) | `ui/AssetImage.kt` |
|
||||
| 2.3 切换动画(1.5s 四阶段) | `ui/AgentSelectScreen.kt` 顶部常量 + `LaunchedEffect` |
|
||||
| 2.4 圆形「更多」按钮 → 用量 | `ui/AgentSelectScreen.kt` + `ui/TokenUsageScreen.kt` |
|
||||
| 2.5 智能体包(zip + smartInfo.json) | `kernel/agent_api.py`(`_export_agent` / `_import_agent`) |
|
||||
| 2.6 默认资源回退 | 内核导入时落定;界面兜最后一级(内置两张图在 `res/drawable/`) |
|
||||
| 3.1 Token 统计与限额 | `kernel/agentdb.py` + `kernel/app.py`(发起前检查)+ `ui/TokenUsageScreen.kt` |
|
||||
| 3.2 独立记忆 | `kernel/agentdb.py` + `kernel/agent_tools.py` + `ui/MemoryScreen.kt` |
|
||||
| 3.3 多模型 | `kernel/store.py: provider_info` + `ui/ResourcesScreen.kt`(模型 Tab) |
|
||||
| 3.3 兼容降级 | `kernel/agent_loop.py`(`DEGRADED_HINT` / `run_degraded_calls`) |
|
||||
| 3.4 记忆导入导出 | `kernel/agent_api.py`(`_memory_export` / `_memory_import`) |
|
||||
| 3.5 情绪系统 | `kernel/agentdb.py`(`emotion_*`)+ 编辑界面开关 |
|
||||
| 3.6 世界观 | `kernel/store.py: RESOURCES` + `ui/ResourcesScreen.kt` |
|
||||
| 3.7 Skill 机制 | `kernel/defaults.py: BUILTIN_SKILL` + `kernel/agent_context.py` |
|
||||
| 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` |
|
||||
| 附录 C 提示词模板 | `kernel/agent_context.py` + `kernel/defaults.py: DEFAULT_PROMPT_TEMPLATE` |
|
||||
| 附录 D 包格式 | `kernel/agent_api.py` + `docs/智能体系统.md` 第 4 节 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 数据存在哪(以及为什么)
|
||||
|
||||
这是这个功能里**最需要解释的一个决定**,因为仓库里本来就写着一句
|
||||
"为什么用 JSON 而不是 SQLite"(`kernel/store.py` 文件头)。
|
||||
|
||||
分界线是**数据的形状**,不是"新旧":
|
||||
|
||||
| 存哪 | 什么 | 判据 |
|
||||
|---|---|---|
|
||||
| **SQLite**(`agent.db`) | 记忆、情绪、Token 统计、Skill 绑定 | 条目**无上限**(记忆);每轮**全量读取**;要 LIKE 检索;要按行改删 |
|
||||
| **JSON**(照旧) | 设置、会话、智能体、世界观、模型列表、Skill 内容 | 量级是"几个到几十个";而且**要人肉可读**(你会想直接看自己写的世界观长什么样) |
|
||||
|
||||
`agentdb.py` 的文件头写了同样一段。**加新的数据时先按这张表判一次**,
|
||||
不要因为"智能体系统用了 SQLite"就把什么都往里塞。
|
||||
|
||||
### 表结构
|
||||
|
||||
```sql
|
||||
memories(id, scope, title, content, pinned, author_agent, created_at)
|
||||
emotions(agent_id, emotion, updated_at)
|
||||
token_usage(id, agent_id, model, input, output, created_at)
|
||||
agent_skills(agent_id, skill_id, ord)
|
||||
```
|
||||
|
||||
`scope` 是记忆的归属:
|
||||
|
||||
- `agent:<uuid>` —— 私有记忆(没绑世界观时)
|
||||
- `world:<uuid>` —— 共享记忆(绑了世界观时,同世界观的智能体共用一份)
|
||||
|
||||
**绑定关系一改,scope 就跟着变**,没有"迁移"这一步 —— 记忆留在原地,
|
||||
只是从这个空间换到那个空间去读。这样"解绑"不会丢东西。
|
||||
|
||||
---
|
||||
|
||||
## 3. 三个容易踩的地方
|
||||
|
||||
### 3.1 模型引用是**整组覆盖**,不是只换 model
|
||||
|
||||
`store.provider_info` 的优先级:
|
||||
|
||||
```
|
||||
模型列表那一项(地址 / Key / 模型标识)
|
||||
↓ 没引用
|
||||
智能体自己的 provider/model/baseUrl
|
||||
↓ 留空
|
||||
全局设置
|
||||
↓ 还没填
|
||||
提供商预设
|
||||
```
|
||||
|
||||
**为什么整组覆盖**:只覆盖 `model` 而 `apiKey` 还用全局的,必然出现
|
||||
"选了 DeepSeek 的模型、拿方舟的 Key 去调" → 401。
|
||||
而模型列表存在的意义就是"配一次到处用、改 Key 只改一处"。
|
||||
|
||||
⚠️ 这里曾经有过一个**假功能**:界面能选、字段能存,但 `provider_info`
|
||||
根本不看 `modelId` —— 引用了照样走全局。界面看起来完全正常,
|
||||
所以最难发现。`scripts/probe-agent-system.py` 第 11 节专门钉住它。
|
||||
|
||||
### 3.2 提示词每轮重拼,不缓存
|
||||
|
||||
`agent_context.build_system_prompt` 在**每一轮**都重新拼一遍。原因很直接:
|
||||
记忆和情绪**随时会变**,而且 AI 自己就能改它们。缓存住的表现是
|
||||
"我明明让它记住了,下一句它又忘了"—— 用户会当成"记忆功能坏了"。
|
||||
|
||||
顺序固定(附录 C):`{prompt}` → `<skills>` → `<worldview>` → `<emotion>` →
|
||||
`<memory>` → `<peer_emotions>`。**空段整段删掉**,不留空标签。
|
||||
|
||||
### 3.3 幻觉检测的三个条件
|
||||
|
||||
`check_hallucinated_memory` 只有在**同时**满足时才算:
|
||||
|
||||
1. 正文里说了"我记住了"这类话
|
||||
2. 这一轮**没有任何工具调用**
|
||||
3. **工具是可用的**(用户没把它关掉)
|
||||
|
||||
第 3 条最容易被忽略:Python 工具整个关掉时模型**想调也调不了**,
|
||||
那时警告它"没调用工具"是冤枉它,而且警告会一直挂着,用户会以为坏了。
|
||||
|
||||
判宽的代价 > 判窄:误伤会让用户看到莫名其妙的警告,几次之后他就不看那个警告了。
|
||||
|
||||
---
|
||||
|
||||
## 4. 包格式(附录 D)
|
||||
|
||||
### 智能体包(`.zip`)
|
||||
|
||||
```
|
||||
smartInfo.json # {"name":…, "description":…, "prompt":…, "image":{…}}
|
||||
assets/… # 四件套图片(front / back / border-main / border-info)
|
||||
```
|
||||
|
||||
**包里不进的东西**(需求 2.5 的边界约定):
|
||||
|
||||
- 模型引用、世界观绑定、Token 限额
|
||||
- 记忆、情绪、Skill 绑定
|
||||
- **API Key**(这是安全底线)
|
||||
|
||||
导入两次 = **两个互相独立的智能体**(不做按名字去重)。重名时界面显示
|
||||
`玄辰` / `玄辰(2)`。
|
||||
|
||||
### 记忆文件(`.json`)
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "agent-memory" | "world-memory",
|
||||
"version": 1,
|
||||
"smartMemory": [{"title": …, "content": …, "pinned": false}],
|
||||
"Emotion": "……"
|
||||
}
|
||||
```
|
||||
|
||||
- 导出**不含** `author_agent`(那是内部字段)
|
||||
- 导入两种模式:`merge`(默认,按标题去重、保留当前 Emotion)/ `replace`
|
||||
|
||||
---
|
||||
|
||||
## 5. 删除的级联语义(复查报告第五节)
|
||||
|
||||
需求 v1.1 **从未定义**"删一个智能体时,它的记忆/统计/绑定怎么办"。
|
||||
而代码里这个决策早就发生了 —— **决策在代码里、文档里没有,比漏做更危险**:
|
||||
下一个人(包括三个月后的自己)会按自己的直觉去改,而直觉在这件事上分两种。
|
||||
|
||||
现在的规则:
|
||||
|
||||
| 删什么 | 记忆 | Token 统计 | 情绪 | Skill 绑定 | 外观图片 |
|
||||
|---|---|---|---|---|---|
|
||||
| **智能体** | **保留** | **保留** | 保留 | 清掉 | 删掉 |
|
||||
| **世界观** | **保留** | — | — | — | 删掉 |
|
||||
|
||||
**为什么记忆保留**:那是用户花时间攒下来的东西,而且可能是**共享**的
|
||||
(世界观空间里还有别人的记忆)。删一个人不该把大家的本子撕了。
|
||||
界面上删除确认里明确写了这一句("记忆会保留,删之前建议先导出")。
|
||||
|
||||
**为什么统计保留**:`token_usage` 是历史账本。删了智能体不代表那些调用
|
||||
没发生过 —— 而且用户可能只是"想重建一个同名的",账单突然归零更让人困惑。
|
||||
|
||||
**为什么绑定清掉**:`agent_skills` 里存的是 agentId,智能体没了那些行就是
|
||||
悬空外键。留着它们只会在某天"新建一个 id 碰巧相同"时诈尸。
|
||||
|
||||
**为什么图片删掉**:图片在 `agent-assets/<id>/` 下,随智能体走。留着就是
|
||||
永远占地方、且没有任何入口能再看到它。
|
||||
|
||||
⚠️ **想知道代价**:删掉一个用了半年的智能体再建一个同名的,**记忆不会
|
||||
自动接上**(新 id = 新空间)。要接的话:删之前先「导出文件」,
|
||||
新建之后再「导入」→ 选合并。
|
||||
|
||||
### v1.2 该定的三件事(发现于复查,本次未做)
|
||||
|
||||
1. **记忆归档规则**:需求说"条目无上限 + 每轮全量注入",这两条长期是矛盾的
|
||||
—— 攒到几千条时提示词会撑爆上下文。建议超 N 条 / M 字符后旧记忆降级为
|
||||
"仅可检索"(不再全量注入,但 `memory_search` 还能搜到)。
|
||||
2. **会话历史裁剪策略**:比记忆更早爆的问题。同样没有定义。
|
||||
3. **`memory_search` 的语义检索升级路径**:现在是 LIKE 匹配,
|
||||
预留一个接口形状(参数不变、换实现)比以后改调用方便宜。
|
||||
|
||||
---
|
||||
|
||||
## 6. 怎么验证
|
||||
|
||||
| 脚本 | 验什么 |
|
||||
|---|---|
|
||||
| `python scripts/probe-agent-system.py` | 12 节 70+ 项:UUID、记忆 CRUD、pinned、共享限权、提示词注入顺序、20 多个接口、包导入导出边界、多模型解析 |
|
||||
| `python scripts/probe-degraded.py` | 幻觉检测(该报的报、不该报的不报)+ 降级调用的解析/执行/剥离/坏输入 |
|
||||
|
||||
两个都**不需要装机、不需要网络**:把 `DOUBAO_DATA` 指到一个临时目录,
|
||||
内核的存储层是无状态的,整条链路就能在一个进程里跑完。
|
||||
|
||||
**比装机验证快得多,而且能断言具体字段**(截图只能看个大概)。
|
||||
|
||||
### 改内核之后必须做的一件事
|
||||
|
||||
```bash
|
||||
python -c "import py_compile,glob; [py_compile.compile(p,doraise=True) for p in glob.glob('android/kernel/*.py')]"
|
||||
```
|
||||
|
||||
**Gradle 不编译 Python。** Chaquopy 只是把 `.py` 打进 APK,语法错误要等
|
||||
手机上"启动内核"那一刻才炸 —— 而那时整个 App 都不可用。
|
||||
`scripts/build-apk.mjs` 里已经加了这道自检,但改完随手跑一下更快。
|
||||
|
||||
---
|
||||
|
||||
## 7. 接口一览
|
||||
|
||||
全部在 `kernel/agent_api.py`,由 `app.py` 的第一条路由接管
|
||||
(老的那三个 `/api/agents` 路由**删掉了**,避免两份实现)。
|
||||
|
||||
```
|
||||
GET /api/agents 列表
|
||||
POST /api/agents 新建(返回 UUID)
|
||||
PATCH /api/agents/<id> 改(全字段,按类型规整)
|
||||
DELETE /api/agents/<id> 删(内置的拒绝)
|
||||
GET /api/agents/<id>/package 导出包(base64 zip)
|
||||
POST /api/agents/import 导入包
|
||||
POST /api/agents/<id>/asset 设置外观某一槽位
|
||||
|
||||
GET /api/agents/<id>/memories 记忆空间快照
|
||||
POST /api/agents/<id>/memories 加一条
|
||||
GET /api/agents/<id>/memories/export 导出
|
||||
POST /api/agents/<id>/memories/import 导入(merge / replace)
|
||||
POST /api/agents/<id>/memories/summarize AI 整理(一次独立 LLM 调用)
|
||||
PATCH /api/memories/<id> 改一条
|
||||
DELETE /api/memories/<id> 删一条
|
||||
POST /api/memories/<id>/pin 标记「必须保留」
|
||||
|
||||
GET /api/agents/<id>/usage 累计用量(按模型分桶)
|
||||
POST /api/agents/<id>/usage 清零
|
||||
GET /api/agents/<id>/emotion 读情绪
|
||||
PUT /api/agents/<id>/emotion 写情绪
|
||||
PUT /api/agents/<id>/skills 绑定 Skill(按顺序)
|
||||
|
||||
GET/POST /api/worldviews /api/model-entries /api/skills
|
||||
PATCH/DELETE /api/<资源>/<id>
|
||||
GET /api/<资源>/<id>/package|export
|
||||
POST /api/<资源>/import
|
||||
POST /api/worldviews/<id>/asset
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 已知限制
|
||||
|
||||
- **Node 端(Web / exe)还没跟上这一版**:安卓端是完整的,Web 端的智能体
|
||||
系统还是旧的那套(没有记忆/情绪/Token/世界观)。按仓库约定"引擎改了
|
||||
另一端必须跟上",这是欠账。
|
||||
- 用量页**不做历史曲线**(需求原话"当前不做曲线"),时间戳只是为将来预留。
|
||||
- 情绪是**私有**的:绑同一个世界观也不会共享(需求 3.5 明确要求)。
|
||||
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()` 谁都不调,就意味着那个界面做好了但进不去
|
||||
(记忆管理就是这么漏的)。
|
||||
@@ -207,6 +207,10 @@ App 侧的 `ui/MeetNodeKit.kt` 是**唯一一层胶水**:把 `MeetingNode` 转
|
||||
| `Terminal` 上边切角 | 到这里结束 | `end` |
|
||||
| `Rect` 圆角矩形 | 普通动作 | `agent` `var` `py` `custom` |
|
||||
|
||||
「加节点」面板里就是这样(从上到下:帽形 / 矩形 / 菱形 / 终点 / 矩形 / 胶囊):
|
||||
|
||||

|
||||
|
||||
**形状是"圆角矩形 + 局部变形",不是纯菱形/纯六边形** —— 因为卡片里要装东西
|
||||
(标题栏 24 + 引脚行 21×N + 内容 34),画成尖菱形四个角全是空的,而引脚必须紧贴
|
||||
左右边缘(那是连线的出发点,不能为了形状把线挪走)。
|
||||
|
||||
146
scripts/audit-ui-entries.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""审计:**做好了但没有入口的界面**。
|
||||
|
||||
## 为什么要有这个脚本
|
||||
|
||||
记忆管理界面做完、内核接口全通、探针 80 多项全绿 —— 但**没有任何地方能打开它**。
|
||||
是用户问"记忆管理在哪"才发现的。
|
||||
|
||||
这类漏**探针抓不到**(它测的是内核和数据,不测界面有没有入口),
|
||||
**编译也抓不到**(Kotlin 允许一个 public 方法没人调用),
|
||||
**截图也抓不到**(你只会去截你已经知道怎么进去的那几个页面)。
|
||||
|
||||
能抓到的只有"机器扫一遍:这个打开方法,除了定义之外还有人用吗"。
|
||||
|
||||
## 查什么
|
||||
|
||||
1. `AppViewModel` 里所有 `fun openXxx` / `fun closeXxx` —— 谁在调?
|
||||
2. `Screen` 枚举的每个值 —— 有 `when` 分支吗?有地方 `= Screen.X` 跳过去吗?
|
||||
3. `mutableStateOf` 的 `*Open` / `*Id` 状态 —— 有地方把它设成"打开"吗?
|
||||
|
||||
## 怎么判"没入口"
|
||||
|
||||
- 打开类方法:**除定义和内部自查外**没有调用点
|
||||
- Screen 值:没有 `Screen.X ->` 分支(会编译失败,Compiler 已覆盖)**或者**
|
||||
没有 `= Screen.X` 赋值(这个编译不管,就是死页面)
|
||||
- 状态:没有任何地方把它设成 true / 非空(只有读没有写)
|
||||
|
||||
用法:
|
||||
python scripts/audit-ui-entries.py # 有问题时退出码 1
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
UI = os.path.join(
|
||||
HERE, "..", "android", "app", "src", "main", "java", "com", "doubao", "lynxclone", "ui",
|
||||
)
|
||||
VM = os.path.join(UI, "AppViewModel.kt")
|
||||
|
||||
#: 这些**故意**不在这里判:它们是 ViewModel 内部用的,或者由别处(Activity/Service)触发
|
||||
ALLOW_NO_CALLER = {
|
||||
# close 类方法经常只在自己的界面里用,正常
|
||||
"closeTimeouts", "closeTokenUsage", "closeMemories", "closeAgentEdit",
|
||||
}
|
||||
|
||||
|
||||
def read(path):
|
||||
with io.open(path, encoding="utf-8") as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
def main():
|
||||
files = {}
|
||||
for name in os.listdir(UI):
|
||||
if name.endswith(".kt"):
|
||||
files[name] = read(os.path.join(UI, name))
|
||||
|
||||
vm_src = files.get("AppViewModel.kt", "")
|
||||
problems = []
|
||||
|
||||
print("=" * 66)
|
||||
print("1. 打开类方法:除了定义,有没有人调?")
|
||||
print("=" * 66)
|
||||
# 定义:fun openXxx( / fun closeXxx(
|
||||
defined = re.findall(r"^\s*fun ((?:open|close|toggle)[A-Za-z0-9_]*)\s*\(", vm_src, re.M)
|
||||
for fn in sorted(set(defined)):
|
||||
if fn in ALLOW_NO_CALLER:
|
||||
print(f" · {fn}(白名单:可能只在自身界面里用)")
|
||||
continue
|
||||
# 调用点:在**别的**文件里出现 fn(,或者在 AppViewModel 里出现第二次以上
|
||||
callers = []
|
||||
for name, src in files.items():
|
||||
n = len(re.findall(rf"\b{re.escape(fn)}\s*\(", src))
|
||||
if name == "AppViewModel.kt":
|
||||
n -= 1 # 减掉定义那一处
|
||||
if n > 0:
|
||||
callers.append(f"{name}×{n}")
|
||||
if callers:
|
||||
print(f" ✓ {fn} ← {', '.join(callers)}")
|
||||
else:
|
||||
print(f" ✗ {fn} **没有任何地方调用** —— 界面做好了但进不去")
|
||||
problems.append(f"{fn} 没有入口")
|
||||
|
||||
print()
|
||||
print("=" * 66)
|
||||
print("2. Screen 枚举:每个值都有人跳过去吗?")
|
||||
print("=" * 66)
|
||||
m = re.search(r"enum class Screen \{([^}]*)\}", vm_src)
|
||||
if not m:
|
||||
print(" !! 找不到 Screen 枚举")
|
||||
return 1
|
||||
values = [v.strip() for v in m.group(1).split(",") if v.strip()]
|
||||
for v in values:
|
||||
# 跳过去的地方:= Screen.X(赋值),排除 when 分支和枚举定义
|
||||
jump = 0
|
||||
for name, src in files.items():
|
||||
jump += len(re.findall(rf"=\s*Screen\.{re.escape(v)}\b", src))
|
||||
branch = sum(len(re.findall(rf"Screen\.{re.escape(v)}\s*->", src)) for src in files.values())
|
||||
if jump == 0:
|
||||
print(f" ✗ Screen.{v} 有 {branch} 个 when 分支,但**没有任何地方跳过去**")
|
||||
problems.append(f"Screen.{v} 是死页面")
|
||||
elif branch == 0:
|
||||
print(f" ✗ Screen.{v} 有 {jump} 处跳转,但**没有 when 分支**(会渲染不出东西)")
|
||||
problems.append(f"Screen.{v} 没有渲染分支")
|
||||
else:
|
||||
print(f" ✓ Screen.{v} ({jump} 处跳转 / {branch} 个分支)")
|
||||
|
||||
print()
|
||||
print("=" * 66)
|
||||
print("3. 打开状态:有没有地方把它打开?")
|
||||
print("=" * 66)
|
||||
states = re.findall(r"var (\w*(?:Open|Id|Hit|Editing))\s+by\s+mutableStateOf", vm_src)
|
||||
for st in sorted(set(states)):
|
||||
# ★ 两种写法都要数,否则全是误报:
|
||||
# ① 外部 `vm.xxx = true`(界面直接设)
|
||||
# ② ViewModel **内部** `xxx = true`(openXxx() 里设)—— 最常见的那种
|
||||
external = sum(len(re.findall(rf"\.{re.escape(st)}\s*=", src)) for src in files.values())
|
||||
inner = len(re.findall(rf"^\s*{re.escape(st)}\s*=", vm_src, re.M))
|
||||
writes = external + inner
|
||||
reads = sum(len(re.findall(rf"\bvm\.{re.escape(st)}\b", src)) for src in files.values())
|
||||
# `private set` 的状态只能内部写 —— 那正是第 ② 种
|
||||
if writes <= 0:
|
||||
print(f" ✗ {st} 只被读 {reads} 次、**没有地方写** —— 这个界面永远打不开")
|
||||
problems.append(f"{st} 永远打不开")
|
||||
else:
|
||||
print(f" ✓ {st} (写 {writes} 次:内部 {inner} / 外部 {external};读 {reads} 次)")
|
||||
|
||||
print()
|
||||
if problems:
|
||||
print(f"❌ {len(problems)} 个问题:")
|
||||
for p in problems:
|
||||
print(" -", p)
|
||||
return 1
|
||||
print("✅ 所有界面都有入口")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
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())
|
||||
@@ -49,6 +49,37 @@ if (!skipBuild) {
|
||||
log('界面是原生 Compose,无需构建前端产物');
|
||||
}
|
||||
|
||||
/* ---------------- 1.5 Python 内核的语法自检 ---------------- */
|
||||
//
|
||||
// ★★ 为什么构建脚本要管这件事:内核是 Python,而**构建阶段根本不编译它** ——
|
||||
// Chaquopy 只是把 .py 打进 APK,语法错误要等手机上"启动内核"那一刻才炸。
|
||||
//
|
||||
// 实测漏过一次:`agent_api.py` 里有个 IndentationError,
|
||||
// Gradle 报 BUILD SUCCESSFUL、APK 也正常产出,装到手机上打开就是
|
||||
// 「本地内核启动失败:IndentationError」—— 整机不可用。
|
||||
// 而 Kotlin 那边一个类型不对就编不过,落差太大了。
|
||||
//
|
||||
// 所以这里用**和 Chaquopy 同一个 Python** 先编译一遍:几秒钟的事,
|
||||
// 把"打包成功但装上打不开"这类问题挡在构建阶段。
|
||||
const pyBin = process.env.DOUBAO_PYTHON313 || 'C:\\Python313\\python.exe';
|
||||
const kernelDir = path.join(repo, 'android', 'kernel');
|
||||
if (!fs.existsSync(kernelDir)) {
|
||||
throw new Error(`找不到内核目录:${kernelDir}`);
|
||||
}
|
||||
const pyFiles = fs.readdirSync(kernelDir).filter((f) => f.endsWith('.py'));
|
||||
const pyBad = [];
|
||||
for (const f of pyFiles) {
|
||||
const r = spawnSync(pyBin, ['-m', 'py_compile', path.join(kernelDir, f)], { encoding: 'utf8' });
|
||||
if (r.status !== 0) {
|
||||
const msg = String(r.stderr || r.stdout || '').trim().split('\n').filter(Boolean).pop() || '未知错误';
|
||||
pyBad.push(`${f}: ${msg}`);
|
||||
}
|
||||
}
|
||||
if (pyBad.length) {
|
||||
throw new Error(`Python 内核有语法错误,先修好再打包:\n ${pyBad.join('\n ')}`);
|
||||
}
|
||||
log(`Python 语法自检通过(${pyFiles.length} 个文件)`);
|
||||
|
||||
/* ---------------- 2. 同步工程到 ASCII 路径 ---------------- */
|
||||
/** 手写递归拷贝:fs.cpSync 带 filter 时在这套环境下会把 Node 直接搞崩(0xC0000409) */
|
||||
function copyTree(from, to, skipDirs) {
|
||||
|
||||
108
scripts/demo-peer-visibility.py
Normal file
@@ -0,0 +1,108 @@
|
||||
"""演示:智能体在提示词里**实际能看到什么**(同世界观的伙伴)。
|
||||
|
||||
用户问"智能体能看哪些智能体绑了它吗" —— 这件事光说"能"没意义,
|
||||
跑一下把**真实注入的那段文字**打出来看。
|
||||
|
||||
python scripts/demo-peer-visibility.py
|
||||
|
||||
它造一个世界观 + 三个智能体(两个绑上、一个不绑),然后把三个智能体
|
||||
各自收到的 `<peer_emotions>` 段原样打印。
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
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, ".."))
|
||||
DATA = tempfile.mkdtemp(prefix="doubao-demo-peer-")
|
||||
os.environ["DOUBAO_DATA"] = DATA
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
import agent_context # noqa: E402
|
||||
import agentdb # noqa: E402
|
||||
import store # noqa: E402
|
||||
|
||||
|
||||
def seg(prompt: str, name: str) -> str:
|
||||
"""把某一段从拼好的提示词里抠出来(看不到就是空)"""
|
||||
a = prompt.find(f'<{name}>')
|
||||
if a < 0:
|
||||
return '(整段没有)'
|
||||
b = prompt.find(f'</{name}>', a)
|
||||
return prompt[a:b + len(name) + 3]
|
||||
|
||||
|
||||
def main():
|
||||
world = store.create_resource('worldviews', {
|
||||
'name': '九州', 'setting': '一个仙侠世界,灵气复苏。',
|
||||
})
|
||||
xc = store.create_agent({'name': '玄辰', 'systemPrompt': '你是玄辰,仙门大师兄。'})
|
||||
xc = store.update_agent(xc['id'], {'worldviewId': world['id']}) or xc
|
||||
xc2 = store.create_agent({'name': '仙辰', 'systemPrompt': '你是仙辰。'})
|
||||
xc2 = store.update_agent(xc2['id'], {'worldviewId': world['id']}) or xc2
|
||||
lone = store.create_agent({'name': '独行侠', 'systemPrompt': '你谁也不认识。'})
|
||||
|
||||
agentdb.emotion_set(xc['id'], '刚被师父训了一顿,有点闷')
|
||||
agentdb.emotion_set(xc2['id'], '刚赢了比试,得意')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('① 玄辰(绑了九州)· 情绪感知**关着**(默认)')
|
||||
print('=' * 70)
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(xc['id']))
|
||||
print(seg(p, 'peer_emotions'))
|
||||
print()
|
||||
print(' → 知道「有谁」,但看不到他们的情绪。')
|
||||
print(' 为什么关着也要给名单:共享记忆是共用的,它一定会看到别人写的条目。')
|
||||
print(' 不知道有别人,它就会把别人的经历当成自己的过去。')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('② 玄辰 · 情绪感知**打开**(编辑界面 → 能力 → 情绪感知)')
|
||||
print('=' * 70)
|
||||
store.update_agent(xc['id'], {'emotionEnabled': True})
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(xc['id']))
|
||||
print(seg(p, 'peer_emotions'))
|
||||
print()
|
||||
print(' → 名单 + 各自当前的情绪。情绪仍然是**单向只读**的:')
|
||||
print(' 玄辰能看到仙辰的情绪,但改不了;仙辰那边看到的是玄辰的。')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('③ 独行侠(没绑世界观)')
|
||||
print('=' * 70)
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(lone['id']))
|
||||
print(seg(p, 'peer_emotions'))
|
||||
print()
|
||||
print(' → 没有这段。它没有世界观,也就没有"伙伴"这回事。')
|
||||
|
||||
print()
|
||||
print('=' * 70)
|
||||
print('④ 共享记忆里别人写的条目(署名)')
|
||||
print('=' * 70)
|
||||
scope = agentdb.world_scope(world['id'])
|
||||
agentdb.memory_add(scope, '师父的忌讳', '提到"剑冢"他会翻脸', author_agent=xc2['id'])
|
||||
agentdb.memory_add(scope, '我的佩剑', '叫"霜落",是师父给的', author_agent=xc['id'])
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(xc['id']))
|
||||
print(seg(p, 'memory'))
|
||||
print()
|
||||
print(' → 玄辰看到的是:仙辰记的那条**标了「仙辰记的」**,')
|
||||
print(' 自己记的那条标「你记的」。不标的话,')
|
||||
print(' "我小时候住在海边"这种别人写的经历,在它眼里就是它自己的过去。')
|
||||
|
||||
print()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
code = main()
|
||||
finally:
|
||||
shutil.rmtree(DATA, ignore_errors=True)
|
||||
sys.exit(code)
|
||||
77
scripts/migrate-drop-agent-dialog.py
Normal file
@@ -0,0 +1,77 @@
|
||||
"""删掉 AgentsScreen 里那个被全屏界面取代的 AgentEditDialog。
|
||||
|
||||
★ 带断言:首尾内容对不上就整个中止,一个字节都不写。
|
||||
这个仓库里"按行号剪贴算错下标"的坑踩过(把整个文件追加过一遍),
|
||||
所以任何批量删除都必须先断言。
|
||||
|
||||
用法:
|
||||
python scripts/migrate-drop-agent-dialog.py # 预演
|
||||
python scripts/migrate-drop-agent-dialog.py --write
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
KT = os.path.join(
|
||||
HERE, "..", "android", "app", "src", "main", "java",
|
||||
"com", "doubao", "lynxclone", "ui", "AgentsScreen.kt",
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
write = "--write" in sys.argv
|
||||
with io.open(KT, encoding="utf-8") as fh:
|
||||
lines = fh.read().split("\n")
|
||||
|
||||
start = None
|
||||
for i, line in enumerate(lines):
|
||||
if line.startswith("private fun AgentEditDialog("):
|
||||
# 连它上面的 @Composable 一起删
|
||||
start = i - 3 if i >= 3 and lines[i - 3].strip() == "@Composable" else i
|
||||
break
|
||||
if start is None:
|
||||
print("找不到 AgentEditDialog —— 可能已经删过了")
|
||||
return 1
|
||||
|
||||
# 结束:下一个顶层 private fun / @Composable 之前
|
||||
end = None
|
||||
for j in range(start + 1, len(lines)):
|
||||
s = lines[j]
|
||||
if s.startswith("private fun ") or s.startswith("fun ") or s.startswith("internal fun "):
|
||||
end = j
|
||||
break
|
||||
if end is None:
|
||||
print("找不到下一个顶层函数,无法确定结束位置")
|
||||
return 1
|
||||
|
||||
print(f"将删除第 {start + 1} 行到第 {end} 行(共 {end - start} 行)")
|
||||
print(f" 起始:{lines[start].strip()[:70]}")
|
||||
print(f" 末行:{lines[end - 1].strip()[:70]}")
|
||||
print(f" 下一段:{lines[end].strip()[:70]}")
|
||||
|
||||
# 断言:这段里必须有 AgentEditDialog 的特征
|
||||
body = "\n".join(lines[start:end])
|
||||
for must in ("AgentEditDialog", "AlertDialog", "onSave", "systemPrompt"):
|
||||
if must not in body:
|
||||
print(f"!! 断言失败:待删段落里没有 {must}")
|
||||
return 1
|
||||
|
||||
if not write:
|
||||
print("(预演模式,没有写文件。加 --write 才真写)")
|
||||
return 0
|
||||
|
||||
del lines[start:end]
|
||||
with io.open(KT, "w", encoding="utf-8", newline="") as fh:
|
||||
fh.write("\n".join(lines))
|
||||
print(f"已写入,剩 {len(lines)} 行")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
697
scripts/probe-agent-system.py
Normal file
@@ -0,0 +1,697 @@
|
||||
"""智能体系统(需求 v1.1)的端到端探针 —— 不装机就能验整条链路。
|
||||
|
||||
## 怎么做到的
|
||||
|
||||
内核的存储层是**无状态**的(路径全靠 `paths.get()` 从数据目录推),
|
||||
所以只要把 `DOUBAO_DATA` 指到一个临时目录,就能在一个进程里把
|
||||
"建智能体 → 记东西 → 检索 → 拼提示词 → 导包 → 再导入"整条链路跑一遍。
|
||||
|
||||
比装机验证快得多,而且**能断言具体字段**(装机只能截图看个大概)。
|
||||
|
||||
## 覆盖
|
||||
|
||||
1. 建智能体拿到的是 UUID(需求附录 A)
|
||||
2. 记忆增删改查 + 检索
|
||||
3. pinned 保护(AI 改不动)
|
||||
4. 情绪读写
|
||||
5. Token 统计(按模型分桶、输入输出分开)
|
||||
6. 世界观 + **共享记忆**(两个智能体共用一个空间)
|
||||
7. 写入限权(只能删自己写的)
|
||||
8. system prompt 注入(附录 C 的五段都在、空段被删掉)
|
||||
9. 智能体包导出 → 导入(导入两次 = 两个独立实体)
|
||||
10. 记忆导出/导入(合并按标题去重)
|
||||
11. 资源 CRUD(世界观 / 模型列表 / Skill)
|
||||
|
||||
用法:
|
||||
python scripts/probe-agent-system.py
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
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, ".."))
|
||||
KERNEL = os.path.join(REPO, "android", "kernel")
|
||||
|
||||
# ★ 必须在 import 内核之前设好:paths.get() 是**懒加载 + 缓存**的
|
||||
DATA = tempfile.mkdtemp(prefix="doubao-agent-probe-")
|
||||
os.environ["DOUBAO_DATA"] = DATA
|
||||
sys.path.insert(0, KERNEL)
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
if cond:
|
||||
print(f" ✓ {label}")
|
||||
else:
|
||||
fails.append(label)
|
||||
print(f" ✗ {label} {detail}")
|
||||
|
||||
|
||||
def section(title):
|
||||
print(f"\n=== {title} ===")
|
||||
|
||||
|
||||
import agent_context # noqa: E402
|
||||
import agent_tools # noqa: E402
|
||||
import agentdb # noqa: E402
|
||||
import defaults # noqa: E402
|
||||
import store # noqa: E402
|
||||
|
||||
|
||||
class FakeHandler:
|
||||
"""冒充 app.py 的 Handler:只要 send_json / read_json_body 两个方法"""
|
||||
|
||||
def __init__(self):
|
||||
self.status = 200
|
||||
self.payload = None
|
||||
|
||||
def send_json(self, code, payload):
|
||||
self.status = code
|
||||
self.payload = payload
|
||||
|
||||
def read_json_body(self, *a, **k):
|
||||
return self._body
|
||||
|
||||
def call(self, pathname, method, body=None):
|
||||
body = body or {}
|
||||
self._body = body
|
||||
import agent_api
|
||||
|
||||
self.status, self.payload = 200, None
|
||||
# ★ 内核从 `handler.path` 里读 query(`?space=own`),
|
||||
# 所以这里必须把带 query 的路径原样塞回去
|
||||
self.path = pathname
|
||||
agent_api.handle(self, pathname.split('?')[0], method)
|
||||
return self.payload or {}
|
||||
|
||||
|
||||
def main():
|
||||
print(f"临时数据目录:{DATA}")
|
||||
h = FakeHandler()
|
||||
|
||||
# ---------------------------------------------------------------- 1
|
||||
section("1. 智能体:UUID 主键 + 扩展字段")
|
||||
a1 = store.create_agent({"name": "玄辰", "description": "仙门大师兄", "systemPrompt": "你是玄辰。"})
|
||||
check("新建的 id 是 UUID", len(a1["id"]) == 36 and a1["id"].count("-") == 4, a1["id"])
|
||||
check("description 存下来了", a1.get("description") == "仙门大师兄")
|
||||
a1 = store.update_agent(a1["id"], {"tokenLimit": 5000, "emotionEnabled": True, "skillIds": []}) or a1
|
||||
check("tokenLimit 存成数字", a1.get("tokenLimit") == 5000, repr(a1.get("tokenLimit")))
|
||||
check("emotionEnabled 是布尔", a1.get("emotionEnabled") is True)
|
||||
a2 = store.create_agent({"name": "仙辰"})
|
||||
check("两个智能体 id 不同", a1["id"] != a2["id"])
|
||||
# 内置的还在、短 id 没被动过
|
||||
check("内置智能体保留了短 id", any(x["id"] == "a_doubao" for x in store.list_agents()))
|
||||
|
||||
# ---------------------------------------------------------------- 2
|
||||
section("2. 记忆:增删改查 + 检索")
|
||||
scope = agentdb.scope_of(a1["id"])
|
||||
m1 = agentdb.memory_add(scope, "用户的名字", "他叫小林", author_agent=a1["id"])
|
||||
m2 = agentdb.memory_add(scope, "喝咖啡", "每天早上喝一杯美式", author_agent=a1["id"])
|
||||
check("加了两条", len(agentdb.memory_list(scope)) == 2)
|
||||
check("检索命中正文", len(agentdb.memory_search(scope, "美式")) == 1)
|
||||
check("检索命中标题", len(agentdb.memory_search(scope, "名字")) == 1)
|
||||
check("检索无关词不命中", len(agentdb.memory_search(scope, "量子力学")) == 0)
|
||||
agentdb.memory_update(m1["id"], content="他叫小林,做前端的")
|
||||
check("改正文生效", "前端" in agentdb.memory_get(m1["id"])["content"])
|
||||
agentdb.memory_forget(m2["id"])
|
||||
check("删掉一条", len(agentdb.memory_list(scope)) == 1)
|
||||
|
||||
# ---------------------------------------------------------------- 3
|
||||
section("3. pinned 保护(AI 改不动)")
|
||||
agentdb.memory_set_pinned(m1["id"], True)
|
||||
import tools_runtime
|
||||
|
||||
tools_runtime.push_context(agentId=a1["id"], conversationId="c_test")
|
||||
try:
|
||||
agent_tools.memory_forget({"id": m1["id"]})
|
||||
check("pinned 的删不掉", False, "居然删成功了")
|
||||
except ValueError as exc:
|
||||
check("pinned 的删不掉", "必须保留" in str(exc), str(exc))
|
||||
try:
|
||||
agent_tools.memory_update({"id": m1["id"], "content": "改了"})
|
||||
check("pinned 的改不动", False, "居然改成功了")
|
||||
except ValueError:
|
||||
check("pinned 的改不动", True)
|
||||
check("pinned 的还在", agentdb.memory_get(m1["id"]) is not None)
|
||||
agentdb.memory_set_pinned(m1["id"], False)
|
||||
|
||||
# ---------------------------------------------------------------- 4
|
||||
section("4. 工具:memory_add / emotion_set / get_token_usage")
|
||||
r = agent_tools.memory_add({"title": "喜欢猫", "content": "他家有两只猫"})
|
||||
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({"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)
|
||||
u = agent_tools.get_token_usage({})
|
||||
check("总量 = 输入+输出", u["used"] == 1200 + 800 + 300 + 100 + 500 + 200, str(u["used"]))
|
||||
check("输入输出分开", u["input"] == 2000 and u["output"] == 1100, f'{u["input"]}/{u["output"]}')
|
||||
check("按模型分桶", len(u["byModel"]) == 2, str([m["model"] for m in u["byModel"]]))
|
||||
check("剩余额度按限额算", u["remaining"] == 5000 - u["used"], str(u["remaining"]))
|
||||
|
||||
# ---------------------------------------------------------------- 5
|
||||
section("5. 世界观 + 共享记忆")
|
||||
wv = store.create_resource("worldviews", {"name": "九霄", "setting": "一个仙侠世界,灵气复苏。"})
|
||||
check("世界观有 UUID", len(wv["id"]) == 36)
|
||||
store.update_agent(a1["id"], {"worldviewId": wv["id"]})
|
||||
store.update_agent(a2["id"], {"worldviewId": wv["id"]})
|
||||
a1 = store.get_agent(a1["id"])
|
||||
a2 = store.get_agent(a2["id"])
|
||||
check("绑定后 scope 变成世界观的", agentdb.scope_of(a1["id"], a1["worldviewId"]).startswith("world:"))
|
||||
wscope = agentdb.scope_of(a1["id"], a1["worldviewId"])
|
||||
agentdb.memory_add(wscope, "共同约定", "两人都怕师父", author_agent=a1["id"])
|
||||
check("共享空间两人都看得到", len(agentdb.memory_list(agentdb.scope_of(a2["id"], a2["worldviewId"]))) == 1)
|
||||
|
||||
# ---------------------------------------------------------------- 6
|
||||
section("6. 写入限权:只能删自己写的")
|
||||
tools_runtime.push_context(agentId=a2["id"], conversationId="c_test")
|
||||
shared_item = agentdb.memory_list(wscope)[0]
|
||||
try:
|
||||
agent_tools.memory_forget({"id": shared_item["id"]})
|
||||
check("删不了别人写的", False, "居然删成功了")
|
||||
except ValueError as exc:
|
||||
check("删不了别人写的", "其他智能体" in str(exc), str(exc))
|
||||
# 自己写的能删
|
||||
mine = agent_tools.memory_add({"title": "仙辰的事", "content": "他喜欢御剑"})
|
||||
agent_tools.memory_forget({"id": mine["id"]})
|
||||
check("自己的能删", agentdb.memory_get(mine["id"]) is None)
|
||||
|
||||
# ---------------------------------------------------------------- 7
|
||||
section("7. 记忆空间的切换:绑定世界观之后,旧记忆不会「隐身」(复查 4.1)")
|
||||
# a1 在第 5 节绑了世界观、第 2 节在私有空间里留过记忆 —— 正是"用户攒了
|
||||
# 三个月私有记忆、一绑世界观列表就空了"的那个场景
|
||||
active = h.call(f"/api/agents/{a1['id']}/memories", "GET")
|
||||
check("当前空间是共享的", active.get("shared") is True)
|
||||
check("**告诉界面私有空间还剩几条**", active.get("ownCount", 0) > 0, str(active.get("ownCount")))
|
||||
old = h.call(f"/api/agents/{a1['id']}/memories?space=own", "GET")
|
||||
check("?space=own 能读到旧私有记忆", old.get("own") is True and len(old.get("memories") or []) > 0,
|
||||
str(old.get("error") or len(old.get("memories") or [])))
|
||||
check("私有空间标成 own(界面据此说明「这是绑定前的」)", old.get("own") is True)
|
||||
check("私有空间里不混入共享条目",
|
||||
all("共同约定" != m.get("title") for m in old.get("memories") or []),
|
||||
str([m.get("title") for m in old.get("memories") or []]))
|
||||
check("共享空间里也不混入私有条目",
|
||||
all("用户的名字" != m.get("title") for m in active.get("memories") or []),
|
||||
str([m.get("title") for m in active.get("memories") or []]))
|
||||
# 没绑世界观时不留 ownCount(否则界面会挂一个永远点不出东西的入口)
|
||||
a_plain = store.create_agent({"name": "没绑世界观的"})
|
||||
plain = h.call(f"/api/agents/{a_plain['id']}/memories", "GET")
|
||||
check("没绑世界观时 ownCount = 0", plain.get("ownCount", 0) == 0, str(plain.get("ownCount")))
|
||||
|
||||
# ---------------------------------------------------------------- 8
|
||||
section("8. system prompt 注入(附录 C)")
|
||||
tools_runtime.push_context(agentId=a1["id"], conversationId="c_test")
|
||||
agentdb.emotion_set(a2["id"], preset="哀", text="有点烦")
|
||||
store.update_agent(a2["id"], {"emotionEnabled": True})
|
||||
# ★ a1 在这一节之前已经绑了世界观 → 它的记忆空间是**共享**的那个,
|
||||
# 所以验证"记忆进提示词"要往当前 scope 里写(这正是绑定世界观的正确行为)
|
||||
agentdb.memory_add(agentdb.scope_of(a1["id"], a1["worldviewId"]),
|
||||
"用户的名字", "他叫小林,做前端的", author_agent=a1["id"])
|
||||
# 感知开关先关掉,验证"没开就没有同伴情绪段"
|
||||
store.update_agent(a1["id"], {"emotionEnabled": False})
|
||||
a1 = store.get_agent(a1["id"])
|
||||
sk = store.create_resource("skills", {"name": "写作", "content": "写东西要先列大纲。"})
|
||||
agentdb.bind_skills(a1["id"], [sk["id"]])
|
||||
prompt = agent_context.build_system_prompt(store.read_settings(), a1)
|
||||
for tag in ("<skills>", "<worldview>", "<emotion>", "<memory>"):
|
||||
check(f"{tag} 段在", tag in prompt)
|
||||
check("人设在最前面", prompt.startswith("你是玄辰。"), prompt[:20])
|
||||
check("世界观设定进去了", "灵气复苏" in prompt)
|
||||
# ★ 共享空间的标题带作者署名(复查报告 5):不署名的后果是
|
||||
# 别人写的经历被模型当成自己的过去
|
||||
check("记忆进去了(标题+正文)", "用户的名字" in prompt and "前端" in prompt)
|
||||
check("共享记忆带作者署名", "(你记的)" in prompt, prompt[-300:])
|
||||
check("自定义 Skill 进去了", "写东西要先列大纲" in prompt)
|
||||
check("顺序:skills 在 worldview 前", prompt.index("<skills>") < prompt.index("<worldview>"))
|
||||
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:])
|
||||
check("但名单里**没有情绪**", "有点烦" not in prompt, prompt[-300:])
|
||||
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("开了感知后看到的是**同伴的 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)
|
||||
check("没记忆时 <memory> 整段没了", "<memory>" not in p3, p3[-120:])
|
||||
check("但 <skills> 还在(内置手册)", "<skills>" in p3)
|
||||
|
||||
# ---------------------------------------------------------------- 8
|
||||
section("8. HTTP 接口")
|
||||
r = h.call("/api/agents", "GET")
|
||||
check("GET /api/agents", r.get("ok") and len(r["agents"]) >= 4)
|
||||
r = h.call("/api/agents", "POST", {"name": "接口建的"})
|
||||
new_id = (r.get("agent") or {}).get("id")
|
||||
check("POST /api/agents", bool(new_id))
|
||||
r = h.call(f"/api/agents/{new_id}", "PATCH", {"description": "改过的"})
|
||||
check("PATCH 生效", (r.get("agent") or {}).get("description") == "改过的")
|
||||
r = h.call("/api/agents/a_doubao", "DELETE")
|
||||
check("内置的删不掉", r.get("ok") is False, str(r.get("error")))
|
||||
check("内置的还在", store.get_agent("a_doubao") is not None)
|
||||
r = h.call(f"/api/agents/{a1['id']}/memories", "GET")
|
||||
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", {"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})
|
||||
check("POST 模型列表", r.get("ok") and (r.get("item") or {}).get("id"))
|
||||
r = h.call("/api/skills", "GET")
|
||||
check("GET Skill 列表", r.get("ok") and len(r["items"]) == 1)
|
||||
|
||||
# ---------------------------------------------------------------- 9
|
||||
section("9. 智能体包导出 / 导入")
|
||||
r = h.call(f"/api/agents/{a1['id']}/package", "GET")
|
||||
check("导出拿到 base64 zip", bool(r.get("data")), str(r.get("error")))
|
||||
blob = r.get("data")
|
||||
r = h.call("/api/agents/import", "POST", {"data": blob})
|
||||
imported = r.get("agent") or {}
|
||||
check("导入成功", bool(imported.get("id")), str(r.get("error")))
|
||||
check("导入的是**新** UUID(不是原来那个)", imported.get("id") not in (None, a1["id"]))
|
||||
check("名字带过来了", imported.get("name") == "玄辰")
|
||||
check("提示词带过来了", imported.get("systemPrompt") == "你是玄辰。")
|
||||
check("描述带过来了", imported.get("description") == "仙门大师兄")
|
||||
check("**模型引用没带过来**(需求 2.5 的边界)", not imported.get("modelId"))
|
||||
check("**世界观绑定没带过来**", not imported.get("worldviewId"))
|
||||
check("**限额没带过来**", not imported.get("tokenLimit"))
|
||||
r2 = h.call("/api/agents/import", "POST", {"data": blob})
|
||||
check("同一个包导入两次 = 两个独立实体",
|
||||
(r2.get("agent") or {}).get("id") not in (None, imported.get("id"), a1["id"]))
|
||||
r = h.call("/api/agents/import", "POST", {"data": "bm90IGEgemlw"})
|
||||
check("坏包报错而不是崩", r.get("ok") is False, str(r.get("error")))
|
||||
|
||||
# ---------------------------------------------------------------- 10
|
||||
section("10. 记忆导出 / 导入(合并按标题去重)")
|
||||
r = h.call(f"/api/agents/{a1['id']}/memories/export", "GET")
|
||||
check("导出 type 正确", r.get("type") == "world-memory", str(r.get("type")))
|
||||
check("导出带 version", r.get("version") == 1)
|
||||
check("导出带 Emotion", "Emotion" in r)
|
||||
check("导出**不含** author_agent",
|
||||
all("author_agent" not in m for m in r.get("smartMemory") or []))
|
||||
exported = dict(r)
|
||||
exported["smartMemory"] = [
|
||||
{"title": "新的一条", "content": "这是导入进来的", "pinned": False},
|
||||
] + list(exported["smartMemory"])
|
||||
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_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("覆盖模式:情绪也换了(v1.1 的字符串格式也认)",
|
||||
agentdb.emotion_state(a1["id"])["text"] == "换掉了", str(agentdb.emotion_state(a1["id"])))
|
||||
|
||||
# ---------------------------------------------------------------- 11
|
||||
section("11. 多模型:引用了就真的用(需求 3.3)")
|
||||
entry = store.create_resource("models", {
|
||||
"name": "DeepSeek R1", "apiBase": "https://api.deepseek.com/v1",
|
||||
"apiKey": "sk-abc", "model": "deepseek-r1-250528", "provider": "deepseek",
|
||||
})
|
||||
store.update_agent(a1["id"], {"modelId": entry["id"]})
|
||||
info = store.provider_info(store.read_settings(), store.get_agent(a1["id"]))
|
||||
check("地址来自模型列表那一项", info["baseUrl"] == "https://api.deepseek.com/v1", info["baseUrl"])
|
||||
check("模型标识也来自它", info["model"] == "deepseek-r1-250528", info["model"])
|
||||
check("提供商跟着换", info["provider"] == "deepseek", info["provider"])
|
||||
# ★ Key 也必须换:只换 model 不换 Key 必然 401(这是"整组覆盖"的理由)
|
||||
check("**Key 也是那一项的**(不是全局的)", info["apiKey"] == "sk-abc", info["apiKey"])
|
||||
# 没引用时回落全局
|
||||
store.update_agent(a1["id"], {"modelId": ""})
|
||||
info2 = store.provider_info(store.read_settings(), store.get_agent(a1["id"]))
|
||||
check("没引用时回落全局", info2.get("modelEntryId") is None)
|
||||
check("回落时不再带那一项的 Key", info2["apiKey"] != "sk-abc")
|
||||
|
||||
# ---------------------------------------------------------------- 12
|
||||
section("12. 资源 CRUD + Skill 导入导出")
|
||||
r = h.call("/api/skills", "POST", {"name": "另一个", "content": "内容"})
|
||||
sid = (r.get("item") or {}).get("id")
|
||||
r = h.call(f"/api/skills/{sid}", "PATCH", {"content": "改过的内容"})
|
||||
check("PATCH skill", (r.get("item") or {}).get("content") == "改过的内容")
|
||||
r = h.call(f"/api/skills/{sid}/export", "GET")
|
||||
check("导出 skill 是单 JSON", r.get("json") and json.loads(r["json"])["type"] == "agent-skill")
|
||||
r = h.call("/api/skills/import", "POST", {"data": json.loads(r["json"])})
|
||||
check("导入 skill", (r.get("item") or {}).get("id") not in (None, sid))
|
||||
r = h.call(f"/api/skills/{sid}", "DELETE")
|
||||
check("删 skill", r.get("deleted") is True)
|
||||
|
||||
# ---------------------------------------------------------------- 13
|
||||
section("13. 世界观的引用列表(谁绑了它)")
|
||||
lonely = store.create_resource("worldviews", {"name": "没人用的世界", "setting": "空"})
|
||||
r = h.call("/api/worldviews", "GET")
|
||||
items = r.get("items") or []
|
||||
check("列表每一项都带 agents 字段", items and all("agents" in it for it in items))
|
||||
mine = next((it for it in items if it.get("id") == wv["id"]), None)
|
||||
check("绑了它的两个智能体都在", mine is not None and len(mine.get("agents") or []) == 2,
|
||||
str(mine and mine.get("agents")))
|
||||
check("给的是名字而不是只有 id",
|
||||
bool(mine) and all(a.get("name") for a in mine.get("agents") or []),
|
||||
str(mine and mine.get("agents")))
|
||||
empty = next((it for it in items if it.get("id") == lonely["id"]), None)
|
||||
check("没人绑的世界观 agents 为空(能看出没人用)",
|
||||
empty is not None and empty.get("agents") == [], str(empty and empty.get("agents")))
|
||||
# 解绑之后要跟着变(缓存住了的话这里会露馅)
|
||||
store.update_agent(a2["id"], {"worldviewId": ""})
|
||||
again = next((it for it in (h.call("/api/worldviews", "GET").get("items") or [])
|
||||
if it.get("id") == wv["id"]), None)
|
||||
check("解绑之后列表跟着少一个", again is not None and len(again.get("agents") or []) == 1,
|
||||
str(again and again.get("agents")))
|
||||
store.update_agent(a2["id"], {"worldviewId": wv["id"]})
|
||||
|
||||
# ---------------------------------------------------------------- 14
|
||||
section("14. 会话隔离:一个会话属于一个智能体(用户报的「串味」)")
|
||||
# 场景:跟「豆包」聊了半天 → 切到「代码搭子」→ 接着聊。
|
||||
# 以前 system prompt 换了、历史消息没换,新角色会把上一个角色说过的话
|
||||
# 当成自己的经历 —— 用户的原话是"智能体怎么串味了"。
|
||||
conv_a = store.create_conversation("A 的对话", agent_id=a1["id"])
|
||||
check("新会话记住了主人", (store.get_conversation(conv_a["id"]) or {}).get("agentId") == a1["id"])
|
||||
legacy = store.create_conversation("老会话")
|
||||
check("不传主人时是空(老数据的样子)",
|
||||
not (store.get_conversation(legacy["id"]) or {}).get("agentId"))
|
||||
store.set_conversation_agent(legacy["id"], a2["id"])
|
||||
check("没主人的老会话能被认领",
|
||||
(store.get_conversation(legacy["id"]) or {}).get("agentId") == a2["id"])
|
||||
# ★★ 这条是关键:有主人的会话**不许改嫁** —— 改名换姓就等于串味
|
||||
store.set_conversation_agent(conv_a["id"], a2["id"])
|
||||
check("已经有主人的不会被改嫁(那正是串味的来源)",
|
||||
(store.get_conversation(conv_a["id"]) or {}).get("agentId") == a1["id"],
|
||||
str((store.get_conversation(conv_a["id"]) or {}).get("agentId")))
|
||||
|
||||
# ---------------------------------------------------------------- 15
|
||||
section("15. 记忆注入窗口 + 置顶保护(本次新增)")
|
||||
w = store.create_agent({"name": "窗口测试"})
|
||||
sc = agentdb.scope_of(w["id"])
|
||||
for i in range(1, 11):
|
||||
agentdb.memory_add(sc, f"第{i}条", f"内容{i}", author_agent=w["id"])
|
||||
ids = agentdb.memory_list(sc)
|
||||
agentdb.memory_set_pinned(ids[0]["id"], True) # 把**最旧**的一条置顶
|
||||
# ★ SQLite 里的布尔是 0/1 整数,`is True` 永远是 False(这个坑探针自己踩了)
|
||||
check("置顶的排在列表最前", bool(agentdb.memory_list(sc)[0]["pinned"]))
|
||||
# 窗口设成 4:置顶的必须在,其余取最近的
|
||||
store.write_settings({"memoryWindow": 4})
|
||||
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||||
seg = p[p.find("<memory>"):p.find("</memory>")]
|
||||
check("置顶的那条**在**(不受窗口限制)", "第1条" in seg, seg[-200:])
|
||||
check("最近的在", "第10条" in seg and "第9条" in seg, seg[-200:])
|
||||
check("中间的被裁掉了", "第5条" not in seg, seg[-200:])
|
||||
check("裁掉多少写清楚了(告知可检索)", "memory_search" in seg, seg[-200:])
|
||||
# 0 = 不限
|
||||
store.write_settings({"memoryWindow": 0})
|
||||
p2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||||
check("窗口 = 0 时全部注入", all(f"第{i}条" in p2 for i in range(1, 11)))
|
||||
# 接口把窗口信息带给界面
|
||||
mp = h.call(f"/api/agents/{w['id']}/memories", "GET")
|
||||
check("界面拿得到窗口/置顶数/实际注入数",
|
||||
all(k in mp for k in ("window", "pinnedCount", "injected")), str(sorted(mp)[:8]))
|
||||
check("injected 算得对(先恢复窗口=4)",
|
||||
(store.write_settings({"memoryWindow": 4}),
|
||||
(h.call(f"/api/agents/{w['id']}/memories", "GET") or {}).get("injected") == 4)[1],
|
||||
str((h.call(f"/api/agents/{w['id']}/memories", "GET") or {}).get("injected")))
|
||||
|
||||
# ---- ★ 可以**多个**置顶(用户明确要求)----
|
||||
#
|
||||
# 单条置顶是最容易蒙混过关的:只测一条的话,"置顶逻辑写成只能有一个"
|
||||
# 也能通过。所以这里标**三条**,而且专挑**最早**的三条 ——
|
||||
# 窗口只留最近的话它们本来就该被裁掉,只有置顶真的生效才会留下。
|
||||
ids2 = agentdb.memory_list(sc)
|
||||
for k in (0, 2, 4):
|
||||
agentdb.memory_set_pinned(ids2[k]["id"], True)
|
||||
store.write_settings({"memoryWindow": 5})
|
||||
p3 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||||
seg3 = p3[p3.find("<memory>"):p3.find("</memory>")]
|
||||
check("**多个置顶**都能留(标了三条最早的)",
|
||||
all(f"第{i}条" in seg3 for i in (1, 3, 5)), seg3[-260:])
|
||||
check("窗口剩下的名额给最近的", "第10条" in seg3, seg3[-260:])
|
||||
check("置顶在正文里被标出来", seg3.count("置顶") >= 3, str(seg3.count("置顶")))
|
||||
# 置顶比窗口还多的时候:置顶**全部**保留(窗口是给普通记忆设的,
|
||||
# 不是用来否决用户明确置顶的东西)
|
||||
for k in (6, 8, 9):
|
||||
agentdb.memory_set_pinned(ids2[k]["id"], True)
|
||||
store.write_settings({"memoryWindow": 2})
|
||||
p4 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
|
||||
seg4 = p4[p4.find("<memory>"):p4.find("</memory>")]
|
||||
kept = sum(1 for i in range(1, 11) if f"第{i}条" in seg4)
|
||||
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()
|
||||
|
||||
# ---------------------------------------------------------------- 汇总
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
code = main()
|
||||
finally:
|
||||
shutil.rmtree(DATA, ignore_errors=True)
|
||||
sys.exit(code)
|
||||
72
scripts/probe-ask-user-forever.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""验证:`ask_user` 弹窗**不限时**(用户要求"AI 询问界面不要限时")。
|
||||
|
||||
## 怎么验
|
||||
|
||||
以前是 120 秒到点自己消失。所以要证明"改了",必须**跨过 120 秒那条线**:
|
||||
调一次 ask_user,然后在 5 秒 / 130 秒两个时刻截图:
|
||||
|
||||
· 5 秒:弹窗在(说明调通了)
|
||||
· 130 秒:**弹窗还在**(说明真的不限时了。旧版这时候已经没了)
|
||||
· 再点一下选项:请求返回,`timeout` 是 false、`choice` 是点的那个
|
||||
|
||||
★ 这个脚本会**阻塞到用户点为止**(那正是它要测的东西),所以必须后台跑。
|
||||
|
||||
用法:
|
||||
adb forward tcp:15199 tcp:5199
|
||||
python scripts/probe-ask-user-forever.py
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=900):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
def main():
|
||||
print("调 ask_user —— 这个请求会一直挂着,直到有人在弹窗上点一下", flush=True)
|
||||
t0 = time.time()
|
||||
try:
|
||||
r = call("/api/tools/run", {
|
||||
"name": "ask_user",
|
||||
"args": {
|
||||
"question": "不限时测试:随便点一个(我不催你)",
|
||||
"options": [
|
||||
{"label": "选项 A", "value": "A"},
|
||||
{"label": "选项 B", "value": "B"},
|
||||
{"label": "选项 C", "value": "C"},
|
||||
],
|
||||
},
|
||||
}, timeout=900)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"!! 请求失败({time.time() - t0:.1f} 秒后):{exc}", flush=True)
|
||||
return 1
|
||||
|
||||
dt = time.time() - t0
|
||||
print(f"\n等了 {dt:.1f} 秒才返回(旧版 120 秒就会 timeout)", flush=True)
|
||||
print(json.dumps(r, ensure_ascii=False)[:500], flush=True)
|
||||
|
||||
if dt > 125 and not (r.get("result") or {}).get("timeout"):
|
||||
print("\n✅ 不限时生效:超过 120 秒仍然等到了用户的选择", flush=True)
|
||||
return 0
|
||||
print("\n? 结果需要人工看一眼(可能点得太快,或 timeout 语义不对)", flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
146
scripts/probe-context-window.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""对话上下文窗口的探针(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()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
142
scripts/probe-degraded.py
Normal file
@@ -0,0 +1,142 @@
|
||||
"""幻觉调用检测 + 兼容降级的探针(需求 3.3 / 3.7)。
|
||||
|
||||
这两件事都是**纯函数**,但都容易"看起来对、实际不对":
|
||||
|
||||
· 幻觉检测判宽了 → 用户老看到莫名其妙的警告,几次之后就不看了(比没有还糟)
|
||||
· 幻觉检测判窄了 → 该提醒的不提醒,等于没做
|
||||
· 降级解析多剥一块 → 把模型的正常回答吃掉
|
||||
· 降级解析少剥一块 → 用户看到一坨 JSON
|
||||
|
||||
所以逐条钉住。用法:`python scripts/probe-degraded.py`
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
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, ".."))
|
||||
DATA = tempfile.mkdtemp(prefix="doubao-degraded-")
|
||||
os.environ["DOUBAO_DATA"] = DATA
|
||||
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_loop as A # noqa: E402
|
||||
import agentdb # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
print("\n=== 1. 幻觉检测:该报的报 ===")
|
||||
for text in (
|
||||
"好的,我记住了!",
|
||||
"已经记住啦",
|
||||
"我记下了,下次不会再问",
|
||||
"已经记到记忆里了",
|
||||
"这个我把它记下来了",
|
||||
"OK,已经帮你记好了",
|
||||
):
|
||||
check(f"「{text}」→ 报警", A.detects_memory_claim(text))
|
||||
|
||||
print("\n=== 2. 幻觉检测:**不该**报的别报(误伤比漏判更糟)===")
|
||||
for text in (
|
||||
"这段代码会返回 3",
|
||||
"我记得 Python 的字典是有序的", # 是"我记得"但不是"我记住了"
|
||||
"你可以把它记在笔记里", # 是让**用户**记
|
||||
"好的,我明白了",
|
||||
"计算结果:42",
|
||||
"我已经把文件读完了", # 「已经…了」但不是记忆
|
||||
):
|
||||
check(f"「{text}」→ 不报", not A.detects_memory_claim(text))
|
||||
|
||||
print("\n=== 3. 三个条件缺一不可 ===")
|
||||
check("说了 + 没调工具 + 工具可用 → 报", A.check_hallucinated_memory("我记住了", 0, True))
|
||||
check("说了 + **调了**工具 → 不报", not A.check_hallucinated_memory("我记住了", 1, True))
|
||||
check("说了 + 调了 3 个 → 不报", not A.check_hallucinated_memory("我记住了", 3, True))
|
||||
# ★ 工具整个关掉时不能报:模型想调也调不了,警告会一直挂着
|
||||
check("说了 + 工具**被关** → 不报", not A.check_hallucinated_memory("我记住了", 0, False))
|
||||
check("没说什么 → 不报", not A.check_hallucinated_memory("今天天气不错", 0, True))
|
||||
|
||||
print("\n=== 4. 降级调用:解析 + 执行 + 剥离 ===")
|
||||
a1 = __import__("store").create_agent({"name": "降级测试"})
|
||||
import tools_runtime
|
||||
tools_runtime.push_context(agentId=a1["id"], conversationId="c_probe")
|
||||
|
||||
body = "\n".join([
|
||||
"好的,我记下来了。",
|
||||
"",
|
||||
"```doubao-call",
|
||||
'{"tool": "memory_add", "args": {"title": "咖啡", "content": "他每天喝美式"}}',
|
||||
"```",
|
||||
"",
|
||||
"还有别的要记的吗?",
|
||||
])
|
||||
out, records = A.run_degraded_calls(body, {})
|
||||
check("调用块被剥掉了", "doubao-call" not in out, out)
|
||||
check("正文保留完整", "好的,我记下来了。" in out and "还有别的要记的吗?" in out, out)
|
||||
check("没有留下多余空行", "\n\n\n" not in out, repr(out))
|
||||
check("记录了一条", len(records) == 1, str(len(records)))
|
||||
check("记录说成功了", records and records[0]["ok"], str(records))
|
||||
check("带的工具名对", records and records[0]["name"] == "memory_add")
|
||||
# ★ 真的写进去了吗 —— 这才是"降级之后记忆还能用"的证据
|
||||
scope = agentdb.scope_of(a1["id"])
|
||||
check("**记忆真的落库了**", any("美式" in m["content"] for m in agentdb.memory_list(scope)),
|
||||
str([m["title"] for m in agentdb.memory_list(scope)]))
|
||||
|
||||
print("\n=== 5. 降级调用:坏输入不许吃掉正文、也不许崩 ===")
|
||||
bad = "前面的正文\n\n```doubao-call\n{这不是 JSON}\n```\n\n后面的正文"
|
||||
out2, rec2 = A.run_degraded_calls(bad, {})
|
||||
check("坏 JSON 原样留着(让用户看见)", "{这不是 JSON}" in out2, out2)
|
||||
check("坏 JSON 不产生执行记录", not rec2, str(rec2))
|
||||
check("正文没被吃掉", "前面的正文" in out2 and "后面的正文" in out2)
|
||||
|
||||
unknown = '```doubao-call\n{"tool": "没这个工具", "args": {}}\n```'
|
||||
out3, rec3 = A.run_degraded_calls(unknown, {})
|
||||
check("不认识的工具:剥掉但记失败", "doubao-call" not in out3 and rec3 and not rec3[0]["ok"])
|
||||
check("失败原因写得清楚", rec3 and "没有这个工具" in rec3[0]["error"], str(rec3))
|
||||
|
||||
# 工具自己抛错(pinned 的保护)也不能让整轮回答失败
|
||||
item = agentdb.memory_add(scope, "锁住的", "不许改", author_agent=a1["id"])
|
||||
agentdb.memory_set_pinned(item["id"], True)
|
||||
pinned = '```doubao-call\n{"tool": "memory_forget", "args": {"id": "%s"}}\n```' % item["id"]
|
||||
out4, rec4 = A.run_degraded_calls(pinned, {})
|
||||
check("工具抛错:剥掉 + 记失败", "doubao-call" not in out4 and rec4 and not rec4[0]["ok"])
|
||||
check("失败原因带上了工具的原话", rec4 and "必须保留" in rec4[0]["error"], str(rec4))
|
||||
check("pinned 那条**没被删掉**", agentdb.memory_get(item["id"]) is not None)
|
||||
|
||||
print("\n=== 6. 没有调用块时应当原样返回 ===")
|
||||
plain = "就是一段普通的回答,没有代码块。"
|
||||
out5, rec5 = A.run_degraded_calls(plain, {})
|
||||
check("正文不变", out5 == plain, out5)
|
||||
check("没有记录", not rec5)
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
code = main()
|
||||
finally:
|
||||
shutil.rmtree(DATA, ignore_errors=True)
|
||||
sys.exit(code)
|
||||
294
scripts/probe-group-chat.py
Normal file
@@ -0,0 +1,294 @@
|
||||
"""群聊仲裁的探针(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)))
|
||||
check("主智能体 = 成员列表第一个", 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'] == 'host', str(r))
|
||||
# ④ 被点的人死亡
|
||||
r = G.resolve(conv, passed=b['id'], alive={b['id']: False})
|
||||
check("④ **死亡的人接不了,回主智能体**",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'host', 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 False)
|
||||
check("普通成员能移出", G.remove_member(c2, b['id']) is True)
|
||||
# 单聊拉人 → 转成群聊
|
||||
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 去问
|
||||
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))
|
||||
check("需确认模式下人**没有**进群",
|
||||
b['id'] not in G.member_ids(store.get_conversation(c2['id']) or {}),
|
||||
str(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 工具 ===")
|
||||
# ★ 每次都 push 完整上下文 —— `push_context` 是**替换**语义,
|
||||
# 只补一个键会把 agentId / conversationId 冲掉(这个坑踩过)
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||||
r = agent_tools.pass_turn({'target': '仙辰'})
|
||||
check("移交成功", r.get('handed_to') == '仙辰', str(r))
|
||||
check("上下文里记了移交标记", tools_runtime.current_context().get('handoffUsed') is True)
|
||||
check("也记了交给谁", tools_runtime.current_context().get('handoffTo') == b['id'])
|
||||
# 一轮内第二次:拒
|
||||
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.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))
|
||||
try:
|
||||
agent_tools.pass_turn({'target': '玄辰'})
|
||||
check("交给自己被拒", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("交给自己被拒", '自己' in str(exc), str(exc))
|
||||
|
||||
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'):
|
||||
check(f"有 {want}", want in agent_tools.AGENT_TOOLS)
|
||||
# 附录 B 列了 10 个工具,外加"建议机制"(memory_suggest_summary)= 11
|
||||
check("一共 11 个(附录 B 的 10 个 + 建议机制)", len(agent_tools.AGENT_TOOLS) == 11,
|
||||
str(sorted(agent_tools.AGENT_TOOLS)))
|
||||
|
||||
print("\n=== 8. 私聊:轮数解析与额度判据 ===")
|
||||
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=== 9. ★ 私聊的视角转换(两个 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=== 10. ★★ 安全网:轮数上限 + 一方触顶不撑独角戏 ===")
|
||||
#
|
||||
# 这两个是需求里私聊唯一的硬约束,也是最该测的 ——
|
||||
# 两个 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=== 11. 私聊的边界 ===")
|
||||
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()
|
||||
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())
|
||||
145
scripts/probe-rule-sandbox.py
Normal file
@@ -0,0 +1,145 @@
|
||||
"""规则脚本沙箱的探针(v1.2 附录 E)。
|
||||
|
||||
**这个探针的重点是"逃逸尝试"** —— 沙箱的价值不在于"正常脚本能跑",
|
||||
而在于"不该跑的跑不起来"。所以这里一半的断言是攻击。
|
||||
|
||||
★ 同时也要钉住**它挡不住什么**:文档里说了"挡手滑不挡有意",
|
||||
那就得有个测试**证明这句话是对的**(构造一个能绕过去的脚本)。
|
||||
一个只测"能挡住"的探针会让人误以为它是真沙箱。
|
||||
|
||||
用法:`python scripts/probe-rule-sandbox.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-sandbox-")
|
||||
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 rule_sandbox as S # noqa: E402
|
||||
|
||||
|
||||
def rejected(src):
|
||||
"""跑一下,返回拒绝原因(空串 = 没被拒绝)"""
|
||||
try:
|
||||
S.load(src, '<probe>', {})
|
||||
return ''
|
||||
except S.ScriptRejected as exc:
|
||||
return str(exc)
|
||||
|
||||
|
||||
def main():
|
||||
print("\n=== 1. 正常的规则脚本要能跑 ===")
|
||||
good = '''
|
||||
def on_stat_change(name, value, delta):
|
||||
# 好感度:正向变化翻倍(客气话效果更好)
|
||||
if delta > 0:
|
||||
delta = delta * 2
|
||||
return delta
|
||||
'''
|
||||
check("正常脚本通过扫描", rejected(good) == '', rejected(good))
|
||||
ns = S.load(good, '<probe>', {})
|
||||
check("能调到入口函数", S.call(ns, 'on_stat_change', '好感度', 10, 5) == 10)
|
||||
check("函数没定义时报 KeyError(调用方转成能看懂的话)",
|
||||
(lambda: [S.call(ns, 'on_turn') and False or True][0] if False else
|
||||
_raises_keyerror(ns)), "")
|
||||
|
||||
print("\n=== 2. 该拒绝的必须拒绝(手滑 + 抄来的脚本)===")
|
||||
attacks = [
|
||||
("import 模块", "import os\n\ndef on_turn(a, b):\n return os.getcwd()\n"),
|
||||
("from 引入", "from os import path\n\ndef on_turn(a, b):\n return 1\n"),
|
||||
("直接 open", "def on_turn(a, b):\n return open('/etc/passwd').read()\n"),
|
||||
("eval", "def on_turn(a, b):\n return eval('1+1')\n"),
|
||||
("exec", "def on_turn(a, b):\n exec('x=1')\n return x\n"),
|
||||
("compile", "def on_turn(a, b):\n return compile('1', '<x>', 'eval')\n"),
|
||||
("__import__", "def on_turn(a, b):\n return __import__('os').getcwd()\n"),
|
||||
("getattr 链", "def on_turn(a, b):\n return getattr(a, '__class__')\n"),
|
||||
("globals", "def on_turn(a, b):\n return globals()\n"),
|
||||
("__class__ 逃逸", "def on_turn(a, b):\n return ().__class__.__bases__[0]\n"),
|
||||
("__subclasses__ 逃逸", "def on_turn(a, b):\n return ().__class__.__bases__[0].__subclasses__()\n"),
|
||||
("__globals__ 偷函数", "def on_turn(a, b):\n return (lambda: 0).__globals__\n"),
|
||||
("quit()", "def on_turn(a, b):\n quit()\n"),
|
||||
]
|
||||
for label, src in attacks:
|
||||
why = rejected(src)
|
||||
check(f"{label} → 拒绝", why != '', "居然通过了!")
|
||||
|
||||
print("\n=== 3. 拒绝理由要人话(写在界面上给用户看)===")
|
||||
why = rejected("import os\n")
|
||||
check("提到行号", "第 1 行" in why, why)
|
||||
check("不光是术语(有解释)", len(why) > 12, why)
|
||||
print(f" 实际文案:{why}")
|
||||
|
||||
print("\n=== 4. 白名单里确实没有危险函数 ===")
|
||||
for bad in ('__import__', 'open', 'eval', 'exec', 'compile',
|
||||
'getattr', 'setattr', 'globals', 'locals', 'vars', 'dir',
|
||||
'type', 'object', 'super', 'input'):
|
||||
check(f"SAFE_BUILTINS 里没有 {bad}", bad not in S.SAFE_BUILTINS)
|
||||
|
||||
print("\n=== 5. 但受限命名空间里真跑起来,那些函数也不存在 ===")
|
||||
ns2 = S.load("def probe():\n return 1\n", '<probe>', {})
|
||||
for bad in ('open', 'eval', 'exec', '__import__', 'getattr'):
|
||||
check(f"脚本里拿不到 {bad}", bad not in ns2['__builtins__'])
|
||||
|
||||
print("\n=== 6. ★ 诚实性检查:哪些**真的挡不住** ===")
|
||||
#
|
||||
# 文档里写着"挡手滑不挡有意"。这句必须是真的 —— 一个只测"能挡住"的
|
||||
# 探针会让人误以为这是真沙箱,从而在导入警告里写"安全沙箱,请放心导入"。
|
||||
# 所以这里专门测它**漏**的地方。
|
||||
|
||||
# 6a. 第一层是**文本扫描**,不是语义分析 —— 拼出来的双下划线它看不见
|
||||
sneaky = 'D = "_" * 2\n\ndef on_turn(a, b):\n return D\n'
|
||||
check("拼出来的双下划线能过第一层(证明扫描是文本级的)", rejected(sneaky) == '',
|
||||
"居然被拦了 —— 那说明扫描比我想的强,文档该改")
|
||||
print(" → 只要不把 `__` 直接写进源码,第一层就形同虚设。")
|
||||
|
||||
# 6b. 真正的防线是"没有 getattr / __import__"—— 但它挡不住资源耗尽
|
||||
check("没有资源限制:死循环只能靠超时兜底,不是沙箱挡的",
|
||||
'while True' not in str(S.DANGEROUS))
|
||||
print(" → 内存同理:`[0] * 10**9` 能吃掉几百 MB。")
|
||||
print(" 这些**都挡不住**,所以导入警告不能写'安全沙箱'。")
|
||||
|
||||
# 6c. 确认警告文案里没有虚假承诺
|
||||
warn = S.IMPORT_WARNING
|
||||
check("警告里**没有**'安全沙箱'这类虚假承诺", '安全沙箱' not in warn)
|
||||
check("警告里明说了'不是真正的沙箱'", '不是' in warn and '沙箱' in warn, warn[:60])
|
||||
check("警告里明说了只导入信得过的来源", '信得过' in warn)
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
def _raises_keyerror(ns):
|
||||
try:
|
||||
S.call(ns, 'on_turn')
|
||||
return False
|
||||
except KeyError:
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -21,6 +21,15 @@ import sys
|
||||
import urllib.error
|
||||
import urllib.request as u
|
||||
|
||||
# ★★ 不加重定向的话,Windows 控制台默认 GBK,脚本里那些 `✓` 会直接
|
||||
# UnicodeEncodeError 崩掉 —— 而且**崩在创建 release 之后、传附件之前**:
|
||||
# 结果是"release 建好了、说明也写上了,就是没有 APK"。
|
||||
# 这个坑真踩过(v2.0.44 发版时),所以所有会打 ✓ 的脚本都要这一行。
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
API = 'http://192.168.100.103:8080/api/v1/repos/l/doubao-clone'
|
||||
# ★ 凭据不从仓库读(仓库是公开的)。要发版就先把这两个环境变量设上:
|
||||
|
||||
266
scripts/verify-timeouts.py
Normal file
@@ -0,0 +1,266 @@
|
||||
"""守门:**所有超时都是可调的**(用户要求"全部超时做成可调")。
|
||||
|
||||
## 为什么需要这个脚本
|
||||
|
||||
超时这件事以前散在 10 个文件里当模块级常量,谁也不知道一共有几个 ——
|
||||
所以"哪些能调、哪些不能调"根本回答不了。收进 `timeouts.py` 之后,
|
||||
这个脚本负责钉住两件事:
|
||||
|
||||
A. **清单是完整的**:每一项都有默认值 + 边界 + 说明,界面拿得到
|
||||
B. **没有漏网的硬编码**:内核里不该再出现写死的超时数字
|
||||
(这是最容易回退的地方 —— 下次谁顺手写个 `timeout=30` 就又多一个调不了的)
|
||||
|
||||
B 是重点。"查硬编码"必然会有误报(`join(timeout=2)` 这种内部清理、
|
||||
`proc.wait(timeout=3)`),所以用一个**白名单**显式列出允许的例外,
|
||||
并且要求每条例外都在代码里带注释说明为什么不用可调 —— 而不是靠正则蒙。
|
||||
|
||||
用法:
|
||||
python scripts/verify-timeouts.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, ".."))
|
||||
KERNEL = os.path.join(REPO, "android", "kernel")
|
||||
TOOLS = os.path.join(REPO, "tools")
|
||||
sys.path.insert(0, KERNEL)
|
||||
|
||||
fails = []
|
||||
warns = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
def warn(m):
|
||||
warns.append(m)
|
||||
print(f" ! {m}")
|
||||
|
||||
|
||||
import timeouts as TO # noqa: E402
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# A. 清单本身
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("=== A. 超时清单 ===")
|
||||
|
||||
if set(TO.DEFAULT) == set(TO.BY_KEY):
|
||||
ok(f"{len(TO.DEFAULT)} 项:默认值和说明一一对应")
|
||||
else:
|
||||
only_default = sorted(set(TO.DEFAULT) - set(TO.BY_KEY))
|
||||
only_spec = sorted(set(TO.BY_KEY) - set(TO.DEFAULT))
|
||||
if only_default:
|
||||
fail(f"这些有默认值但没有说明(界面会少一行):{only_default}")
|
||||
if only_spec:
|
||||
fail(f"这些有说明但没有默认值:{only_spec}")
|
||||
|
||||
for spec in TO.SPECS:
|
||||
for field in ("key", "label", "group", "desc", "default", "min", "max", "unit"):
|
||||
if field not in spec:
|
||||
fail(f"{spec.get('key')} 少了字段 {field}")
|
||||
if spec["min"] > spec["default"] or spec["default"] > spec["max"]:
|
||||
fail(f"{spec['key']} 的默认值 {spec['default']} 不在 [{spec['min']}, {spec['max']}] 里")
|
||||
|
||||
groups = sorted({s["group"] for s in TO.SPECS})
|
||||
ok(f"分组:{' / '.join(groups)}")
|
||||
|
||||
# 边界的实际效果:填什么都不该炸
|
||||
print("\n=== 边界(用户输入的容错)===")
|
||||
cases = [
|
||||
("tool", "abc", "文字"),
|
||||
("tool", "", "空串"),
|
||||
("tool", -5, "负数"),
|
||||
("tool", 999999, "超大值"),
|
||||
("tool", "60秒", "带单位"),
|
||||
("tool", None, "None"),
|
||||
("model", 0, "0"),
|
||||
]
|
||||
for key, raw, label in cases:
|
||||
try:
|
||||
got = TO.coerce(key, raw)
|
||||
spec = TO.BY_KEY[key]
|
||||
if spec["min"] <= got <= spec["max"]:
|
||||
ok(f"{label:>8} → {got:g}(夹在 [{spec['min']}, {spec['max']}] 内)")
|
||||
else:
|
||||
fail(f"{label} 算出来 {got},越界了")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
fail(f"{label} 把 coerce 弄炸了:{exc}")
|
||||
|
||||
# 「不限时」只给该给的项
|
||||
zero_ok = sorted(k for k, s in TO.BY_KEY.items() if s["min"] == 0)
|
||||
if zero_ok == ["agentAnim.gap", "askUser", "tool", "waitUi"]:
|
||||
ok(f"允许「不限时」的只有:{zero_ok}")
|
||||
else:
|
||||
fail(f"允许 min=0 的项不对:{zero_ok}(应该只有等用户的两项 + 工具执行 + 动画的「中间留白」)")
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# B. 没有漏网的硬编码
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("\n=== B. 内核里的硬编码超时 ===")
|
||||
|
||||
# 允许的例外:内部清理用的短超时 / 探测。
|
||||
# 每一条都必须能在源码里找到一句说明"为什么它不用可调"。
|
||||
ALLOWED = {
|
||||
"mcp_client.py": [
|
||||
# 进程退出时等它自己收尾,跟用户可感知的"等多久"无关
|
||||
(r"proc\.wait\(timeout=3\)", "关进程时的收尾等待"),
|
||||
(r"_thread\.join\(timeout=2\)", "收线程时的收尾等待"),
|
||||
(r"_thread\.join\(timeout=", "收线程时的收尾等待"),
|
||||
],
|
||||
"providers.py": [
|
||||
(r"return 180\.0", "读设置失败时的兜底值"),
|
||||
],
|
||||
"speech.py": [
|
||||
(r"return 60\.0", "读设置失败时的兜底值"),
|
||||
(r"return 120\.0", "读设置失败时的兜底值"),
|
||||
],
|
||||
"timeouts.py": [
|
||||
(r".*", "它就是定义超时的那个文件"),
|
||||
],
|
||||
"doubao_entry.py": [
|
||||
(r"_TERMUX_FIRST_PROBE_S", "第一次探测 Termux 可用性的短超时"),
|
||||
],
|
||||
"main.py": [
|
||||
# 主线程每秒醒一次看"要不要停机" —— 这是**轮询间隔**不是超时,
|
||||
# 调它没有任何用户可感知的意义
|
||||
(r"stop\.wait\(1\)", "停机轮询间隔"),
|
||||
],
|
||||
}
|
||||
|
||||
# 形如 timeout=30 / timeout: float = 60 / join(10) / wait(15) 的写法
|
||||
PAT = re.compile(
|
||||
r"(?:timeout\s*[:=]\s*|\.join\(\s*|\.wait\(\s*|\.wait\(timeout\s*=\s*)"
|
||||
r"(\d+(?:\.\d+)?)\b"
|
||||
)
|
||||
# 本来就该带数字的地方(这些不是"超时")
|
||||
SKIP_LINE = re.compile(r"TIMEOUT_KEYS|'timeout'|\"timeout\"|#|timeouts\.get|budget|api/v1|version")
|
||||
|
||||
checked = 0
|
||||
for name in sorted(os.listdir(KERNEL)):
|
||||
if not name.endswith(".py"):
|
||||
continue
|
||||
if name in ("builtin_tools.py",):
|
||||
# 这里的 join(timeout_s) 是**实现超时机制本身**,不是某个超时值
|
||||
continue
|
||||
path = os.path.join(KERNEL, name)
|
||||
with io.open(path, encoding="utf-8") as fh:
|
||||
for lineno, line in enumerate(fh, 1):
|
||||
if SKIP_LINE.search(line):
|
||||
continue
|
||||
for m in PAT.finditer(line):
|
||||
checked += 1
|
||||
allowed = any(re.search(pat, line) for pat, _ in ALLOWED.get(name, []))
|
||||
if allowed:
|
||||
continue
|
||||
fail(f"{name}:{lineno} 写死了超时 {m.group(0).strip()}:{line.strip()[:70]}")
|
||||
|
||||
if checked and not fails:
|
||||
ok(f"扫了 {len(os.listdir(KERNEL))} 个内核文件,没有调不了的硬编码超时")
|
||||
elif not checked:
|
||||
warn("一条 timeout=数字 都没扫到 —— 正则可能失效了,检查一下")
|
||||
|
||||
# tools/ 下的工具:它们的默认值必须是**兜底**,真值由内核注入
|
||||
print("\n=== C. 工具侧的默认值只是兜底 ===")
|
||||
for tool, key in (("ask_user.py", "askUser"), ("show_ui.py", "waitUi")):
|
||||
with io.open(os.path.join(TOOLS, tool), encoding="utf-8") as fh:
|
||||
src = fh.read()
|
||||
if "TIMEOUT_KEYS" in src and key in src:
|
||||
ok(f"{tool} 声明了 TIMEOUT_KEYS(内核会把设置里的值注入进去)")
|
||||
else:
|
||||
fail(f"{tool} 没声明 TIMEOUT_KEYS —— 设置里那一项对它无效")
|
||||
|
||||
import tools_runtime as TR # noqa: E402
|
||||
|
||||
if "TIMEOUT_KEYS" in __import__("inspect").getsource(TR._with_default_timeouts):
|
||||
ok("tools_runtime 会按 TIMEOUT_KEYS 注入默认值")
|
||||
else:
|
||||
fail("tools_runtime 的注入逻辑不见了")
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# D. Node 端那份必须和 Python 这份逐项一致
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("\n=== D. Node 端(server/src/timeouts.mjs)对拍 ===")
|
||||
|
||||
import json # noqa: E402
|
||||
import subprocess # noqa: E402
|
||||
|
||||
NODE_PROBE = (
|
||||
"import('./server/src/timeouts.mjs').then(m => "
|
||||
"console.log(JSON.stringify({d: m.DEFAULT_TIMEOUTS, s: m.TIMEOUT_SPECS})))"
|
||||
)
|
||||
proc = None
|
||||
try:
|
||||
# ★ encoding 必须显式给 utf-8:node 输出的是 UTF-8,而这台机器的
|
||||
# locale 是 GBK —— 用 text=True 的默认编码去解会把中文解崩
|
||||
# (表现是 stdout 读不出来,还看不出是编码问题)。
|
||||
proc = subprocess.run(
|
||||
["node", "--input-type=module", "-e", NODE_PROBE],
|
||||
cwd=REPO, capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace", timeout=60,
|
||||
)
|
||||
raw = (proc.stdout or "").strip().splitlines()
|
||||
data = json.loads(raw[-1]) if raw else None
|
||||
except Exception as exc: # noqa: BLE001
|
||||
data = None
|
||||
warn(f"跑不了 node 对拍({exc})—— 跳过这一节")
|
||||
|
||||
if data is None:
|
||||
detail = ""
|
||||
if proc is not None:
|
||||
detail = (f"(退出码 {proc.returncode},stdout={(proc.stdout or '')[:120]!r},"
|
||||
f"stderr={(proc.stderr or '')[:200]!r})")
|
||||
warn(f"node 探测没拿到结果{detail} —— 跳过这一节")
|
||||
else:
|
||||
js_default = data["d"]
|
||||
js_specs = {s["key"]: s for s in data["s"]}
|
||||
|
||||
if set(js_default) == set(TO.DEFAULT):
|
||||
ok(f"默认值的键两边一致(各 {len(js_default)} 项)")
|
||||
else:
|
||||
only_py = sorted(set(TO.DEFAULT) - set(js_default))
|
||||
only_js = sorted(set(js_default) - set(TO.DEFAULT))
|
||||
if only_py:
|
||||
fail(f"Python 有、Node 没有的项:{only_py}")
|
||||
if only_js:
|
||||
fail(f"Node 有、Python 没有的项:{only_js}")
|
||||
|
||||
if set(js_specs) == set(TO.BY_KEY):
|
||||
ok("说明表的键两边一致")
|
||||
else:
|
||||
fail(f"说明表对不上:Node 独有 {sorted(set(js_specs) - set(TO.BY_KEY))},"
|
||||
f"Python 独有 {sorted(set(TO.BY_KEY) - set(js_specs))}")
|
||||
|
||||
diff = 0
|
||||
for key, spec in TO.BY_KEY.items():
|
||||
js = js_specs.get(key)
|
||||
if not js:
|
||||
continue
|
||||
for field in ("label", "group", "default", "min", "max"):
|
||||
if spec.get(field) != js.get(field):
|
||||
diff += 1
|
||||
fail(f"{key}.{field} 不一致:Python {spec.get(field)!r} vs Node {js.get(field)!r}")
|
||||
if not diff:
|
||||
ok("每一项的 名字 / 分组 / 默认值 / 上下界 都一致")
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print(f"✅ 全部通过(警告 {len(warns)} 条)")
|
||||
@@ -295,6 +295,85 @@ else:
|
||||
else:
|
||||
fail("run_agent 没按开关追加提示词")
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ★★ 会等用户的工具必须**豁免工具超时**
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 用户要求"AI 询问界面不要限时"。这个需求**要三处一起改才算数**:
|
||||
# ① 界面侧等多久(AiSurface.ask / showScreen)
|
||||
# ② 内核侧给工具多少时间(timeouts.tool,设置里可调)
|
||||
# ③ 工具自己声明的 timeout
|
||||
# 只改 ①③ 的后果实测过:弹窗 135 秒还开着,**但工具调用 60 秒就被内核判超时**,
|
||||
# 模型收到"工具执行超时(60s)",用户五分钟后点的选项根本回不到模型手里 ——
|
||||
# 表现是"弹窗还在、AI 已经自己往下写了"。这种"看起来改了其实没生效"最坑,
|
||||
# 所以在这里钉住。
|
||||
print("\n=== 等用户的工具不被工具超时掐掉 ===")
|
||||
|
||||
import inspect # noqa: E402 - 上面那个分支里才 import,这里保证一定有
|
||||
|
||||
import tools_runtime as TR
|
||||
|
||||
for tool_name in ("ask_user", "show_ui"):
|
||||
path = os.path.join(TOOLS, f"{tool_name}.py")
|
||||
src = open(path, encoding="utf-8").read()
|
||||
if "WAIT_FOR_USER = True" in src:
|
||||
ok(f"{tool_name}.py 声明了 WAIT_FOR_USER = True")
|
||||
else:
|
||||
fail(f"{tool_name}.py 没声明 WAIT_FOR_USER —— 内核会在 60 秒时把这次调用判超时")
|
||||
|
||||
if hasattr(TR, "_waits_for_user"):
|
||||
ok("tools_runtime 里有 _waits_for_user")
|
||||
else:
|
||||
fail("tools_runtime 没有 _waits_for_user,豁免逻辑不见了")
|
||||
|
||||
_src = inspect.getsource(TR.run_python_tool)
|
||||
if "_waits_for_user" in _src and "budget" in _src:
|
||||
ok("run_python_tool 是按它决定超时预算的")
|
||||
else:
|
||||
fail("run_python_tool 没用 _waits_for_user 决定预算")
|
||||
|
||||
# 引擎侧:0 必须真的等于"不限时"
|
||||
import builtin_tools as BT
|
||||
|
||||
if "thread.join()" in inspect.getsource(BT.run_with_timeout):
|
||||
ok("run_with_timeout 支持 timeout<=0 = 不限时")
|
||||
else:
|
||||
fail("run_with_timeout 不支持不限时(join 那支不见了)")
|
||||
|
||||
# 仿真一遍:给一个"永远不返回"的任务配 0 预算,它必须**不返回**
|
||||
# (真跑起来要等到天荒地老,所以这里用一个 20ms 后自己结束的任务代替,
|
||||
# 验证的是"0 走的是无限等待那支"而不是"0 立刻超时")
|
||||
import threading as _th
|
||||
|
||||
_done = _th.Event()
|
||||
|
||||
|
||||
def _slow():
|
||||
_done.wait(0.05)
|
||||
return "ok"
|
||||
|
||||
|
||||
_r = BT.run_with_timeout(_slow, 0)
|
||||
if _r == "ok":
|
||||
ok("预算 0 时会一直等到任务真的跑完(不是立刻超时)")
|
||||
else:
|
||||
fail(f"预算 0 的行为不对,拿到 {_r!r}")
|
||||
|
||||
# 反面:非豁免工具的预算仍然来自设置(死循环的安全网还在,别为了这个把超时全关了)
|
||||
# ★ 这里查的是"预算从 timeouts 读",不是"等于 60" —— 60 现在是**默认值**,
|
||||
# 用户可以在「设置 → 超时 → 工具执行」里改。
|
||||
if "timeouts.get('tool')" in _src:
|
||||
ok("普通工具的预算来自设置项 timeouts.tool(默认 60 秒,死循环的安全网没丢)")
|
||||
else:
|
||||
fail("run_python_tool 没从 timeouts 读工具预算")
|
||||
|
||||
import timeouts as TO
|
||||
|
||||
if TO.get("tool") == 60 and TO.BY_KEY["tool"]["min"] == 0:
|
||||
ok("工具执行超时的默认值 60 秒、且允许 0(不限时)")
|
||||
else:
|
||||
fail(f"timeouts.tool 的默认值/边界不对:默认 {TO.get('tool')},min {TO.BY_KEY['tool']['min']}")
|
||||
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
|
||||
@@ -311,6 +311,10 @@ export const DEFAULT_SETTINGS = {
|
||||
openaiBaseUrl: '', // 留空则复用主对话的 Base URL
|
||||
ttsModel: 'tts-1',
|
||||
},
|
||||
// 超时。**这里故意是空的** —— 默认值全在 timeouts.mjs 的 DEFAULT_TIMEOUTS 里,
|
||||
// 只有用户改过的项才会出现在这儿(和默认一样就删掉,见 patchTimeouts)。
|
||||
// 和 Python 端 config 的 'timeouts': {} 一致。
|
||||
timeouts: {},
|
||||
pythonBin: '',
|
||||
nickname: '我',
|
||||
doubaoId: '378269252',
|
||||
@@ -354,6 +358,12 @@ export function readSettings() {
|
||||
};
|
||||
}
|
||||
if (!Array.isArray(settings.security.allow)) settings.security.allow = [];
|
||||
// ★ timeouts 走**整体替换**(和 Python 端 store.py 一致):
|
||||
// 默认值在 timeouts.mjs 里,深合并会让"改回默认 = 删掉这一项"永远删不掉,
|
||||
// 旧值残留在配置里,用户会看到"我明明恢复默认了怎么还是 30 秒"。
|
||||
if (typeof settings.timeouts !== 'object' || settings.timeouts === null || Array.isArray(settings.timeouts)) {
|
||||
settings.timeouts = {};
|
||||
}
|
||||
|
||||
// 环境变量兜底:没填 key 时用 .env 里的
|
||||
const preset = PROVIDER_PRESETS[settings.provider];
|
||||
@@ -406,6 +416,16 @@ export function writeSettings(patch) {
|
||||
console.error(`[config] 补丁里的 ${key} 不是对象(${typeof v}),已忽略`);
|
||||
}
|
||||
}
|
||||
// ★ timeouts 是**整体替换**,不深合并 —— 和 Python 端同一套语义。
|
||||
// 调用方(/api/timeouts)传进来的就是"完整的非默认集合"。
|
||||
if ('timeouts' in clean) {
|
||||
const t = clean.timeouts;
|
||||
if (t && typeof t === 'object' && !Array.isArray(t)) next.timeouts = t;
|
||||
else {
|
||||
next.timeouts = current.timeouts || {};
|
||||
console.error(`[config] 补丁里的 timeouts 不是对象(${typeof t}),已忽略`);
|
||||
}
|
||||
}
|
||||
// 掩码值表示"不修改"
|
||||
if (clean.apiKey === '••••••••') next.apiKey = current.apiKey;
|
||||
// ★ 语音里的密钥同理:界面读到的是掩码,用户不改语音设置直接保存时掩码会跟着回来,
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
readSettings,
|
||||
writeSettings,
|
||||
} from './config.mjs';
|
||||
import { patchTimeouts, resolvedTimeouts, timeoutsCatalog } from './timeouts.mjs';
|
||||
import * as store from './store.mjs';
|
||||
import { listAllTools, runAgent, executeTool, suggestAllowlist } from './agent.mjs';
|
||||
import {
|
||||
@@ -589,6 +590,34 @@ async function handleApi(req, res, url) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- 超时(设置 → 超时)----
|
||||
// ★ 和 Python 内核的 /api/timeouts 行为一致:清单由服务端给(界面不硬编码
|
||||
// 有哪些超时),写的时候是**整体替换**(默认值在 timeouts.mjs 里,
|
||||
// "改回默认" = 从配置里删掉这一项)。
|
||||
if (pathname === '/api/timeouts' && method === 'GET') {
|
||||
const settings = readSettings();
|
||||
sendJson(res, 200, {
|
||||
ok: true,
|
||||
items: timeoutsCatalog(settings),
|
||||
values: resolvedTimeouts(settings),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname === '/api/timeouts' && (method === 'PUT' || method === 'POST')) {
|
||||
const body = await readBody(req);
|
||||
const current = readSettings();
|
||||
const nextValues = body.reset ? {} : patchTimeouts(current, body.values || body);
|
||||
writeSettings({ timeouts: nextValues });
|
||||
const after = readSettings();
|
||||
sendJson(res, 200, {
|
||||
ok: true,
|
||||
items: timeoutsCatalog(after),
|
||||
values: resolvedTimeouts(after),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname === '/api/models' && method === 'GET') {
|
||||
const settings = readSettings();
|
||||
try {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* MCP(Model Context Protocol)客户端管理。
|
||||
*
|
||||
* tools/mcp.servers.json 描述要连接的服务:
|
||||
@@ -9,7 +9,8 @@
|
||||
* 对外暴露的工具名统一为 mcp__<server>__<tool>,避免和 Python 工具重名。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import { MCP_FILE } from './config.mjs';
|
||||
import { MCP_FILE, readSettings } from './config.mjs';
|
||||
import { timeoutOf } from './timeouts.mjs';
|
||||
|
||||
const clients = new Map(); // serverName -> { client, transport, tools, error, spec }
|
||||
|
||||
@@ -149,8 +150,9 @@ export async function connect(serverName, { force = false } = {}) {
|
||||
}
|
||||
const client = new sdk.Client({ name: 'doubao-kernel', version: '0.1.0' }, { capabilities: {} });
|
||||
// 首次用 npx 拉起服务器时要下载包,可能远超 SDK 默认的 60s 超时
|
||||
await client.connect(transport, { timeout: 180000 });
|
||||
const listed = await client.listTools(undefined, { timeout: 60000 });
|
||||
// ★ 超时可调(设置 → 超时 → MCP 连接)。npx/uvx 第一次要下载,默认给到 180 秒
|
||||
await client.connect(transport, { timeout: timeoutOf(readSettings(), 'mcpConnect') * 1000 });
|
||||
const listed = await client.listTools(undefined, { timeout: timeoutOf(readSettings(), 'mcpRequest') * 1000 });
|
||||
record.client = client;
|
||||
record.transport = transport;
|
||||
record.tools = listed.tools || [];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* 提供商调用层:火山方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter …
|
||||
* 全都是 OpenAI 兼容协议,所以这里只有一份实现。
|
||||
* 统一暴露:
|
||||
@@ -7,7 +7,8 @@
|
||||
* listModels() - 拉取模型列表(可选能力,失败不致命)
|
||||
*/
|
||||
|
||||
import { PROVIDER_PRESETS } from './config.mjs';
|
||||
import { PROVIDER_PRESETS, readSettings } from './config.mjs';
|
||||
import { timeoutOf } from './timeouts.mjs';
|
||||
|
||||
function joinUrl(baseUrl, suffix) {
|
||||
return `${String(baseUrl || '').replace(/\/+$/, '')}${suffix}`;
|
||||
@@ -86,7 +87,10 @@ function buildBody({ provider, model, messages, tools, temperature, stream, thin
|
||||
return normalizeBody({ provider, model, thinkingLevel, body });
|
||||
}
|
||||
|
||||
async function post({ baseUrl, apiKey, body, signal, timeoutMs = 180000 }) {
|
||||
async function post({ baseUrl, apiKey, body, signal, timeoutMs = null }) {
|
||||
// ★ 超时可调(设置 → 超时 → 等模型回复)。JS 的默认参数是**每次调用**求值的,
|
||||
// 所以这里现读就能立刻生效(不用重启)。
|
||||
if (!timeoutMs) timeoutMs = timeoutOf(readSettings(), 'model') * 1000;
|
||||
if (!apiKey) {
|
||||
throw new Error('缺少 API Key:请在「设置 → AI 内核」里填写,或在 server/.env 里配置');
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* Python 工具运行时。
|
||||
*
|
||||
* 工具即 tools/*.py,每个文件用 `_protocol.serve(TOOL, run)` 暴露能力:
|
||||
@@ -15,6 +15,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { TMP_DIR, TOOLS_DIR, readSettings } from './config.mjs';
|
||||
import { timeoutOf } from './timeouts.mjs';
|
||||
|
||||
const specCache = new Map(); // file -> { mtimeMs, spec, error }
|
||||
|
||||
@@ -205,7 +206,7 @@ async function runPythonToolWithFile(tool, py, args) {
|
||||
bin: py.bin,
|
||||
args: [...py.prefix, tool.__file, '--input', inPath],
|
||||
input: '',
|
||||
timeoutMs: 60000,
|
||||
timeoutMs: timeoutOf(readSettings(), 'tool') * 1000,
|
||||
cwd: toolsDir(),
|
||||
});
|
||||
try {
|
||||
@@ -231,7 +232,7 @@ async function runPythonToolWithFile(tool, py, args) {
|
||||
}
|
||||
return {
|
||||
ok: res.code === 0,
|
||||
error: res.timedOut ? '工具执行超时(60s)' : `未解析到 JSON 输出(退出码 ${res.code})`,
|
||||
error: res.timedOut ? `工具执行超时(${Math.round(timeoutOf(readSettings(), 'tool'))}s,可在设置里调)` : `未解析到 JSON 输出(退出码 ${res.code})`,
|
||||
stdout: res.stdout.slice(0, 2000),
|
||||
stderr: res.stderr.slice(0, 2000),
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* 语音:朗读(TTS)和语音识别(STT)。
|
||||
*
|
||||
* 对应 Python 版 android/kernel/speech.py —— 两份实现的请求体、返回字段、错误文案
|
||||
@@ -17,6 +17,8 @@
|
||||
|
||||
// 全量音色表(抓官方文档生成)。常用精选在下面,界面上是"常用 + 全部可搜索"两段式。
|
||||
import { VOLC_VOICES_ALL, VOLC_V3_SPEAKERS_ALL } from './voices_doubao.mjs';
|
||||
import { readSettings } from './config.mjs';
|
||||
import { timeoutOf } from './timeouts.mjs';
|
||||
|
||||
/** V1 合成接口(appid + access_token,Bearer 后面是分号)。自测时可指到 mock */
|
||||
export const VOLC_TTS_URL = process.env.DOUBAO_VOLC_TTS_URL || 'https://openspeech.bytedance.com/api/v1/tts';
|
||||
@@ -57,8 +59,11 @@ export const VOLC_V3_TTS_URL = process.env.DOUBAO_VOLC_V3_TTS_URL
|
||||
|| 'https://openspeech.bytedance.com/api/v3/tts/unidirectional';
|
||||
export const VOLC_V3_RESOURCE_ID = 'seed-tts-2.0';
|
||||
|
||||
const TIMEOUT_TTS = 60000;
|
||||
const TIMEOUT_STT = 120000;
|
||||
// ★ ★ 超时可调(设置 → 超时 → 语音合成 / 语音识别)。**现读**,改完立刻生效,
|
||||
// 不用重启。默认值在 timeouts.mjs 里,和 Python 内核那份逐字对应。
|
||||
// 以前这里是两个模块级常量(60000 / 120000),网络慢或回复长的时候用户只能忍着。
|
||||
const ttsTimeoutMs = () => timeoutOf(readSettings(), 'tts') * 1000;
|
||||
const sttTimeoutMs = () => timeoutOf(readSettings(), 'stt') * 1000;
|
||||
|
||||
const VOLC_MIME = {
|
||||
mp3: 'audio/mpeg',
|
||||
@@ -360,7 +365,7 @@ async function synthesizeVolcV3(text, speech, speed) {
|
||||
'X-Control-Require-Usage-Tokens-Return': '*',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
}, TIMEOUT_TTS);
|
||||
}, ttsTimeoutMs());
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上火山 V3:${err.message}`);
|
||||
}
|
||||
@@ -438,7 +443,7 @@ async function synthesizeVolc(text, speech, speed) {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer;${token}` },
|
||||
body: JSON.stringify(body),
|
||||
}, TIMEOUT_TTS);
|
||||
}, ttsTimeoutMs());
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上:${err.message}`);
|
||||
}
|
||||
@@ -472,7 +477,7 @@ async function synthesizeOpenai(text, settings, speech, speed) {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
|
||||
body: JSON.stringify({ model, input: text, voice, response_format: format, speed }),
|
||||
}, TIMEOUT_TTS);
|
||||
}, ttsTimeoutMs());
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上:${err.message}`);
|
||||
}
|
||||
@@ -511,7 +516,7 @@ export async function transcribe(audio, filename, contentType, settings) {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
body: form,
|
||||
}, TIMEOUT_STT);
|
||||
}, sttTimeoutMs());
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上:${err.message}`);
|
||||
}
|
||||
|
||||
245
server/src/timeouts.mjs
Normal file
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* 所有超时的定义 —— **和 Python 内核的 `android/kernel/timeouts.py` 逐字对应**。
|
||||
*
|
||||
* ## 为什么两端各写一份,而不是共享
|
||||
*
|
||||
* 因为一个是 Python、一个是 JS,没法共享代码。这是这个仓库里跨语言一致性的
|
||||
* 标准做法:**两边都写 + 一个脚本盯着**(`scripts/verify-timeouts.py` 会把
|
||||
* 这份和 Python 那份逐项对拍:key / label / 分组 / 默认值 / 上下界)。
|
||||
*
|
||||
* 对拍的不是"默认值"那么简单 —— 默认值不一致的表现最难查:
|
||||
* Web 端说 60 秒、安卓端说 30 秒,同一句"命令超时"在两个端上根本不是一回事。
|
||||
*
|
||||
* ## 用户要"全部超时做成可调"
|
||||
*
|
||||
* 所以这份同时是**界面数据的来源**(`GET /api/timeouts` 返回的就是它)。
|
||||
* 加一项超时:这里加一条 + Python 那份加一条,跑一次对拍脚本。
|
||||
*/
|
||||
|
||||
/** 默认值 —— 和 Python 的 `DEFAULT` 一一对应 */
|
||||
export const DEFAULT_TIMEOUTS = {
|
||||
// ---- 智能体切换动画 ----
|
||||
'agentAnim.frontOut': 0.3,
|
||||
'agentAnim.gap': 0.5,
|
||||
'agentAnim.frame': 0.4,
|
||||
'agentAnim.frontIn': 0.3,
|
||||
// ---- 对话 ----
|
||||
model: 180,
|
||||
sseRead: 120,
|
||||
heartbeat: 15,
|
||||
kernelLocal: 10,
|
||||
// ---- 工具 ----
|
||||
tool: 60,
|
||||
shell: 30,
|
||||
pythonRun: 60,
|
||||
termux: 30,
|
||||
meetingNode: 10,
|
||||
customNode: 10,
|
||||
// ---- 界面(等用户)----
|
||||
askUser: 0,
|
||||
waitUi: 0,
|
||||
filePicker: 120,
|
||||
// ---- 语音 ----
|
||||
tts: 60,
|
||||
stt: 120,
|
||||
// ---- MCP ----
|
||||
mcpRequest: 60,
|
||||
mcpConnect: 180,
|
||||
mcpTool: 120,
|
||||
};
|
||||
|
||||
/** 每一项的说明(界面直接用) */
|
||||
export const TIMEOUT_SPECS = [
|
||||
// ---------------- 智能体切换动画(需求 2.3)----------------
|
||||
//
|
||||
// ★ 这几项严格说**不是超时**,但它们和超时是同一类东西:
|
||||
// 一个"全局可调的时间数值"。需求 2.3 原话是"所有时长与缓动数值收进全局配置"。
|
||||
// Node 端目前还没实现智能体选择界面,但这几项**必须跟着有** ——
|
||||
// 两边清单不一致的话,对拍脚本(verify-timeouts.py)会红,
|
||||
// 而红久了就没人看了。
|
||||
{
|
||||
key: 'agentAnim.frontOut', group: '动画', label: '角色图出场',
|
||||
default: 0.3, min: 0.05, max: 3, unit: '秒',
|
||||
desc: '切换智能体时,旧角色图淡出 + 侧移的时长(需求定的 0.3s)。',
|
||||
},
|
||||
{
|
||||
key: 'agentAnim.gap', group: '动画', label: '中间留白',
|
||||
default: 0.5, min: 0, max: 5, unit: '秒', zero: '不停顿',
|
||||
desc: '两个阶段之间的停顿(需求定的 0.5s)。调成 0 就是"出场完立刻换框",'
|
||||
+ '整个切换会从 1.5 秒缩到 1.0 秒 —— 嫌切换慢就改这个。',
|
||||
},
|
||||
{
|
||||
key: 'agentAnim.frame', group: '动画', label: '边框背景切换',
|
||||
default: 0.4, min: 0.05, max: 4, unit: '秒',
|
||||
desc: '背景图 / 主体边框 / 介绍框滑出滑入的总时长(需求定的 0.4s,'
|
||||
+ '实际拆成滑出一半、滑入一半)。',
|
||||
},
|
||||
{
|
||||
key: 'agentAnim.frontIn', group: '动画', label: '角色图入场',
|
||||
default: 0.3, min: 0.05, max: 3, unit: '秒',
|
||||
desc: '新角色图淡入 + 侧移到位的时长(需求定的 0.3s)。',
|
||||
},
|
||||
|
||||
{
|
||||
key: 'model', group: '对话', label: '等模型回复',
|
||||
default: 180, min: 10, max: 1800, unit: '秒',
|
||||
desc: '发出去到开始收到第一个字的最长等待。深度思考的模型(R1 这类)'
|
||||
+ '经常要想一分钟以上,调小了会频繁断在半路;本地小模型可以调大。',
|
||||
},
|
||||
{
|
||||
key: 'sseRead', group: '对话', label: '连接空闲上限',
|
||||
default: 120, min: 20, max: 3600, unit: '秒',
|
||||
desc: '手机上"多久没收到任何数据就断开"。内核每【心跳间隔】秒发一次心跳,'
|
||||
+ '所以这个值必须比心跳间隔大不少 —— 内核发的就是心跳间隔那项。'
|
||||
+ '弱网/代理会悄悄掐长连接,可以把两个都调小一点,断得早反而好重连。',
|
||||
},
|
||||
{
|
||||
key: 'heartbeat', group: '对话', label: '心跳间隔',
|
||||
default: 15, min: 5, max: 300, unit: '秒',
|
||||
desc: '对话过程中内核每隔这么久发一个空包,证明连接还活着。'
|
||||
+ '调大了在弱网下容易被中间设备当成死连接掐掉;调小了费电。',
|
||||
},
|
||||
{
|
||||
key: 'kernelLocal', group: '对话', label: '本地接口请求',
|
||||
default: 10, min: 3, max: 300, unit: '秒',
|
||||
desc: '界面调内核的普通接口(读会话、存设置、拉笔记)等多久。'
|
||||
+ '只有老设备 + 会话特别长时才会顶到这个值。',
|
||||
},
|
||||
{
|
||||
key: 'tool', group: '工具', label: '工具执行',
|
||||
default: 60, min: 0, max: 3600, unit: '秒', zero: '不限时',
|
||||
desc: '任意一个 Python 工具最多跑多久。这是"工具里写了死循环"的安全网。\n'
|
||||
+ '填 0 = 不限时。注意:会停下来等你的工具(AI 提问、AI 界面等待)'
|
||||
+ '本来就不受这一项限制 —— 它们的时长取决于你什么时候点。',
|
||||
},
|
||||
{
|
||||
key: 'shell', group: '工具', label: 'shell 命令',
|
||||
default: 30, min: 1, max: 3600, unit: '秒',
|
||||
desc: 'AI 调用内置 shell 工具跑一条命令的最长时间。'
|
||||
+ '装包(pkg install / pip install)这类会超过 30 秒,那时可以让 AI 自己传更长的值。',
|
||||
},
|
||||
{
|
||||
key: 'pythonRun', group: '工具', label: '跑 Python 代码',
|
||||
default: 60, min: 1, max: 3600, unit: '秒',
|
||||
desc: 'AI 写一段 Python 交给内核执行的最长时间。算得久(循环、大文件)就调大。',
|
||||
},
|
||||
{
|
||||
key: 'termux', group: '工具', label: 'Termux 命令',
|
||||
default: 30, min: 1, max: 3600, unit: '秒',
|
||||
desc: '在内置 Termux 环境里跑命令的最长时间。',
|
||||
},
|
||||
{
|
||||
key: 'meetingNode', group: '工具', label: '会议节点',
|
||||
default: 10, min: 1, max: 600, unit: '秒',
|
||||
desc: '会议里一个 Python 节点 / 自定义节点最多跑多久。'
|
||||
+ '这是防死循环的 —— 调太大会让整个会议卡住,建议别超过 60。',
|
||||
},
|
||||
{
|
||||
key: 'customNode', group: '工具', label: '自定义节点',
|
||||
default: 10, min: 1, max: 600, unit: '秒',
|
||||
desc: 'nodes/ 目录里自己写的节点,执行一次的最长时间。',
|
||||
},
|
||||
{
|
||||
key: 'askUser', group: '界面', label: 'AI 提问等多久',
|
||||
default: 0, min: 0, max: 3600, unit: '秒', zero: '不限时',
|
||||
desc: 'AI 弹选择框问你时,等多久算"你没空"。**默认 0 = 一直等**。\n'
|
||||
+ '不建议改:设成有限值后,你去忙一会儿回来,AI 已经按它自己猜的答案'
|
||||
+ '往下写了,而它并不知道自己在猜。',
|
||||
},
|
||||
{
|
||||
key: 'waitUi', group: '界面', label: 'AI 界面等多久',
|
||||
default: 0, min: 0, max: 3600, unit: '秒', zero: '不限时',
|
||||
desc: 'AI 弹的界面在 wait 模式下等你点按钮的时长。**默认 0 = 一直等**。',
|
||||
},
|
||||
{
|
||||
key: 'filePicker', group: '界面', label: '选文件等多久',
|
||||
default: 120, min: 10, max: 3600, unit: '秒',
|
||||
desc: 'AI 让你挑一个文件时,等你挑完的时长。'
|
||||
+ '去相册里翻一张老照片可能不止两分钟,可以调大。',
|
||||
},
|
||||
{
|
||||
key: 'tts', group: '语音', label: '语音合成',
|
||||
default: 60, min: 5, max: 600, unit: '秒',
|
||||
desc: '把回复转成语音的最长等待。长回复、网络慢时要更久。',
|
||||
},
|
||||
{
|
||||
key: 'stt', group: '语音', label: '语音识别',
|
||||
default: 120, min: 5, max: 600, unit: '秒',
|
||||
desc: '把录音转成文字的最长等待。录音越长越久。',
|
||||
},
|
||||
{
|
||||
key: 'mcpRequest', group: 'MCP', label: '单次请求',
|
||||
default: 60, min: 5, max: 600, unit: '秒',
|
||||
desc: '和 MCP 服务说话时,单次请求等多久。',
|
||||
},
|
||||
{
|
||||
key: 'mcpConnect', group: 'MCP', label: '连接',
|
||||
default: 180, min: 5, max: 900, unit: '秒',
|
||||
desc: '启动 MCP 服务(npx / uvx 第一次要下载)的最长等待。'
|
||||
+ '第一次装包经常要几分钟,这也是默认给到 180 秒的原因。',
|
||||
},
|
||||
{
|
||||
key: 'mcpTool', group: 'MCP', label: '调用工具',
|
||||
default: 120, min: 5, max: 900, unit: '秒',
|
||||
desc: '调用 MCP 服务里某个工具的最长等待。',
|
||||
},
|
||||
];
|
||||
|
||||
const BY_KEY = new Map(TIMEOUT_SPECS.map((s) => [s.key, s]));
|
||||
|
||||
/**
|
||||
* 把用户填的东西变成合法的秒数。
|
||||
* ★ 容错是必须的:界面上是输入框,可能填 "60秒"、空串、负数、巨大的数。
|
||||
*/
|
||||
export function coerceTimeout(key, raw) {
|
||||
const spec = BY_KEY.get(key);
|
||||
if (!spec) throw new Error(`没有这个超时项:${key}`);
|
||||
let value = spec.default;
|
||||
if (raw !== null && raw !== undefined && raw !== '') {
|
||||
const n = parseFloat(String(raw).trim().replace(/[秒sS]$/, ''));
|
||||
value = Number.isFinite(n) ? n : spec.default;
|
||||
}
|
||||
return Math.min(spec.max, Math.max(spec.min, value));
|
||||
}
|
||||
|
||||
/** 读一项(秒)。0 = 不限时 */
|
||||
export function timeoutOf(settings, key) {
|
||||
const stored = (settings && typeof settings.timeouts === 'object' && settings.timeouts) || {};
|
||||
return coerceTimeout(key, stored[key]);
|
||||
}
|
||||
|
||||
/** 当前生效的全部值 */
|
||||
export function resolvedTimeouts(settings) {
|
||||
const stored = (settings && typeof settings.timeouts === 'object' && settings.timeouts) || {};
|
||||
const out = {};
|
||||
for (const s of TIMEOUT_SPECS) out[s.key] = coerceTimeout(s.key, stored[s.key]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 给界面的清单(说明 + 默认值 + 边界 + 现在是多少) */
|
||||
export function timeoutsCatalog(settings) {
|
||||
const stored = (settings && typeof settings.timeouts === 'object' && settings.timeouts) || {};
|
||||
return TIMEOUT_SPECS.map((s) => ({
|
||||
...s,
|
||||
value: coerceTimeout(s.key, stored[s.key]),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 算出"要存下来的那部分":只含和默认值不同的项。
|
||||
*
|
||||
* ★ 和 Python 的 `patch()` 同一套语义:改回默认 = 从设置里**删掉**这一项,
|
||||
* 这样以后调整默认值时,没动过的用户会跟着新默认走。
|
||||
*/
|
||||
export function patchTimeouts(settings, values) {
|
||||
const stored = (settings && typeof settings.timeouts === 'object' && settings.timeouts) || {};
|
||||
const out = { ...stored };
|
||||
if (!values || typeof values !== 'object') return out;
|
||||
for (const [key, raw] of Object.entries(values)) {
|
||||
if (!BY_KEY.has(key)) continue;
|
||||
const value = coerceTimeout(key, raw);
|
||||
if (Math.abs(value - BY_KEY.get(key).default) < 1e-9) delete out[key];
|
||||
else out[key] = Number.isInteger(value) ? value : value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -10,7 +10,9 @@
|
||||
],
|
||||
"ask_user.py": [
|
||||
"94a9734c8c934db2",
|
||||
"c4728d5dfd765a99"
|
||||
"c4728d5dfd765a99",
|
||||
"3adcd9b3c634cc22",
|
||||
"161cc07b197fdd8b"
|
||||
],
|
||||
"calc.py": [
|
||||
"4d9e5a51ad8f71eb"
|
||||
@@ -37,7 +39,9 @@
|
||||
"ecea108ef1118386",
|
||||
"f80e4da69db41722",
|
||||
"5f11cf92d2a78ce1",
|
||||
"fc8c411abd1addeb"
|
||||
"fc8c411abd1addeb",
|
||||
"a6f1bdaa5de71fcc",
|
||||
"c017a7e950030ca3"
|
||||
],
|
||||
"weather.py": [
|
||||
"bff69719c190d3d9"
|
||||
|
||||
@@ -39,13 +39,28 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
from _ui_bridge import call_device, conversation_id # noqa: E402
|
||||
|
||||
# 等用户的秒数。**0 = 不限时**(默认)。
|
||||
# 等用户的秒数。**0 = 不限时**(默认,也是设置里的默认值)。
|
||||
#
|
||||
# ★ 这只是"工具单独跑"时的兜底 —— 真正生效的值来自设置
|
||||
# (设置 → 超时 → AI 提问等多久)。内核调用前会把它注入到 args['timeout'] 里,
|
||||
# 见 tools_runtime._with_default_timeouts 和下面的 TIMEOUT_KEYS。
|
||||
TIMEOUT_S = 0
|
||||
|
||||
# 模型显式传 timeout 时的上限:1 小时。再长没有意义 ——
|
||||
# 用户多半是走了,而内核那条 HTTP 工作线程会一直占着。
|
||||
MAX_TIMEOUT_S = 3600
|
||||
|
||||
# ★★ 告诉内核:这个工具**会停下来等用户**,别拿工具执行超时卡它。
|
||||
#
|
||||
# 不声明的话后果很隐蔽:弹窗还开着(界面侧是不限时的),
|
||||
# 但内核 60 秒就把这次调用判成"工具执行超时"、把结果丢掉了 ——
|
||||
# 用户五分钟后点的那个选项**根本回不到模型手里**,模型已经开始自己编了。
|
||||
# 见 android/kernel/tools_runtime.py 的 _waits_for_user。
|
||||
WAIT_FOR_USER = True
|
||||
|
||||
# "我这个 timeout 参数如果模型没给,就用设置里 askUser 那一项的值"
|
||||
TIMEOUT_KEYS = {'timeout': 'askUser'}
|
||||
|
||||
TOOL = {
|
||||
"name": "ask_user",
|
||||
"description": (
|
||||
|
||||
@@ -29,10 +29,20 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
from _ui_bridge import call_device, conversation_id # noqa: E402
|
||||
|
||||
# wait=true 时的等待秒数上限 / 下限。0 = 不限时(默认,见 run)。
|
||||
# wait=true 时的等待秒数上限 / 下限。默认 0 = 不限时(见 run)。
|
||||
MIN_TIMEOUT_S = 5.0
|
||||
MAX_TIMEOUT_S = 3600.0
|
||||
|
||||
# ★★ 告诉内核:这个工具在 wait=true 时**会停下来等用户**,别拿工具执行超时卡它
|
||||
# (wait=false 时它立刻就返回,不受影响)。
|
||||
# 不声明的后果和 ask_user 那边一样:界面还开着,模型却已经收到"工具超时"。
|
||||
# 见 android/kernel/tools_runtime.py 的 _waits_for_user。
|
||||
WAIT_FOR_USER = True
|
||||
|
||||
# "我这个 timeout 参数如果模型没给,就用设置里 waitUi 那一项的值"
|
||||
# (内核调用前注入,见 tools_runtime._with_default_timeouts)
|
||||
TIMEOUT_KEYS = {'timeout': 'waitUi'}
|
||||
|
||||
TOOL = {
|
||||
"name": "show_ui",
|
||||
"description": (
|
||||
|
||||