Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1a9229aa75 | |||
| e11e178810 | |||
| 6bcb5d72f8 | |||
| b693f22f61 | |||
| 6e5ea9d3b6 | |||
| 08eecb9e0a | |||
| 182c0005a4 |
@@ -1,4 +1,4 @@
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
# 豆包复刻 · 原生安卓 + 内置 Termux(附 Web / Windows 版)
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
@@ -435,6 +435,11 @@ python scripts/probe-degraded.py # 幻觉检测 + 不支持 function calli
|
||||
> 而那时整个 App 不可用。`scripts/build-apk.mjs` 里加了这道闸,
|
||||
> 但它拦的是"打包",不是"你刚改的那一行"。
|
||||
|
||||
**全部界面和入口在哪**:[`docs/界面总览.md`](docs/界面总览.md) ——
|
||||
把 App 里所有界面画成树(含"每个界面从哪进"),而且
|
||||
`python scripts/audit-ui-tree.py` 会拿它**和源码对拍**:
|
||||
代码里有、文档没画的界面会直接报错("界面做好了但没入口"这类问题光靠人查必然会漏)。
|
||||
|
||||
**还没做的**:Node 端(Web / exe)的智能体系统仍是旧的那套 ——
|
||||
按仓库约定"引擎改了另一端必须跟上",这是欠账。
|
||||
|
||||
|
||||
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 252
|
||||
versionName = "2.0.52"
|
||||
versionCode = 255
|
||||
versionName = "2.0.55"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -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 { "云端合成失败" }
|
||||
|
||||
@@ -263,7 +263,7 @@ fun AppRoot(
|
||||
worldMode = true,
|
||||
loading = false,
|
||||
hint = "",
|
||||
onSetEmotion = {},
|
||||
onSetEmotion = { _, _ -> },
|
||||
onAdd = { _, _ -> },
|
||||
onUpdate = { _, _, _ -> },
|
||||
// 删是可以的:限权只约束 AI,用户有权清掉任何人写的
|
||||
@@ -318,7 +318,7 @@ fun AppRoot(
|
||||
agentNames = vm.agents.associate { it.id to it.name },
|
||||
loading = vm.memoryLoading,
|
||||
hint = vm.memoryHint,
|
||||
onSetEmotion = { vm.setEmotion(it) },
|
||||
onSetEmotion = { preset, text -> vm.setEmotion(preset, text) },
|
||||
onAdd = { t, c -> vm.addMemory(t, c) },
|
||||
onUpdate = { id, t, c -> vm.updateMemory(id, t, c) },
|
||||
onDelete = { vm.deleteMemory(it) },
|
||||
|
||||
@@ -531,12 +531,17 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
fun setEmotion(text: String) {
|
||||
fun setEmotion(preset: String, text: String) {
|
||||
val id = memoryAgentId
|
||||
if (id.isBlank()) return
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.setEmotion(id, text) } }
|
||||
runCatching { withContext(Dispatchers.IO) { client.setEmotion(id, preset, text) } }
|
||||
refreshMemories()
|
||||
// ★★ 还必须刷新**全局状态** —— 顶栏的情绪标签、聊天页的**死亡禁言**
|
||||
// 读的都是 `state.emotions`,只刷记忆页的话界面上什么都看不出来。
|
||||
// (这个漏是真机验证抓到的:把智能体改成「死亡」之后回聊天页,
|
||||
// 输入条照样能用。)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -182,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() }
|
||||
}
|
||||
@@ -367,7 +373,42 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
)
|
||||
}
|
||||
}
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
// ★★ 死亡禁言(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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,11 +478,15 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
// ★ 当前情绪(复查报告 2.6):AI 自己能改情绪,改了却看不出来,
|
||||
// 这个功能就只是个看不见的字段。放在名字旁边、字号小一半 ——
|
||||
// 它是个状态注脚,不该抢名字的注意力。
|
||||
val emo = vm.state.emotions[vm.activeAgent?.id ?: ""].orEmpty()
|
||||
if (emo.isNotBlank()) {
|
||||
// ★ v1.2:这里显示的是 **preset(五档)**,不是那句自由文本 ——
|
||||
// 自由文本是角色的内心独白,摆在顶栏上不合适;preset 才是
|
||||
// "一眼看出他现在什么情绪"那个粒度。点开记忆页能看到全文。
|
||||
val emo = vm.state.emotions[vm.activeAgent?.id ?: ""]
|
||||
val emoLabel = emo?.preset.orEmpty()
|
||||
if (emoLabel.isNotBlank() && emoLabel != "平常") {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
emo.take(8),
|
||||
emoLabel.take(8),
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
maxLines = 1,
|
||||
|
||||
@@ -35,6 +35,8 @@ import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.MemoryItem
|
||||
import com.doubao.lynxclone.data.PRESETS
|
||||
import com.doubao.lynxclone.data.PRESET_DEAD
|
||||
import com.doubao.lynxclone.data.MemorySpace
|
||||
|
||||
/*
|
||||
@@ -77,7 +79,8 @@ fun MemoryScreen(
|
||||
worldMode: Boolean = false,
|
||||
loading: Boolean,
|
||||
hint: String,
|
||||
onSetEmotion: (String) -> Unit,
|
||||
/** 保存情绪:preset(五档)+ text(自由一句) */
|
||||
onSetEmotion: (String, String) -> Unit,
|
||||
onAdd: (String, String) -> Unit,
|
||||
onUpdate: (String, String?, String?) -> Unit,
|
||||
onDelete: (String) -> Unit,
|
||||
@@ -96,7 +99,9 @@ fun MemoryScreen(
|
||||
) {
|
||||
var editing by remember { mutableStateOf<MemoryItem?>(null) }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
var emotionDraft by remember(space?.emotion) { mutableStateOf(space?.emotion ?: "") }
|
||||
/** 情绪的双字段草稿(v1.2)。preset 是五档之一、text 是自由文本 */
|
||||
var emotionPreset by remember(space?.emotion) { mutableStateOf(space?.emotion?.preset ?: "平常") }
|
||||
var emotionText by remember(space?.emotion) { mutableStateOf(space?.emotion?.text ?: "") }
|
||||
// 一次确认,正好是弹窗该用的地方(AGENTS.md 那张表)
|
||||
var confirmSummarize by remember { mutableStateOf(false) }
|
||||
/** 调注入窗口(输入条数,0 = 不限) */
|
||||
@@ -198,13 +203,19 @@ fun MemoryScreen(
|
||||
buildString {
|
||||
append("窗口:")
|
||||
append(if (win <= 0) "不限(全部都带)" else "最近 $win 条")
|
||||
if (space.pinnedCount > 0) {
|
||||
append(";其中 ${space.pinnedCount} 条置顶的永远带,不受窗口限制")
|
||||
}
|
||||
append("。")
|
||||
// ★ "能置顶几条"必须在界面上说清:不说的话用户会默认
|
||||
// "只能有一条"(很自然的假设),而实际上标几条都行,
|
||||
// 而且它们**永远**带进去、不受窗口限制。
|
||||
append(
|
||||
if (space.pinnedCount > 0) "已置顶 ${space.pinnedCount} 条"
|
||||
else "可以置顶任意多条"
|
||||
)
|
||||
append(",置顶的永远带、不受窗口限制")
|
||||
if (injected < total) {
|
||||
append("。没带进去的没丢,AI 用 memory_search 还能搜到。")
|
||||
append(";没带进去的没丢,AI 用 memory_search 还能搜到")
|
||||
}
|
||||
append(" 点这里调 ›")
|
||||
append("。 点这里调 ›")
|
||||
},
|
||||
fontSize = 10.sp,
|
||||
lineHeight = 15.sp,
|
||||
@@ -302,24 +313,67 @@ fun MemoryScreen(
|
||||
.padding(12.dp),
|
||||
) {
|
||||
Text(
|
||||
"AI 自己能改(emotion_set),你也可以在这里改。它每次对话都会被带进提示词。",
|
||||
"preset 决定系统行为(立绘换哪张、能不能对话、同伴看到什么脸色);" +
|
||||
"下面那句话只是扮演质感。AI 自己能改,你也可以在这里改。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// ★ 五档选择器,顺序就是需求里的顺序(喜 怒 哀 平常 死亡)。
|
||||
// 「死亡」单独标红 —— 它是**唯一有系统后果**的档位。
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
for (p in PRESETS) {
|
||||
val on = p == emotionPreset
|
||||
val danger = p == PRESET_DEAD
|
||||
Text(
|
||||
p,
|
||||
fontSize = 13.sp,
|
||||
color = when {
|
||||
on -> Color.White
|
||||
danger -> Color(0xFFB3261E)
|
||||
else -> doubaoText()
|
||||
},
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(
|
||||
when {
|
||||
on && danger -> Color(0xFFB3261E)
|
||||
on -> Doubao.Blue
|
||||
else -> doubaoCard()
|
||||
},
|
||||
)
|
||||
.clickable { emotionPreset = p }
|
||||
.padding(horizontal = 14.dp, vertical = 7.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
// 死亡是唯一需要额外解释的档位:它会让这个智能体**不能对话**。
|
||||
// 不说清楚的话,用户点了「死亡」然后发现消息发不出去,会以为坏了。
|
||||
if (emotionPreset == PRESET_DEAD) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"「死亡」状态下这个智能体不能对话(输入条会禁用)。" +
|
||||
"把它改回其他档就是复活 —— 这是你的权力,AI 自己不能从死亡改活。",
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = emotionDraft,
|
||||
onValueChange = { emotionDraft = it },
|
||||
placeholder = { Text("比如:刚被夸了,有点得意", fontSize = 13.sp) },
|
||||
value = emotionText,
|
||||
onValueChange = { emotionText = it },
|
||||
placeholder = { Text("他此刻在想什么(自由一句,比如:强作镇定,手心全是汗)", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
|
||||
TextButton(
|
||||
onClick = { onSetEmotion(emotionDraft.trim()) },
|
||||
enabled = emotionDraft.trim() != (space?.emotion ?: ""),
|
||||
onClick = { onSetEmotion(emotionPreset, emotionText.trim()) },
|
||||
enabled = emotionPreset != (space?.emotion?.preset ?: "平常") ||
|
||||
emotionText.trim() != (space?.emotion?.text ?: ""),
|
||||
) { Text("保存情绪", fontSize = 13.sp) }
|
||||
}
|
||||
}
|
||||
@@ -386,8 +440,10 @@ fun MemoryScreen(
|
||||
Column {
|
||||
Text(
|
||||
"每轮最多把多少条记忆放进提示词。\n\n" +
|
||||
"置顶的永远带,不受这个数限制;其余按时间取最近的。\n" +
|
||||
"没带进去的不会丢 —— AI 用 memory_search 还能搜到。\n\n" +
|
||||
"置顶的永远带,不受这个数限制 —— 而且可以置顶任意多条" +
|
||||
"(标几条都行,它们一定都在)。\n" +
|
||||
"其余按时间取最近的。没带进去的不会丢," +
|
||||
"AI 用 memory_search 还能搜到。\n\n" +
|
||||
"填 0 = 不限(全量注入)。记忆攒到几百条时提示词会很贵," +
|
||||
"而且早期的会挤掉最近的对话上下文。",
|
||||
fontSize = 12.sp,
|
||||
@@ -426,10 +482,10 @@ fun MemoryScreen(
|
||||
buildString {
|
||||
append("这会把现在这 ${space?.memories?.size ?: 0} 条零散、重复的记忆")
|
||||
append("压缩成更少、更完整的几条。\n\n")
|
||||
append("· 标了「必须保留」的(现在有 $pinnedCount 条)**原样不动**,不参与合并\n")
|
||||
append("· 它会**只做合并改写**,不许编造新的事实\n")
|
||||
append("· 标了「置顶」的(现在有 $pinnedCount 条)原样不动,不参与合并\n")
|
||||
append("· 它只做合并改写,不许编造新的事实\n")
|
||||
append("· 这是一次真实的模型调用,会花 Token(但不受额度限制)\n\n")
|
||||
append("想保住哪几条,先取消对话框去标上「必须保留」。")
|
||||
append("想保住哪几条,先取消对话框去标上「置顶」。")
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
@@ -268,7 +268,7 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
||||
'activeScope': scope, # 当前生效的是哪个空间
|
||||
'worldviewId': agent.get('worldviewId') or '',
|
||||
'memories': agentdb.memory_list(own),
|
||||
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||
'emotion': agentdb.emotion_state(agent.get('id') or ''),
|
||||
'suggestion': '',
|
||||
}
|
||||
items = agentdb.memory_list(scope)
|
||||
@@ -294,7 +294,7 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
||||
'window': window,
|
||||
'pinnedCount': pinned_count,
|
||||
'injected': injected,
|
||||
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||
'emotion': agentdb.emotion_state(agent.get('id') or ''),
|
||||
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
||||
}
|
||||
|
||||
@@ -398,12 +398,19 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
err(404, '没有这个智能体')
|
||||
return True
|
||||
if method == 'GET':
|
||||
handler.send_json(200, {'ok': True, 'emotion': agentdb.emotion_get(agent['id'])})
|
||||
handler.send_json(200, {'ok': True, 'emotion': agentdb.emotion_state(agent['id'])})
|
||||
return True
|
||||
if method in ('PUT', 'POST'):
|
||||
emo = str(body().get('emotion') or '')
|
||||
agentdb.emotion_set(agent['id'], emo[:200])
|
||||
handler.send_json(200, {'ok': True, 'emotion': emo[:200]})
|
||||
b = body()
|
||||
# ★ 这条路由是**界面**在用的(记忆页的情绪区)——
|
||||
# 所以它**允许**把「死亡」改回别的值:那是需求 3.5 说的
|
||||
# "用户手动改回是兜底主权"。禁止自愈只发生在 AI 的工具通道上。
|
||||
nxt = agentdb.emotion_set(
|
||||
agent['id'],
|
||||
preset=str(b.get('preset') or '').strip() or None,
|
||||
text=None if b.get('text') is None else str(b.get('text') or '')[:200],
|
||||
)
|
||||
handler.send_json(200, {'ok': True, 'emotion': nxt})
|
||||
return True
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'skills':
|
||||
@@ -553,7 +560,7 @@ def _memory_export(agent: dict) -> dict:
|
||||
'version': 1,
|
||||
'name': agent.get('name') or '',
|
||||
'smartMemory': items,
|
||||
'Emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||
'Emotion': agentdb.emotion_state(agent.get('id') or ''),
|
||||
}
|
||||
|
||||
|
||||
@@ -606,7 +613,7 @@ def _memory_import(handler, agent: dict, body: dict, err) -> bool:
|
||||
emotion_kept = True
|
||||
if mode == 'replace' and payload.get('Emotion') is not None:
|
||||
# 覆盖模式连情绪一起换(需求 3.4);合并模式保留当前值
|
||||
agentdb.emotion_set(agent.get('id') or '', str(payload.get('Emotion') or ''))
|
||||
agentdb.emotion_set(agent.get('id') or '', **agentdb.emotion_from_export(payload.get('Emotion')))
|
||||
emotion_kept = False
|
||||
|
||||
return _send_json_ok(handler, {
|
||||
|
||||
@@ -94,11 +94,32 @@ def memory_scope(agent: dict) -> str:
|
||||
|
||||
|
||||
def build_emotion(agent: dict) -> str:
|
||||
"""`<emotion>` 段:自己的情绪(**始终私有**,绑了世界观也不共享 —— 需求 3.5)"""
|
||||
"""
|
||||
`<emotion>` 段:自己的情绪(**始终私有**,绑了世界观也不共享 —— 需求 3.5)。
|
||||
|
||||
v1.2 双字段,两行都带(附录 C 的模板就是这样):
|
||||
|
||||
preset: 怒
|
||||
text: 这背叛让我无法原谅
|
||||
|
||||
`preset` 是给它**自己**用的(它要据此调整行为),`text` 是扮演质感。
|
||||
两个都注入 —— 这是唯一一处两者都出现的地方(给同伴的只有 preset)。
|
||||
|
||||
★ 「平常 + 没写文本」时整段省掉:不然每个没情绪的智能体都白带一段
|
||||
没有信息量的 `<emotion>`,还占 token。空段整段删除是附录 C 的规矩。
|
||||
"""
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
if not agent_id:
|
||||
return ''
|
||||
return (_safe(lambda: agentdb.emotion_get(agent_id), '') or '').strip()
|
||||
st = _safe(lambda: agentdb.emotion_state(agent_id), None) or {}
|
||||
preset = (st.get('preset') or '').strip()
|
||||
text = (st.get('text') or '').strip()
|
||||
if not text and preset in ('', agentdb.PRESET_DEFAULT):
|
||||
return ''
|
||||
lines = [f'preset: {preset or agentdb.PRESET_DEFAULT}']
|
||||
if text:
|
||||
lines.append(f'text: {text}')
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def build_memory(agent: dict) -> str:
|
||||
@@ -239,8 +260,11 @@ def build_peer_emotions(agent: dict) -> str:
|
||||
# ★ `by_id.items()` 给的是 (id, **整个 agent 字典**),不是 (id, 名字)——
|
||||
# 直接 f'{name}-{emo}' 会把 agent 的 JSON 拼进提示词(踩过)
|
||||
name = one.get('name') or '某人'
|
||||
# ★ v1.2:这里给的是 **preset(五档)不是 text**。
|
||||
# text 是那个角色的内心独白,读给别的角色听等于扒开他的脑子;
|
||||
# preset 才是"看得出来他现在什么脸色"这个粒度。
|
||||
emo = emo_by_id.get(aid) or ''
|
||||
parts.append(f'{name}-{emo}' if emo else f'{name}(没说自己在想什么)')
|
||||
parts.append(f'{name}-{emo}' if emo else f'{name}(看不出什么情绪)')
|
||||
return ';'.join(parts)
|
||||
|
||||
|
||||
|
||||
@@ -268,29 +268,62 @@ def memory_suggest_summary(args: dict) -> dict:
|
||||
EMOTION_SET = {
|
||||
'name': 'emotion_set',
|
||||
'description': (
|
||||
'更新**你自己**当前的情绪状态(一小段话,比如"刚被夸了,有点得意")。'
|
||||
'它会跟着你到下一次对话,也会显示在系统提示词里。'
|
||||
'更新**你自己**当前的情绪状态。两个字段都要给:\n'
|
||||
'· preset:五档之一 —— 喜 / 怒 / 哀 / 平常 / 死亡。它决定系统行为'
|
||||
'(立绘换哪张、同伴看到你什么脸色、死亡时能不能继续说话)。\n'
|
||||
'· text:一句自由描述,比如"刚被夸了,有点得意"。这只是扮演质感。\n'
|
||||
'情绪要跟着对话内容自然变化,不用每轮都改。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'emotion': {'type': 'string', 'description': '你现在的情绪'},
|
||||
'preset': {
|
||||
'type': 'string',
|
||||
'enum': list(agentdb.PRESETS),
|
||||
'description': '五档情绪之一',
|
||||
},
|
||||
'text': {'type': 'string', 'description': '一句自由描述(可选)'},
|
||||
},
|
||||
'required': ['emotion'],
|
||||
'required': ['preset'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def emotion_set(args: dict) -> dict:
|
||||
"""
|
||||
写自己的情绪(需求 3.5 双字段)。
|
||||
|
||||
★★ **禁止把自己从「死亡」改活**(需求 3.5 明文)。
|
||||
|
||||
为什么:死亡是"这个角色没了"。能自己复活的话死亡就没有重量 ——
|
||||
用户会看到 AI 上一句刚咽气、下一句又活蹦乱跳,整个系统的可信度就没了。
|
||||
|
||||
复活只有两条**别的**通道,都不经过这里:
|
||||
· 用户手动改(兜底主权,在记忆页的情绪区)
|
||||
· 状态脚本改(定时复活 / 解药剧情,见 §3.11 —— 那条路走沙箱,不走工具)
|
||||
"""
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
emo = str(args.get('emotion') or '').strip()
|
||||
if not emo:
|
||||
raise ValueError('emotion 不能为空(不想保留情绪的话直接别调用这个工具)')
|
||||
agentdb.emotion_set(agent.get('id') or '', emo[:200])
|
||||
return {'emotion': emo[:200], 'note': '已更新你自己的情绪。'}
|
||||
agent_id = agent.get('id') or ''
|
||||
preset = str(args.get('preset') or '').strip()
|
||||
text = str(args.get('text') or '').strip()
|
||||
if preset not in agentdb.PRESETS:
|
||||
raise ValueError(
|
||||
f'preset 只能是这五个之一:{"、".join(agentdb.PRESETS)}(收到的是「{preset}」)'
|
||||
)
|
||||
cur = agentdb.emotion_state(agent_id)
|
||||
if cur.get('preset') == agentdb.PRESET_DEAD and preset != agentdb.PRESET_DEAD:
|
||||
raise ValueError(
|
||||
'你已经是「死亡」状态,**不能自己复活**。'
|
||||
'复活只能由用户手动操作,或者由世界观里的状态脚本触发(比如定时复活、解药剧情)。'
|
||||
)
|
||||
nxt = agentdb.emotion_set(agent_id, preset=preset, text=text or None)
|
||||
return {
|
||||
'preset': nxt['preset'],
|
||||
'text': nxt['text'],
|
||||
'note': '已更新你自己的情绪。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
@@ -93,7 +93,13 @@ CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS emotions (
|
||||
agent_id TEXT PRIMARY KEY,
|
||||
emotion TEXT NOT NULL DEFAULT '',
|
||||
-- v1.2(需求 3.5)把情绪拆成双字段:
|
||||
-- preset 五档枚举,**驱动系统行为**(立绘切换、死亡规则)
|
||||
-- text AI 自写的自由文本,只管**扮演质感**
|
||||
-- 老库里的 `emotion` 单列由 _migrate() 搬进 text,列本身留着不动
|
||||
-- (SQLite 删列要重建表,不值当;留着也永远不会有人再读它)
|
||||
preset TEXT NOT NULL DEFAULT '平常',
|
||||
text TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
@@ -126,10 +132,48 @@ def init() -> None:
|
||||
return
|
||||
conn = _connect()
|
||||
conn.executescript(SCHEMA)
|
||||
_migrate(conn)
|
||||
conn.commit()
|
||||
_init_done = True
|
||||
|
||||
|
||||
def _migrate(conn) -> None:
|
||||
"""
|
||||
老库的结构升级(幂等,每次 init 都跑一遍,没得升就什么都不做)。
|
||||
|
||||
★ 为什么要单独一个函数、而不是只靠 `CREATE TABLE IF NOT EXISTS`:
|
||||
那个只在**表不存在**时建表。表已经存在的话,加列它一概不管 ——
|
||||
于是老用户的库里 `emotions` 表永远只有 `emotion` 一列,
|
||||
而新代码读的是 `preset` / `text`,一读就是 `no such column`。
|
||||
|
||||
v1.2 这一条:`emotion`(单字段自由文本)→ `preset` + `text`。
|
||||
老的那列**留着不动**(SQLite 删列要重建整张表,不值当),
|
||||
它的内容搬进 `text` —— 因为老字段本来存的就是自由文本。
|
||||
"""
|
||||
cols = {r['name'] for r in conn.execute('PRAGMA table_info(emotions)').fetchall()}
|
||||
if 'preset' not in cols:
|
||||
conn.execute("ALTER TABLE emotions ADD COLUMN preset TEXT NOT NULL DEFAULT '平常'")
|
||||
if 'text' not in cols:
|
||||
conn.execute("ALTER TABLE emotions ADD COLUMN text TEXT NOT NULL DEFAULT ''")
|
||||
if 'emotion' in cols:
|
||||
# 老数据的自由文本 → text;preset 全是默认的「平常」
|
||||
conn.execute('UPDATE emotions SET text = emotion')
|
||||
|
||||
|
||||
#: v1.2 情绪的五档枚举(需求 3.5)。
|
||||
#:
|
||||
#: `preset` 和 `text` 的分工是这个设计的关键:
|
||||
#: · preset **驱动系统行为** —— 立绘切哪张、能不能对话(死亡)、
|
||||
#: 以及注入给同世界观伙伴的那个"脸色"
|
||||
#: · text 只是 **AI 自写的自由文本**,管扮演质感
|
||||
#:
|
||||
#: 合成一个字段做不到:系统要按 preset 分支,而自然语言没法当分支条件;
|
||||
#: 只用 preset 又太干,"怒"和"悲愤交加但强作镇定"是两回事。
|
||||
PRESETS = ('喜', '怒', '哀', '平常', '死亡')
|
||||
PRESET_DEFAULT = '平常'
|
||||
PRESET_DEAD = '死亡'
|
||||
|
||||
|
||||
def reset_init() -> None:
|
||||
"""测试用:换过数据目录之后强制重新建表"""
|
||||
global _init_done
|
||||
@@ -324,39 +368,106 @@ def memory_titles(scope: str) -> list:
|
||||
# 情绪(始终按智能体私有,即使绑定了世界观 —— 需求 3.5)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def emotion_get(agent_id: str) -> str:
|
||||
def emotion_state(agent_id: str) -> dict:
|
||||
"""
|
||||
读一个智能体的情绪 → `{'preset': ..., 'text': ...}`(需求 3.5 双字段)。
|
||||
|
||||
★ 没记过情绪时返回默认值(「平常」+ 空文本),而不是空 —— 调用方
|
||||
(注入模板、界面)就不用各自处理 None 了。
|
||||
"""
|
||||
init()
|
||||
row = _connect().execute(
|
||||
'SELECT emotion FROM emotions WHERE agent_id = ?', (agent_id or '',),
|
||||
'SELECT preset, text FROM emotions WHERE agent_id = ?', (agent_id or '',),
|
||||
).fetchone()
|
||||
return row['emotion'] if row else ''
|
||||
if not row:
|
||||
return {'preset': PRESET_DEFAULT, 'text': ''}
|
||||
preset = (row['preset'] or '').strip() or PRESET_DEFAULT
|
||||
return {'preset': preset, 'text': (row['text'] or '')}
|
||||
|
||||
|
||||
def emotion_set(agent_id: str, emotion: str) -> str:
|
||||
def emotion_set(agent_id: str, preset: str = None, text: str = None) -> dict:
|
||||
"""
|
||||
写情绪(双字段,**只写传进来的那些**)。
|
||||
|
||||
★★ 这里**不做死亡校验** —— 校验放在 AI 的通道上
|
||||
(`agent_tools.emotion_set`),不在数据层。
|
||||
|
||||
为什么:需求 3.5 说"用户手动改回是兜底主权"。数据层要是拦了,
|
||||
**界面就没办法复活了** —— 那是把用户的权力一起拦掉了。
|
||||
权限的边界在"谁在改"(AI / 用户),不在"改什么",所以它在通道上。
|
||||
"""
|
||||
init()
|
||||
cur = emotion_state(agent_id)
|
||||
nxt = {
|
||||
'preset': (preset or cur['preset'] or PRESET_DEFAULT),
|
||||
'text': cur['text'] if text is None else (text or ''),
|
||||
}
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'INSERT INTO emotions (agent_id, emotion, updated_at) VALUES (?, ?, ?) '
|
||||
'ON CONFLICT(agent_id) DO UPDATE SET emotion = excluded.emotion, updated_at = excluded.updated_at',
|
||||
(agent_id or '', emotion or '', now_iso()),
|
||||
'INSERT INTO emotions (agent_id, preset, text, updated_at) VALUES (?, ?, ?, ?) '
|
||||
'ON CONFLICT(agent_id) DO UPDATE SET preset = excluded.preset, '
|
||||
'text = excluded.text, updated_at = excluded.updated_at',
|
||||
(agent_id or '', nxt['preset'], nxt['text'], now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
return emotion or ''
|
||||
return nxt
|
||||
|
||||
|
||||
def is_dead(agent_id: str) -> bool:
|
||||
"""这个智能体是不是「死亡」状态(需求 3.5:死亡的不能对话)"""
|
||||
return emotion_state(agent_id)['preset'] == PRESET_DEAD
|
||||
|
||||
|
||||
def emotion_from_export(raw) -> dict:
|
||||
"""
|
||||
解析记忆/情绪导出文件里的 `Emotion` 字段,返回**可以直接展开给
|
||||
`emotion_set(**...)` 的关键字参数**。
|
||||
|
||||
★★ 两种格式都得认:
|
||||
|
||||
· **v1.1**:`"Emotion": "刚被夸了,有点得意"` —— 一个字符串
|
||||
· **v1.2**:`"Emotion": {"preset": "喜", "text": "……"}` —— 一个对象
|
||||
|
||||
用户手里可能存着 v1.1 导出的文件。只认新格式的话,他导入时会
|
||||
**在情绪这一步直接抛异常**,而前半截记忆已经写进去了 ——
|
||||
留下一个"记忆进来了、情绪没进来"的半成品,最难查。
|
||||
|
||||
`None` 表示"这一项不要动"(`emotion_set` 的语义:只写传进来的)。
|
||||
"""
|
||||
if isinstance(raw, dict):
|
||||
preset = str(raw.get('preset') or '').strip() or None
|
||||
# 老库里 preset 可能不在五档里(用户手改过文件)—— 夹一下,
|
||||
# 不认识就当没给,免得把界面搞出一个选不中的档位
|
||||
if preset and preset not in PRESETS:
|
||||
preset = None
|
||||
text = raw.get('text')
|
||||
return {'preset': preset, 'text': None if text is None else str(text)}
|
||||
|
||||
if isinstance(raw, str):
|
||||
# v1.1 的单字段:它本来存的就是自由文本 → 全给 text,preset 不动
|
||||
return {'preset': None, 'text': raw}
|
||||
|
||||
return {'preset': None, 'text': None}
|
||||
|
||||
|
||||
def peer_emotions(worldview_id: str, exclude_agent: str, agent_ids: list) -> list:
|
||||
"""
|
||||
同世界观、**其他**智能体的「名字 + 情绪」(情绪感知开关打开时才注入)。
|
||||
同世界观、**其他**智能体的「id + preset」。
|
||||
|
||||
★ v1.2 起注入的是 **preset(五档)而不是自由文本**(需求 3.5 原文:
|
||||
"开启后注入同世界观其他智能体的「名字 + preset」")。
|
||||
原因:`text` 是那个角色的**内心独白**,读给别的角色听等于扒开他的脑子;
|
||||
preset 是"看得出来他现在什么脸色"——那才是别人该看到的信息粒度。
|
||||
|
||||
[agent_ids] 是绑定了这个世界观的全部智能体 id(由调用方从 agents.json 里挑,
|
||||
这里不碰 JSON —— 数据层只管数据库里有什么)。返回 [(agent_id, emotion)]。
|
||||
这里不碰 JSON —— 数据层只管数据库里有什么)。返回 [(agent_id, preset)]。
|
||||
"""
|
||||
init()
|
||||
out = []
|
||||
for aid in agent_ids or []:
|
||||
if not aid or aid == exclude_agent:
|
||||
continue
|
||||
out.append((aid, emotion_get(aid)))
|
||||
out.append((aid, emotion_state(aid)['preset']))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -582,12 +582,16 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
'mcpConfig': mcp_client.read_mcp_config(),
|
||||
'conversations': store.list_conversations(),
|
||||
'agents': store.list_agents(),
|
||||
# 每个智能体当前的情绪(复查报告 2.6)。
|
||||
# 每个智能体当前的情绪(v1.2 双字段)。
|
||||
# ★ 情绪原来只在提示词里生效 —— AI 用 emotion_set 改了情绪,
|
||||
# 用户完全无感知,这个功能就成了一个看不见的字段。
|
||||
# `preset` 驱动界面(立绘、死亡禁言、成员标签),
|
||||
# `text` 是扮演质感。
|
||||
# **有情绪才带上**:没记过的(默认「平常」+ 空文本)不占位。
|
||||
'emotions': {
|
||||
a.get('id'): e for a in store.list_agents()
|
||||
if (e := (agentdb.emotion_get(a.get('id') or '') or '').strip())
|
||||
a.get('id'): st for a in store.list_agents()
|
||||
if (st := agentdb.emotion_state(a.get('id') or ''))
|
||||
and (st.get('text') or st.get('preset') != agentdb.PRESET_DEFAULT)
|
||||
},
|
||||
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
||||
# 都不大(几个到几十个),一次带给界面省得进页面再拉一次
|
||||
@@ -1688,6 +1692,23 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
emit({'type': 'rebased', 'conversationId': conversation_id,
|
||||
'reason': 'agent_changed'})
|
||||
|
||||
# ★★ 死亡的智能体**不能对话**(需求 3.5)。
|
||||
#
|
||||
# 判定放在**发起前**,和 Token 限额同一层:不是在生成时才拦
|
||||
# (那时候已经花了钱),而是根本不让这一轮开始。
|
||||
#
|
||||
# 复活只有两条通道,都不在这里:
|
||||
# · 用户手动改(界面上的情绪区,兜底主权)
|
||||
# · 状态脚本改(定时复活/解药剧情,走沙箱)
|
||||
if agent_id and agentdb.is_dead(agent_id):
|
||||
emit({
|
||||
'type': 'error',
|
||||
'code': 'agent_dead',
|
||||
'message': f'「{(agent or {}).get("name") or "这个智能体"}」已经死亡,无法对话。',
|
||||
'hint': '在「记忆 → 情绪」里把它改回其他状态就能复活。',
|
||||
})
|
||||
return
|
||||
|
||||
# ★★ Token 限额:**发起前**拦(需求 3.1)。
|
||||
#
|
||||
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
||||
|
||||
189
android/kernel/rule_sandbox.py
Normal file
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'
|
||||
'只导入你信得过的来源。'
|
||||
)
|
||||
148
docs/v1.2实施计划.md
Normal file
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**(除非它真的死了)。
|
||||
268
docs/界面总览.md
Normal file
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()` 谁都不调,就意味着那个界面做好了但进不去
|
||||
(记忆管理就是这么漏的)。
|
||||
211
scripts/audit-ui-tree.py
Normal file
211
scripts/audit-ui-tree.py
Normal file
@@ -0,0 +1,211 @@
|
||||
"""校验 `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 新增的三个界面(还没写代码,见 PLANNED)----
|
||||
"群成员": ["GroupMembersScreen"],
|
||||
"规则包编辑": ["RulePackScreen"],
|
||||
"状态数值": ["StatsScreen"],
|
||||
}
|
||||
|
||||
#: 这些 `*Screen` 组件**不是**独立界面,不进文档树
|
||||
SKELETON = {
|
||||
"FullScreen", # 全屏界面的骨架(顶栏 + 内容),被所有页面复用
|
||||
}
|
||||
|
||||
#: **计划中**的界面:v1.2 文档(§6)要求"先改界面总览再写代码",
|
||||
#: 所以文档里会先出现一些代码里还没有的界面。这些不算错误,
|
||||
#: 但脚本会把它们**列出来**(每次跑都提醒"还有几个没落地")——
|
||||
#: 免得计划悄悄烂在文档里。
|
||||
#:
|
||||
#: 落地之后**必须从这里删掉**,否则它就成了一张永久的免罪符。
|
||||
PLANNED = {
|
||||
"群成员": "v1.2 §6.2",
|
||||
"规则包编辑": "v1.2 §6.2",
|
||||
"状态数值": "v1.2 §6.2",
|
||||
}
|
||||
|
||||
|
||||
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())
|
||||
@@ -150,8 +150,9 @@ def main():
|
||||
check("memory_add 返回 id", bool(r.get("id")))
|
||||
r = agent_tools.memory_search({"keyword": "猫"})
|
||||
check("memory_search 找到刚记的", r["count"] >= 1, str(r["count"]))
|
||||
agent_tools.emotion_set({"emotion": "刚被夸了,有点得意"})
|
||||
check("情绪写进去了", "得意" in agentdb.emotion_get(a1["id"]))
|
||||
agent_tools.emotion_set({"preset": "喜", "text": "刚被夸了,有点得意"})
|
||||
check("情绪写进去了(双字段)", "得意" in agentdb.emotion_state(a1["id"])["text"])
|
||||
check("preset 也写进去了", agentdb.emotion_state(a1["id"])["preset"] == "喜")
|
||||
agentdb.token_add(a1["id"], "doubao-pro", 1200, 800)
|
||||
agentdb.token_add(a1["id"], "doubao-pro", 300, 100)
|
||||
agentdb.token_add(a1["id"], "deepseek-r1", 500, 200)
|
||||
@@ -213,7 +214,7 @@ def main():
|
||||
# ---------------------------------------------------------------- 8
|
||||
section("8. system prompt 注入(附录 C)")
|
||||
tools_runtime.push_context(agentId=a1["id"], conversationId="c_test")
|
||||
agentdb.emotion_set(a2["id"], "有点烦")
|
||||
agentdb.emotion_set(a2["id"], preset="哀", text="有点烦")
|
||||
store.update_agent(a2["id"], {"emotionEnabled": True})
|
||||
# ★ a1 在这一节之前已经绑了世界观 → 它的记忆空间是**共享**的那个,
|
||||
# 所以验证"记忆进提示词"要往当前 scope 里写(这正是绑定世界观的正确行为)
|
||||
@@ -244,7 +245,9 @@ def main():
|
||||
check("名单里也没有 agent 的 JSON", "'builtin'" not in prompt and "worldviewId'" not in prompt)
|
||||
store.update_agent(a1["id"], {"emotionEnabled": True})
|
||||
prompt2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a1["id"]))
|
||||
check("开了感知后有同伴情绪", "<peer_emotions>" in prompt2 and "仙辰-有点烦" in prompt2, prompt2[-200:])
|
||||
check("开了感知后看到的是**同伴的 preset**(不是他的内心独白)",
|
||||
"<peer_emotions>" in prompt2 and "仙辰-哀" in prompt2, prompt2[-200:])
|
||||
check("**同伴的 text 不外泄**", "有点烦" not in prompt2.split("<peer_emotions>")[-1], prompt2[-200:])
|
||||
# 空段要整段删掉
|
||||
a3 = store.create_agent({"name": "空白的"})
|
||||
p3 = agent_context.build_system_prompt(store.read_settings(), a3)
|
||||
@@ -267,8 +270,9 @@ def main():
|
||||
check("GET 记忆列表", r.get("ok") and r.get("shared") is True)
|
||||
r = h.call(f"/api/agents/{a1['id']}/usage", "GET")
|
||||
check("GET 用量", r.get("ok") and r.get("total", 0) > 0)
|
||||
r = h.call(f"/api/agents/{a1['id']}/emotion", "PUT", {"emotion": "挺开心的"})
|
||||
check("PUT 情绪", r.get("emotion") == "挺开心的")
|
||||
r = h.call(f"/api/agents/{a1['id']}/emotion", "PUT", {"preset": "喜", "text": "挺开心的"})
|
||||
check("PUT 情绪(双字段)", (r.get("emotion") or {}).get("text") == "挺开心的", str(r.get("emotion")))
|
||||
check("preset 也存了", (r.get("emotion") or {}).get("preset") == "喜")
|
||||
r = h.call("/api/worldviews", "GET")
|
||||
check("GET 世界观列表", r.get("ok") and len(r["items"]) == 1)
|
||||
r = h.call("/api/model-entries", "POST", {"name": "豆包 Pro", "model": "doubao-pro", "pricePerK": 0.8})
|
||||
@@ -312,11 +316,12 @@ def main():
|
||||
r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST", {"data": exported, "mode": "merge"})
|
||||
check("合并模式:新增了 1 条", r.get("added") == 1, str(r))
|
||||
check("合并模式:同名的跳过了", r.get("skipped", 0) >= 1, str(r))
|
||||
check("合并模式:保留当前情绪", agentdb.emotion_get(a1["id"]) == "挺开心的")
|
||||
check("合并模式:保留当前情绪", agentdb.emotion_state(a1["id"])["text"] == "挺开心的")
|
||||
r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST",
|
||||
{"data": {"type": "agent-memory", "version": 1, "smartMemory": [], "Emotion": "换掉了"},
|
||||
"mode": "replace"})
|
||||
check("覆盖模式:情绪也换了", agentdb.emotion_get(a1["id"]) == "换掉了", agentdb.emotion_get(a1["id"]))
|
||||
check("覆盖模式:情绪也换了(v1.1 的字符串格式也认)",
|
||||
agentdb.emotion_state(a1["id"])["text"] == "换掉了", str(agentdb.emotion_state(a1["id"])))
|
||||
|
||||
# ---------------------------------------------------------------- 11
|
||||
section("11. 多模型:引用了就真的用(需求 3.3)")
|
||||
@@ -422,8 +427,135 @@ def main():
|
||||
(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)))
|
||||
|
||||
# ---------------------------------------------------------------- 汇总
|
||||
print()
|
||||
if fails:
|
||||
|
||||
145
scripts/probe-rule-sandbox.py
Normal file
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())
|
||||
Reference in New Issue
Block a user