feat(v1.2): 阶段 0 —— 情绪双字段 + 立绘联动的地基 + 死亡规则(v2.0.55)
按 v1.2 需求开工。情绪双字段是所有新功能的**地基**:立绘联动按 preset 切图、 peer_emotions 注入 preset、状态脚本改情绪,三个都压在它上面,所以先做它。 ## 数据层 `emotions` 表:`emotion`(单字段自由文本)→ `preset` + `text`。 - `preset` 五档(喜/怒/哀/平常/死亡)**驱动系统行为**;`text` 只管扮演质感。 合成一个做不到:系统要按 preset 分支,而自然语言没法当分支条件。 - **迁移**:老的自由文本搬进 `text`,preset 给「平常」。旧列留着不动 (SQLite 删列要重建整张表,不值当)。 - 新增 `emotion_state` / `emotion_from_export` / `is_dead`; `emotion_set` 改成"只写传进来的那些"(preset 和 text 分开可选)。 - `emotion_from_export` **两种格式都认**:v1.1 的字符串、v1.2 的对象。 只认新格式的话,用户拿老文件导入会在情绪这一步抛异常, 而前半截记忆已经写进去了 —— 留下一个"记忆进来了、情绪没进来"的半成品。 ## 死亡规则(需求 3.5) - 死亡的智能体**不能对话**:内核在**发起前**拦(和 Token 限额同一层, 不是生成时才拒绝,那时候钱已经花了) - **AI 不能把自己从死亡改活** —— 这条限制放在 **AI 的工具通道**上 (`agent_tools.emotion_set`),**不在数据层**:数据层拦了的话, 界面就没法复活了,而那正是需求写的"用户手动改回是兜底主权" - 死亡状态**照常播报**给同世界观伙伴 ## 注入 - `<emotion>` 两字段都带(附录 C 的格式);「平常 + 空文本」整段省掉 - `<peer_emotions>` 注入 **preset 不是 text** —— text 是那个角色的内心独白, 读给别的角色听等于扒开他的脑子 ## 界面 - 记忆页情绪区:五档选择器(「死亡」标红)+ 自由文本;选中死亡时多一行 红字说明(不说的话用户点了死亡发现发不出消息,会以为坏了) - 聊天页顶栏显示 preset;**死亡时输入条换成提示条**,点「去复活 ›」直达情绪区 ## ★ 真机验证抓到一个探针抓不到的 bug 改完情绪后界面上**什么都没发生** —— `setEmotion` 只刷新了记忆页, 没刷新全局状态,而顶栏标签和死亡禁言读的都是 `state.emotions`。 这种"数据存进去了、界面不知道"的漏,探针(测内核)一个都抓不到。 ## 验证 探针新增两节 14 项: - **17 节 老库迁移**:用**内存库**测(换文件的做法被 WAL 坑过一次—— 连着的连接 + `-wal` 里的新数据会把复制进去的老库盖掉,测出来是假阴性)。 覆盖:能搬、preset 默认、幂等、新库跑它是空操作。 - **18 节 死亡规则**:AI 能把自己改成死亡、**不能自愈**、用户能改活、 死亡照常播报、不认识的 preset 被拒且理由列出合法值、只写 text 时 preset 不动。 五个探针全绿;装机实测五档选择器 + 迁移过来的老文本 + 死亡禁言提示条。
This commit is contained in:
@@ -30,8 +30,8 @@ android {
|
|||||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||||
* 改小了会装不上)。
|
* 改小了会装不上)。
|
||||||
*/
|
*/
|
||||||
versionCode = 254
|
versionCode = 255
|
||||||
versionName = "2.0.54"
|
versionName = "2.0.55"
|
||||||
|
|
||||||
ndk {
|
ndk {
|
||||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||||
|
|||||||
@@ -263,7 +263,7 @@ fun AppRoot(
|
|||||||
worldMode = true,
|
worldMode = true,
|
||||||
loading = false,
|
loading = false,
|
||||||
hint = "",
|
hint = "",
|
||||||
onSetEmotion = {},
|
onSetEmotion = { _, _ -> },
|
||||||
onAdd = { _, _ -> },
|
onAdd = { _, _ -> },
|
||||||
onUpdate = { _, _, _ -> },
|
onUpdate = { _, _, _ -> },
|
||||||
// 删是可以的:限权只约束 AI,用户有权清掉任何人写的
|
// 删是可以的:限权只约束 AI,用户有权清掉任何人写的
|
||||||
@@ -318,7 +318,7 @@ fun AppRoot(
|
|||||||
agentNames = vm.agents.associate { it.id to it.name },
|
agentNames = vm.agents.associate { it.id to it.name },
|
||||||
loading = vm.memoryLoading,
|
loading = vm.memoryLoading,
|
||||||
hint = vm.memoryHint,
|
hint = vm.memoryHint,
|
||||||
onSetEmotion = { vm.setEmotion(it) },
|
onSetEmotion = { preset, text -> vm.setEmotion(preset, text) },
|
||||||
onAdd = { t, c -> vm.addMemory(t, c) },
|
onAdd = { t, c -> vm.addMemory(t, c) },
|
||||||
onUpdate = { id, t, c -> vm.updateMemory(id, t, c) },
|
onUpdate = { id, t, c -> vm.updateMemory(id, t, c) },
|
||||||
onDelete = { vm.deleteMemory(it) },
|
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
|
val id = memoryAgentId
|
||||||
if (id.isBlank()) return
|
if (id.isBlank()) return
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
runCatching { withContext(Dispatchers.IO) { client.setEmotion(id, text) } }
|
runCatching { withContext(Dispatchers.IO) { client.setEmotion(id, preset, text) } }
|
||||||
refreshMemories()
|
refreshMemories()
|
||||||
|
// ★★ 还必须刷新**全局状态** —— 顶栏的情绪标签、聊天页的**死亡禁言**
|
||||||
|
// 读的都是 `state.emotions`,只刷记忆页的话界面上什么都看不出来。
|
||||||
|
// (这个漏是真机验证抓到的:把智能体改成「死亡」之后回聊天页,
|
||||||
|
// 输入条照样能用。)
|
||||||
|
refresh()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package com.doubao.lynxclone.ui
|
package com.doubao.lynxclone.ui
|
||||||
|
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
@@ -373,9 +373,44 @@ fun ChatScreen(vm: AppViewModel) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// ★★ 死亡禁言(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)
|
InputBar(vm, onPickFile, onMic, speech)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
|
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
|
||||||
AnimatedVisibility(
|
AnimatedVisibility(
|
||||||
@@ -443,11 +478,15 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
|||||||
// ★ 当前情绪(复查报告 2.6):AI 自己能改情绪,改了却看不出来,
|
// ★ 当前情绪(复查报告 2.6):AI 自己能改情绪,改了却看不出来,
|
||||||
// 这个功能就只是个看不见的字段。放在名字旁边、字号小一半 ——
|
// 这个功能就只是个看不见的字段。放在名字旁边、字号小一半 ——
|
||||||
// 它是个状态注脚,不该抢名字的注意力。
|
// 它是个状态注脚,不该抢名字的注意力。
|
||||||
val emo = vm.state.emotions[vm.activeAgent?.id ?: ""].orEmpty()
|
// ★ v1.2:这里显示的是 **preset(五档)**,不是那句自由文本 ——
|
||||||
if (emo.isNotBlank()) {
|
// 自由文本是角色的内心独白,摆在顶栏上不合适;preset 才是
|
||||||
|
// "一眼看出他现在什么情绪"那个粒度。点开记忆页能看到全文。
|
||||||
|
val emo = vm.state.emotions[vm.activeAgent?.id ?: ""]
|
||||||
|
val emoLabel = emo?.preset.orEmpty()
|
||||||
|
if (emoLabel.isNotBlank() && emoLabel != "平常") {
|
||||||
Spacer(Modifier.width(6.dp))
|
Spacer(Modifier.width(6.dp))
|
||||||
Text(
|
Text(
|
||||||
emo.take(8),
|
emoLabel.take(8),
|
||||||
fontSize = 10.sp,
|
fontSize = 10.sp,
|
||||||
color = Doubao.Blue,
|
color = Doubao.Blue,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
|
|||||||
@@ -35,6 +35,8 @@ import androidx.compose.ui.text.input.KeyboardType
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import com.doubao.lynxclone.data.MemoryItem
|
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
|
import com.doubao.lynxclone.data.MemorySpace
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -77,7 +79,8 @@ fun MemoryScreen(
|
|||||||
worldMode: Boolean = false,
|
worldMode: Boolean = false,
|
||||||
loading: Boolean,
|
loading: Boolean,
|
||||||
hint: String,
|
hint: String,
|
||||||
onSetEmotion: (String) -> Unit,
|
/** 保存情绪:preset(五档)+ text(自由一句) */
|
||||||
|
onSetEmotion: (String, String) -> Unit,
|
||||||
onAdd: (String, String) -> Unit,
|
onAdd: (String, String) -> Unit,
|
||||||
onUpdate: (String, String?, String?) -> Unit,
|
onUpdate: (String, String?, String?) -> Unit,
|
||||||
onDelete: (String) -> Unit,
|
onDelete: (String) -> Unit,
|
||||||
@@ -96,7 +99,9 @@ fun MemoryScreen(
|
|||||||
) {
|
) {
|
||||||
var editing by remember { mutableStateOf<MemoryItem?>(null) }
|
var editing by remember { mutableStateOf<MemoryItem?>(null) }
|
||||||
var adding by remember { mutableStateOf(false) }
|
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 那张表)
|
// 一次确认,正好是弹窗该用的地方(AGENTS.md 那张表)
|
||||||
var confirmSummarize by remember { mutableStateOf(false) }
|
var confirmSummarize by remember { mutableStateOf(false) }
|
||||||
/** 调注入窗口(输入条数,0 = 不限) */
|
/** 调注入窗口(输入条数,0 = 不限) */
|
||||||
@@ -308,24 +313,67 @@ fun MemoryScreen(
|
|||||||
.padding(12.dp),
|
.padding(12.dp),
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
"AI 自己能改(emotion_set),你也可以在这里改。它每次对话都会被带进提示词。",
|
"preset 决定系统行为(立绘换哪张、能不能对话、同伴看到什么脸色);" +
|
||||||
|
"下面那句话只是扮演质感。AI 自己能改,你也可以在这里改。",
|
||||||
fontSize = 11.sp,
|
fontSize = 11.sp,
|
||||||
lineHeight = 16.sp,
|
lineHeight = 16.sp,
|
||||||
color = doubaoTextSecondary(),
|
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))
|
Spacer(Modifier.height(8.dp))
|
||||||
|
Text(
|
||||||
|
"「死亡」状态下这个智能体不能对话(输入条会禁用)。" +
|
||||||
|
"把它改回其他档就是复活 —— 这是你的权力,AI 自己不能从死亡改活。",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
lineHeight = 16.sp,
|
||||||
|
color = Color(0xFFB3261E),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = emotionDraft,
|
value = emotionText,
|
||||||
onValueChange = { emotionDraft = it },
|
onValueChange = { emotionText = it },
|
||||||
placeholder = { Text("比如:刚被夸了,有点得意", fontSize = 13.sp) },
|
placeholder = { Text("他此刻在想什么(自由一句,比如:强作镇定,手心全是汗)", fontSize = 12.sp) },
|
||||||
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp),
|
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp),
|
||||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(6.dp))
|
Spacer(Modifier.height(6.dp))
|
||||||
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
|
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
|
||||||
TextButton(
|
TextButton(
|
||||||
onClick = { onSetEmotion(emotionDraft.trim()) },
|
onClick = { onSetEmotion(emotionPreset, emotionText.trim()) },
|
||||||
enabled = emotionDraft.trim() != (space?.emotion ?: ""),
|
enabled = emotionPreset != (space?.emotion?.preset ?: "平常") ||
|
||||||
|
emotionText.trim() != (space?.emotion?.text ?: ""),
|
||||||
) { Text("保存情绪", fontSize = 13.sp) }
|
) { Text("保存情绪", fontSize = 13.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, # 当前生效的是哪个空间
|
'activeScope': scope, # 当前生效的是哪个空间
|
||||||
'worldviewId': agent.get('worldviewId') or '',
|
'worldviewId': agent.get('worldviewId') or '',
|
||||||
'memories': agentdb.memory_list(own),
|
'memories': agentdb.memory_list(own),
|
||||||
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
'emotion': agentdb.emotion_state(agent.get('id') or ''),
|
||||||
'suggestion': '',
|
'suggestion': '',
|
||||||
}
|
}
|
||||||
items = agentdb.memory_list(scope)
|
items = agentdb.memory_list(scope)
|
||||||
@@ -294,7 +294,7 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
|||||||
'window': window,
|
'window': window,
|
||||||
'pinnedCount': pinned_count,
|
'pinnedCount': pinned_count,
|
||||||
'injected': injected,
|
'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 ''),
|
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -398,12 +398,19 @@ def handle(handler, pathname: str, method: str) -> bool:
|
|||||||
err(404, '没有这个智能体')
|
err(404, '没有这个智能体')
|
||||||
return True
|
return True
|
||||||
if method == 'GET':
|
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
|
return True
|
||||||
if method in ('PUT', 'POST'):
|
if method in ('PUT', 'POST'):
|
||||||
emo = str(body().get('emotion') or '')
|
b = body()
|
||||||
agentdb.emotion_set(agent['id'], emo[:200])
|
# ★ 这条路由是**界面**在用的(记忆页的情绪区)——
|
||||||
handler.send_json(200, {'ok': True, 'emotion': emo[:200]})
|
# 所以它**允许**把「死亡」改回别的值:那是需求 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
|
return True
|
||||||
|
|
||||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'skills':
|
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'skills':
|
||||||
@@ -553,7 +560,7 @@ def _memory_export(agent: dict) -> dict:
|
|||||||
'version': 1,
|
'version': 1,
|
||||||
'name': agent.get('name') or '',
|
'name': agent.get('name') or '',
|
||||||
'smartMemory': items,
|
'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
|
emotion_kept = True
|
||||||
if mode == 'replace' and payload.get('Emotion') is not None:
|
if mode == 'replace' and payload.get('Emotion') is not None:
|
||||||
# 覆盖模式连情绪一起换(需求 3.4);合并模式保留当前值
|
# 覆盖模式连情绪一起换(需求 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
|
emotion_kept = False
|
||||||
|
|
||||||
return _send_json_ok(handler, {
|
return _send_json_ok(handler, {
|
||||||
|
|||||||
@@ -94,11 +94,32 @@ def memory_scope(agent: dict) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def build_emotion(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 ''
|
agent_id = (agent or {}).get('id') or ''
|
||||||
if not agent_id:
|
if not agent_id:
|
||||||
return ''
|
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:
|
def build_memory(agent: dict) -> str:
|
||||||
@@ -239,8 +260,11 @@ def build_peer_emotions(agent: dict) -> str:
|
|||||||
# ★ `by_id.items()` 给的是 (id, **整个 agent 字典**),不是 (id, 名字)——
|
# ★ `by_id.items()` 给的是 (id, **整个 agent 字典**),不是 (id, 名字)——
|
||||||
# 直接 f'{name}-{emo}' 会把 agent 的 JSON 拼进提示词(踩过)
|
# 直接 f'{name}-{emo}' 会把 agent 的 JSON 拼进提示词(踩过)
|
||||||
name = one.get('name') or '某人'
|
name = one.get('name') or '某人'
|
||||||
|
# ★ v1.2:这里给的是 **preset(五档)不是 text**。
|
||||||
|
# text 是那个角色的内心独白,读给别的角色听等于扒开他的脑子;
|
||||||
|
# preset 才是"看得出来他现在什么脸色"这个粒度。
|
||||||
emo = emo_by_id.get(aid) or ''
|
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)
|
return ';'.join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -268,29 +268,62 @@ def memory_suggest_summary(args: dict) -> dict:
|
|||||||
EMOTION_SET = {
|
EMOTION_SET = {
|
||||||
'name': 'emotion_set',
|
'name': 'emotion_set',
|
||||||
'description': (
|
'description': (
|
||||||
'更新**你自己**当前的情绪状态(一小段话,比如"刚被夸了,有点得意")。'
|
'更新**你自己**当前的情绪状态。两个字段都要给:\n'
|
||||||
'它会跟着你到下一次对话,也会显示在系统提示词里。'
|
'· preset:五档之一 —— 喜 / 怒 / 哀 / 平常 / 死亡。它决定系统行为'
|
||||||
|
'(立绘换哪张、同伴看到你什么脸色、死亡时能不能继续说话)。\n'
|
||||||
|
'· text:一句自由描述,比如"刚被夸了,有点得意"。这只是扮演质感。\n'
|
||||||
'情绪要跟着对话内容自然变化,不用每轮都改。'
|
'情绪要跟着对话内容自然变化,不用每轮都改。'
|
||||||
),
|
),
|
||||||
'parameters': {
|
'parameters': {
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
'emotion': {'type': 'string', 'description': '你现在的情绪'},
|
'preset': {
|
||||||
|
'type': 'string',
|
||||||
|
'enum': list(agentdb.PRESETS),
|
||||||
|
'description': '五档情绪之一',
|
||||||
},
|
},
|
||||||
'required': ['emotion'],
|
'text': {'type': 'string', 'description': '一句自由描述(可选)'},
|
||||||
|
},
|
||||||
|
'required': ['preset'],
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def emotion_set(args: dict) -> dict:
|
def emotion_set(args: dict) -> dict:
|
||||||
|
"""
|
||||||
|
写自己的情绪(需求 3.5 双字段)。
|
||||||
|
|
||||||
|
★★ **禁止把自己从「死亡」改活**(需求 3.5 明文)。
|
||||||
|
|
||||||
|
为什么:死亡是"这个角色没了"。能自己复活的话死亡就没有重量 ——
|
||||||
|
用户会看到 AI 上一句刚咽气、下一句又活蹦乱跳,整个系统的可信度就没了。
|
||||||
|
|
||||||
|
复活只有两条**别的**通道,都不经过这里:
|
||||||
|
· 用户手动改(兜底主权,在记忆页的情绪区)
|
||||||
|
· 状态脚本改(定时复活 / 解药剧情,见 §3.11 —— 那条路走沙箱,不走工具)
|
||||||
|
"""
|
||||||
agent = _me()
|
agent = _me()
|
||||||
if not agent:
|
if not agent:
|
||||||
raise ValueError('拿不到当前智能体')
|
raise ValueError('拿不到当前智能体')
|
||||||
emo = str(args.get('emotion') or '').strip()
|
agent_id = agent.get('id') or ''
|
||||||
if not emo:
|
preset = str(args.get('preset') or '').strip()
|
||||||
raise ValueError('emotion 不能为空(不想保留情绪的话直接别调用这个工具)')
|
text = str(args.get('text') or '').strip()
|
||||||
agentdb.emotion_set(agent.get('id') or '', emo[:200])
|
if preset not in agentdb.PRESETS:
|
||||||
return {'emotion': emo[:200], 'note': '已更新你自己的情绪。'}
|
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 (
|
CREATE TABLE IF NOT EXISTS emotions (
|
||||||
agent_id TEXT PRIMARY KEY,
|
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
|
updated_at TEXT NOT NULL
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -126,10 +132,48 @@ def init() -> None:
|
|||||||
return
|
return
|
||||||
conn = _connect()
|
conn = _connect()
|
||||||
conn.executescript(SCHEMA)
|
conn.executescript(SCHEMA)
|
||||||
|
_migrate(conn)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
_init_done = True
|
_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:
|
def reset_init() -> None:
|
||||||
"""测试用:换过数据目录之后强制重新建表"""
|
"""测试用:换过数据目录之后强制重新建表"""
|
||||||
global _init_done
|
global _init_done
|
||||||
@@ -324,39 +368,106 @@ def memory_titles(scope: str) -> list:
|
|||||||
# 情绪(始终按智能体私有,即使绑定了世界观 —— 需求 3.5)
|
# 情绪(始终按智能体私有,即使绑定了世界观 —— 需求 3.5)
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
def emotion_get(agent_id: str) -> str:
|
def emotion_state(agent_id: str) -> dict:
|
||||||
|
"""
|
||||||
|
读一个智能体的情绪 → `{'preset': ..., 'text': ...}`(需求 3.5 双字段)。
|
||||||
|
|
||||||
|
★ 没记过情绪时返回默认值(「平常」+ 空文本),而不是空 —— 调用方
|
||||||
|
(注入模板、界面)就不用各自处理 None 了。
|
||||||
|
"""
|
||||||
init()
|
init()
|
||||||
row = _connect().execute(
|
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()
|
).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()
|
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 = _connect()
|
||||||
conn.execute(
|
conn.execute(
|
||||||
'INSERT INTO emotions (agent_id, emotion, updated_at) VALUES (?, ?, ?) '
|
'INSERT INTO emotions (agent_id, preset, text, updated_at) VALUES (?, ?, ?, ?) '
|
||||||
'ON CONFLICT(agent_id) DO UPDATE SET emotion = excluded.emotion, updated_at = excluded.updated_at',
|
'ON CONFLICT(agent_id) DO UPDATE SET preset = excluded.preset, '
|
||||||
(agent_id or '', emotion or '', now_iso()),
|
'text = excluded.text, updated_at = excluded.updated_at',
|
||||||
|
(agent_id or '', nxt['preset'], nxt['text'], now_iso()),
|
||||||
)
|
)
|
||||||
conn.commit()
|
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:
|
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 里挑,
|
[agent_ids] 是绑定了这个世界观的全部智能体 id(由调用方从 agents.json 里挑,
|
||||||
这里不碰 JSON —— 数据层只管数据库里有什么)。返回 [(agent_id, emotion)]。
|
这里不碰 JSON —— 数据层只管数据库里有什么)。返回 [(agent_id, preset)]。
|
||||||
"""
|
"""
|
||||||
init()
|
init()
|
||||||
out = []
|
out = []
|
||||||
for aid in agent_ids or []:
|
for aid in agent_ids or []:
|
||||||
if not aid or aid == exclude_agent:
|
if not aid or aid == exclude_agent:
|
||||||
continue
|
continue
|
||||||
out.append((aid, emotion_get(aid)))
|
out.append((aid, emotion_state(aid)['preset']))
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -582,12 +582,16 @@ class KernelHandler(BaseHTTPRequestHandler):
|
|||||||
'mcpConfig': mcp_client.read_mcp_config(),
|
'mcpConfig': mcp_client.read_mcp_config(),
|
||||||
'conversations': store.list_conversations(),
|
'conversations': store.list_conversations(),
|
||||||
'agents': store.list_agents(),
|
'agents': store.list_agents(),
|
||||||
# 每个智能体当前的情绪(复查报告 2.6)。
|
# 每个智能体当前的情绪(v1.2 双字段)。
|
||||||
# ★ 情绪原来只在提示词里生效 —— AI 用 emotion_set 改了情绪,
|
# ★ 情绪原来只在提示词里生效 —— AI 用 emotion_set 改了情绪,
|
||||||
# 用户完全无感知,这个功能就成了一个看不见的字段。
|
# 用户完全无感知,这个功能就成了一个看不见的字段。
|
||||||
|
# `preset` 驱动界面(立绘、死亡禁言、成员标签),
|
||||||
|
# `text` 是扮演质感。
|
||||||
|
# **有情绪才带上**:没记过的(默认「平常」+ 空文本)不占位。
|
||||||
'emotions': {
|
'emotions': {
|
||||||
a.get('id'): e for a in store.list_agents()
|
a.get('id'): st for a in store.list_agents()
|
||||||
if (e := (agentdb.emotion_get(a.get('id') or '') or '').strip())
|
if (st := agentdb.emotion_state(a.get('id') or ''))
|
||||||
|
and (st.get('text') or st.get('preset') != agentdb.PRESET_DEFAULT)
|
||||||
},
|
},
|
||||||
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
||||||
# 都不大(几个到几十个),一次带给界面省得进页面再拉一次
|
# 都不大(几个到几十个),一次带给界面省得进页面再拉一次
|
||||||
@@ -1688,6 +1692,23 @@ class KernelHandler(BaseHTTPRequestHandler):
|
|||||||
emit({'type': 'rebased', 'conversationId': conversation_id,
|
emit({'type': 'rebased', 'conversationId': conversation_id,
|
||||||
'reason': 'agent_changed'})
|
'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)。
|
# ★★ Token 限额:**发起前**拦(需求 3.1)。
|
||||||
#
|
#
|
||||||
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
||||||
|
|||||||
@@ -150,8 +150,9 @@ def main():
|
|||||||
check("memory_add 返回 id", bool(r.get("id")))
|
check("memory_add 返回 id", bool(r.get("id")))
|
||||||
r = agent_tools.memory_search({"keyword": "猫"})
|
r = agent_tools.memory_search({"keyword": "猫"})
|
||||||
check("memory_search 找到刚记的", r["count"] >= 1, str(r["count"]))
|
check("memory_search 找到刚记的", r["count"] >= 1, str(r["count"]))
|
||||||
agent_tools.emotion_set({"emotion": "刚被夸了,有点得意"})
|
agent_tools.emotion_set({"preset": "喜", "text": "刚被夸了,有点得意"})
|
||||||
check("情绪写进去了", "得意" in agentdb.emotion_get(a1["id"]))
|
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", 1200, 800)
|
||||||
agentdb.token_add(a1["id"], "doubao-pro", 300, 100)
|
agentdb.token_add(a1["id"], "doubao-pro", 300, 100)
|
||||||
agentdb.token_add(a1["id"], "deepseek-r1", 500, 200)
|
agentdb.token_add(a1["id"], "deepseek-r1", 500, 200)
|
||||||
@@ -213,7 +214,7 @@ def main():
|
|||||||
# ---------------------------------------------------------------- 8
|
# ---------------------------------------------------------------- 8
|
||||||
section("8. system prompt 注入(附录 C)")
|
section("8. system prompt 注入(附录 C)")
|
||||||
tools_runtime.push_context(agentId=a1["id"], conversationId="c_test")
|
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})
|
store.update_agent(a2["id"], {"emotionEnabled": True})
|
||||||
# ★ a1 在这一节之前已经绑了世界观 → 它的记忆空间是**共享**的那个,
|
# ★ a1 在这一节之前已经绑了世界观 → 它的记忆空间是**共享**的那个,
|
||||||
# 所以验证"记忆进提示词"要往当前 scope 里写(这正是绑定世界观的正确行为)
|
# 所以验证"记忆进提示词"要往当前 scope 里写(这正是绑定世界观的正确行为)
|
||||||
@@ -244,7 +245,9 @@ def main():
|
|||||||
check("名单里也没有 agent 的 JSON", "'builtin'" not in prompt and "worldviewId'" not in prompt)
|
check("名单里也没有 agent 的 JSON", "'builtin'" not in prompt and "worldviewId'" not in prompt)
|
||||||
store.update_agent(a1["id"], {"emotionEnabled": True})
|
store.update_agent(a1["id"], {"emotionEnabled": True})
|
||||||
prompt2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a1["id"]))
|
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": "空白的"})
|
a3 = store.create_agent({"name": "空白的"})
|
||||||
p3 = agent_context.build_system_prompt(store.read_settings(), a3)
|
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)
|
check("GET 记忆列表", r.get("ok") and r.get("shared") is True)
|
||||||
r = h.call(f"/api/agents/{a1['id']}/usage", "GET")
|
r = h.call(f"/api/agents/{a1['id']}/usage", "GET")
|
||||||
check("GET 用量", r.get("ok") and r.get("total", 0) > 0)
|
check("GET 用量", r.get("ok") and r.get("total", 0) > 0)
|
||||||
r = h.call(f"/api/agents/{a1['id']}/emotion", "PUT", {"emotion": "挺开心的"})
|
r = h.call(f"/api/agents/{a1['id']}/emotion", "PUT", {"preset": "喜", "text": "挺开心的"})
|
||||||
check("PUT 情绪", r.get("emotion") == "挺开心的")
|
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")
|
r = h.call("/api/worldviews", "GET")
|
||||||
check("GET 世界观列表", r.get("ok") and len(r["items"]) == 1)
|
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})
|
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"})
|
r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST", {"data": exported, "mode": "merge"})
|
||||||
check("合并模式:新增了 1 条", r.get("added") == 1, str(r))
|
check("合并模式:新增了 1 条", r.get("added") == 1, str(r))
|
||||||
check("合并模式:同名的跳过了", r.get("skipped", 0) >= 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",
|
r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST",
|
||||||
{"data": {"type": "agent-memory", "version": 1, "smartMemory": [], "Emotion": "换掉了"},
|
{"data": {"type": "agent-memory", "version": 1, "smartMemory": [], "Emotion": "换掉了"},
|
||||||
"mode": "replace"})
|
"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
|
# ---------------------------------------------------------------- 11
|
||||||
section("11. 多模型:引用了就真的用(需求 3.3)")
|
section("11. 多模型:引用了就真的用(需求 3.3)")
|
||||||
@@ -473,6 +478,84 @@ def main():
|
|||||||
m2 = speech.voice_for(st, store.get_agent(half["id"]))
|
m2 = speech.voice_for(st, store.get_agent(half["id"]))
|
||||||
check("只设音色时引擎回落全局", m2.get("ttsVoice") == "only-voice", str(m2.get("ttsVoice")))
|
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()
|
print()
|
||||||
if fails:
|
if fails:
|
||||||
|
|||||||
Reference in New Issue
Block a user