Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 57a9ff4ea1 | |||
| ab063d0674 | |||
| 3d5c02e7a9 | |||
| 4ed6c6a4ee | |||
| f665b83b34 | |||
| 1c07e37932 | |||
| daccc3fd10 | |||
| e62dd7b87b | |||
| 8ccf009958 | |||
| ff1c2e3400 | |||
| bea9debe15 | |||
| 8ac14bdaa2 | |||
| f84c68762b | |||
| 5878ec7a7f | |||
| 77b4f3d74f | |||
| fbfd50eb56 | |||
| 5a7ed44226 | |||
| 0b80ca4830 | |||
| c1da6486a4 | |||
| f877bd6ee8 | |||
| c9e0d689c0 | |||
| cceffd77ec | |||
| 2142e119c6 | |||
| 4ad2ea8e90 | |||
| bbc32dcb46 | |||
| 778c19b088 | |||
| 7e7aea0f48 | |||
| 4effa968ac |
@@ -1,4 +1,4 @@
|
||||
plugins {
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 257
|
||||
versionName = "2.0.57"
|
||||
versionCode = 278
|
||||
versionName = "2.0.78"
|
||||
|
||||
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
|
||||
@@ -71,8 +71,18 @@ class SpeechController(
|
||||
|
||||
/* ------------------------------ 朗读 ------------------------------ */
|
||||
|
||||
/** 念第 index 条消息 */
|
||||
fun speak(text: String, index: Int) {
|
||||
/**
|
||||
* 念第 [index] 条消息。
|
||||
*
|
||||
* [who] = **说这句话的智能体**(群聊里每条消息的发言者都不一样)。
|
||||
* 传空串就退回 [agentId] 那个"当前智能体"。
|
||||
*
|
||||
* ★★ 这个参数是补上来的:以前只会拿"当前对话的主人"去要音色,
|
||||
* 于是群聊里小黑和寐眠各配了不同音色,读出来却始终是同一个声音
|
||||
* (用户报的"群聊的时候不同智能体的语音不会切换")。
|
||||
* 内核其实**一直在消息里存 agentId**,只是客户端没读。
|
||||
*/
|
||||
fun speak(text: String, index: Int, who: String = "") {
|
||||
if (text.isBlank()) return
|
||||
// 正在念同一条 → 再点一次就是停
|
||||
if (speakingIndex == index && speaker.isPlaying) {
|
||||
@@ -86,6 +96,7 @@ class SpeechController(
|
||||
cancelRecording()
|
||||
|
||||
speakingIndex = index
|
||||
val voice = who.ifBlank { agentId() }
|
||||
scope.launch {
|
||||
// ★ 首选流式:内核边合成边下发 PCM,这边边收边喂 AudioTrack,
|
||||
// 首句大约 1 秒就能出声(整段合成再播要等 3 秒以上)。
|
||||
@@ -99,7 +110,7 @@ class SpeechController(
|
||||
// 用户看到的就是"一读语音就闪退"。
|
||||
val played = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
client.streamTts(text, agentId()).use { r ->
|
||||
client.streamTts(text, voice).use { r ->
|
||||
val mime = r.body?.contentType().toString()
|
||||
val source = r.body?.source()
|
||||
source != null && speaker.playStream(mime, source)
|
||||
@@ -117,7 +128,7 @@ class SpeechController(
|
||||
}
|
||||
|
||||
try {
|
||||
val result = client.speak(text, agentId())
|
||||
val result = client.speak(text, voice)
|
||||
if (!result.optBoolean("ok")) {
|
||||
// 云端失败就退回系统 TTS —— 用户点了朗读却一点动静都没有是最差的体验
|
||||
val reason = result.optString("error").ifBlank { "云端合成失败" }
|
||||
@@ -167,8 +178,8 @@ class SpeechController(
|
||||
*/
|
||||
private var lastAutoReadKey: String? = null
|
||||
|
||||
/** 自动朗读:新回复刚落地时调它 */
|
||||
fun maybeAutoRead(text: String, index: Int) {
|
||||
/** 自动朗读:新回复刚落地时调它。[who] 同 [speak] —— 群聊里要按发言者挑音色 */
|
||||
fun maybeAutoRead(text: String, index: Int, who: String = "") {
|
||||
if (!autoRead || text.isBlank()) return
|
||||
if (recording) return
|
||||
|
||||
@@ -178,7 +189,7 @@ class SpeechController(
|
||||
if (speakingIndex == index && speaker.isPlaying) return
|
||||
|
||||
lastAutoReadKey = key
|
||||
speak(text, index)
|
||||
speak(text, index, who)
|
||||
}
|
||||
|
||||
/** 手动点朗读时清掉自动朗读的记录,免得"念过了就不再自动念"影响到后面 */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
@@ -104,12 +104,9 @@ fun AgentEditScreen(
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank()) return@rememberLauncherForActivityResult
|
||||
runCatching {
|
||||
val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
val name = (uri.lastPathSegment ?: "image.png").substringAfterLast('/')
|
||||
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
vm.uploadAgentAsset(draft.id, slot, name, b64)
|
||||
}.onFailure { vm.showHint("读不出这张图") }
|
||||
// 读图 / 压缩 / 上传全在 ViewModel 的 IO 线程里 ——
|
||||
// launcher 回调是**主线程**,解码一张 30MB 的手机照片放这儿会卡死界面
|
||||
vm.uploadAgentAssetFrom(ctx.applicationContext, draft.id, slot, uri)
|
||||
}
|
||||
|
||||
// 导出智能体包(需求 2.5):内核打包成 zip → base64 → 这里落盘。
|
||||
@@ -203,6 +200,8 @@ fun AgentEditScreen(
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
},
|
||||
onClear = { vm.uploadAgentAsset(draft.id, "front:$preset", "", "") },
|
||||
// 立绘空着时显示内置默认人物 —— 那正是回退链的最后一级
|
||||
showDefaultPerson = true,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
@@ -319,6 +318,18 @@ fun AgentEditScreen(
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Hint("用满之后会拦住发送,并附一句告别(那句话可以在设置里改)。留空就是无限制。")
|
||||
Spacer(Modifier.height(12.dp))
|
||||
// ★ v1.2 §6.1:拉起其他智能体的方式。
|
||||
// 内核(`agent_tools.invite_agent`)早就按这个字段分流了,
|
||||
// 但界面上一直**没有入口** —— 于是 `confirm` 那一档
|
||||
// 用户永远打不开,等于需求里这个选项不存在。
|
||||
ToggleRow(
|
||||
title = "拉人要先问我",
|
||||
sub = "打开后,AI 想邀请别的智能体进群时会先问一句;" +
|
||||
"关闭则直接拉进来(都会在正文里说一声)。",
|
||||
checked = draft.inviteMode == "confirm",
|
||||
onChange = { draft = draft.copy(inviteMode = if (it) "confirm" else "silent") },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 技能 ---------------- */
|
||||
@@ -433,22 +444,9 @@ private fun AgentImage.pathOf(key: String): String = when (key) {
|
||||
else -> borderInfo
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Card(content: @Composable () -> Unit) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) { content() }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Hint(text: String) {
|
||||
Text(text, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
// ★ `Card` / `Hint` 已经挪到 DoubaoUi.kt 变成公共组件了 ——
|
||||
// 原来它们是这个文件私有的,于是别的界面想用只能复制一份
|
||||
// ([群成员] 就要用),而"同一段逻辑抄两份"是这个仓库的老毛病。
|
||||
|
||||
/** 一行里并排的两个入口按钮(记忆 / 用量这种"跳去另一个界面"的动作) */
|
||||
@Composable
|
||||
@@ -556,6 +554,15 @@ private fun AssetRow(
|
||||
path: String,
|
||||
onPick: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
/**
|
||||
* 空的时候要不要显示**内置默认人物**的缩略图。
|
||||
*
|
||||
* ★ 只有**立绘**该显示它(那正是回退链的最后一级)。
|
||||
* 背景图 / 边框为空时显示一张**人物照**是误导 ——
|
||||
* 用户会以为"我没设背景,怎么有个女的"(截图反馈过)。
|
||||
* 那三个空着就画一个空框 + 一个「空」字,如实表达"这里什么都没有"。
|
||||
*/
|
||||
showDefaultPerson: Boolean = false,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
@@ -567,14 +574,18 @@ private fun AssetRow(
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (path.isBlank()) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
alpha = 0.35f,
|
||||
)
|
||||
if (showDefaultPerson) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.agent_default_character),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize().clip(RoundedCornerShape(8.dp)),
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.TopCenter,
|
||||
alpha = 0.35f,
|
||||
)
|
||||
} else {
|
||||
Text("空", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
} else {
|
||||
AssetImage(
|
||||
path = path,
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.StatValue
|
||||
import com.doubao.lynxclone.data.StatusInstance
|
||||
|
||||
/**
|
||||
* [状态数值](v1.2 §3.10 数值 / §3.11 状态)。
|
||||
*
|
||||
* ## 三个入口共用这一个界面
|
||||
*
|
||||
* 需求 §6.1 指定的三个入口:**聊天页状态栏** / **智能体编辑的"它的状态"** /
|
||||
* **群成员的「状态」按钮**。三处都调 `vm.openStats(agentId)`。
|
||||
*
|
||||
* ★ 只写一个界面是有意的:三个入口各写一份的话,"数值怎么显示、
|
||||
* 能不能改、状态剩几轮怎么标"这三件事会各有一套说法 ——
|
||||
* 而这个仓库里"同一逻辑抄两份"已经反复出现过。
|
||||
*
|
||||
* ## 用户能直接改数值,AI 不能
|
||||
*
|
||||
* AI 的 `change_stat` 只能申请**增量**,还要过脚本裁决(§3.10)。
|
||||
* 用户是规则的主人 —— 点一下就能直接设成任何值。
|
||||
* 但内核照样会 clamp 到 `[min,max]`:超出范围的值会让进度条和区间注入
|
||||
* 全都错位。所以**回来之后要以返回值刷新**,不能乐观地先用自己填的。
|
||||
*/
|
||||
@Composable
|
||||
fun AgentStatsScreen(
|
||||
vm: AppViewModel,
|
||||
agentId: String,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val stats = vm.agentStats
|
||||
var editing by remember { mutableStateOf("") }
|
||||
var input by remember { mutableStateOf("") }
|
||||
|
||||
FullScreen(
|
||||
title = "状态数值",
|
||||
subtitle = stats?.name?.takeIf { it.isNotBlank() } ?: "读不出来",
|
||||
onBack = onBack,
|
||||
) {
|
||||
if (stats == null) {
|
||||
Hint("正在读……")
|
||||
return@FullScreen
|
||||
}
|
||||
if (stats.rulePackId.isBlank()) {
|
||||
// 没挂规则包就没有数值系统 —— 如实说清楚,别让用户以为是加载失败
|
||||
Hint(
|
||||
"这个智能体还没有数值系统。\n\n" +
|
||||
"数值和状态由「数值状态包」定义 —— 去 资源 → 规则包 " +
|
||||
"建一个(或导入一个),再把它挂到智能体所在的世界观上。",
|
||||
)
|
||||
return@FullScreen
|
||||
}
|
||||
|
||||
SectionLabel("数值")
|
||||
Card {
|
||||
if (stats.stats.isEmpty()) {
|
||||
Hint("这个规则包里没有数值。")
|
||||
}
|
||||
for (s in stats.stats) {
|
||||
StatRow(
|
||||
stat = s,
|
||||
editing = editing == s.name,
|
||||
input = input,
|
||||
onInput = { input = it },
|
||||
onStartEdit = { editing = s.name; input = fmtNum(s.value) },
|
||||
onCancel = { editing = "" },
|
||||
onCommit = {
|
||||
vm.setStatDirect(s.name, input.toDoubleOrNull() ?: s.value)
|
||||
editing = ""
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (stats.rulePackName.isNotBlank()) {
|
||||
Hint("来自规则包「${stats.rulePackName}」。")
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态")
|
||||
Card {
|
||||
if (stats.statuses.isEmpty()) {
|
||||
Hint("身上没有状态。")
|
||||
}
|
||||
for (st in stats.statuses) {
|
||||
StatusRow(st)
|
||||
}
|
||||
}
|
||||
Hint(
|
||||
"定时状态每参与一轮减 1,归零就消失;持久状态不会自己过期。" +
|
||||
"状态提示词会被注入到它的系统提示里。",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatRow(
|
||||
stat: StatValue,
|
||||
editing: Boolean,
|
||||
input: String,
|
||||
onInput: (String) -> Unit,
|
||||
onStartEdit: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
onCommit: () -> Unit,
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stat.name, fontSize = 13.sp, color = doubaoText(), modifier = Modifier.weight(1f))
|
||||
if (stat.shared) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TinyTag("全世界观共用")
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
if (editing) {
|
||||
// 直接设值 —— 用户主权。★ 就地在行内变成输入框,不再压一层
|
||||
// 对话框(AGENTS.md:一次输入用弹窗也行,但这里已经有上下文,
|
||||
// 就地改更省事,而且弹窗会盖住进度条)
|
||||
androidx.compose.material3.OutlinedTextField(
|
||||
value = input,
|
||||
onValueChange = onInput,
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.width(84.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
RowAction("好") { onCommit() }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
RowAction("取消") { onCancel() }
|
||||
} else {
|
||||
Text(
|
||||
"${fmtNum(stat.value)} / ${fmtNum(stat.max)}",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("改") { onStartEdit() }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// 进度条:`ratio()` 在模型里(三个入口共用一份换算,圆角和取整才不会各说各话)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(doubaoSurface()),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth(stat.ratio())
|
||||
.height(6.dp)
|
||||
.clip(RoundedCornerShape(3.dp))
|
||||
.background(Doubao.Blue),
|
||||
)
|
||||
}
|
||||
if (stat.text.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(stat.text, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusRow(st: StatusInstance) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(st.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(6.dp))
|
||||
TinyTag(if (st.isPersistent) "持久" else "剩 ${st.remaining} 轮")
|
||||
if (st.stacks > 1) {
|
||||
Spacer(Modifier.width(4.dp))
|
||||
TinyTag("×${st.stacks}")
|
||||
}
|
||||
}
|
||||
if (st.hint.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(st.hint, fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TinyTag(text: String) {
|
||||
Text(
|
||||
text,
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.12f))
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** 数值显示:整数就不带小数点(45.0 → 45),不然看着别扭 */
|
||||
private fun fmtNum(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
@@ -19,6 +19,10 @@ import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
// ★ 扩展函数(`Modifier.verticalScroll`)**不能用全限定名调用** ——
|
||||
// 必须 import 进来。这个坑花了两轮构建才撞明白。
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -224,6 +228,19 @@ fun AppRoot(
|
||||
vm.moreSheetOpen = false
|
||||
vm.screen = Screen.Settings
|
||||
},
|
||||
// 从抽屉挪进来的三个
|
||||
onNewGroup = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.newGroupTopic()
|
||||
},
|
||||
onOpenNotes = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.openNotes()
|
||||
},
|
||||
onOpenModels = {
|
||||
vm.moreSheetOpen = false
|
||||
vm.modelPickerOpen = true
|
||||
},
|
||||
onClose = { vm.moreSheetOpen = false },
|
||||
)
|
||||
}
|
||||
@@ -333,6 +350,87 @@ fun AppRoot(
|
||||
)
|
||||
}
|
||||
|
||||
// 「新建群聊」:挑一个搭子(当前智能体当主角 = 主智能体)
|
||||
//
|
||||
// ★ 用对话框而不是全屏:这是**一次选择**(挑一个人就完了),
|
||||
// 智能体一般不超过十个,一屏放得下 —— 正是 AGENTS.md 里
|
||||
// "一次确认 / 纯菜单用弹窗"那一档。
|
||||
if (vm.pickGroupPeer) {
|
||||
val others = vm.state.agents.filter { it.id != vm.activeAgent?.id }
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.cancelPickGroupPeer() },
|
||||
title = { Text("和谁一起聊") },
|
||||
text = {
|
||||
if (others.isEmpty()) {
|
||||
Text("还没有别的智能体。先去「智能体」里建一个。", fontSize = 13.sp)
|
||||
} else {
|
||||
// ★ 用全限定名:这个文件的 import 列表里没有
|
||||
// verticalScroll / rememberScrollState,
|
||||
// 而它们只在这一处用得到(别的滚动都在各自的界面文件里)
|
||||
// ★ 这层滚动用**全限定调用**:`Modifier.verticalScroll`
|
||||
// 是个扩展函数,光写名字这里解析不到,而为了它一行
|
||||
// 往这个文件顶部加 import 不划算(只此一处用得到)
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
for (a in others) {
|
||||
Text(
|
||||
a.name,
|
||||
fontSize = 14.sp,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { vm.createGroupWith(a.id) }
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { vm.cancelPickGroupPeer() },
|
||||
) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// [规则包编辑](v1.2 附录 D)—— 全屏
|
||||
AnimatedVisibility(
|
||||
visible = vm.editingRulePack != null,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
RulePackEditScreen(vm = vm, onBack = { vm.closeRulePackEdit() })
|
||||
}
|
||||
|
||||
// 「群成员」(v1.2 §3.9)—— 用户手动增删成员无条件
|
||||
AnimatedVisibility(
|
||||
visible = vm.membersConvId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
GroupMembersScreen(
|
||||
vm = vm,
|
||||
conversationId = vm.membersConvId,
|
||||
onBack = { vm.closeMembers() },
|
||||
// 成员行上的「状态」→ 开 [状态数值](三个入口之一)
|
||||
onOpenStats = { vm.openStats(it) },
|
||||
)
|
||||
}
|
||||
|
||||
// [状态数值](v1.2 §3.10 / §3.11)—— 三个入口共用这一个界面:
|
||||
// 聊天页的状态栏、智能体编辑的"它的状态"、群成员的「状态」按钮
|
||||
AnimatedVisibility(
|
||||
visible = vm.statsAgentId.isNotBlank(),
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
AgentStatsScreen(
|
||||
vm = vm,
|
||||
agentId = vm.statsAgentId,
|
||||
onBack = { vm.closeStats() },
|
||||
)
|
||||
}
|
||||
|
||||
// 导入记忆:先读文件,再让用户选**合并还是覆盖**(复查报告 4.2.4)。
|
||||
//
|
||||
// ★ 默认是合并:覆盖是破坏性的,用户点错一次就全没了。
|
||||
@@ -493,7 +591,18 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
* 列表这种要滚动的东西不用弹窗或折叠面板)
|
||||
*/
|
||||
// 分区标题:抽屉里两组东西(功能 / 对话)不标一下容易混在一起看
|
||||
SectionLabel("功能", Modifier.padding(horizontal = 20.dp, vertical = 6.dp))
|
||||
// ★ 分组标题的留白也一起放松 —— 只加项间距的话,
|
||||
// 标题会和第一项粘在一起,看着像"标题属于上一组"
|
||||
SectionLabel("功能", Modifier.padding(start = 22.dp, top = 14.dp, bottom = 6.dp))
|
||||
// ★★ 抽屉第一层**只留四件天天用的**(用户明确说"太挤了"、
|
||||
// "把别的放更多里"):
|
||||
//
|
||||
// 开启新话题 · 智能体 · 记忆 · 更多功能
|
||||
//
|
||||
// 笔记 / 模型 / 新建群聊都挪进「更多功能」了。
|
||||
// 「模型」虽然也常用,但它是个**配置**(配好基本不动),
|
||||
// 腾出来的位置留给底下的对话列表更值 ——
|
||||
// 而对话列表才是用户 90% 打开抽屉的目的。
|
||||
DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() }
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
// ★ 抽屉这一项进的是**选择界面**(需求 2.1 的入口页),
|
||||
@@ -507,31 +616,48 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
vm.drawerOpen = false
|
||||
vm.activeAgent?.id?.let { vm.openMemories(it) }
|
||||
}
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
DrawerItem(Icons.Filled.EditNote, "笔记") {
|
||||
vm.drawerOpen = false
|
||||
vm.openNotes()
|
||||
}
|
||||
// 「模型」那一栏:和豆包一样把当前模型 + 思考强度摆右边
|
||||
DrawerItem(
|
||||
Icons.Filled.Memory, "模型",
|
||||
trailing = "${shortModel(vm.settings.model)} ${thinkingLabel(vm.settings.thinkingLevel)}",
|
||||
) {
|
||||
vm.modelPickerOpen = true
|
||||
vm.drawerOpen = false
|
||||
}
|
||||
DrawerItem(Icons.Filled.Apps, "更多功能") {
|
||||
vm.drawerOpen = false
|
||||
vm.moreSheetOpen = true
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("对话", Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
|
||||
|
||||
// ★ 群聊和单聊**分开列**(用户要求)。
|
||||
//
|
||||
// 混在一起排的时候,群聊会被一堆单聊埋到下面去 ——
|
||||
// 而这两类的**行为**本来就不一样:群聊有成员表、点名条、
|
||||
// 谁在说话跟着换;单聊只有一个主人。混在一起用户还得靠标题猜。
|
||||
//
|
||||
// 私聊记录(两个 AI 自己聊的)归到「对话」那一组 ——
|
||||
// 它没有"多个成员在群里"的语义,是两条消息流而已。
|
||||
val groups = vm.state.conversations.filter { it.isGroup }
|
||||
val singles = vm.state.conversations.filter { !it.isGroup }
|
||||
|
||||
LazyColumn(Modifier.weight(1f)) {
|
||||
items(vm.state.conversations.size) { i ->
|
||||
ConversationRow(vm, vm.state.conversations[i])
|
||||
if (groups.isNotEmpty()) {
|
||||
item {
|
||||
SectionLabel("群聊", Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp))
|
||||
}
|
||||
items(groups.size) { i -> ConversationRow(vm, groups[i]) }
|
||||
}
|
||||
item {
|
||||
SectionLabel(
|
||||
if (groups.isEmpty()) "对话" else "单聊",
|
||||
Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp),
|
||||
)
|
||||
}
|
||||
if (singles.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
"还没有单聊。点上面的「开启新话题」挑一个智能体。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 22.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(singles.size) { i -> ConversationRow(vm, singles[i]) }
|
||||
}
|
||||
|
||||
Row(
|
||||
@@ -584,11 +710,14 @@ private fun DrawerItem(
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 10.dp, vertical = 2.dp)
|
||||
// ★ 项之间的留白从 2dp 提到 6dp、项内从 13dp 提到 16dp。
|
||||
// 原来每项视觉高度只有 ~48dp,七项叠在一起糊成一片 ——
|
||||
// 用户反馈"太挤了"。现在每项 ~60dp,手指点起来也稳。
|
||||
.padding(horizontal = 10.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(bg)
|
||||
.clickable(interactionSource = source, indication = null, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 13.dp),
|
||||
.padding(horizontal = 12.dp, vertical = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, null, tint = doubaoText(), modifier = Modifier.size(22.dp))
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -27,6 +29,7 @@ import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应;AgentSelect 是需求 v1.1 新增的选择页) */
|
||||
enum class Screen { Chat, Profile, Settings, Skills, Agents, AgentSelect, Resources, Terminal, Meetings }
|
||||
@@ -193,6 +196,7 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
.put("modelId", agent.modelId)
|
||||
.put("worldviewId", agent.worldviewId)
|
||||
.put("emotionEnabled", agent.emotionEnabled)
|
||||
.put("inviteMode", agent.inviteMode)
|
||||
.put("tokenLimit", agent.tokenLimit)
|
||||
// ★ 外观四件套:键名带连字符(需求 2.5 定的包格式),
|
||||
// 转换只有 AgentImage.toJson() 这一处
|
||||
@@ -221,10 +225,13 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
*/
|
||||
fun uploadAgentAsset(agentId: String, key: String, name: String, base64: String) {
|
||||
viewModelScope.launch {
|
||||
val saved = runCatching {
|
||||
val err = runCatching {
|
||||
withContext(Dispatchers.IO) { client.setAgentAsset(agentId, key, name, base64) }
|
||||
}.getOrNull()
|
||||
if (saved == null) showHint("这张图没传上去") else refresh()
|
||||
}.exceptionOrNull()
|
||||
// ★ 把服务端那句话**原样**带出来。上一版一律显示「这张图没传上去」,
|
||||
// 于是"图太大 / 请求体不是合法 JSON / 槽位不对"三种完全不同的原因
|
||||
// 在用户眼里一模一样 —— 只能来问,而这一问就是好几轮。
|
||||
if (err != null) showHint(err.message ?: "这张图没传上去") else refresh()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,13 +318,58 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从选图器给的 URI 直接上传一张外观图(读图 / 压缩 / base64 / 上传全在 IO 线程)。
|
||||
*
|
||||
* ★ 为什么不让界面自己读字节再调 [uploadAgentAsset]:
|
||||
* ① launcher 的回调跑在**主线程**上,而这里要解码的可能是 30MB 的手机照片,
|
||||
* 放主线程就是几百毫秒到几秒的卡死;
|
||||
* ② 智能体编辑页和世界观编辑页各抄一份读图代码的话,
|
||||
* 下次修"大图"这种坑必然只修一份 —— 这个仓库里已经反复出现过。
|
||||
*/
|
||||
fun uploadAgentAssetFrom(context: Context, agentId: String, key: String, uri: Uri) {
|
||||
viewModelScope.launch {
|
||||
val outcome = runCatching {
|
||||
val picked = withContext(Dispatchers.IO) { readImageForUpload(context, uri) }
|
||||
withContext(Dispatchers.IO) {
|
||||
client.setAgentAsset(agentId, key, picked.name, picked.base64)
|
||||
}
|
||||
picked
|
||||
}
|
||||
outcome
|
||||
// 成功也说一句"压到多大了" —— 用户传 30MB 的图回来看到 300KB,
|
||||
// 不说清楚会以为图被弄坏了
|
||||
.onSuccess { showHint(it.note); refresh() }
|
||||
// 失败原因原样带出来:图太大 / 读不出 / 服务端拒绝,是三件事
|
||||
.onFailure { showHint(it.message ?: "这张图没传上去") }
|
||||
}
|
||||
}
|
||||
|
||||
/** 上传世界观的一张外观图(和智能体走同一个接口形状,只是路径不同) */
|
||||
fun uploadWorldviewAsset(id: String, key: String, name: String, base64: String) {
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
val err = runCatching {
|
||||
withContext(Dispatchers.IO) { client.setWorldviewAsset(id, key, name, base64) }
|
||||
}.exceptionOrNull()
|
||||
// ★ 这里原来把 runCatching 的结果**整个丢掉了** —— 传失败也照样 refresh,
|
||||
// 界面一动不动,用户只能说"设置不了"。失败必须说出来。
|
||||
if (err != null) showHint(err.message ?: "这张图没传上去") else refresh()
|
||||
}
|
||||
}
|
||||
|
||||
/** 世界观的选图上传,和 [uploadAgentAssetFrom] 同一条路 */
|
||||
fun uploadWorldviewAssetFrom(context: Context, id: String, key: String, uri: Uri) {
|
||||
viewModelScope.launch {
|
||||
val outcome = runCatching {
|
||||
val picked = withContext(Dispatchers.IO) { readImageForUpload(context, uri) }
|
||||
withContext(Dispatchers.IO) {
|
||||
client.setWorldviewAsset(id, key, picked.name, picked.base64)
|
||||
}
|
||||
picked
|
||||
}
|
||||
refresh()
|
||||
outcome
|
||||
.onSuccess { showHint(it.note); refresh() }
|
||||
.onFailure { showHint(it.message ?: "这张图没传上去") }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,6 +383,390 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
* ★ 结果要**说清楚导入了什么**:成功什么都不提示的话,
|
||||
* 用户不知道是成功了还是没反应。
|
||||
*/
|
||||
// ----------------------------------------------------------------------- //
|
||||
// 群聊成员(v1.2 §3.9:"用户手动增删成员无条件")
|
||||
// ----------------------------------------------------------------------- //
|
||||
|
||||
/** 成员 **id → 名字**(界面各处都要显示名字,不要各拼一遍) */
|
||||
fun memberNames(conv: Conversation): List<Pair<String, String>> =
|
||||
conv.participants.mapNotNull { id ->
|
||||
state.agents.firstOrNull { it.id == id }?.let { id to it.name }
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------- //
|
||||
// 规则包编辑(v1.2 附录 D)
|
||||
// ----------------------------------------------------------------------- //
|
||||
|
||||
/**
|
||||
* 正在编辑的规则包(空 = 没开 [规则包编辑])。
|
||||
*
|
||||
* ★ 这里放的是**完整包**(带脚本源码)—— 列表里那份来自 `/api/state`,
|
||||
* 脚本源码被剔掉了(每次刷新都传几 KB 是浪费)。
|
||||
*/
|
||||
var editingRulePack by mutableStateOf<com.doubao.lynxclone.data.RulePack?>(null)
|
||||
private set
|
||||
|
||||
/** 打开 [规则包编辑]:单独拉一次完整包 */
|
||||
fun openRulePackEdit(id: String) {
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.rulePack(id) } }
|
||||
.onSuccess { editingRulePack = it }
|
||||
.onFailure { showHint("读不到这个包:${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
fun closeRulePackEdit() {
|
||||
editingRulePack = null
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建一个**带模板**的规则包,然后直接进编辑页。
|
||||
*
|
||||
* ★ 为什么要有"模板":一个新包如果是空的,用户进去只看到几张空表,
|
||||
* 不知道"数值该长什么样、脚本该写什么" —— 而这是这个功能里
|
||||
* 门槛最高的地方。给一份能跑的样例(两条数值 + 两条状态 +
|
||||
* 一段带三个入口的脚本),改起来比从零写容易得多。
|
||||
*
|
||||
* ★ 模板里的脚本**是可用的**:照着它改就行,不是伪代码。
|
||||
*/
|
||||
fun createRulePackFromTemplate() {
|
||||
viewModelScope.launch {
|
||||
val pack = runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
client.createRulePack(
|
||||
"新规则包", "示例:好感度会随对话变化,中毒每轮扣好感。",
|
||||
com.doubao.lynxclone.data.rulePackTemplateInfo(),
|
||||
com.doubao.lynxclone.data.RULE_PACK_TEMPLATE_SCRIPTS,
|
||||
)
|
||||
}
|
||||
}.getOrElse {
|
||||
showHint("建不了:${it.message}")
|
||||
return@launch
|
||||
}
|
||||
refresh()
|
||||
openRulePackEdit(pack.id)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存规则包(名称 / 说明 / 脚本 / 定义一起存)。
|
||||
*
|
||||
* ★ **脚本必须和定义一起存**:定义里写着 `script: "favor.py"`,
|
||||
* 脚本没存的话那个名字指向一个不存在的文件 —— 表现是"裁决没生效",
|
||||
* 而界面上一切正常(这才是最难查的)。
|
||||
*/
|
||||
fun saveRulePack(
|
||||
name: String,
|
||||
note: String,
|
||||
info: org.json.JSONObject,
|
||||
scripts: Map<String, String>,
|
||||
) {
|
||||
val cur = editingRulePack ?: return
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
client.saveRulePack(cur.id, name, note, info, scripts)
|
||||
}
|
||||
}.onSuccess {
|
||||
showHint("存好了")
|
||||
editingRulePack = it
|
||||
refresh()
|
||||
}.onFailure { showHint("存不了:${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建一个群聊:**当前智能体 + 挑一个搭子**(v1.2 §3.9)。
|
||||
*
|
||||
* ★ 为什么至少要挑一个:群聊的发言权仲裁里"主智能体兜底"靠的是
|
||||
* 成员列表第 0 个。只有一个人的"群"退化成单聊,没有任何意义,
|
||||
* 还会让用户以为群聊没生效。
|
||||
*
|
||||
* ★ 建完**直接进成员页**:用户刚挑完人,下一步十有八九就是
|
||||
* "再加一个"或者"看看都有谁" —— 让他自己再找一遍入口是浪费。
|
||||
*/
|
||||
var pickGroupPeer by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
fun newGroupTopic() {
|
||||
pickGroupPeer = true
|
||||
}
|
||||
|
||||
fun cancelPickGroupPeer() {
|
||||
pickGroupPeer = false
|
||||
}
|
||||
|
||||
/** 挑好了搭子 → 建群并进去 */
|
||||
fun createGroupWith(agentId: String) {
|
||||
pickGroupPeer = false
|
||||
val first = activeAgent?.id.orEmpty()
|
||||
if (first.isBlank() || first == agentId) {
|
||||
showHint("先选一个智能体当主角")
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
client.newGroupConversation("群聊", listOf(first, agentId))
|
||||
}
|
||||
}.onSuccess { c ->
|
||||
if (c.id.isNotBlank()) {
|
||||
activeConversationId = c.id
|
||||
// ★ `messages` 是 SnapshotStateList(Compose 的),不能整体赋值
|
||||
messages.clear()
|
||||
}
|
||||
refresh()
|
||||
openMembers(c.id)
|
||||
}.onFailure { showHint("建群失败:${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
/** 把当前会话变成群聊(拉第二个人进来时;单聊**就地升级**,不新建会话) */
|
||||
fun makeGroup(agentId: String) {
|
||||
val conv = state.conversations.firstOrNull { it.id == activeConversationId }
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
if (conv == null || conv.participants.isEmpty()) {
|
||||
// 还没有会话 → 用当前智能体 + 新来的建一个群
|
||||
val first = state.settings.activeAgentId.ifBlank {
|
||||
state.agents.firstOrNull()?.id.orEmpty()
|
||||
}
|
||||
client.newGroupConversation(
|
||||
"群聊", listOf(first, agentId).filter { it.isNotBlank() })
|
||||
} else {
|
||||
client.addMember(conv.id, agentId)
|
||||
}
|
||||
}
|
||||
}.onSuccess {
|
||||
showHint("已经拉进来了")
|
||||
refresh()
|
||||
}.onFailure { showHint("拉人失败:${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
fun addMember(agentId: String) {
|
||||
val cid = activeConversationId
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.addMember(cid, agentId) } }
|
||||
.onSuccess { showHint("加好了"); refresh() }
|
||||
.onFailure { showHint(it.message ?: "加不进去") }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移出一个成员。
|
||||
*
|
||||
* ★ 主智能体移不掉 —— 它是**无人被点名时的兜底发言者**,移了就冷场。
|
||||
* 界面也要把那个按钮藏起来(两道,因为界面是给用户看的、内核是给
|
||||
* "绕过界面"的路径兜底的)。
|
||||
*/
|
||||
fun removeMember(agentId: String) {
|
||||
val cid = activeConversationId
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.removeMember(cid, agentId) } }
|
||||
.onSuccess { showHint("移出去了"); refresh() }
|
||||
.onFailure { showHint(it.message ?: "移不出去") }
|
||||
}
|
||||
}
|
||||
|
||||
/** 规则包导入**待确认**的那份数据(非空 = 界面要弹「包含可执行 Python 脚本」警告)。
|
||||
*
|
||||
* ★ 为什么要一个中间态:包里有 `.py` 时内核**拒绝直接导入**,
|
||||
* 返回 `needConfirm` + 警告文案。界面拿到之后弹确认框,
|
||||
* 用户点了「继续」才带着 `confirmScripts` 再传一次。
|
||||
*
|
||||
* 这条关口放在**服务端**是有意的 —— 界面弹框只是礼貌,
|
||||
* 绕过界面直接调接口也必须拦得住(脚本每轮在用户设备上跑)。
|
||||
*/
|
||||
var pendingRulePack by mutableStateOf("")
|
||||
private set
|
||||
var rulePackWarning by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/** 关掉警告框(用户点了取消) */
|
||||
fun dismissRulePack() {
|
||||
pendingRulePack = ""
|
||||
rulePackWarning = ""
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入规则包(v1.2 附录 D)。
|
||||
*
|
||||
* 第一次调用只**探路**:内核发现包里有脚本就返回警告、不落库;
|
||||
* 用户确认后 [confirmed] 传 true 再调一次。
|
||||
*/
|
||||
fun importRulePack(base64: String, confirmed: Boolean = false) {
|
||||
viewModelScope.launch {
|
||||
val r = runCatching {
|
||||
withContext(Dispatchers.IO) { client.importRulePack(base64, confirmed) }
|
||||
}.getOrElse {
|
||||
showHint("导入失败:${it.message ?: it.javaClass.simpleName}")
|
||||
return@launch
|
||||
}
|
||||
if (r.optBoolean("needConfirm")) {
|
||||
pendingRulePack = base64
|
||||
rulePackWarning = r.optString("warning")
|
||||
return@launch
|
||||
}
|
||||
if (!r.optBoolean("ok", true)) {
|
||||
showHint(r.optString("error").ifBlank { "导入失败" })
|
||||
return@launch
|
||||
}
|
||||
val n = r.optInt("stats") + r.optInt("statuses")
|
||||
val s = r.optInt("scripts")
|
||||
pendingRulePack = ""
|
||||
rulePackWarning = ""
|
||||
showHint("已导入规则包:$n 条定义" + if (s > 0) "、" + s + " 个脚本" else "")
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记 / 取消标记第 [index] 条消息为「重要」(v1.2 §4.3)。
|
||||
*
|
||||
* ★ 被标记的消息在**上下文窗口裁剪**时破格永久携带 ——
|
||||
* 平时"攒够 5 轮裁 5 轮",这几条会一直留着。
|
||||
* 所以提示语要写清**效果**,不然用户不知道这个标记是干什么的。
|
||||
*/
|
||||
fun toggleImportant(index: Int) {
|
||||
val cid = activeConversationId
|
||||
val msg = messages.getOrNull(index) ?: return
|
||||
val cur = msg.important
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
// ★ 传**内容**不传下标:界面的列表和存储的不保证一一对应
|
||||
withContext(Dispatchers.IO) { client.markImportant(cid, msg.content, !cur) }
|
||||
}.onSuccess {
|
||||
// ★★ **本地也改一下**,不能只靠 refresh()。
|
||||
//
|
||||
// 界面上这份 `messages` 和存储里那份**本来就不是总同步**
|
||||
// (这一版之前就存在的行为),只 refresh 的话用户看不到
|
||||
// 那个「★ 重要」标记 —— 表现是"我标了但界面上没反应",
|
||||
// 而那正是最初把标记打到别人身上的同一个根因。
|
||||
messages.getOrNull(index)?.let { old ->
|
||||
messages[index] = old.copy(important = !cur)
|
||||
}
|
||||
showHint(
|
||||
if (!cur) "标成重要了 —— 以后裁剪上下文时这条会一直留着"
|
||||
else "取消标记了",
|
||||
)
|
||||
}.onFailure { showHint(it.message ?: "标不了") }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 内核给这条对话"换了归属"时的说明(非空 = 界面上提示一句)。
|
||||
*
|
||||
* ★ 它是个**用户能感知**的变化:对话突然换了个身份。
|
||||
* 不提示的话用户会以为自己点错了什么。显示一次就清掉。
|
||||
*/
|
||||
var rebasedNote by mutableStateOf("")
|
||||
private set
|
||||
|
||||
fun clearRebasedNote() {
|
||||
rebasedNote = ""
|
||||
}
|
||||
|
||||
/** 这一轮谁在说话(群聊仲裁的结果,v1.2 §3.9) */
|
||||
var currentSpeakerId by mutableStateOf("")
|
||||
private set
|
||||
/** 为什么是他("没人被点名,主智能体兜底"这类解释) */
|
||||
var speakerNote by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/** 背景是否跟随当前说话者(v1.2 §6.1,默认开) */
|
||||
fun setFollowSpeaker(on: Boolean) = saveSettings(mapOf("followSpeaker" to on))
|
||||
|
||||
/** v1.2 §4.3:对话上下文窗口(轮)/ 裁剪批量 / 私聊轮数 —— 都存在全局设置里 */
|
||||
fun setContextWindow(n: Int) = saveSettings(mapOf("contextWindow" to n))
|
||||
fun setContextBatch(n: Int) = saveSettings(mapOf("contextBatch" to n))
|
||||
fun setPrivateChatRounds(n: Int) = saveSettings(mapOf("privateChatRounds" to n))
|
||||
|
||||
// ----------------------------------------------------------------------- //
|
||||
// 私聊(v1.2 §3.9 形态 B)—— 两个智能体在后台自主对聊
|
||||
// ----------------------------------------------------------------------- //
|
||||
|
||||
/**
|
||||
* 正在私下聊的是谁(非空 = 界面上显示"他们正在聊…")。
|
||||
*
|
||||
* ★ 私聊接口**会跑一会儿**(默认 10 轮 = 20 次 LLM 调用)。
|
||||
* 没做成异步任务队列是个取舍:那要一整套"任务 id + 轮询 + 取消",
|
||||
* 而私聊是用户**主动发起、等着看结果**的动作 ——
|
||||
* 界面上转个圈比"发起之后不知道去哪儿看"好。
|
||||
*/
|
||||
var privateChatRunning by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/** 上一次私聊的结果说明("聊了 12 句,摘要已写进共享记忆") */
|
||||
var privateChatResult by mutableStateOf("")
|
||||
private set
|
||||
|
||||
fun startPrivateChat(firstId: String, secondId: String) {
|
||||
if (firstId.isBlank() || secondId.isBlank() || firstId == secondId) {
|
||||
showHint("要挑两个不同的智能体")
|
||||
return
|
||||
}
|
||||
val a = state.agents.firstOrNull { it.id == firstId }
|
||||
val b = state.agents.firstOrNull { it.id == secondId }
|
||||
privateChatRunning = "${a?.name ?: "?"} 和 ${b?.name ?: "?"}"
|
||||
privateChatResult = ""
|
||||
viewModelScope.launch {
|
||||
val r = runCatching {
|
||||
withContext(Dispatchers.IO) { client.privateChat(firstId, secondId) }
|
||||
}.getOrElse {
|
||||
privateChatRunning = ""
|
||||
showHint("聊不起来:${it.message}")
|
||||
return@launch
|
||||
}
|
||||
privateChatRunning = ""
|
||||
val n = r.optInt("rounds")
|
||||
privateChatResult = when (r.optString("endReason")) {
|
||||
// ★ 三种结束原因分开说 —— 用户要知道"为什么停了"
|
||||
"limit" -> "聊了 $n 句:${r.optString("endedBy")}的额度用完了," +
|
||||
"另一方收了个尾就结束了。"
|
||||
"error" -> "聊了 $n 句:中途出错了,已经停下来了。"
|
||||
else -> "聊了 $n 句,到轮数上限就停了。"
|
||||
} + if (r.optString("summary").isNotBlank()) "摘要已经写进共享记忆。" else ""
|
||||
showHint(privateChatResult)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
/** 已经选中的两个(点名字切换) */
|
||||
var privatePair by mutableStateOf(listOf<String>())
|
||||
private set
|
||||
|
||||
/**
|
||||
* 点一个名字:已选就取消,没选就加上(**最多两个**)。
|
||||
*
|
||||
* ★ 用"点名字切换"而不是两个下拉框:手机上两个下拉框要点四次、
|
||||
* 还得在两个弹层之间来回,而这里一共就十来个智能体。
|
||||
*/
|
||||
fun togglePrivatePick(agentId: String) {
|
||||
val cur = privatePair.toMutableList()
|
||||
if (!cur.remove(agentId)) {
|
||||
if (cur.size >= 2) return // 只让选两个
|
||||
cur.add(agentId)
|
||||
}
|
||||
privatePair = cur
|
||||
}
|
||||
|
||||
fun cancelPrivatePick() {
|
||||
privatePair = emptyList()
|
||||
}
|
||||
|
||||
/** 开始私聊(挑好人之后) */
|
||||
fun startPickedPrivateChat() {
|
||||
val p = privatePair
|
||||
if (p.size != 2) {
|
||||
showHint("挑两个人")
|
||||
return
|
||||
}
|
||||
privatePair = emptyList()
|
||||
startPrivateChat(p[0], p[1])
|
||||
}
|
||||
|
||||
fun importPackage(kind: String, base64: String, textJson: String) {
|
||||
viewModelScope.launch {
|
||||
val msg = runCatching {
|
||||
@@ -446,6 +882,74 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
var memoryLoading by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 正在看的群成员界面(空 = 没开)。
|
||||
*
|
||||
* ★ 和 `memoryAgentId` 一样用状态变量 + `return@Composable`,不是弹窗 ——
|
||||
* 成员列表要滚动,弹窗装不下(AGENTS.md 的界面约定)。
|
||||
*/
|
||||
var membersConvId by mutableStateOf("")
|
||||
private set
|
||||
|
||||
fun openMembers(conversationId: String) {
|
||||
membersConvId = conversationId
|
||||
}
|
||||
|
||||
fun closeMembers() {
|
||||
membersConvId = ""
|
||||
}
|
||||
|
||||
/** 正在看的 [状态数值] 浮层(空 = 没开) */
|
||||
var statsAgentId by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/** 当前这个智能体的数值 + 状态([状态数值] 界面用) */
|
||||
var agentStats by mutableStateOf<com.doubao.lynxclone.data.AgentStats?>(null)
|
||||
private set
|
||||
|
||||
fun openStats(agentId: String) {
|
||||
statsAgentId = agentId
|
||||
agentStats = null
|
||||
refreshStats()
|
||||
}
|
||||
|
||||
fun closeStats() {
|
||||
statsAgentId = ""
|
||||
agentStats = null
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉这个智能体的数值 + 状态。
|
||||
*
|
||||
* ★ 数值和状态**一个接口一起拿**(内核那边就是这么设计的)——
|
||||
* 界面上它们总是同屏出现的,分两次请求就得处理"一个到了一个没到"
|
||||
* 的中间态,而那个中间态用户看得见(列表先显示一半)。
|
||||
*/
|
||||
fun refreshStats() {
|
||||
val id = statsAgentId.ifBlank { return }
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.agentStats(id) } }
|
||||
.onSuccess { agentStats = it }
|
||||
.onFailure { showHint("读不到它的状态:${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户**直接设一个数值**。
|
||||
*
|
||||
* ★ 和 AI 走的路不同:AI 的 `change_stat` 只能申请**增量**、会被脚本裁决;
|
||||
* 用户是规则的主人,可以直接设值 —— 但内核照样会 clamp 到 [min,max],
|
||||
* 所以回来之后要以**返回值**为准刷新界面(不能乐观地先用自己填的那个值)。
|
||||
*/
|
||||
fun setStatDirect(name: String, value: Double) {
|
||||
val id = statsAgentId.ifBlank { return }
|
||||
viewModelScope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { client.setStat(id, name, value) } }
|
||||
.onSuccess { agentStats = it }
|
||||
.onFailure { showHint(it.message ?: "改不了") }
|
||||
}
|
||||
}
|
||||
|
||||
/** AI 整理记忆的结果提示("12 条 → 7 条"这种) */
|
||||
var memoryHint by mutableStateOf("")
|
||||
private set
|
||||
@@ -896,6 +1400,87 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
|
||||
private var chatJob: AtomicBoolean? = null
|
||||
|
||||
/**
|
||||
* 这一轮 AI 是不是用 `pass_turn` 把话交给了别人(群聊才有)→ 跑完自动替他续一轮。
|
||||
*
|
||||
* ★ 用 [AtomicBoolean] 而不是普通 `var`:置位发生在
|
||||
* `client.chat` 的**回调线程**(IO)上,读取发生在 `finally`(协程)里 ——
|
||||
* 两边不是一个线程。用普通变量的话,这个"续不续轮"的判断就是在赌调度,
|
||||
* 表现是"有时候能聊起来、有时候不能"(比稳定不工作更难查)。
|
||||
*
|
||||
* ★ 没有它的话,群聊里的"AI 互相说话"就只是**半截**:
|
||||
* A 把话让给 B,然后这一轮就结束了,B 永远没开口 ——
|
||||
* 用户得再发一条消息才看得到 B 说话。
|
||||
*/
|
||||
private val handoffDone = AtomicBoolean(false)
|
||||
|
||||
/**
|
||||
* 这一轮 AI 把话交给了**谁**(id / 名字)。
|
||||
*
|
||||
* ★ 用 `AtomicReference` 的理由和 [handoffDone] 一样:写在 `client.chat`
|
||||
* 的**回调线程**(IO)上,而 `runChat` 的 `finally` 紧接着就要读它 ——
|
||||
* 普通 `var` 的话,"交给谁"会随调度时有时无,表现是手动模式那个
|
||||
* 「让他说」按钮**有时候不出来**。
|
||||
*/
|
||||
private val handoffToRef = AtomicReference("")
|
||||
private val handoffFromRef = AtomicReference("")
|
||||
|
||||
/** 已经连续自动续了几轮。防止两个 AI 你一句我一句停不下来(那是烧钱) */
|
||||
private var autoRounds = 0
|
||||
|
||||
/**
|
||||
* 待用户决定的移交:AI 把话交给了谁。
|
||||
*
|
||||
* ★★ 用户的原话:「talk_to 是用户可以选择传递和停止,有自动模式(不用用户确认)」。
|
||||
*
|
||||
* 所以默认**不自动续** —— 一轮跑完如果 AI 交了话,
|
||||
* 聊天页底下出现一条「X 把话交给了 Y」+「让他说」「停在这」,
|
||||
* **由用户决定**。设置里开了「AI 对聊自动模式」才跳过这一步。
|
||||
*
|
||||
* 这也顺带解决了烧钱:默认不会自己一直聊下去。
|
||||
*/
|
||||
var pendingHandoffName by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/** 是谁交出去的(显示用) */
|
||||
var pendingHandoffFromName by mutableStateOf("")
|
||||
private set
|
||||
|
||||
/** 交给的那个人(点「让他说」时用) */
|
||||
private var pendingHandoffTo = ""
|
||||
|
||||
/** 用户点「让他说」—— 接着让下一个人开口 */
|
||||
fun continueHandoff() {
|
||||
val to = pendingHandoffTo
|
||||
if (to.isBlank()) return
|
||||
pendingHandoffTo = ""
|
||||
pendingHandoffName = ""
|
||||
pendingHandoffFromName = ""
|
||||
autoRounds++
|
||||
runChat("", emptyList(), auto = true, forceSpeaker = to)
|
||||
}
|
||||
|
||||
/** 用户点「停在这」—— 到此为止,不再往下递 */
|
||||
fun stopHandoff() {
|
||||
val who = pendingHandoffName
|
||||
pendingHandoffTo = ""
|
||||
pendingHandoffName = ""
|
||||
pendingHandoffFromName = ""
|
||||
handoffDone.set(false)
|
||||
if (who.isNotBlank()) showHint("停在这里了($who 没接)")
|
||||
}
|
||||
|
||||
/** AI 对聊的自动模式(不用用户确认)。设置里那个开关 */
|
||||
fun setAiTalkAuto(on: Boolean) = saveSettings(mapOf("aiTalkAuto" to on))
|
||||
|
||||
/**
|
||||
* 一次自动对聊最多续几轮。
|
||||
*
|
||||
* 3 是个保守值:够看出"他们真的在对话",又不至于用户一转头回来
|
||||
* 发现 Token 少了一大截。想聊更久,用户再发一句就是了。
|
||||
*/
|
||||
private val autoRoundCap = 3
|
||||
|
||||
init {
|
||||
// 内核线程弹界面 → 这里切主线程更新 Compose 状态
|
||||
AiSurface.subscribe { kind ->
|
||||
@@ -1032,10 +1617,36 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
|
||||
/* ------------------------------ 会话 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 重新拉当前会话的消息列表(只重载消息,不切屏、不动别的状态)。
|
||||
*
|
||||
* ★★ 为什么需要它(用户报的「talk_to 看不到智能体说啥」):
|
||||
* 工具是在**轮中**往对话里写东西的 —— `talk_to` 就是:它把
|
||||
* 「我对你说的话」直接落库了。而本地这份 `messages` 只在流式里追增量,
|
||||
* 根本不知道库里多了几条,于是**那句话说出去就看不见**,
|
||||
* 要退出去重进这条对话才看得到。
|
||||
*
|
||||
* ★ 不用 `openConversation`:它会切屏、清空、还重读一次 meta ——
|
||||
* 刚跑完一轮就调它太重,屏幕上还会闪一下。
|
||||
*/
|
||||
private suspend fun reloadMessages() {
|
||||
val id = activeConversationId.ifBlank { "c_main" }
|
||||
val list = runCatching {
|
||||
withContext(Dispatchers.IO) { client.conversation(id) }
|
||||
}.getOrNull() ?: return
|
||||
// 流式期间本地插的那条 pending 占位不在库里,重载正好换成落库的版本
|
||||
messages.clear()
|
||||
messages.addAll(list)
|
||||
}
|
||||
|
||||
fun openConversation(id: String) {
|
||||
activeConversationId = id
|
||||
drawerOpen = false
|
||||
screen = Screen.Chat
|
||||
// ★ 换会话就把「上一轮谁在说」清掉 —— 不清的话,从群 A 切到群 B,
|
||||
// B 的顶栏和背景会显示**A 那个发言人**(用户报的"对不上"里就有这一种)。
|
||||
currentSpeakerId = ""
|
||||
speakerNote = ""
|
||||
viewModelScope.launch {
|
||||
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
|
||||
messages.clear()
|
||||
@@ -1127,10 +1738,126 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
runChat(t, emptyList())
|
||||
}
|
||||
|
||||
private fun runChat(text: String, files: List<Attachment>) {
|
||||
messages.add(ChatMessage(role = "user", content = text, attachments = files))
|
||||
/**
|
||||
* 停止这一轮生成(用户点「停止」)。
|
||||
*
|
||||
* ★★ 这个方法是补上来的:`chatJob` 这个取消句柄**一直存在**,
|
||||
* 内核也一路支持取消(`cancelled` 从 HTTP 传到 agent_loop 的每一跳),
|
||||
* 但**没有任何界面调用它** —— 用户只能干等它把话说完
|
||||
* (用户报的:「对话过程中可中断」)。
|
||||
* 这次修语音那条链时又撞见同一个模式:
|
||||
* 能力全都在,缺的只是最后那一个按钮。
|
||||
*
|
||||
* ★ 置 true 而不是 cancel 协程:让内核那头**正常收尾**(把已经生成的部分
|
||||
* 落库、事件流正常结束),硬 cancel 会留下半截状态。
|
||||
*/
|
||||
fun stopGenerating() {
|
||||
val job = chatJob
|
||||
if (job == null) {
|
||||
showHint("这一轮已经结束了")
|
||||
return
|
||||
}
|
||||
job.set(true)
|
||||
showHint("已停止")
|
||||
}
|
||||
|
||||
/**
|
||||
* 让群里的成员**轮流对话**(用户要的「智能体可以和群聊中另外一个智能体对话」)。
|
||||
*
|
||||
* ★★ 为什么不是"等 AI 自己 `pass_turn`":实测它**并不总会**移交 ——
|
||||
* 它更愿意自己把话说完。所以那条路靠不住,用户按了没反应。
|
||||
* 这里改成界面**直接按顺序把发言权递过去**(`forceSpeaker`),
|
||||
* 不依赖 AI 配合,才保证一定聊得起来。
|
||||
*
|
||||
* ★ 只取前两个成员:人多了"轮流"就说不清是谁跟谁,
|
||||
* 而且 Token 会成倍涨。想换人就让某个人被 @ 一次,发言权就过去了。
|
||||
*
|
||||
* ★ 随时可以打断:生成中那个圆钮是「停止」,点一下
|
||||
* `aiTalkLeft` 就随着 `cancel.get()` 一起失效。
|
||||
*/
|
||||
/**
|
||||
* 点名(点群聊底部的 `@某人`)。
|
||||
*
|
||||
* ★ 只做两件事:把 `@名字 ` 插进草稿、把「让他们聊」掐掉
|
||||
* (用户点了名 = 他要接管发言权了)。
|
||||
*
|
||||
* ★★ **不碰 `currentSpeakerId`** —— 这是上一版踩的坑。
|
||||
* 用户的原话:「背景是根据当前对话来的,**不是让你 @ 谁就换哪个背景**」。
|
||||
* 点一下按钮就把顶栏和背景切成那个人,但消息根本没发出去、
|
||||
* 对方也还没开口,于是屏幕上出现"顶栏是寐眠、最后一条消息是小黑"——
|
||||
* 正是他截图里指出来的那种不对。
|
||||
*
|
||||
* 现在改成:**发出去、内核仲裁完、`speaker` 事件回来才切**。
|
||||
* 那个事件是轮前的,所以观感上依然是"一点就换",但换的是
|
||||
* **真正要开口的那个人**,名副其实。
|
||||
*/
|
||||
fun mentionAgent(name: String) {
|
||||
aiTalkLeft = 0
|
||||
aiTalkTurn = 0
|
||||
aiTalkPair = emptyList()
|
||||
draft = draft + "@$name "
|
||||
}
|
||||
|
||||
fun startAiTalk(rounds: Int = 4) {
|
||||
val conv = state.conversations.firstOrNull { it.id == activeConversationId }
|
||||
if (conv == null || !conv.isGroup) {
|
||||
showHint("这条不是群聊")
|
||||
return
|
||||
}
|
||||
if (streaming) {
|
||||
showHint("它还在说,先点停止")
|
||||
return
|
||||
}
|
||||
val members = conv.participants.filter { id -> state.agents.any { it.id == id } }
|
||||
if (members.size < 2) {
|
||||
showHint("群里至少要有两个智能体才能对聊")
|
||||
return
|
||||
}
|
||||
aiTalkPair = members.take(2)
|
||||
// 第 1 轮就在这里发起了,所以"还剩"是 rounds - 1
|
||||
aiTalkLeft = (rounds - 1).coerceAtLeast(0)
|
||||
aiTalkTurn = 1
|
||||
val first = state.agents.firstOrNull { it.id == aiTalkPair[0] }?.name.orEmpty()
|
||||
val second = state.agents.firstOrNull { it.id == aiTalkPair[1] }?.name.orEmpty()
|
||||
showHint("让他们聊:$first ↔ $second(随时可以停止)")
|
||||
runChat("", emptyList(), auto = true, forceSpeaker = aiTalkPair[0])
|
||||
}
|
||||
|
||||
/** 「让他们聊」还剩几轮(0 = 没在自动对聊) */
|
||||
private var aiTalkLeft = 0
|
||||
|
||||
/** 已经轮到第几个(在 [aiTalkPair] 里循环) */
|
||||
private var aiTalkTurn = 0
|
||||
|
||||
/** 对聊的两个人(只取两个,见 [startAiTalk]) */
|
||||
private var aiTalkPair: List<String> = emptyList()
|
||||
|
||||
private fun runChat(text: String, files: List<Attachment>, auto: Boolean = false, forceSpeaker: String = "") {
|
||||
if (!auto) {
|
||||
// ★ 用户自己开口了:**立刻掐掉自动对聊**。
|
||||
//
|
||||
// 不掐的话,用户 @ 了寐眠,但那一轮仍带着 `forceSpeaker`
|
||||
// (正轮到小黑),于是**小黑替寐眠答** ——
|
||||
// 用户看到的是"我明明 @ 了他,回答的却是别人",感受上就是"没上下文"。
|
||||
// 内核那边也把优先级改成了「用户 @ 压过 forced」,这里是第一道。
|
||||
aiTalkLeft = 0
|
||||
aiTalkTurn = 0
|
||||
aiTalkPair = emptyList()
|
||||
// 用户自己开的头:把自动续轮的计数清零
|
||||
autoRounds = 0
|
||||
messages.add(ChatMessage(role = "user", content = text, attachments = files))
|
||||
}
|
||||
messages.add(ChatMessage(role = "assistant", content = "", pending = true))
|
||||
streaming = true
|
||||
handoffDone.set(false)
|
||||
handoffToRef.set("")
|
||||
handoffFromRef.set("")
|
||||
// 用户自己发消息 = 他要接手了,把待决的那个"要不要让他说"收起来
|
||||
if (!auto) {
|
||||
pendingHandoffTo = ""
|
||||
pendingHandoffName = ""
|
||||
pendingHandoffFromName = ""
|
||||
}
|
||||
|
||||
val cancel = AtomicBoolean(false)
|
||||
chatJob = cancel
|
||||
@@ -1144,7 +1871,12 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
attachments = files,
|
||||
agentId = activeAgent?.id,
|
||||
cancelled = cancel,
|
||||
) { event -> onStreamEvent(event) }
|
||||
onEvent = { event -> onStreamEvent(event) },
|
||||
// 自动续的那几轮不带用户消息(内核据此不追加)
|
||||
autoContinue = auto,
|
||||
// 「让他们聊」时**直接指定**这一轮谁说话,不指望 AI 自己移交
|
||||
forceSpeaker = forceSpeaker,
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
patchLast { it.copy(error = true, pending = false, content = it.content.ifBlank { "出错了:${e.message}" }) }
|
||||
@@ -1154,12 +1886,69 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
chatJob = null
|
||||
patchLast { it.copy(pending = false) }
|
||||
refresh()
|
||||
// ★ 重载消息:工具可能在**轮中**往对话里写过东西
|
||||
// (`talk_to` 就是)—— 不重载的话那句话根本看不见
|
||||
reloadMessages()
|
||||
|
||||
// ★★ 群聊里 AI 把话交给了别人 → 自动替他续一轮。
|
||||
//
|
||||
// 这样两个智能体就能**自己聊起来**,而不是
|
||||
// "用户说一句、A 让给 B、然后就没下文了"。
|
||||
// 用户随时可以点「停止」打断(`cancel.get()`),
|
||||
// 也随时可以直接发消息把话题拉回来。
|
||||
val conv = state.conversations.firstOrNull { it.id == activeConversationId }
|
||||
val canContinue = !cancel.get() && conv?.isGroup == true
|
||||
|
||||
if (canContinue && aiTalkLeft > 0) {
|
||||
// ① 「让他们聊」:用户**亲手按了按钮**,按顺序把发言权递下去
|
||||
// (这条不用再确认一次,那按钮本身就是确认)
|
||||
aiTalkLeft--
|
||||
aiTalkTurn++
|
||||
val next = aiTalkPair[aiTalkTurn % aiTalkPair.size]
|
||||
runChat("", emptyList(), auto = true, forceSpeaker = next)
|
||||
} else if (canContinue && handoffDone.get()) {
|
||||
// ② AI 自己用 talk_to / pass_turn 把话交给了别人
|
||||
handoffDone.set(false)
|
||||
if (state.settings.aiTalkAuto) {
|
||||
// 自动模式:不用用户确认,直接接着让他说
|
||||
if (autoRounds < autoRoundCap) {
|
||||
autoRounds++
|
||||
runChat("", emptyList(), auto = true)
|
||||
}
|
||||
} else {
|
||||
// ★ 手动模式(默认):**摆出两个按钮等用户决定**
|
||||
// —— 用户要求「可以选择传递和停止」
|
||||
pendingHandoffTo = handoffToRef.get()
|
||||
pendingHandoffName = state.agents
|
||||
.firstOrNull { it.id == handoffToRef.get() }?.name.orEmpty()
|
||||
pendingHandoffFromName = handoffFromRef.get()
|
||||
}
|
||||
} else {
|
||||
// 收尾:清掉自动对聊的计数,免得下次发消息又自己续上
|
||||
aiTalkLeft = 0
|
||||
aiTalkTurn = 0
|
||||
aiTalkPair = emptyList()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 事件回调可能在 IO 线程,统一切回主线程改状态 */
|
||||
private fun onStreamEvent(event: StreamEvent) {
|
||||
// ★★ 这一行必须在 `launch` **外面**。
|
||||
//
|
||||
// `client.chat` 的回调是同步跑在 IO 线程上的,而 `runChat` 的
|
||||
// `finally` 紧接着就要读这个标志来决定续不续轮。
|
||||
// 放进 launch 里就变成异步 —— 会和 finally 抢,抢输了那一轮就不续,
|
||||
// 表现是"两个 AI 有时候能聊、有时候聊不起来"。
|
||||
if (event is StreamEvent.Handoff) {
|
||||
handoffDone.set(true)
|
||||
handoffToRef.set(event.to)
|
||||
handoffFromRef.set(
|
||||
state.agents.firstOrNull { it.id == event.from }?.name.orEmpty()
|
||||
)
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
when (event) {
|
||||
is StreamEvent.Delta -> patchLast { it.copy(content = it.content + event.text) }
|
||||
@@ -1185,9 +1974,62 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
})
|
||||
}
|
||||
// ★ 内核说"这个会话不是当前智能体的,我另起了一个"(兜底路径)。
|
||||
// 界面必须跟着切,否则会继续往老会话上追加 —— 还是串味。
|
||||
//
|
||||
// ★★ **只换 id,绝不要调 `openConversation`** —— 踩过:
|
||||
// `openConversation` 会先 `messages.clear()` 再去服务端拉,
|
||||
// 而这时候**这一轮的回复还没落盘**,拉回来是空的;
|
||||
// 流还在继续往 `messages` 里追加,清空之后就再也回不来了。
|
||||
// 表现就是用户说的"**回话直接消失了**"(发一句、看到回复、
|
||||
// 然后它自己没了)。
|
||||
//
|
||||
// 只换 id 就够了:流会照常往本地列表追加,
|
||||
// 而 `saved` 事件之后服务端那边的会话对象也是新的。
|
||||
is StreamEvent.Rebased -> {
|
||||
if (event.conversationId.isNotBlank()) openConversation(event.conversationId)
|
||||
if (event.conversationId.isNotBlank()) {
|
||||
activeConversationId = event.conversationId
|
||||
rebasedNote = "这条对话原本属于别的智能体,已经为它新开了一个"
|
||||
}
|
||||
}
|
||||
// ★ 群聊的**发言权仲裁**结果(v1.2 §3.9):内核决定这一轮谁说话。
|
||||
// 界面据此换立绘/背景(设置里可关),并让用户知道
|
||||
// "为什么是他在接话"(点名 / 移交 / 兜底)。
|
||||
// ★ 状态过期/剩余轮数:播报出来("中毒已经消退了")。
|
||||
// 以前这个事件在解析层就被丢了,用户完全感知不到。
|
||||
is StreamEvent.Status -> {
|
||||
if (event.expired) showHint("「${event.name}」已经消退了")
|
||||
}
|
||||
// ★ 状态脚本报错:**必须让用户看见**(附录 E 的"UI 提示")。
|
||||
// 脚本是他自己写的,静默失败等于让他对着"回复有点怪"猜。
|
||||
is StreamEvent.RuleError -> showHint("规则脚本出错了:${event.message}")
|
||||
is StreamEvent.Speaker -> {
|
||||
currentSpeakerId = event.agentId
|
||||
speakerNote = event.note
|
||||
// ★★ 把发言人写进**这一条正在生成的消息**。
|
||||
//
|
||||
// 这条消息是流式期间客户端**自己建的**
|
||||
// (`runChat` 里 `ChatMessage(role="assistant", pending=true)`),
|
||||
// 当时还不知道谁会说,所以 `agentId` 是空的 ——
|
||||
// 而它**不会**跟着 `refresh()` 更新(那个只换 `state`,
|
||||
// 不动本地的 `messages`)。
|
||||
//
|
||||
// 于是:内核库里存的 `agentId` 明明是对的(寐眠),
|
||||
// 界面上这条的却是空 → 名字标签退回"当前对话的主人"
|
||||
// (小黑)、朗读也退回全局音色(还是小黑)。
|
||||
// 用户看到的就是「@ 了寐眠、标签和声音却都是小黑」。
|
||||
if (event.agentId.isNotBlank()) {
|
||||
patchLast { if (it.agentId.isBlank()) it.copy(agentId = event.agentId) else it }
|
||||
}
|
||||
}
|
||||
// ★ AI 轮中把话交给了别人 → 这一轮跑完要**自动替他续一轮**,
|
||||
// 不然就是"用户说一句 → A 让给 B → B 永远没开口"
|
||||
// (用户报的"还是不能互相对话")。
|
||||
//
|
||||
// ★ 判据必须是**轮中**这个事件,不能只看上面 `speaker` 的 reason:
|
||||
// 那个是轮前发的,而 `pass_turn` 是轮中调的。
|
||||
is StreamEvent.Handoff -> {
|
||||
// 标志已经在 onStreamEvent 开头同步置过了(那里不能等 launch)
|
||||
val who = state.agents.firstOrNull { it.id == event.to }?.name.orEmpty()
|
||||
if (who.isNotBlank()) speakerNote = "把话交给了 $who"
|
||||
}
|
||||
is StreamEvent.Failure -> {
|
||||
// ★ 额度用完不是"出错了",是**一个需要你决定的状态**:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -13,7 +13,9 @@ import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -54,6 +56,7 @@ import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.ChatMessage
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -232,7 +235,9 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
delay(600)
|
||||
val now = vm.messages.lastOrNull()
|
||||
if (now === msg && !now.pending && now.content == msg.content) {
|
||||
speech.maybeAutoRead(now.content, vm.messages.size - 1)
|
||||
// 带上这条消息的发言者 —— 群聊里每个人音色不同,
|
||||
// 不带就一律用"当前智能体"的声音
|
||||
speech.maybeAutoRead(now.content, vm.messages.size - 1, now.agentId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -262,9 +267,16 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().background(doubaoBg())) {
|
||||
ChatHeader(vm, agent?.name ?: "豆包", speech)
|
||||
// ★ 顶栏的名字和**背景用的是同一个人**(`backdropAgent`)——
|
||||
// 用户的原话是「还是没换标题和背景呀」:寐眠在说话,
|
||||
// 顶栏和背景就该都是寐眠。两处各取各的必然对不上。
|
||||
val shown = backdropAgent(vm)
|
||||
ChatHeader(vm, shown?.name ?: (agent?.name ?: "豆包"), speech)
|
||||
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
// 立绘/背景铺在**消息下面**(用户要的"整个背景都是角色")
|
||||
ChatBackdrop(vm)
|
||||
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
@@ -278,7 +290,11 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
tagline.endsWith("?") || tagline.contains(","))
|
||||
val greeting =
|
||||
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
|
||||
item { AppearOnce { HeroSection(greeting) } }
|
||||
// ★ 这里原来还有一个 168dp 的圆形立绘(ChatPortrait)——
|
||||
// 背景层(ChatBackdrop)接手之后它就是多余的:两张同一个人的图
|
||||
// 叠在一起,而且圆形 Crop 会把全身图裁到腰上,很难看。
|
||||
item { AppearOnce { HeroText(greeting) } }
|
||||
item { AppearOnce { PortraitHint(vm) } }
|
||||
}
|
||||
items(vm.messages.size) { index ->
|
||||
AppearOnce(offsetY = 10.dp) {
|
||||
@@ -316,7 +332,15 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
|
||||
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
|
||||
|
||||
if (vm.conversationEnded) {
|
||||
// ★ 私聊记录是**只读**的(v1.2 §3.9 形态 B)——那两个 AI 是
|
||||
// 在你不在场的时候聊的,往里插话等于改历史记录。
|
||||
// 这里把输入条整条换掉,而不是"能输入但发不出去"。
|
||||
val privateConv = vm.state.conversations
|
||||
.firstOrNull { it.id == vm.activeConversationId }?.isPrivate == true
|
||||
if (privateConv) {
|
||||
Box(Modifier.weight(1f))
|
||||
Hint("这是两个智能体的私聊记录,只读。想让他们再聊一次,去「群成员」页。")
|
||||
} else if (vm.conversationEnded) {
|
||||
/**
|
||||
* ★★ 对话被 AI 结束了 —— **屏幕中间一个横幅,写着关闭原因**。
|
||||
*
|
||||
@@ -337,6 +361,28 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
} else {
|
||||
// 本次对话的用量(需求 4.1)跟着输入条一起显示 ——
|
||||
// 放在输入框正上方是因为它是"这次对话"的属性,而输入框就是这次对话的入口
|
||||
// ★ 对话被换了归属时的提示(见 AppViewModel 的 rebasedNote)
|
||||
if (vm.rebasedNote.isNotBlank()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
vm.rebasedNote,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
RowAction("知道了") { vm.clearRebasedNote() }
|
||||
}
|
||||
}
|
||||
// ★ 群聊的成员快捷条(v1.2 §3.9):点头像 = @ 点名,被点的人这一轮一定发言
|
||||
//
|
||||
// ★★ 顺序:先「要不要让他接着说」,再点名条 ——
|
||||
// 前者的决策更靠前(它决定这一轮还继不继续),
|
||||
// 而且它只在有待决移交时才出现。
|
||||
HandoffBar(vm)
|
||||
GroupQuickBar(vm)
|
||||
SessionUsageBar(vm)
|
||||
// 额度用完被拦住了 → 给出路(复查报告 2.4)。
|
||||
// 只拦不给入口的话,用户会以为这个智能体坏了。
|
||||
@@ -378,8 +424,18 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
// 内核那道拦截是权威,但**界面上也要拦一道** ——
|
||||
// 让用户敲完一整句话、点发送、再被拒绝,是最差的体验。
|
||||
// 提示条点一下直达记忆页的情绪区(那就是复活入口)。
|
||||
//
|
||||
// ★★ 但**群聊不锁输入框**:死了一个,群里还有别人能接话
|
||||
// (内核的 `group_chat.resolve` 会把死人跳过、换下一个人)。
|
||||
// 整条锁掉的话,用户只能干看着一个群不能用 ——
|
||||
// 用户报的「角色死亡输入框怎么不能用了」就是这个。
|
||||
// 群聊里只留一条提示,输入框照给。
|
||||
val deadAgent = vm.activeAgent
|
||||
if (deadAgent != null && vm.state.emotions[deadAgent.id]?.dead == true) {
|
||||
val dead = deadAgent != null && vm.state.emotions[deadAgent.id]?.dead == true
|
||||
val convNow = vm.state.conversations
|
||||
.firstOrNull { it.id == vm.activeConversationId.ifBlank { "c_main" } }
|
||||
val groupNow = convNow?.isGroup == true
|
||||
if (dead && !groupNow) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -390,7 +446,7 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"「${deadAgent.name}」已经死亡,不能对话。",
|
||||
"「${deadAgent?.name}」已经死亡,不能对话。",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
modifier = Modifier.weight(1f),
|
||||
@@ -402,11 +458,23 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(Color(0xFFB3261E))
|
||||
.clickable { vm.openMemories(deadAgent.id) }
|
||||
.clickable { deadAgent?.let { vm.openMemories(it.id) } }
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
if (dead && groupNow) {
|
||||
// 群聊:只提示,**不拦**。被点名的人死了的话,
|
||||
// 内核会换下一个人接(不再"回主智能体",群里没有主人)
|
||||
Text(
|
||||
"「${deadAgent?.name}」已经死亡 —— 群里其他人还能接话。",
|
||||
fontSize = 11.sp,
|
||||
color = Color(0xFFB3261E),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 14.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
}
|
||||
}
|
||||
@@ -459,7 +527,8 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro
|
||||
) {
|
||||
// 有自定义角色图就显示它(需求 2.5 的资源回退在内核侧已经落定,
|
||||
// 这里 path 为空就还是原来的图标)
|
||||
val art = vm.activeAgent?.image?.portrait.orEmpty()
|
||||
// ★ 跟**同一个人**:名字是寐眠、头像却是小黑,用户一眼就看出不对
|
||||
val art = backdropAgent(vm)?.image?.portrait.orEmpty()
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = art,
|
||||
@@ -548,22 +617,15 @@ private fun HeaderIcon(
|
||||
/* ------------------------------ 空态大头像 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
private fun HeroSection(greeting: String) {
|
||||
private fun HeroText(greeting: String) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(top = 34.dp, bottom = 18.dp),
|
||||
Modifier.fillMaxWidth().padding(bottom = 18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(168.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(96.dp))
|
||||
}
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(doubaoBubble())
|
||||
.background(doubaoBubbleVeil())
|
||||
.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
) {
|
||||
Text(greeting, fontSize = 16.sp, lineHeight = 26.sp, color = doubaoText())
|
||||
@@ -571,21 +633,199 @@ private fun HeroSection(greeting: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 聊天页顶部的立绘(v1.2 §6.1)。
|
||||
*
|
||||
* ★ **跟随说话者**(设置里可关,默认开):群聊时谁发言就换成谁的立绘 ——
|
||||
* 一眼看出"这句是谁说的"。关掉时固定用主智能体(成员列表第一个)。
|
||||
*
|
||||
* ★ 0.3 秒的 crossfade:立绘是**情绪驱动**的,可能一轮换一次;
|
||||
* 硬切会让人以为界面闪了一下。0.3s 刚好够看出"换了",又不拖沓。
|
||||
* (这也正是需求里点名的 0.3s —— 和群聊背景跟随共用同一套缓动,
|
||||
* 两处各写一个数字的话,将来改一处必漏另一处。)
|
||||
*/
|
||||
/**
|
||||
* 顶栏和背景该显示**谁** —— **当前正在说话的那个人**。
|
||||
*
|
||||
* ★★ 用户的原话:「还是没换标题和背景呀」。
|
||||
*
|
||||
* 我上一版理解成「跟当前对话的主人走」,那是错的 ——
|
||||
* 他要的是**寐眠说话时,顶栏和背景都是寐眠**。
|
||||
*
|
||||
* 「不是让你 @ 谁就换哪个背景」那句,意思是**不要光点一下 @ 按钮
|
||||
* 就提前换**;要跟着**真实的发言者**。内核每轮都 emit 一个
|
||||
* `speaker` 事件(群聊里就是仲裁结果),跟着它走既"立即"又"名副其实"。
|
||||
*
|
||||
* ★ 只在**群聊**里用 `currentSpeakerId`:单聊时它可能还是上一轮群里
|
||||
* 留下的值,会把单聊的顶栏带跑偏。单聊就认会话主人。
|
||||
*
|
||||
* ★ 顶栏、背景、【朗读音色】三处都从这里/`msg.agentId` 取,
|
||||
* 保证同一条消息上的名字、图、声音是**同一个人**。
|
||||
*/
|
||||
private fun backdropAgent(vm: AppViewModel): Agent? {
|
||||
val convId = vm.activeConversationId.ifBlank { "c_main" }
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == convId }
|
||||
if (conv?.isGroup == true && vm.currentSpeakerId.isNotBlank()) {
|
||||
vm.state.agents.firstOrNull { it.id == vm.currentSpeakerId }?.let { return it }
|
||||
}
|
||||
return vm.state.agents.firstOrNull { it.id == conv?.agentId.orEmpty() } ?: vm.activeAgent
|
||||
}
|
||||
|
||||
/**
|
||||
* 聊天页的**立绘背景层**(用户要求:「整个背景都是角色卡」)。
|
||||
*
|
||||
* ★ 以前立绘只在**一句话都没说**的时候露一个 168dp 的圆,
|
||||
* 一开始聊就只剩顶栏那个 24dp 头像 —— 用户的原话是「就头像是立绘」,
|
||||
* 而他要的是整个背景都是这个角色。
|
||||
*
|
||||
* ★★ 显示的是**当前对话的智能体**(`activeAgent`),不是"这一轮谁在说"。
|
||||
* 用户澄清过:「背景是根据当前对话来的,不是让你 @ 谁就换哪个背景」。
|
||||
* 背景表达的是**这个场景是谁的**(和顶栏那个名字同一件事);
|
||||
* 群聊里两个人一来一回时背景跟着闪,既晃眼又和顶栏对不上。
|
||||
* "谁在说话"是**每条消息**自己的事,用 `msg.agentId`(见 [SpeakerTag])。
|
||||
*
|
||||
* ★ 两条硬约束:
|
||||
* · **必须铺在消息下面**(Box 里排在 LazyColumn 之前),否则字被盖住;
|
||||
* · **图要实心、气泡要半透明** —— 这是用户点名要的一对
|
||||
* (「立绘不要透明的」+「聊天框半透明」)。反过来做(图淡化、气泡实心)
|
||||
* 等于两头都不讨好:立绘看不清,气泡也白透。
|
||||
* 所以可读性交给气泡那边([doubaoBubbleVeil]),这里不淡化。
|
||||
*
|
||||
* ★ 立绘用 `ContentScale.Fit` 而不是 `Crop`:角色不能被裁掉半个身子。
|
||||
* 背景图反过来,必须 `Crop` —— `Fit` 会留出底色,铺不满。
|
||||
*/
|
||||
@Composable
|
||||
private fun ChatBackdrop(vm: AppViewModel) {
|
||||
val who = backdropAgent(vm)
|
||||
val back = who?.image?.back.orEmpty()
|
||||
val art = who?.image?.portrait.orEmpty()
|
||||
if (back.isBlank() && art.isBlank()) return
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
if (back.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = back,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
}
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(
|
||||
path = art,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 没配立绘时**说清楚 + 给入口**。
|
||||
*
|
||||
* ★ 回退链最后一级就是「内置默认人物」(需求 §2.6),所以背景层显示那张图**没错** ——
|
||||
* 但界面上一个字都不说的话,用户只会觉得"立绘功能没生效",
|
||||
* 而不知道**得自己去传**(内置那四个示例智能体默认都没有图)。
|
||||
*
|
||||
* ★ 它原来长在一个 168dp 圆形立绘(`ChatPortrait`)底下,和背景层重复,
|
||||
* 已经拆开:图归背景层,这句话单独留着。
|
||||
*/
|
||||
@Composable
|
||||
private fun PortraitHint(vm: AppViewModel) {
|
||||
val who = backdropAgent(vm) ?: return
|
||||
if (who.image.portrait.isNotBlank()) return
|
||||
Text(
|
||||
"还没有立绘 · 点这里去传一张",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.clickable { vm.openAgentEdit(who) },
|
||||
)
|
||||
}
|
||||
|
||||
/* ------------------------------ 消息 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 气泡上方那行**小字:这条是谁说的**。
|
||||
*
|
||||
* ★ 只在**群聊**显示(用户要求:「对话前面写明是谁在说话」)。
|
||||
* 单聊里只有一个人,每条都标一遍就是噪音 —— 那个名字顶栏已经有了。
|
||||
*
|
||||
* ★ 名字从 `msg.agentId` 查(内核一直在消息里存群聊仲裁后的发言者)。
|
||||
* 老消息没这个字段 → 退回当前智能体;群聊里退错了也只是名字不对,
|
||||
* 不影响别的(比不显示强,因为不显示就完全分不清谁是谁)。
|
||||
*
|
||||
* ★ 自己那侧写「你」而不是昵称:翻记录时"哪句是我说的"要一眼看出来,
|
||||
* 用昵称反而要在脑子里做一次映射。
|
||||
*/
|
||||
@Composable
|
||||
private fun SpeakerTag(vm: AppViewModel, msg: ChatMessage, mine: Boolean) {
|
||||
// ★ 会话 id 可能是空串(内核用 "c_main" 兜底)
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId.ifBlank { "c_main" } }
|
||||
// 单聊只有一个人,每条都标一遍是噪音;群聊和私聊记录(两个 AI 自己聊的)
|
||||
// 都是"多人在场",不标就完全分不清谁是谁
|
||||
if (conv == null || (!conv.isGroup && !conv.isPrivate)) return
|
||||
val name = if (mine) {
|
||||
"你"
|
||||
} else {
|
||||
vm.state.agents.firstOrNull { it.id == msg.agentId }?.name.orEmpty()
|
||||
.ifBlank { vm.activeAgent?.name.orEmpty() }
|
||||
}
|
||||
if (name.isBlank()) return
|
||||
Text(
|
||||
name,
|
||||
fontSize = 11.sp,
|
||||
color = if (mine) doubaoTextSecondary() else Doubao.Blue,
|
||||
modifier = Modifier.padding(start = 4.dp, end = 4.dp, bottom = 3.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: SpeechController) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val speaking = speech.speakingIndex == index
|
||||
// 长按气泡 → 这个菜单(v1.2 §4.3 的「标记重要」)
|
||||
var importantMenu by remember { mutableStateOf(false) }
|
||||
|
||||
if (msg.role == "user") {
|
||||
// ★ 长按**用户**消息才能标重要。需求说的是"消息操作栏加标记重要",
|
||||
// 这里只做用户那一侧,理由是**效果差异**:
|
||||
// 被标的消息在上下文窗口裁剪时破格携带,而 AI 的回复通常就在
|
||||
// 最近几轮里、本来就裁不到;用户想留住的是**很久以前问过的那句**。
|
||||
if (importantMenu) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { importantMenu = false },
|
||||
title = { Text(if (msg.important) "这条标过了" else "这条消息") },
|
||||
text = {
|
||||
Text(
|
||||
if (msg.important) {
|
||||
"取消之后它就按普通消息处理了 —— 攒够一批会被裁掉。"
|
||||
} else {
|
||||
"标成重要之后,以后裁剪上下文时这条会一直留着," +
|
||||
"不管过了多少轮。"
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { vm.toggleImportant(index); importantMenu = false },
|
||||
) { Text(if (msg.important) "取消标记" else "标记重要", color = Doubao.Blue) }
|
||||
},
|
||||
dismissButton = {
|
||||
androidx.compose.material3.TextButton(
|
||||
onClick = { importantMenu = false },
|
||||
) { Text("算了") }
|
||||
},
|
||||
)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
SpeakerTag(vm, msg, mine = true)
|
||||
msg.attachments.forEach { file ->
|
||||
Box(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoBubble())
|
||||
.background(doubaoBubbleMine())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -604,18 +844,35 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
Modifier
|
||||
.widthIn(max = 288.dp)
|
||||
.clip(RoundedCornerShape(18.dp, 18.dp, 4.dp, 18.dp))
|
||||
.background(Doubao.Blue)
|
||||
.background(doubaoBubbleMine())
|
||||
.combinedClickable(
|
||||
onClick = { clipboard.setText(AnnotatedString(msg.content)) },
|
||||
onLongClick = { importantMenu = true },
|
||||
)
|
||||
.padding(horizontal = 14.dp, vertical = 11.dp),
|
||||
) {
|
||||
Text(msg.content, color = Color.White, fontSize = 16.sp, lineHeight = 25.sp)
|
||||
}
|
||||
}
|
||||
// 标过的给一个小标记 —— 不然用户忘了自己标过哪几条,
|
||||
// 而"这条会不会被裁掉"是他自己决定的
|
||||
if (msg.important) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"★ 重要(不会被裁掉)",
|
||||
fontSize = 10.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start) {
|
||||
// 群聊里标出**这条是谁说的**(用户要求:「对话前面写明是谁在说话」)
|
||||
SpeakerTag(vm, msg, mine = false)
|
||||
|
||||
val hasReasoning = msg.reasoning.isNotBlank()
|
||||
val hasTrace = msg.toolTrace.isNotEmpty()
|
||||
|
||||
@@ -700,7 +957,7 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
Modifier
|
||||
.widthIn(max = 300.dp)
|
||||
.clip(RoundedCornerShape(4.dp, 18.dp, 18.dp, 18.dp))
|
||||
.background(if (msg.error) Doubao.ErrorBg else doubaoBubble())
|
||||
.background(if (msg.error) Doubao.ErrorBg else doubaoBubbleVeil())
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
) {
|
||||
when {
|
||||
@@ -824,7 +1081,8 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
// 手动点朗读时清掉"自动朗读念过了"的记录:
|
||||
// 用户主动点,就该正常播(或再点一次停),不受自动朗读的去重影响
|
||||
speech.forgetAutoRead()
|
||||
speech.speak(msg.content, index)
|
||||
// 用**这条消息**的发言者挑音色(群聊里每个人不一样)
|
||||
speech.speak(msg.content, index, msg.agentId)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
@@ -1047,7 +1305,25 @@ private fun InputBar(
|
||||
|
||||
Spacer(Modifier.width(8.dp))
|
||||
|
||||
if (canSend) {
|
||||
// ★★ 正在生成时,右边那个圆钮变成「停止」。
|
||||
//
|
||||
// 取消能力**一直都有**:内核从 HTTP 到 agent_loop 一路支持 `cancelled`,
|
||||
// ViewModel 里也建好了 `chatJob`(AtomicBoolean)——
|
||||
// 但没有任何界面调它,用户只能干等它把话说完。
|
||||
// 用户的原话就是「对话过程中可中断」。
|
||||
if (vm.streaming) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.background(doubaoSurface())
|
||||
.border(1.dp, doubaoBorder(), CircleShape)
|
||||
.clickable(onClick = { vm.stopGenerating() }),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Stop, "停止生成", tint = Doubao.Blue, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
} else if (canSend) {
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
@@ -1136,3 +1412,95 @@ private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 「要不要让他接着说」——
|
||||
* AI 用 `talk_to` / `pass_turn` 把话交给别人之后,这里摆两个按钮。
|
||||
*
|
||||
* ★★ 用户的原话:「talk_to 是用户可以选择传递和停止,有自动模式(不用用户确认)」。
|
||||
*
|
||||
* 所以默认(手动)就**停在这儿等用户点**:
|
||||
* · 「让他说」= 继续把这一轮交出去;
|
||||
* · 「停在这」= 到此为止。
|
||||
* 设置里开了「AI 对聊自动模式」就不出现这条,直接接着跑。
|
||||
*
|
||||
* ★ 顺带解决了烧钱:默认不会自己一直聊下去。
|
||||
* ★ 位置在输入框正上方、点名条**上面**:这是"接着聊还是打住"的决策现场。
|
||||
*/
|
||||
@Composable
|
||||
private fun HandoffBar(vm: AppViewModel) {
|
||||
if (vm.pendingHandoffName.isBlank()) return
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoCard())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"${vm.pendingHandoffFromName.ifBlank { "它" }} 把话交给了 ${vm.pendingHandoffName}",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
DoubaoPill(text = "让他说", onClick = { vm.continueHandoff() })
|
||||
Spacer(Modifier.width(6.dp))
|
||||
RowAction("停在这") { vm.stopHandoff() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 群聊的成员快捷条(v1.2 §3.9)。
|
||||
*
|
||||
* ★ 位置在**输入框正上方**:这里是"这一轮要点谁"的决策现场,
|
||||
* 点头像就把 `@名字 ` 插进草稿里 —— 和用户手打 `@` 完全等价
|
||||
* (内核的 `group_chat.mention_in` 就是按 `@名字` 匹配的)。
|
||||
*
|
||||
* ★ 只有群聊才显示。单聊显示一排"只有一个人"的头像没有意义,
|
||||
* 而且会白占一行高度。
|
||||
*/
|
||||
@Composable
|
||||
private fun GroupQuickBar(vm: AppViewModel) {
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId }
|
||||
if (conv == null || !conv.isGroup) return
|
||||
val members = conv.participants.mapNotNull { id ->
|
||||
vm.state.agents.firstOrNull { it.id == id }?.let { id to it.name }
|
||||
}
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
// 点名条:**不标"(主)"** —— 用户要求「群聊去掉主人设定」,
|
||||
// 群里没有老大,没人被 @ 时按顺序轮(kernel 的 group_chat.rotate_next)
|
||||
for (pair in members) {
|
||||
// 只插草稿 —— **不碰顶栏/背景**。那两处等内核仲裁完
|
||||
// (`speaker` 事件)才切,不然会"点了还没发就换了人"
|
||||
DoubaoPill(text = "@${pair.second}", onClick = { vm.mentionAgent(pair.second) })
|
||||
}
|
||||
// ★「让他们聊」:按下就让前两个成员**轮流对话**几轮,随时能停。
|
||||
//
|
||||
// 为什么需要这个按钮:光靠 AI 自己 `pass_turn` 是靠不住的 ——
|
||||
// 实测它更愿意把话说完,于是"两个智能体对话"永远发生不了
|
||||
// (用户报的「还是不能互相对话」)。
|
||||
// 这个按钮不依赖 AI 配合,界面直接按顺序把发言权递过去。
|
||||
DoubaoPill(text = "让他们聊", onClick = { vm.startAiTalk() })
|
||||
RowAction("成员") { vm.openMembers(conv.id) }
|
||||
}
|
||||
// ★ 仲裁**理由**(v1.2 §3.9):内核发了 note,界面以前收了但从不显示 ——
|
||||
// 于是"被点的人已死亡,发言权回主智能体"这种事用户只能自己猜。
|
||||
// 只在有话说时占一行,平时不显示。
|
||||
if (vm.speakerNote.isNotBlank()) {
|
||||
Text(
|
||||
vm.speakerNote,
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,24 @@ fun doubaoText() = if (isDark()) Doubao.DarkText else Doubao.TextPrimary
|
||||
fun doubaoTextSecondary() = if (isDark()) Doubao.DarkTextSecondary else Doubao.TextSecondary
|
||||
@Composable
|
||||
fun doubaoBubble() = if (isDark()) Doubao.DarkBubble else Doubao.BubbleBot
|
||||
|
||||
/**
|
||||
* 聊天气泡的底色(**半透明**)。
|
||||
*
|
||||
* ★ 聊天页现在有一层**实心**的立绘(`ChatScreen.ChatBackdrop`)垫在下面,
|
||||
* 气泡要是也不透明,那张立绘就白铺了 —— 用户要的正是
|
||||
* 「立绘看得见、字也读得清」这一对。
|
||||
*
|
||||
* ★ 0.78 是这两条的交点:再透字就开始糊在图上,再实立绘就等于没有。
|
||||
* 别的页面(卡片、弹窗)继续用不透明的 [doubaoBubble],
|
||||
* 它们底下没有图,半透明只会显脏。
|
||||
*/
|
||||
@Composable
|
||||
fun doubaoBubbleVeil() = doubaoBubble().copy(alpha = 0.78f)
|
||||
|
||||
/** 用户自己那侧的气泡(蓝色),同样要半透明 —— 理由同 [doubaoBubbleVeil] */
|
||||
@Composable
|
||||
fun doubaoBubbleMine() = Doubao.Blue.copy(alpha = 0.82f)
|
||||
@Composable
|
||||
fun doubaoBorder() = if (isDark()) Doubao.DarkBorder else Doubao.Border
|
||||
@Composable
|
||||
@@ -277,3 +295,33 @@ fun SectionLabel(text: String, modifier: Modifier = Modifier) {
|
||||
fontWeight = FontWeight.Normal,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------- //
|
||||
// 通用小件(v1.2)
|
||||
// --------------------------------------------------------------------------- //
|
||||
//
|
||||
// ★ 这两个原来是 AgentEditScreen 的**私有**函数,于是别的界面想用就只能
|
||||
// 复制一份 —— 而"同一段逻辑抄两份"是这个仓库反复出现的毛病。
|
||||
// 挪到这里之后全局一份。
|
||||
|
||||
/** 一张卡片:横向留白 + 圆角 + 表面色 + 内边距 */
|
||||
@androidx.compose.runtime.Composable
|
||||
internal fun Card(content: @androidx.compose.runtime.Composable () -> Unit) {
|
||||
androidx.compose.foundation.layout.Column(
|
||||
androidx.compose.ui.Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(androidx.compose.foundation.shape.RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) { content() }
|
||||
}
|
||||
|
||||
/** 一行灰字说明 */
|
||||
@androidx.compose.runtime.Composable
|
||||
internal fun Hint(text: String) {
|
||||
androidx.compose.material3.Text(
|
||||
text, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.Agent
|
||||
import com.doubao.lynxclone.data.Conversation
|
||||
|
||||
/**
|
||||
* 群成员(v1.2 §3.9)。
|
||||
*
|
||||
* ## 为什么是全屏而不是弹窗
|
||||
*
|
||||
* 需求里写的是"浮层",但按仓库的界面约定(AGENTS.md):**列表用全屏**。
|
||||
* 一屏弹窗大概只够三四行,成员一多就得在弹窗里滚 —— 那还不如直接开一屏,
|
||||
* 而且这里还要放"加人/移出"两组动作。
|
||||
*
|
||||
* ## 谁不能移出
|
||||
*
|
||||
* ★ **主智能体不能移出**(成员列表第一个):它是"没人被点名时兜底发言"的
|
||||
* 那个人,移掉这个群就会冷场。
|
||||
* 界面上把它的按钮藏起来 —— 但那只是给用户看的,**服务端也拦**
|
||||
* (绕过界面直接调接口的路径也得挡住)。
|
||||
*/
|
||||
@Composable
|
||||
fun GroupMembersScreen(
|
||||
vm: AppViewModel,
|
||||
conversationId: String,
|
||||
onBack: () -> Unit,
|
||||
onOpenStats: (String) -> Unit = {},
|
||||
) {
|
||||
val conv: Conversation? = vm.state.conversations.firstOrNull { it.id == conversationId }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
|
||||
FullScreen(
|
||||
title = "群成员",
|
||||
subtitle = conv?.let { "${it.participants.size} 个人在群里" } ?: "会话不见了",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
if (!adding) TopTextAction("加人") { adding = true } else TopTextAction("取消") { adding = false }
|
||||
},
|
||||
) {
|
||||
// ---- 加人(就地展开,不再弹一层 —— 弹窗压弹窗是手机上的灾难)----
|
||||
if (adding) {
|
||||
val inGroup = conv?.participants?.toSet() ?: emptySet()
|
||||
// ★★ **只能拉同世界观的**(用户确认过这条规则)。
|
||||
//
|
||||
// 群聊上下文里有 <worldview> 段、共享记忆也按世界观分空间 ——
|
||||
// 世界观不同的两个人拉进同一个群,"这是哪、我们是谁"都对不上。
|
||||
// 内核 `group_chat.add_member` 也会拒,但**界面先筛掉**:
|
||||
// 让人点了才被告知"加不进去"是最差的体验。
|
||||
val hostWorldview = vm.state.agents
|
||||
.firstOrNull { it.id == conv?.agentId }?.worldviewId.orEmpty()
|
||||
val sameWorldview = vm.state.agents.filter {
|
||||
(it.worldviewId.orEmpty() == hostWorldview)
|
||||
}
|
||||
val candidates = sameWorldview.filter { it.id !in inGroup }
|
||||
val blocked = vm.state.agents.count { it.id !in inGroup && it !in sameWorldview }
|
||||
SectionLabel("拉谁进来")
|
||||
Card {
|
||||
if (candidates.isEmpty()) {
|
||||
Hint(
|
||||
if (blocked > 0) {
|
||||
"没有可以拉的人了。还有 $blocked 个智能体在世界观上跟这个群不一样," +
|
||||
"拉进来会串设定 —— 换个群或者先给它们绑同一个世界观。"
|
||||
} else {
|
||||
"所有同世界观的智能体都在群里了。"
|
||||
},
|
||||
)
|
||||
} else {
|
||||
for (a in candidates) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable {
|
||||
// ★ 注意签名:`makeGroup` 是**这个会话还没有群成员**时
|
||||
// 用的(会新建群聊);已经有成员了就走 `addMember`,
|
||||
// 不能混 —— 混了会把当前会话换掉,用户会一头雾水。
|
||||
if (inGroup.isEmpty()) vm.makeGroup(a.id) else vm.addMember(a.id)
|
||||
// ★★ 加完**不收起**(原来这里 `adding = false`)。
|
||||
// 收起的话,用户加了一个就得再点一次「加人」才能加下一个,
|
||||
// 体感就是"群聊只能拉两个"(真机反馈)。
|
||||
// 刷新后 `candidates` 会少一个,接着点就行。
|
||||
}.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(a, 36)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a.name, fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
Hint("想加几个就加几个 —— 点一个加一个,这排不会收起来。")
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
}
|
||||
|
||||
if (conv == null) {
|
||||
Hint("这个会话已经不在了。")
|
||||
return@FullScreen
|
||||
}
|
||||
|
||||
SectionLabel("成员")
|
||||
Card {
|
||||
for ((i, id) in conv.participants.withIndex()) {
|
||||
val a: Agent? = vm.state.agents.firstOrNull { it.id == id }
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AgentFace(a, 40)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
a?.name ?: "(已删除)",
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
)
|
||||
// ★ 这里原来标了「主」徽章 + "没人被 @ 的时候由它接话"。
|
||||
// 用户要求「群聊去掉主人设定」—— 群里没有老大,
|
||||
// 没人被 @ 时**按顺序轮**(见 kernel/group_chat.rotate_next)。
|
||||
Text(
|
||||
"第 ${i + 1} 个进群的",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("状态") { onOpenStats(id) }
|
||||
Spacer(Modifier.width(6.dp))
|
||||
// ★ 谁都能移出(原来主智能体移不掉)—— 既然没有主人,
|
||||
// 就没有"动不了"的那一个。内核那边会拦住"最后一个"
|
||||
RowAction("移出") { vm.removeMember(id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint(
|
||||
"在聊天页的输入框上方点成员头像就是 @ 点名 —— " +
|
||||
"被点的人这一轮一定发言。没人被点时**按顺序轮**,不会冷场,也没有谁永远优先。",
|
||||
)
|
||||
|
||||
// ★「让他们私下聊聊」(v1.2 §3.9 形态 B)
|
||||
//
|
||||
// 放这儿而不是抽屉里:抽屉已经有七项了(用户刚说过"太挤了"),
|
||||
// 而**群成员页本来就有成员** —— 从这儿点两个人比在抽屉里
|
||||
// 再开一个挑人对话框顺得多。
|
||||
//
|
||||
// 内核早就完整实现了(10 轮安全网、一方触顶另一方单方面收尾、
|
||||
// 摘要进共享记忆),但界面上一直没有入口 —— 这个需求项碰不到。
|
||||
Spacer(Modifier.height(12.dp))
|
||||
SectionLabel("私下聊聊")
|
||||
Card {
|
||||
Hint(
|
||||
"点两个名字,让他们在后台自主对聊 —— 你不在场。" +
|
||||
"聊完的摘要会写进共享记忆,完整记录在会话列表里能翻。",
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
for (id in conv.participants) {
|
||||
val a = vm.state.agents.firstOrNull { it.id == id }
|
||||
val picked = id in vm.privatePair
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { vm.togglePrivatePick(id) }
|
||||
.padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (picked) "✓" else "○",
|
||||
fontSize = 15.sp,
|
||||
color = if (picked) Doubao.Blue else doubaoTextSecondary(),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a?.name ?: "(已删除)", fontSize = 14.sp, color = doubaoText())
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
RowAction("开始私聊") { vm.startPickedPrivateChat() }
|
||||
if (vm.privatePair.isNotEmpty()) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
RowAction("清空选择") { vm.cancelPrivatePick() }
|
||||
}
|
||||
}
|
||||
if (vm.privateChatRunning.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint("${vm.privateChatRunning} 正在聊……(要跑一会儿,别退出去)")
|
||||
}
|
||||
if (vm.privateChatResult.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Hint(vm.privateChatResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 成员的小头像(有立绘用立绘,没有就用名字首字) */
|
||||
@Composable
|
||||
private fun AgentFace(agent: Agent?, size: Int) {
|
||||
val art = agent?.image?.portrait.orEmpty()
|
||||
Box(
|
||||
Modifier
|
||||
.size(size.dp)
|
||||
.clip(CircleShape)
|
||||
.background(doubaoCard()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (art.isNotBlank()) {
|
||||
AssetImage(art, Modifier.size(size.dp), contentScale = ContentScale.Crop)
|
||||
} else {
|
||||
Text(
|
||||
(agent?.name ?: "?").take(1),
|
||||
fontSize = (size * 0.42).sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
139
android/app/src/main/java/com/doubao/lynxclone/ui/ImagePick.kt
Normal file
@@ -0,0 +1,139 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import android.util.Base64
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/**
|
||||
* 选图 → 读成能上传的 base64。
|
||||
*
|
||||
* ## 为什么必须在这里压缩(这是真机上报回来的 bug)
|
||||
*
|
||||
* 用户选的是**手机相册里的照片**,现在动辄 30~55MB(一亿像素)。
|
||||
* 原样读进来会连撞三堵墙:
|
||||
*
|
||||
* ① `readBytes()` 把 55MB 全读进内存,`Base64` 再翻 4/3 倍 → 低端机直接 OOM;
|
||||
* ② 内核 `read_json_body()` 每条接口有自己的上限,图片这条路走的是小上限,
|
||||
* 38MB 的请求体一进去就被判「请求体过大」;
|
||||
* ③ 更糟的是那个异常被上层吞掉,最后报出来的是
|
||||
* **「不认识的外观槽位」** —— 一个和真实原因毫无关系的错误,
|
||||
* 用户只看到"设置不了",查代码的人也会往槽位名上去找。
|
||||
*
|
||||
* 所以压缩不是优化,是**这条链路能不能用**的前提:
|
||||
* 一张 4000×3000 的照片按最长边 1600 采样后大约是 200~400KB,
|
||||
* 比原来小两个数量级,上面三堵墙一次全绕过。
|
||||
*
|
||||
* ## 两种图**不能**压
|
||||
*
|
||||
* - **GIF**:缩放会丢动画(这个 App 明确支持动图,"动图会动"是写在界面上的);
|
||||
* - **SVG**:本来就是矢量,栅格化等于自毁。
|
||||
*
|
||||
* 这两种原样传,只在超过内核 20MB 上限时明确报错 —— 让用户换个文件,
|
||||
* 而不是静默失败。
|
||||
*/
|
||||
|
||||
/** 压缩后最长边不超过它。1600 在手机上看立绘/背景已经够清楚 */
|
||||
private const val MAX_EDGE = 1600
|
||||
|
||||
/** 压到这么大就收手。经验值:1600 边长的 JPEG 通常在 200~400KB */
|
||||
private const val TARGET_BYTES = 3 * 1024 * 1024
|
||||
|
||||
/** 内核 `_set_asset` 的硬上限,超过它一定传不上去,这里提前拦下来把话说清楚 */
|
||||
private const val MAX_BYTES = 20 * 1024 * 1024
|
||||
|
||||
/** 一张选好的图。[note] 是给用户看的一句话,说明这张图被怎么处理了 */
|
||||
data class PickedImage(val name: String, val base64: String, val note: String)
|
||||
|
||||
private fun mb(n: Int): String = String.format("%.1f", n / 1048576.0)
|
||||
|
||||
/**
|
||||
* 读一张图并压到能传的大小。
|
||||
*
|
||||
* 失败时抛 [IllegalStateException],**消息是可以直接显示给用户的中文** ——
|
||||
* 调用方 `catch` 之后原样 `showHint(e.message)` 就行,
|
||||
* 不要再包一层"上传失败",那样又把原因盖掉了。
|
||||
*/
|
||||
fun readImageForUpload(ctx: Context, uri: Uri): PickedImage {
|
||||
val resolver = ctx.contentResolver
|
||||
val rawName = (uri.lastPathSegment ?: "image").substringAfterLast('/').ifBlank { "image" }
|
||||
// ★ 名字靠不住:SAF 给的常常是 `image_1000018030` 这种没有扩展名的。
|
||||
// MIME 才是可信的(getType 对 content:// 会去查 provider)。
|
||||
val mime = (resolver.getType(uri) ?: "").lowercase()
|
||||
val isGif = mime.contains("gif")
|
||||
val isSvg = mime.contains("svg")
|
||||
|
||||
if (isGif || isSvg) {
|
||||
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
?: throw IllegalStateException("读不出这个文件")
|
||||
if (bytes.isEmpty()) throw IllegalStateException("这个文件是空的")
|
||||
if (bytes.size > MAX_BYTES) {
|
||||
throw IllegalStateException("这张图 ${mb(bytes.size)}MB,超过 20MB 上限了,换一张吧")
|
||||
}
|
||||
return PickedImage(
|
||||
name = rawName,
|
||||
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
|
||||
note = if (isGif) "动图原样上传(压缩会丢动画)" else "SVG 原样上传",
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 位图:先只问尺寸,不解码像素 ----
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
|
||||
throw IllegalStateException("这不是一张能识别的图片")
|
||||
}
|
||||
|
||||
// 压不下来就一轮轮降:边长 ×3/4、质量 ×4/5。四轮足够把任何照片压进 3MB
|
||||
var edge = MAX_EDGE
|
||||
var quality = 88
|
||||
var last = 0
|
||||
repeat(4) {
|
||||
val opts = BitmapFactory.Options().apply { inSampleSize = sampleFor(bounds, edge) }
|
||||
val bmp = resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, opts) }
|
||||
?: throw IllegalStateException("读不出这张图")
|
||||
val hasAlpha = bmp.hasAlpha()
|
||||
val out = ByteArrayOutputStream()
|
||||
bmp.compress(if (hasAlpha) Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG, quality, out)
|
||||
val w = bmp.width
|
||||
val h = bmp.height
|
||||
bmp.recycle()
|
||||
val bytes = out.toByteArray()
|
||||
last = bytes.size
|
||||
|
||||
if (bytes.size <= TARGET_BYTES) {
|
||||
return PickedImage(
|
||||
// ★ 扩展名要跟着真实格式走:压成 JPEG 却叫 .png,虽然解码器看魔数也能认,
|
||||
// 但导出的包里会留下一个名不副实的文件
|
||||
name = "${rawName.substringBeforeLast('.')}.${if (hasAlpha) "png" else "jpg"}",
|
||||
base64 = Base64.encodeToString(bytes, Base64.NO_WRAP),
|
||||
note = "已压到 ${w}×${h}、${bytes.size / 1024}KB 再上传",
|
||||
)
|
||||
}
|
||||
edge = edge * 3 / 4
|
||||
quality = (quality * 4) / 5
|
||||
}
|
||||
throw IllegalStateException("这张图压到 ${mb(last)}MB 还是太大,换一张吧")
|
||||
}
|
||||
|
||||
/**
|
||||
* 采样率(2 的幂,`BitmapFactory` 只认这个)。
|
||||
*
|
||||
* ★ 判据是**最长边**(写成 `||`),不是"宽高都超"。
|
||||
* 写成 `&&` 的话 4000×3000 一张只缩到 4000(短边 3000 没到阈值就停了),
|
||||
* JPEG 出来还有 2.2MB;按长边缩一档到 2000×1500 就只有它的三分之一。
|
||||
*
|
||||
* 取**解码后仍然 ≥ maxEdge** 的那一档 —— 宁可多留一点,
|
||||
* 后面还有缩小/降质的循环兜着;反过来取小了就再也补不回清晰度。
|
||||
*/
|
||||
private fun sampleFor(bounds: BitmapFactory.Options, maxEdge: Int): Int {
|
||||
var sample = 1
|
||||
while (bounds.outWidth / (sample * 2) >= maxEdge ||
|
||||
bounds.outHeight / (sample * 2) >= maxEdge
|
||||
) {
|
||||
sample *= 2
|
||||
}
|
||||
return sample
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
@@ -21,6 +21,9 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.Dashboard
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Group
|
||||
import androidx.compose.material.icons.filled.Memory
|
||||
import androidx.compose.material.icons.filled.Layers
|
||||
import androidx.compose.material.icons.filled.Public
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
@@ -44,8 +47,11 @@ import androidx.compose.ui.unit.sp
|
||||
* 抽屉原来平铺了 9 个入口,把底下的**对话列表**挤得只剩一条 ——
|
||||
* 而对话列表恰恰是抽屉最主要的功能:用户 90% 打开抽屉是为了切对话。
|
||||
*
|
||||
* 现在抽屉第一层只留天天用的(新话题 / 智能体 / 笔记 / 模型),
|
||||
* 其余收进这里。
|
||||
* ★★ 后来又收了一次(用户第二次说"太挤了"、"把别的放更多里"):
|
||||
* 抽屉第一层现在只剩**四件天天用的**:新话题 / 智能体 / 记忆 / 更多功能。
|
||||
* 笔记、模型、新建群聊都挪进来了 ——
|
||||
* 「模型」虽然也常用,但它是个**配置**,配好基本不动;
|
||||
* 抽屉里腾出来的位置留给对话列表更值。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面
|
||||
*
|
||||
@@ -60,6 +66,9 @@ fun MoreSheetScreen(
|
||||
onOpenMeetings: () -> Unit,
|
||||
onOpenTerminal: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onNewGroup: () -> Unit,
|
||||
onOpenNotes: () -> Unit,
|
||||
onOpenModels: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
BackHandler(enabled = true) { onClose() }
|
||||
@@ -76,6 +85,28 @@ fun MoreSheetScreen(
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item {
|
||||
// 从抽屉挪进来的三个(都是"偶尔用一次"那一档)
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Group,
|
||||
title = "新建群聊",
|
||||
subtitle = "拉几个智能体到一个会话里,可以 @ 点名",
|
||||
) { onNewGroup() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.EditNote,
|
||||
title = "笔记",
|
||||
subtitle = "AI 替你记下来的东西",
|
||||
) { onOpenNotes() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Memory,
|
||||
title = "模型",
|
||||
subtitle = "换模型 / 思考强度(配好基本不用动)",
|
||||
) { onOpenModels() }
|
||||
}
|
||||
item {
|
||||
MoreRow(
|
||||
icon = Icons.Filled.Dashboard,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
@@ -102,6 +102,10 @@ private val MODEL_FIELDS = listOf(
|
||||
Field("apiKey", "API Key", "留空则用全局设置里那个", password = true),
|
||||
Field("provider", "提供商", "ark / openai / deepseek …(留空则跟随全局)"),
|
||||
Field("pricePerK", "单价(元/千 Token)", "留空 = 不显示费用估算", number = true),
|
||||
// ★ v1.2:命中缓存的单价单独填。各家命中都比未命中便宜得多(常见 1/10),
|
||||
// 不填的话费用按未命中的价格算 —— **越用越高估**,而用户会以为
|
||||
// 自己真花了那些钱。留空 = 按未命中单价算(保守估计,不会低估)。
|
||||
Field("cachePricePerK", "命中单价(元/千 Token)", "留空 = 按上面的单价算(偏保守)", number = true),
|
||||
Field(
|
||||
"noTools", "不支持工具调用",
|
||||
"这个模型不会 function calling(本地小模型、老网关常见)。打开之后不再传 tools," +
|
||||
@@ -121,11 +125,28 @@ private class Kind(
|
||||
val isZip: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* 数值状态包:普通字段只有名字和说明。
|
||||
*
|
||||
* ★ 真正的定义(有哪些数值、哪些状态、各自的区间表和脚本)在
|
||||
* **[规则包编辑]** 全屏界面里改 —— 那是一堆嵌套结构,
|
||||
* 塞进"label + 输入框"的表单里既放不下也说不清。
|
||||
*/
|
||||
private val RULEPACK_FIELDS = listOf(
|
||||
Field("name", "名称", "比如「九州数值规则」"),
|
||||
Field("note", "说明", "给别的使用者看的:这个包是干什么的", multiline = true),
|
||||
)
|
||||
|
||||
private val KINDS = listOf(
|
||||
Kind(
|
||||
"worldviews", "世界观", "世界观", WORLD_FIELDS, isZip = true,
|
||||
hint = "绑定同一个世界观的智能体**共用一份记忆**。导出是一个 zip 包(含设定和四件套图片)。",
|
||||
),
|
||||
Kind(
|
||||
"rulepacks", "数值状态包", "规则包", RULEPACK_FIELDS, isZip = true,
|
||||
hint = "世界观挂上它之后,智能体才有**数值**(好感度、声望……)和**状态**(中毒、庇佑……)。" +
|
||||
"包里可以有 Python 脚本做裁决 —— 导入时内核会让你确认。",
|
||||
),
|
||||
Kind(
|
||||
"skills", "Skill", "Skill", SKILL_FIELDS, isZip = false,
|
||||
hint = "纯文本的「工具使用手册」。内置的记忆/情绪/用量手册**默认就生效**;这里写的是你自己加的规矩。",
|
||||
@@ -149,6 +170,13 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
"worldviews" -> vm.state.worldviews.map {
|
||||
it.id to Triple(it.name, it.setting, it.image)
|
||||
}
|
||||
// v1.2 数值状态包:副标题列出"有几条数值、几条状态、带不带脚本" ——
|
||||
// 那才是用户判断这个包能不能用的信息,光看名字看不出来
|
||||
"rulepacks" -> vm.state.rulePacks.map {
|
||||
val bits = mutableListOf("${it.stats.size} 条数值", "${it.statuses.size} 条状态")
|
||||
if (it.hasScripts) bits += "${it.scripts.size} 个脚本"
|
||||
it.id to Triple(it.name, bits.joinToString(" · "), AgentImage())
|
||||
}
|
||||
"skills" -> vm.state.skills.map { it.id to Triple(it.name, it.content, AgentImage()) }
|
||||
else -> vm.state.modelEntries.map {
|
||||
// ★ 兼容模式在列表上就要看得出来(复查 3.3):进了编辑页才知道
|
||||
@@ -177,13 +205,50 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
}.onSuccess { vm.showHint("已导出") }.onFailure { vm.showHint("导出失败") }
|
||||
}
|
||||
}
|
||||
// ---- 规则包的脚本警告 ----
|
||||
//
|
||||
// ★ 这里是全仓库**唯一**该用弹窗的导入场景:内容就是一段警告 + 两个按钮,
|
||||
// 属于"一次确认"(AGENTS.md 的界面约定:一次确认用弹窗,列表/多组配置
|
||||
// 才开全屏)。真正拦得住的是**服务端**那道 `confirmScripts` 关口,
|
||||
// 这个框只是把风险如实告诉用户。
|
||||
if (vm.pendingRulePack.isNotBlank()) {
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { vm.dismissRulePack() },
|
||||
title = { Text("这个包里带了 Python 脚本") },
|
||||
text = {
|
||||
Text(
|
||||
vm.rulePackWarning.ifBlank {
|
||||
"包里有可执行脚本。导入后它会在你的设备上运行 —— " +
|
||||
"只导入你信得过的来源。"
|
||||
},
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { vm.importRulePack(vm.pendingRulePack, confirmed = true) }) {
|
||||
Text("我知道风险,继续", color = Doubao.Blue)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { vm.dismissRulePack() }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val openDoc = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
if (uri != null) {
|
||||
runCatching {
|
||||
ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
}.onSuccess { bytes ->
|
||||
if (kind.isZip) {
|
||||
vm.importPackage(kind.id, Base64.encodeToString(bytes, Base64.NO_WRAP), "")
|
||||
val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
// ★ 规则包**单独一条路**:它是唯一允许夹带可执行 Python 的
|
||||
// 包类型,内核会让它带 `confirmScripts` 才落库。
|
||||
// 第一次(不确认)会返回 needConfirm + warning,
|
||||
// 界面拿去弹警告;用户点了「我知道风险,继续」再传一次。
|
||||
if (kind.id == "rulepacks") vm.importRulePack(b64)
|
||||
else vm.importPackage(kind.id, b64, "")
|
||||
} else {
|
||||
vm.importPackage(kind.id, "", bytes.toString(Charsets.UTF_8))
|
||||
}
|
||||
@@ -193,7 +258,7 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
|
||||
FullScreen(
|
||||
title = "资源",
|
||||
subtitle = "世界观 · 技能 · 模型(${vm.state.agents.size} 个智能体在引用)",
|
||||
subtitle = "世界观 · 规则包 · 技能 · 模型(${vm.state.agents.size} 个智能体在引用)",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("导入") {
|
||||
@@ -219,7 +284,14 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
RowAction("新建") { editId = null; editing = true }
|
||||
RowAction("新建") {
|
||||
// ★ 规则包**不是**"填两个字段就完事"的东西 —— 它的内容
|
||||
// (定义表 + 脚本)在独立的全屏编辑页里。
|
||||
// 所以「新建」直接建一个**带模板**的包并进去,
|
||||
// 而不是先弹"名称+说明"的表单、再让用户自己去找编辑器。
|
||||
if (kind.id == "rulepacks") { vm.createRulePackFromTemplate(); return@RowAction }
|
||||
editId = null; editing = true
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState())) {
|
||||
@@ -252,7 +324,13 @@ fun ResourcesScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.clickable { editId = id; editing = true }
|
||||
.clickable {
|
||||
// ★ 规则包走**独立的全屏编辑页** —— 它的内容
|
||||
// (定义表 + 脚本)不是"label + 输入框"那套表单
|
||||
// 能表达的,硬塞进去会变成一堆看不懂的文本框
|
||||
if (kind.id == "rulepacks") { vm.openRulePackEdit(id); return@clickable }
|
||||
editId = id; editing = true
|
||||
}
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
@@ -369,11 +447,9 @@ private fun ResourceEditScreen(
|
||||
val slot = pendingSlot
|
||||
pendingSlot = ""
|
||||
if (uri == null || slot.isBlank() || id == null) return@rememberLauncherForActivityResult
|
||||
runCatching {
|
||||
val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)
|
||||
val name = (uri.lastPathSegment ?: "image.png").substringAfterLast('/')
|
||||
vm.uploadWorldviewAsset(id, slot, name, Base64.encodeToString(bytes, Base64.NO_WRAP))
|
||||
}.onFailure { vm.showHint("读不出这张图") }
|
||||
// 和智能体编辑页**同一份实现** —— 这条链路的坑(大图、GIF、SAF 没扩展名)
|
||||
// 两边一模一样,抄两份迟早只修一份
|
||||
vm.uploadWorldviewAssetFrom(ctx.applicationContext, id, slot, uri)
|
||||
}
|
||||
// 上传完 image 会变,跟着刷新预览
|
||||
vm.state.worldviews.firstOrNull { it.id == id }?.let {
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* [规则包编辑](v1.2 附录 D)—— 全屏。
|
||||
*
|
||||
* ## 为什么全屏
|
||||
*
|
||||
* 里面有:名称、说明、两张定义表、若干段 Python 脚本。任何一个都超过
|
||||
* 一屏弹窗能装下的量 —— 按仓库的界面约定,这就是该开全屏的那种。
|
||||
*
|
||||
* ## 脚本框的形状(照抄节点代码组件的做法)
|
||||
*
|
||||
* 两条硬要求,都来自踩过的坑(见 AGENTS.md):
|
||||
*
|
||||
* 1. **不软换行** —— ` else:` 折成两行、缩进全乱,而 Python 的缩进
|
||||
* 就是语法。做法是"把输入框塞进足够宽的横向滚动容器"。
|
||||
* 2. **有高度上限** —— 只写 `heightIn(min=...)` 的话,脚本一长框就长到
|
||||
* 屏幕外,把底下的东西顶出去。
|
||||
*
|
||||
* ## 定义表这版是只读的
|
||||
*
|
||||
* 数值/状态的**结构**(min/max、区间表、叠加层数)是一堆嵌套结构,
|
||||
* 用表单编辑要另做一套增删改。这一版先把**脚本**做成可编辑的
|
||||
* (那是最需要改的部分),定义表只读 + 指路导入导出。
|
||||
* 界面上**如实写着**这一点,不让用户对着只读的表发愣。
|
||||
*/
|
||||
@Composable
|
||||
fun RulePackEditScreen(vm: AppViewModel, onBack: () -> Unit) {
|
||||
val pack = vm.editingRulePack
|
||||
if (pack == null) {
|
||||
FullScreen(title = "规则包编辑", onBack = onBack) { Hint("正在读……") }
|
||||
return
|
||||
}
|
||||
|
||||
var name by remember(pack.id) { mutableStateOf(pack.name) }
|
||||
var note by remember(pack.id) { mutableStateOf(pack.note) }
|
||||
var scripts by remember(pack.id) { mutableStateOf(pack.scripts) }
|
||||
var editing by remember(pack.id) { mutableStateOf("") }
|
||||
var newScript by remember(pack.id) { mutableStateOf("") }
|
||||
var draft by remember(pack.id) { mutableStateOf("") }
|
||||
|
||||
fun infoJson(): JSONObject {
|
||||
val o = JSONObject()
|
||||
o.put("name", name)
|
||||
o.put("stats", JSONArray().apply {
|
||||
for (s in pack.stats) {
|
||||
put(JSONObject()
|
||||
.put("name", s.name).put("min", s.min).put("max", s.max)
|
||||
.put("shared", s.shared).put("script", s.script)
|
||||
.put("ranges", JSONArray().apply {
|
||||
for (r in s.ranges) {
|
||||
put(JSONObject().put("min", r.min).put("max", r.max).put("text", r.text))
|
||||
}
|
||||
}))
|
||||
}
|
||||
})
|
||||
o.put("statuses", JSONArray().apply {
|
||||
for (s in pack.statuses) {
|
||||
put(JSONObject()
|
||||
.put("name", s.name).put("type", s.kind).put("turns", s.turns)
|
||||
.put("max_stack", s.maxStack).put("script", s.script))
|
||||
}
|
||||
})
|
||||
return o
|
||||
}
|
||||
|
||||
FullScreen(
|
||||
title = "规则包编辑",
|
||||
subtitle = "${pack.stats.size} 条数值 · ${pack.statuses.size} 条状态 · ${scripts.size} 个脚本",
|
||||
onBack = onBack,
|
||||
actions = {
|
||||
TopTextAction("保存") { vm.saveRulePack(name, note, infoJson(), scripts) }
|
||||
},
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("名称", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
OutlinedTextField(
|
||||
value = note,
|
||||
onValueChange = { note = it },
|
||||
label = { Text("说明", fontSize = 12.sp) },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
)
|
||||
|
||||
// ---------------- 脚本(可编辑)----------------
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("脚本")
|
||||
if (vm.editingRulePack?.hasScripts != true) {
|
||||
Hint("这个包还没有脚本。数值的裁决、状态的每轮行为、赋予判定都靠脚本。")
|
||||
}
|
||||
Card {
|
||||
for ((fname, src) in scripts) {
|
||||
if (editing == fname) {
|
||||
Text(fname, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
CodeBox(value = draft, onValueChange = { draft = it })
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
RowAction("保存这段") {
|
||||
scripts = scripts + (fname to draft)
|
||||
editing = ""
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("取消") { editing = "" }
|
||||
Spacer(Modifier.width(10.dp))
|
||||
RowAction("删掉") {
|
||||
scripts = scripts - fname
|
||||
editing = ""
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(fname, fontSize = 13.sp, color = doubaoText())
|
||||
Text(
|
||||
"${src.lines().size} 行 · 点开编辑",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
RowAction("编辑") { editing = fname; draft = src }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
// 新建一段
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = newScript,
|
||||
onValueChange = { newScript = it },
|
||||
label = { Text("新脚本文件名", fontSize = 12.sp) },
|
||||
singleLine = true,
|
||||
textStyle = TextStyle(fontSize = 13.sp),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
RowAction("新建") {
|
||||
val f = newScript.trim()
|
||||
if (f.isNotBlank() && !scripts.containsKey(f)) {
|
||||
scripts = scripts + (f to SCRIPT_TEMPLATE)
|
||||
newScript = ""
|
||||
editing = f
|
||||
draft = SCRIPT_TEMPLATE
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 定义(只读)----------------
|
||||
Spacer(Modifier.height(10.dp))
|
||||
SectionLabel("数值定义")
|
||||
Card {
|
||||
if (pack.stats.isEmpty()) Hint("没有数值。")
|
||||
for (s in pack.stats) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
"${fmt(s.min)} ~ ${fmt(s.max)}" + if (s.shared) " · 全世界观共用" else "",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.ranges.isNotEmpty()) {
|
||||
Text(
|
||||
"${s.ranges.size} 段区间:" + s.ranges.joinToString("、") {
|
||||
"${fmt(it.min)}~${fmt(it.max)}「${it.text.take(10)}」"
|
||||
},
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
if (s.script.isNotBlank()) {
|
||||
Text("裁决脚本:${s.script}", fontSize = 11.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
SectionLabel("状态定义")
|
||||
Card {
|
||||
if (pack.statuses.isEmpty()) Hint("没有状态。")
|
||||
for (s in pack.statuses) {
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 5.dp)) {
|
||||
Text(s.name, fontSize = 13.sp, color = doubaoText())
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
(if (s.isPersistent) "持久" else "定时 ${s.turns} 轮") +
|
||||
(if (s.maxStack > 1) " · 最多叠 ${s.maxStack} 层" else ""),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Hint(
|
||||
"定义(数值和状态的增删、区间表)这一版还是只读的 —— " +
|
||||
"用「导出」在电脑上改 info.json 再导入是最快的办法。" +
|
||||
"界面上能改的是脚本,那也是最常改的部分。",
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/** 新建脚本时给的骨架(三个入口都列出来,用户知道可以写什么) */
|
||||
private const val SCRIPT_TEMPLATE = """# 可用的三个入口(写哪个都行,不写的就不执行):
|
||||
|
||||
def on_stat_change(name, value, delta):
|
||||
# 数值裁决:返回生效的增量(可以放大、缩小、返回 0 否决)
|
||||
return delta
|
||||
|
||||
|
||||
def on_turn(self_agent, stats_api):
|
||||
# 每轮生成回复之前跑一次(状态脚本)
|
||||
# stats_api['change_stat']('好感度', -1)
|
||||
# stats_api['set_hint']('中毒', '你眼前发黑')
|
||||
# stats_api['narrate']('毒性发作了')
|
||||
return True
|
||||
|
||||
|
||||
def on_grant(status_name, source_agent):
|
||||
# 别人要给你挂状态时,返回 False 就是抵抗掉
|
||||
return True
|
||||
"""
|
||||
|
||||
/**
|
||||
* 代码框:**不软换行** + **有高度上限**。
|
||||
*
|
||||
* ★ 不软换行:` else:` 折成两行、缩进全乱,而 Python 的缩进就是语法。
|
||||
* 做法是"把输入框塞进足够宽的横向滚动容器"(这个 Compose 版本的
|
||||
* `BasicTextField` 经典重载选不中,见 AGENTS.md)。
|
||||
*
|
||||
* ★ 高度上限:只写 `heightIn(min=...)` 的话脚本一长框就长到屏幕外,
|
||||
* 把底下的东西顶出去,用户够不着。
|
||||
*/
|
||||
@Composable
|
||||
private fun CodeBox(value: String, onValueChange: (String) -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 120.dp, max = 320.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState())) {
|
||||
BasicTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
textStyle = TextStyle(
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoText(),
|
||||
),
|
||||
modifier = Modifier.width(900.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun fmt(v: Double): String =
|
||||
if (v == v.toLong().toDouble()) v.toLong().toString() else v.toString()
|
||||
@@ -512,6 +512,59 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
}
|
||||
|
||||
/* ---------------- 个人资料 ---------------- */
|
||||
// 外观(v1.2 §6.1)
|
||||
SettingsCard("外观") {
|
||||
FormSwitch(
|
||||
title = "背景跟随说话者",
|
||||
sub = "群聊时,展示区的立绘和背景跟着当前发言的人换 —— " +
|
||||
"一眼就能看出这句话是谁说的。关掉的话固定用主智能体的。",
|
||||
checked = vm.state.settings.followSpeaker,
|
||||
onChange = { vm.setFollowSpeaker(it) },
|
||||
)
|
||||
}
|
||||
|
||||
// 对话(v1.2 §3.9 / §4.3)
|
||||
//
|
||||
// ★★ 这几个数字内核早就有、界面一直缺着 —— 用户只能手改 settings.json。
|
||||
// 而它们**都要和内核的默认值一致**,不然界面显示"20"而内核按别的跑。
|
||||
SettingsCard("对话") {
|
||||
NumberRow(
|
||||
title = "对话上下文窗口",
|
||||
sub = "每轮最多带最近多少轮对话进模型。超出的直接丢掉(不摘要)—— " +
|
||||
"该记住的走记忆系统。攒够几轮才裁一次,见下一项。",
|
||||
value = vm.state.settings.contextWindow,
|
||||
onChange = { vm.setContextWindow(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
NumberRow(
|
||||
title = "攒够几轮裁一次",
|
||||
sub = "不是「超一点就裁」,而是攒够这个数才裁一批 —— " +
|
||||
"每轮都裁的话前缀缓存每轮都失效,比多带几轮贵得多。",
|
||||
value = vm.state.settings.contextBatch,
|
||||
onChange = { vm.setContextBatch(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
NumberRow(
|
||||
title = "私聊最多几轮",
|
||||
sub = "两个智能体后台对聊时的上限(一轮 = 双方各说一次)。" +
|
||||
"这是安全网 —— 它们没有「该结束了」的内在信号。",
|
||||
value = vm.state.settings.privateChatRounds,
|
||||
onChange = { vm.setPrivateChatRounds(it) },
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// ★★ 用户要求:「talk_to 是用户可以选择传递和停止,有自动模式
|
||||
// (不用用户确认)」—— 所以默认是**手动**(关),
|
||||
// 群聊里 AI 交了话就停下来等你点;开了这个才是自动接着跑。
|
||||
FormSwitch(
|
||||
title = "AI 对聊自动模式",
|
||||
sub = "关(默认):群里 AI 把话交给别人时,底下会出现" +
|
||||
"「让他说 / 停在这」两个按钮,由你决定要不要接着聊。" +
|
||||
"开:不用确认,自动一轮轮接着跑(最多几轮)。",
|
||||
checked = vm.state.settings.aiTalkAuto,
|
||||
onChange = { vm.setAiTalkAuto(it) },
|
||||
)
|
||||
}
|
||||
|
||||
SettingsCard("个人资料") {
|
||||
FormLabel("昵称")
|
||||
FormField(
|
||||
@@ -1270,3 +1323,41 @@ private fun secretOrNull(raw: String): String? {
|
||||
if (v.all { it == '•' }) return null
|
||||
return v
|
||||
}
|
||||
|
||||
/**
|
||||
* 一行数字设置(v1.2 的上下文窗口 / 裁剪批量 / 私聊轮数)。
|
||||
*
|
||||
* ★ 独立一个组件而不是塞三个 `OutlinedTextField`:它们长得一样、
|
||||
* 行为也一样(只收数字、失焦/改完就存),抄三遍迟早有一处不一样。
|
||||
*/
|
||||
@Composable
|
||||
private fun NumberRow(
|
||||
title: String,
|
||||
sub: String,
|
||||
value: Int,
|
||||
onChange: (Int) -> Unit,
|
||||
) {
|
||||
var draft by remember(value) { mutableStateOf(value.toString()) }
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(title, fontSize = 14.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = draft,
|
||||
onValueChange = { s ->
|
||||
val digits = s.filter { it.isDigit() }.take(4)
|
||||
draft = digits
|
||||
digits.toIntOrNull()?.takeIf { it > 0 }?.let(onChange)
|
||||
},
|
||||
singleLine = true,
|
||||
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
|
||||
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number,
|
||||
),
|
||||
modifier = Modifier.width(100.dp),
|
||||
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(sub, fontSize = 11.sp, lineHeight = 16.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -91,6 +91,24 @@ fun TokenUsageScreen(
|
||||
Spacer(Modifier.width(24.dp))
|
||||
Metric("输出", usage.output)
|
||||
}
|
||||
// ★ 缓存统计(v1.2):**这家没给就不显示**。
|
||||
// 不是每家都返回缓存字段,显示两个恒为 0 的数会让用户
|
||||
// 以为"缓存完全没生效" —— 那是假警报,比不显示更糟。
|
||||
if (usage.hasCacheInfo) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Row {
|
||||
Metric("缓存命中", usage.cacheHit)
|
||||
Spacer(Modifier.width(24.dp))
|
||||
Metric("缓存未命中", usage.cacheMiss)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"命中率 ${(usage.hitRate * 100).toInt()}% —— " +
|
||||
"命中缓存的输入便宜得多,这一段没白存",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
if (usage.pricePerK > 0 && usage.cost != null) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
@@ -180,6 +198,18 @@ fun TokenUsageScreen(
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
// ★ 缓存命中/未命中(v1.2)。**这家没给就不显示这一行** ——
|
||||
// 不是每家都返回缓存字段,显示一个恒为 0 的"命中率"
|
||||
// 会让用户以为"缓存完全没生效"(那是个假警报)
|
||||
if (m.hasCacheInfo) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
"命中 ${fmtTokens(m.cacheHit)} · 未命中 ${fmtTokens(m.cacheMiss)}" +
|
||||
" · 命中率 ${(m.hitRate * 100).toInt()}%",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -213,17 +243,9 @@ fun TokenUsageScreen(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Card(content: @Composable () -> Unit) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(14.dp),
|
||||
) { content() }
|
||||
}
|
||||
// ★ 这里的私有 `Card` 删了 —— 它和 AgentEditScreen 的那个是**同一段代码**
|
||||
// 抄了两份(只有 vertical 内边距差 2dp)。现在统一用 DoubaoUi.kt 里的公共版。
|
||||
// 留着的话两个同签名函数都可见,编译器直接报"重载歧义"。
|
||||
|
||||
@Composable
|
||||
private fun Metric(label: String, value: Long) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
@@ -39,14 +39,17 @@
|
||||
|
||||
import base64
|
||||
import io
|
||||
import zipfile
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
import agent_context
|
||||
import agentdb
|
||||
import paths
|
||||
import rule_engine
|
||||
import rule_sandbox
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -359,7 +362,7 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
if len(seg) < 2 or seg[0] != 'api':
|
||||
return False
|
||||
|
||||
def body():
|
||||
def body(limit: int = 0):
|
||||
"""
|
||||
解析请求体。
|
||||
|
||||
@@ -367,10 +370,22 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
★ 但注意:往下传的时候必须**调用它**(`body()`)——
|
||||
直接把函数对象当 dict 传,报的是 `'function' object has no attribute 'get'`,
|
||||
而那个错看起来像"字段名写错了"。这里踩过一次。
|
||||
★ [limit] 给了就用它,不给就走 `read_json_body` 的默认小上限 ——
|
||||
图片那条路是唯一的例外,见 `ASSET_BODY_LIMIT`。
|
||||
|
||||
★★ 失败时**不能只 `return {}`**:那样"请求体太大 / 不是合法 JSON"
|
||||
会在下游表现成"某个字段是空的",于是报出牛头不对马嘴的错误
|
||||
(真机上就是大图报「不认识的外观槽位」)。原因挂到 handler 上,
|
||||
需要的地方用 `body_error(handler)` 取出来。
|
||||
"""
|
||||
# 每次进来先清掉上一次的残留,否则一次失败会永远跟着后面所有请求
|
||||
handler.body_error = ''
|
||||
try:
|
||||
if limit:
|
||||
return handler.read_json_body(limit)
|
||||
return handler.read_json_body()
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception as exc: # noqa: BLE001
|
||||
handler.body_error = str(exc)
|
||||
return {}
|
||||
|
||||
def err(code: int, msg: str):
|
||||
@@ -387,7 +402,7 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
return True
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _import_agent(handler, body(), err)
|
||||
return _import_agent(handler, body(UPLOAD_BODY_LIMIT), err)
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 3:
|
||||
aid = seg[2]
|
||||
@@ -472,13 +487,79 @@ def handle(handler, pathname: str, method: str) -> bool:
|
||||
handler.send_json(200, {'ok': True, **_usage_payload(agent)})
|
||||
return True
|
||||
|
||||
# ---------------- 数值与状态(§3.10 / §3.11)----------------
|
||||
#
|
||||
# GET 读一个智能体的数值和状态([状态数值] 浮层三个入口都用它)
|
||||
# POST 用户**直接改一个数值**(用户主权 —— 需求里 AI 只能申请增量,
|
||||
# 但用户是规则的主人,他可以直接设成任何值)
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'stats':
|
||||
agent = store.get_agent(seg[2])
|
||||
if not agent:
|
||||
err(404, '没有这个智能体')
|
||||
return True
|
||||
pack_id = agent_context.pack_of(agent)
|
||||
if method == 'GET':
|
||||
handler.send_json(200, _stats_payload(agent, pack_id))
|
||||
return True
|
||||
if method == 'POST':
|
||||
b = body()
|
||||
name = str(b.get('name') or '').strip()
|
||||
d = next((x for x in rule_engine.stat_defs(pack_id) if x['name'] == name), None)
|
||||
if not d:
|
||||
err(404, f'这个世界观里没有叫「{name}」的数值')
|
||||
return True
|
||||
try:
|
||||
want = float(b.get('value'))
|
||||
except (TypeError, ValueError):
|
||||
err(400, 'value 得是个数字')
|
||||
return True
|
||||
# ★ 用户直接设值:**照样 clamp**(不然界面会显示一个超出
|
||||
# [min,max] 的值,进度条和区间注入全都错位)
|
||||
after = rule_engine.clamp(d, want)
|
||||
rule_engine.set_value(agent, d, after)
|
||||
handler.send_json(200, _stats_payload(agent, pack_id))
|
||||
return True
|
||||
|
||||
|
||||
#
|
||||
# ★ 这是**同步**接口,可能要跑一两分钟(默认 10 轮 = 20 次 LLM 调用)。
|
||||
# 没做成异步任务队列,是因为那要一整套"任务 id + 轮询 + 取消"的机制,
|
||||
# 而私聊是**用户主动发起、等着看结果**的动作 ——
|
||||
# 等一等比"发起之后不知道去哪儿看"更好。
|
||||
# `maxRounds` 可以调小(探针和测试靠它)。
|
||||
# ---------------- 私聊:两个智能体幕后对聊(§3.9 形态 B)----------------
|
||||
if seg[1] == 'private-chat' and method == 'POST':
|
||||
b = body()
|
||||
first = store.get_agent(str(b.get('first') or ''))
|
||||
second = store.get_agent(str(b.get('second') or ''))
|
||||
if not first or not second:
|
||||
err(404, '需要两个智能体')
|
||||
return True
|
||||
if first.get('id') == second.get('id'):
|
||||
err(400, '不能让自己跟自己私聊')
|
||||
return True
|
||||
if agentdb.is_dead(first['id']) or agentdb.is_dead(second['id']):
|
||||
# 死亡的人不能说话(§3.5),私聊同理
|
||||
err(400, '有一方已经死亡,无法私聊')
|
||||
return True
|
||||
import private_chat
|
||||
|
||||
settings = store.read_settings()
|
||||
result = private_chat.run_pair(
|
||||
settings, first, second,
|
||||
max_rounds=private_chat.resolve_rounds(settings, b),
|
||||
opener=str(b.get('opener') or ''),
|
||||
)
|
||||
handler.send_json(200, result)
|
||||
return True
|
||||
|
||||
# ---------------- 智能体包 ----------------
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'package' and method == 'GET':
|
||||
return _export_agent(handler, seg[2], err)
|
||||
|
||||
# ---------------- 外观图片(四件套)----------------
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
|
||||
return _set_asset(handler, 'agents', seg[2], body(), err)
|
||||
return _set_asset(handler, 'agents', seg[2], body(UPLOAD_BODY_LIMIT), err)
|
||||
|
||||
# ---------------- 单条记忆 ----------------
|
||||
if seg[1] == 'memories' and len(seg) == 3:
|
||||
@@ -567,7 +648,7 @@ def _memories(handler, method: str, seg: list, body, err) -> bool:
|
||||
|
||||
# /memories/import
|
||||
if tail == ['import'] and method == 'POST':
|
||||
return _memory_import(handler, agent, body(), err)
|
||||
return _memory_import(handler, agent, body(UPLOAD_BODY_LIMIT), err)
|
||||
|
||||
return False
|
||||
|
||||
@@ -738,9 +819,137 @@ _RES_PATH = {
|
||||
'worldviews': 'worldviews',
|
||||
'model-entries': 'models',
|
||||
'skills': 'skills',
|
||||
# v1.2 数值状态包(需求附录 D)。★ 它是**唯一允许夹带可执行脚本**的包类型 ——
|
||||
# 智能体包/世界观包发现脚本一律拒绝导入(见 _resource_import)
|
||||
'rulepacks': 'rulepacks',
|
||||
}
|
||||
|
||||
|
||||
def _export_rulepack(handler, pid: str, err) -> bool:
|
||||
"""
|
||||
导出数值状态包(zip:`info.json` + 各脚本)。
|
||||
|
||||
★ **只导定义、不导当前值**(需求附录 D 原话:"数值的**定义**进包,
|
||||
**当前值**不进包 —— 经历与人设分离,同记忆")。
|
||||
所以把包发给别人,对方拿到的是规则,不是你的好感度。
|
||||
"""
|
||||
pack = store.get_resource('rulepacks', pid)
|
||||
if not pack:
|
||||
err(404, '没有这个规则包')
|
||||
return True
|
||||
info = dict(pack.get('info') or {})
|
||||
info['name'] = pack.get('name') or info.get('name') or '规则包'
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr('info.json', json.dumps(info, ensure_ascii=False, indent=2))
|
||||
for fname, src in (pack.get('scripts') or {}).items():
|
||||
zf.writestr(str(fname), str(src))
|
||||
return _send_json_ok(handler, {
|
||||
'ok': True,
|
||||
'name': pack.get('name') or '',
|
||||
'data': base64.b64encode(buf.getvalue()).decode('ascii'),
|
||||
'hasScripts': bool(pack.get('scripts')),
|
||||
})
|
||||
|
||||
|
||||
def _import_rulepack(handler, body: dict, err) -> bool:
|
||||
"""
|
||||
导入数值状态包。
|
||||
|
||||
★★ 这是**唯一允许夹带可执行脚本**的包类型(需求附录 D)。
|
||||
所以它比别的包多一道**服务端强制**的确认:
|
||||
|
||||
包里真有 `.py` 而请求没带 `confirmScripts: true` → **拒绝导入**,
|
||||
并把警告文案一起返回,界面拿去显示。
|
||||
|
||||
为什么不做成"界面弹个框就行":那只是界面上的礼貌,绕过界面直接
|
||||
调接口就没了。而这条是**安全底线**(脚本每轮在用户设备上跑)。
|
||||
|
||||
★ 智能体包 / 世界观包**仍然禁止夹带脚本** —— 那条在各自的导入里拦。
|
||||
"""
|
||||
raw = body.get('data') or ''
|
||||
if not raw:
|
||||
err(400, '缺少包内容')
|
||||
return True
|
||||
try:
|
||||
blob = base64.b64decode(raw)
|
||||
files = _read_zip(blob)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'包读不出来:{exc}')
|
||||
return True
|
||||
|
||||
# 先找出脚本 —— 在**解析 info.json 之前**就要决定要不要拦,
|
||||
# 因为"有没有脚本"是用户要先知道的事
|
||||
scripts = {
|
||||
os.path.basename(name): data.decode('utf-8', errors='replace')
|
||||
for name, data in files.items()
|
||||
if name.lower().endswith('.py')
|
||||
}
|
||||
if scripts and not body.get('confirmScripts'):
|
||||
return _send_json_ok(handler, {
|
||||
'ok': False,
|
||||
'needConfirm': True,
|
||||
'scriptCount': len(scripts),
|
||||
'warning': rule_sandbox.IMPORT_WARNING,
|
||||
})
|
||||
|
||||
info = None
|
||||
for name in files:
|
||||
if os.path.basename(name).lower() == 'info.json':
|
||||
try:
|
||||
info = json.loads(files[name].decode('utf-8'))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'info.json 解析失败:{exc}')
|
||||
return True
|
||||
break
|
||||
if not isinstance(info, dict):
|
||||
err(400, '包里没有 info.json —— 这不是一个数值状态包')
|
||||
return True
|
||||
|
||||
name = str(info.get('name') or body.get('name') or '规则包')[:40]
|
||||
item = store.create_resource('rulepacks', {
|
||||
'name': name,
|
||||
'note': str(body.get('note') or ''),
|
||||
'info': info,
|
||||
'scripts': scripts,
|
||||
})
|
||||
# 定义同步进库(值不动 —— 那是"定义进包、值不进包"的另一半)
|
||||
counts = rule_engine.sync_defs(item['id'], info)
|
||||
return _send_json_ok(handler, {
|
||||
'ok': True, 'item': item, 'stats': counts.get('stats', 0),
|
||||
'statuses': counts.get('statuses', 0), 'scripts': len(scripts),
|
||||
})
|
||||
|
||||
|
||||
def _stats_payload(agent: dict, pack_id: str) -> dict:
|
||||
"""
|
||||
一个智能体的数值 + 状态([状态数值] 浮层的三个入口共用这一个形状)。
|
||||
|
||||
★ 数值和状态**一起返回**:界面上它们总是同屏出现的("它现在什么状态、
|
||||
各项数值多少"),分两个接口的话界面要处理"一个到了一个没到"的中间态。
|
||||
"""
|
||||
agent = agent or {}
|
||||
defs = rule_engine.stat_defs(pack_id) if pack_id else []
|
||||
stats = []
|
||||
for d in defs:
|
||||
v = rule_engine.value_of(agent, d)
|
||||
stats.append({
|
||||
"name": d["name"], "value": v, "min": d["min"], "max": d["max"],
|
||||
"shared": bool(d.get("shared")),
|
||||
# 当前命中哪一段(界面可以直接显示,不用再实现一遍区间逻辑)
|
||||
"text": rule_engine.range_text(d, v),
|
||||
})
|
||||
pack = store.get_resource("rulepacks", pack_id) if pack_id else {}
|
||||
return {
|
||||
"agentId": agent.get("id") or "",
|
||||
"name": agent.get("name") or "",
|
||||
"stats": stats,
|
||||
"statuses": rule_engine.list_statuses(agent.get("id") or ""),
|
||||
"rulePackId": pack_id or "",
|
||||
"rulePackName": (pack or {}).get("name") or "",
|
||||
}
|
||||
|
||||
|
||||
def _tag_world_agents(items: list) -> list:
|
||||
"""
|
||||
给每个世界观补一个 `agents: [{id, name}]` —— "谁绑了它"。
|
||||
@@ -775,11 +984,19 @@ def _resource_route(handler, seg: list, method: str, body, err):
|
||||
name = _RES_PATH[seg[1]]
|
||||
|
||||
# 包 / JSON 的导入导出(世界观包、Skill 文件)
|
||||
#
|
||||
# ★ 规则包要**抢在通用分支前面**:它的格式不一样(zip 里除了 info.json
|
||||
# 还有一堆 .py),而且多一道"含脚本要确认"的关卡。
|
||||
if name == 'rulepacks':
|
||||
if len(seg) == 4 and seg[3] in ('package', 'export') and method == 'GET':
|
||||
return _export_rulepack(handler, seg[2], err)
|
||||
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _import_rulepack(handler, body(UPLOAD_BODY_LIMIT), err)
|
||||
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _resource_import(handler, name, body(), err)
|
||||
return _resource_import(handler, name, body(UPLOAD_BODY_LIMIT), err)
|
||||
if len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
|
||||
# 世界观的外观图(需求 3.6:沿用同一套四件套)
|
||||
return _set_asset(handler, 'worldviews', seg[2], body(), err)
|
||||
return _set_asset(handler, 'worldviews', seg[2], body(UPLOAD_BODY_LIMIT), err)
|
||||
if len(seg) == 4 and seg[3] == 'memories' and method == 'GET':
|
||||
# 世界观的**共享记忆**(大家共同记得什么)—— 只读视角
|
||||
return _world_memories(handler, seg[2], err)
|
||||
@@ -801,20 +1018,57 @@ def _resource_route(handler, seg: list, method: str, body, err):
|
||||
handler.send_json(200, {'ok': True, 'items': items})
|
||||
return True
|
||||
if method == 'POST':
|
||||
handler.send_json(200, {'ok': True, 'item': store.create_resource(name, body())})
|
||||
item = store.create_resource(name, body())
|
||||
# ★★ 规则包建完要**把定义同步进库**(`stat_defs` / `status_defs`)。
|
||||
#
|
||||
# 不同步的话表现是:"包建出来了、列表里显示 2 条数值,
|
||||
# 但智能体身上一条都读不到" —— 两边单独看都对,中间的连接断了。
|
||||
# 导入那条路一直是同步的(`_import_rulepack` 里做了),
|
||||
# 但**新建**这条路上原来漏了。
|
||||
if name == 'rulepacks':
|
||||
rule_engine.sync_defs(item.get('id') or '')
|
||||
handler.send_json(200, {'ok': True, 'item': item})
|
||||
return True
|
||||
|
||||
if len(seg) == 3:
|
||||
rid = seg[2]
|
||||
if method == 'GET':
|
||||
# ★★ 读**单个**资源 —— 原来这条路是**缺的**(只有列表 GET 和
|
||||
# PATCH/DELETE)。表现很隐蔽:`GET /api/rulepacks/<id>` 落到
|
||||
# 末尾返回 None,[规则包编辑] 于是拿到一个**空包** ——
|
||||
# 页面正常打开、标题正常、只是里面"0 条数值 0 条状态"。
|
||||
# 而那个包其实建出来了(列表里看得见),所以用户会以为
|
||||
# "新建之后东西丢了"。
|
||||
item = store.get_resource(name, rid)
|
||||
if item is None:
|
||||
err(404, '没有这一项')
|
||||
else:
|
||||
# 规则包要带上脚本源码(列表接口里是剔掉的)
|
||||
if name == 'rulepacks':
|
||||
item = {**item, 'scriptCount': len(item.get('scripts') or {})}
|
||||
handler.send_json(200, {'ok': True, 'item': item})
|
||||
return True
|
||||
if method == 'PATCH':
|
||||
updated = store.update_resource(name, rid, body())
|
||||
if updated is None:
|
||||
err(404, '没有这一项')
|
||||
else:
|
||||
# 改完定义同样要同步(改了 min/max 或区间表却不入库,
|
||||
# 表现是"改了没反应")
|
||||
if name == 'rulepacks':
|
||||
rule_engine.sync_defs(rid)
|
||||
handler.send_json(200, {'ok': True, 'item': updated})
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
handler.send_json(200, {'ok': True, 'deleted': store.delete_resource(name, rid)})
|
||||
# ★ 删规则包时**连定义一起删** —— 留着的话那些数值定义成了
|
||||
# 孤儿:包里已经没有它们了,但库里还有,而且值还在 `stat_values`。
|
||||
deleted = store.delete_resource(name, rid)
|
||||
if name == 'rulepacks':
|
||||
conn = agentdb._connect()
|
||||
conn.execute('DELETE FROM stat_defs WHERE pack_id = ?', (rid,))
|
||||
conn.execute('DELETE FROM status_defs WHERE pack_id = ?', (rid,))
|
||||
conn.commit()
|
||||
handler.send_json(200, {'ok': True, 'deleted': deleted})
|
||||
return True
|
||||
return None
|
||||
|
||||
@@ -832,6 +1086,9 @@ def _usage_payload(agent: dict) -> dict:
|
||||
used = usage['total']['input'] + usage['total']['output']
|
||||
# 单价(元/千 Token):在**全局模型列表**里配,填了才估费用
|
||||
price = 0.0
|
||||
cache_price = 0.0
|
||||
entry = {} # ★ 先给个空 dict:下面只有 mid 非空才会填它,
|
||||
# 而返回时无条件读 `entry` —— 不初始化会 NameError
|
||||
mid = agent.get('modelId') or ''
|
||||
if mid:
|
||||
entry = store.get_resource('models', mid) or {}
|
||||
@@ -839,6 +1096,10 @@ def _usage_payload(agent: dict) -> dict:
|
||||
price = float(entry.get('pricePerK') or 0)
|
||||
except (TypeError, ValueError):
|
||||
price = 0.0
|
||||
try:
|
||||
cache_price = float(entry.get('cachePricePerK') or 0)
|
||||
except (TypeError, ValueError):
|
||||
cache_price = 0.0
|
||||
return {
|
||||
'agentId': agent.get('id') or '',
|
||||
'name': agent.get('name') or '',
|
||||
@@ -847,6 +1108,10 @@ def _usage_payload(agent: dict) -> dict:
|
||||
# v1.2 缓存统计:两家都没给时是 0/0,界面据此不显示那一列
|
||||
'cacheHit': usage['total'].get('cacheHit', 0),
|
||||
'cacheMiss': usage['total'].get('cacheMiss', 0),
|
||||
# ★ 命中缓存的单价(v1.2)。各家命中都比未命中便宜得多(常见 1/10),
|
||||
# 只按未命中单价算的话费用会**越用越高估** —— 而用户会以为
|
||||
# 自己真花了那些钱。
|
||||
'cachePricePerK': cache_price,
|
||||
'total': used,
|
||||
'byModel': usage['byModel'],
|
||||
'limit': limit,
|
||||
@@ -891,6 +1156,24 @@ def _export_agent(handler, agent_id: str, err) -> bool:
|
||||
#: 外观四件套的槽位名(和需求 2.5 的 smartInfo.json 一一对应)
|
||||
ASSET_KEYS = ('front', 'back', 'border-main', 'border-info')
|
||||
|
||||
#: **上传类**接口单独给的请求体上限(图片槽位 + 四种包导入)。
|
||||
#:
|
||||
#: ★ 为什么别的接口 4MB、这里要 48MB:这些东西进 JSON 之前都要 base64,
|
||||
#: 体积是原件的 4/3 还要加转义。
|
||||
#: - 图片:真机上用户选的是**手机相册的照片**(30~55MB 很常见),
|
||||
#: base64 之后 38~73MB。默认那 4MB 一进去就被 read_json_body 判
|
||||
#: 「请求体过大」,而上层那个 `except` 把异常吞成空 dict,
|
||||
#: 最后报出来的是「不认识的外观槽位」—— 和真实原因毫无关系的一句话,
|
||||
#: 用户只看到"设置不了"。(这就是真机上报回来的那个 bug。)
|
||||
#: - 包导入:带外观图片的智能体包,zip 上到十几 MB,base64 之后还要再大。
|
||||
#:
|
||||
#: 现在前端会先把位图压到 3MB 以内(见 ImagePick.kt),走这里的常态是几百 KB;
|
||||
#: 这个上限留给**不压缩的 GIF/SVG** 和包导入兜底。
|
||||
#:
|
||||
#: ★ 别把这个上限按"最小的那个调用方"给 —— 这个仓库里已经出现过一次
|
||||
#: 「内核说这图可以(20MB),通道却说请求体太大(4MB)」的自相矛盾。
|
||||
UPLOAD_BODY_LIMIT = 48 * 1024 * 1024
|
||||
|
||||
#: v1.2 立绘表支持的五档(和情绪 preset 对齐,需求 2.5)
|
||||
PORTRAIT_PRESETS = ('喜', '怒', '哀', '平常', '死亡')
|
||||
|
||||
@@ -955,13 +1238,26 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
|
||||
err(404, '没有这一项')
|
||||
return True
|
||||
|
||||
# ★★ `key` 必须在这里读出来 —— 我改五档槽位时**把这行删掉了**,
|
||||
# 于是下面 `key.partition(':')` 直接 NameError → 整个接口 500。
|
||||
# 表现是"角色图设置不了"(任何图都传不上去)。
|
||||
# 而当时的探针**没测这个接口**,所以一路绿着过去了。
|
||||
key = str(body.get('key') or '').strip()
|
||||
# ★ v1.2:立绘是**五档**,所以槽位名允许带档位 —— `front:喜`。
|
||||
# 不带档位的 `front` 视为「平常」档(兼容旧界面和旧调用)。
|
||||
base, _, slot = key.partition(':')
|
||||
base = base.strip()
|
||||
slot = slot.strip()
|
||||
if base not in ASSET_KEYS:
|
||||
err(400, f'不认识的外观槽位:{base}(可选:{"、".join(ASSET_KEYS)})')
|
||||
# ★ 先看请求体是不是根本没读进来(太大 / 不是合法 JSON)。
|
||||
# 那种情况下 `key` 必然是空的,报"槽位不认识"等于把人往完全错误的
|
||||
# 方向带 —— 真机上就是这么发生的:30MB 的照片 → 请求体超上限 →
|
||||
# 报的却是「不认识的外观槽位」,查了半天槽位名。
|
||||
why = getattr(handler, 'body_error', '')
|
||||
if why:
|
||||
err(400, f'上传内容没收全:{why}')
|
||||
else:
|
||||
err(400, f'不认识的外观槽位:{base}(可选:{"、".join(ASSET_KEYS)})')
|
||||
return True
|
||||
if base == 'front':
|
||||
slot = slot or '平常'
|
||||
@@ -996,7 +1292,7 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
|
||||
dest = os.path.join(_asset_dir(owner_id), f'front-{_safe_segment(slot)}-{name}')
|
||||
with open(dest, 'wb') as fh:
|
||||
fh.write(blob)
|
||||
_drop_file(fronts.get(slot)) # 换图时把旧的那张删掉,不然越攒越多
|
||||
_drop_replaced(fronts.get(slot), dest) # 换图时删旧的那张,不然越攒越多
|
||||
fronts[slot] = dest
|
||||
image['front'] = fronts
|
||||
return _send_json_ok(handler, {
|
||||
@@ -1021,7 +1317,7 @@ def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
|
||||
dest = os.path.join(_asset_dir(owner_id), f'{base}-{name}')
|
||||
with open(dest, 'wb') as fh:
|
||||
fh.write(blob)
|
||||
_drop_file(image.get(base))
|
||||
_drop_replaced(image.get(base), dest)
|
||||
image[base] = dest
|
||||
return _send_json_ok(handler, {
|
||||
'item': save(image),
|
||||
@@ -1041,6 +1337,33 @@ def _drop_file(path) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _drop_replaced(old, keep: str) -> None:
|
||||
"""
|
||||
换图时删掉旧的那张 —— 但**新旧是同一个文件时,千万不能删**。
|
||||
|
||||
★★ 这个 bug 是真机上踩出来的(而且随手试一次碰不到):
|
||||
落盘名是 `<槽位>-<原始文件名>`,所以**同一个文件传第二次时新旧同名**,
|
||||
于是这段顺序出问题:
|
||||
open(dest,'wb') 写新内容
|
||||
_drop_file(旧路径) ← 旧路径 == dest,刚写的那张被自己删了
|
||||
image[base] = dest ← 留下一个指向**不存在文件**的引用
|
||||
结果:资源目录空着,state 里却指着一个幽灵路径,界面回退到默认图。
|
||||
表现是"同一张图传第二次就没了"。
|
||||
|
||||
第一次传时用的是 SAF 给的 `image_1000018033` 这种 segment,名字不一样,
|
||||
所以只有"第二次"才触发 —— 用户报的"设置不了"里就混着这一种。
|
||||
"""
|
||||
p = str(old or '').strip()
|
||||
if not p:
|
||||
return
|
||||
try:
|
||||
if os.path.abspath(p) == os.path.abspath(str(keep or '')):
|
||||
return
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
_drop_file(p)
|
||||
|
||||
|
||||
def _import_agent(handler, body, err) -> bool:
|
||||
"""
|
||||
导入智能体包(需求 2.5)。
|
||||
@@ -1182,4 +1505,4 @@ def _resource_import(handler, name: str, body, err) -> bool:
|
||||
|
||||
def _send_json_ok(handler, payload: dict) -> bool:
|
||||
handler.send_json(200, {'ok': True, **payload})
|
||||
return True
|
||||
return True
|
||||
@@ -1,4 +1,4 @@
|
||||
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||||
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||||
|
||||
## 这个模块只做一件事
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import rule_engine
|
||||
import store
|
||||
from defaults import (
|
||||
BUILTIN_SKILL,
|
||||
@@ -337,23 +338,41 @@ def build_system_prompt(settings: dict, agent: dict) -> str:
|
||||
return render(template, values)
|
||||
|
||||
|
||||
def pack_of(agent: dict) -> str:
|
||||
"""
|
||||
这个智能体用的规则包 id(`世界观.rulePackId`),没有就空串。
|
||||
|
||||
★ 数值状态包挂在**世界观**上(需求 §3.6:"v1.2 起,世界观同时是
|
||||
数值状态包的挂载点"),所以没绑世界观就没有规则引擎 —— 返回空串,
|
||||
`<stats>` / `<status>` 两段会被整段删掉。
|
||||
"""
|
||||
wid = ((agent or {}).get('worldviewId') or '').strip()
|
||||
if not wid:
|
||||
return ''
|
||||
world = _safe(lambda: store.get_resource('worldviews', wid), None) or {}
|
||||
return (world.get('rulePackId') or '').strip()
|
||||
|
||||
|
||||
def build_stats(agent: dict) -> str:
|
||||
"""
|
||||
`<stats>` 段:数值系统(需求附录 C / §3.10)。
|
||||
|
||||
★ 占位函数,**阶段 3 实现**。现在返回空串 —— `render` 会把整段删掉,
|
||||
所以提示词里不会出现一个空的 `<stats></stats>`。
|
||||
先把它列进 `SECTIONS` 是为了让模板和渲染两边**一开始就一致**:
|
||||
否则阶段 3 加段名时,会有一版"模板里有、渲染不管"的中间状态,
|
||||
表现是提示词里原样留着 `{stats}` 大括号。
|
||||
格式见 `rule_engine.stats_section`。没绑世界观、或世界观没挂规则包 → 空段。
|
||||
"""
|
||||
return ''
|
||||
pack = pack_of(agent)
|
||||
if not pack:
|
||||
return ''
|
||||
return _safe(lambda: rule_engine.stats_section(agent or {}, pack), '')
|
||||
|
||||
|
||||
def build_status(agent: dict) -> str:
|
||||
"""
|
||||
`<status>` 段:状态系统(需求附录 C / §3.11)。
|
||||
|
||||
★ 同样是**阶段 3 的占位**,见 `build_stats` 的说明。
|
||||
★ 和 `<stats>` 不同,它**不要求绑世界观**:状态一旦被赋予就挂在智能体
|
||||
自己身上,解绑世界观不该让它身上的状态凭空消失(那和"解绑不丢记忆"
|
||||
是同一个道理)。
|
||||
"""
|
||||
return ''
|
||||
if not ((agent or {}).get('id') or ''):
|
||||
return ''
|
||||
return _safe(lambda: rule_engine.status_section(agent or {}), '')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
|
||||
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||||
@@ -11,6 +11,7 @@ Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from typing import Callable, Optional
|
||||
|
||||
import agent_context
|
||||
@@ -328,9 +329,41 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
# 按开关动态追加,两边永远一致。
|
||||
#
|
||||
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
|
||||
# ★ 新一轮开始:清掉上一轮的发言权移交(v1.2 §3.9 的"一轮最多一次")。
|
||||
# 放这儿是因为它必须**每轮**重置,而且和线程无关(工具跑在 worker 线程里)
|
||||
tools_runtime.begin_round()
|
||||
|
||||
if tools_runtime.ui_tools_enabled(settings):
|
||||
system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip()
|
||||
|
||||
# ★★ 状态脚本要在**重拼 prompt 之前**跑(需求附录 E 的顺序,固定):
|
||||
#
|
||||
# 状态脚本执行 → 重拼 prompt → 生成
|
||||
#
|
||||
# 顺序反了的话,脚本这一轮的改动要等下一轮才生效 ——
|
||||
# 表现是"中毒了但 AI 这轮还生龙活虎"。
|
||||
#
|
||||
# ★ 脚本报错**不中断对话**(需求附录 E):错误收集起来给界面提示,
|
||||
# 对话照常往下走。规则脚本是用户自己写的,写错了是常态,
|
||||
# 一次脚本错误把整轮对话搞崩,用户会以为整个 App 坏了。
|
||||
try:
|
||||
import rule_engine
|
||||
|
||||
_turn = rule_engine.run_turn_scripts(agent or {}, agent_context.pack_of(agent or {}))
|
||||
if _turn.get('narration'):
|
||||
# 脚本返回的旁白"作为系统消息注入下一轮"(需求 §3.10)——
|
||||
# 拼在提示词末尾,比单开一条 user 消息干净(不会污染对话记录)
|
||||
system_prompt = (system_prompt + '\n\n【当前状况】\n'
|
||||
+ '\n'.join(_turn['narration'])).strip()
|
||||
for _e in _turn.get('errors') or []:
|
||||
# ★ 异常要**让用户看见**(需求附录 E:"异常归零 + UI 提示")。
|
||||
# 只 print 到 stderr 的话,用户看到的只是"这轮回复有点怪",
|
||||
# 而完全不知道是脚本报错了 —— 而脚本是他自己写的。
|
||||
emit({'type': 'rule_error', 'message': _e})
|
||||
print(f'[rule] {_e}', file=sys.stderr)
|
||||
except Exception as _exc: # noqa: BLE001 - 规则引擎坏了不该让对话发不出去
|
||||
print(f'[rule] 状态脚本执行失败:{_exc}', file=sys.stderr)
|
||||
|
||||
# ★★ 兼容降级(需求 3.3):这个模型不支持 tools 参数时,换成"正文内调用约定"。
|
||||
#
|
||||
# 为什么要这么绕:记忆/情绪这些能力**全靠工具**,而本地小模型、
|
||||
@@ -395,6 +428,16 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
answer = ''
|
||||
reasoning_all = ''
|
||||
tool_call_count = 0
|
||||
# ★ 工具调用的**明细**(不只次数)。
|
||||
#
|
||||
# 界面上的"工具卡片"(调了什么、成没成、返回了什么)以前只有流式那一刻
|
||||
# 能看到 —— 因为这份明细**从来没落过库**,重启 App 就全没了。
|
||||
# 用户的原话:「工具怎么重启就不显示了」。
|
||||
#
|
||||
# 只留 id/name/ok/result 四样:args 可能很长(贴进去的代码),
|
||||
# 而用户真正想回看的是"它做了什么、拿到什么"。result 也截断,
|
||||
# 不然一条消息能撑爆会话 JSON。
|
||||
tool_trace = []
|
||||
usage = None
|
||||
|
||||
for round_index in range(max_rounds):
|
||||
@@ -461,6 +504,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
return {
|
||||
'content': final, 'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
'toolTrace': tool_trace,
|
||||
}
|
||||
|
||||
convo.append({
|
||||
@@ -516,6 +560,13 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
'result': payload,
|
||||
})
|
||||
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
|
||||
# ★ 记明细(落库用,见上面 tool_trace 的注释)
|
||||
tool_trace.append({
|
||||
'id': tc.get('id') or '',
|
||||
'name': tc.get('name') or '',
|
||||
'ok': bool(result.get('ok')),
|
||||
'result': str(payload)[:800],
|
||||
})
|
||||
|
||||
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
|
||||
emit({
|
||||
@@ -530,4 +581,5 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
'toolTrace': tool_trace,
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
|
||||
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
|
||||
|
||||
## 为什么是"内置工具"而不是 `tools/*.py`
|
||||
|
||||
@@ -361,6 +361,389 @@ def get_token_usage(args: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 规则引擎(v1.2 §3.10 / §3.11)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
CHANGE_STAT = {
|
||||
'name': 'change_stat',
|
||||
'description': (
|
||||
'申请改变**你自己**身上某个数值。\n'
|
||||
'★ 只能给**增量**(+5 / -10),**不能写绝对值** —— 因为数值可能被'
|
||||
'世界观里的规则脚本裁决(放大、缩小、甚至否决),绝对值会让那套规则失效。\n'
|
||||
'真实结果以返回值里的 after 为准:你以为加了 5,可能实际加了 10 或者 0。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'name': {'type': 'string', 'description': '数值名(见系统提示词的 <stats> 段)'},
|
||||
'delta': {'type': 'number', 'description': '想改变多少(可正可负)'},
|
||||
},
|
||||
'required': ['name', 'delta'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def change_stat(args: dict) -> dict:
|
||||
"""
|
||||
申请数值增量(需求 §3.10)。
|
||||
|
||||
内核流程是固定的:**脚本裁决 → clamp → 写库 → 下一轮注入反映新值**。
|
||||
这里只负责把请求转过去、把**真实结果**回来告诉模型 ——
|
||||
它必须知道"我以为加 5,实际加了 10"(否则下一轮它会按错误的心智继续演)。
|
||||
"""
|
||||
import agent_context
|
||||
import rule_engine
|
||||
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
pack = agent_context.pack_of(agent)
|
||||
if not pack:
|
||||
raise ValueError('你还没有绑定世界观,身上没有数值系统')
|
||||
name = str(args.get('name') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('name 不能为空')
|
||||
raw = args.get('delta')
|
||||
try:
|
||||
delta = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f'delta 得是个数字(收到的是「{raw}」)') from None
|
||||
r = rule_engine.change(agent, pack, name, delta)
|
||||
if not r.get('ok'):
|
||||
raise ValueError(r.get('error') or '改数值失败')
|
||||
out = {
|
||||
'name': name,
|
||||
'applied': r.get('applied'),
|
||||
'before': r.get('before'),
|
||||
'after': r.get('after'),
|
||||
}
|
||||
if r.get('text'):
|
||||
out['now'] = r['text']
|
||||
if r.get('narration'):
|
||||
out['narration'] = r['narration']
|
||||
if r.get('applied') != delta:
|
||||
# ★ 被裁决过了要**明说**,不然模型会以为自己算错了
|
||||
out['note'] = f'你申请的是 {delta:+g},规则裁决后实际生效 {r.get("applied"):+g}。'
|
||||
return out
|
||||
|
||||
|
||||
GRANT_STATUS = {
|
||||
'name': 'grant_status',
|
||||
'description': (
|
||||
'给**同一个世界观里**的另一个智能体施加一个状态(比如中毒、庇佑)。\n'
|
||||
'对方可能**抵抗**(那是他的设定),被抵抗时你会拿到明确回执。\n'
|
||||
'跨世界观一律无效。同名状态重复施加默认**刷新时长**,不会叠层。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '目标的**名字**(或 id)'},
|
||||
'status_name': {'type': 'string', 'description': '状态名(见世界观规则包)'},
|
||||
'turns': {'type': 'integer', 'description': '持续几轮(可选,默认按定义)'},
|
||||
},
|
||||
'required': ['target', 'status_name'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _find_agent(needle: str):
|
||||
"""
|
||||
按名字或 id 找智能体。
|
||||
|
||||
★ 为什么按**名字**找:模型在提示词里看到的伙伴就是名字
|
||||
(`<peer_emotions>` 给的是"仙辰-哀"),它拿不到 id。
|
||||
重名时取第一个 —— 重名本来就不该发生(界面会显示 玄辰/玄辰(2),
|
||||
但那是显示层的事)。
|
||||
"""
|
||||
import store
|
||||
|
||||
key = str(needle or '').strip()
|
||||
if not key:
|
||||
return None
|
||||
for a in store.list_agents():
|
||||
if a.get('id') == key:
|
||||
return a
|
||||
for a in store.list_agents():
|
||||
if (a.get('name') or '').strip() == key:
|
||||
return a
|
||||
return None
|
||||
|
||||
|
||||
def grant_status(args: dict) -> dict:
|
||||
"""给同世界观的另一个智能体施加状态(需求 §3.11)"""
|
||||
import agent_context
|
||||
import rule_engine
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
pack = agent_context.pack_of(me)
|
||||
if not pack:
|
||||
raise ValueError('你还没有绑定世界观,用不了状态系统')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
# 给自己挂状态用别的途径没有意义 —— 直接说不支持,
|
||||
# 免得模型以为"自残"是个正常操作
|
||||
raise ValueError('不能给自己施加状态,只能施加给同世界观的其他智能体')
|
||||
status_name = str(args.get('status_name') or '').strip()
|
||||
try:
|
||||
turns = int(args.get('turns') or 0)
|
||||
except (TypeError, ValueError):
|
||||
turns = 0
|
||||
r = rule_engine.grant(me, pack, target, status_name, turns)
|
||||
if not r.get('ok'):
|
||||
# ★ 被抵抗时**抛错**而不是返回 ok:false —— 需求说"A 必须知道结果",
|
||||
# 而工具抛错是模型一定会看到的那条路(返回里的字段它可能忽略)
|
||||
raise ValueError(r.get('error') or '赋予失败')
|
||||
return {
|
||||
'target': r.get('target'),
|
||||
'status': r.get('name'),
|
||||
'remaining': r.get('remaining'),
|
||||
'refreshed': r.get('refreshed'),
|
||||
'note': ('对方本来就有这个状态,已刷新时长。' if r.get('refreshed')
|
||||
else f'已施加给「{r.get("target")}」。'),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 多智能体对话(v1.2 §3.9)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
INVITE_AGENT = {
|
||||
'name': 'invite_agent',
|
||||
'description': (
|
||||
'把**同一个世界观里**的另一个智能体拉进当前群聊,让他也能说话。\n'
|
||||
'只能拉同世界观的人;单聊会话要先转成群聊。\n'
|
||||
'★ 拉之前先在正文里跟用户说一声 —— 别默默往对话里塞人。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '要拉进来的智能体的名字'},
|
||||
},
|
||||
'required': ['target'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def invite_agent(args: dict) -> dict:
|
||||
"""
|
||||
拉起同世界观的智能体进群(需求 §3.9 形态 A)。
|
||||
|
||||
按智能体自己的配置分流(需求 §6.1 的「拉起其他智能体:静默 / 需确认」):
|
||||
|
||||
· **静默**:直接进场,系统消息播报「仙辰加入了对话」
|
||||
· **需确认**:这次调用**不直接拉人**,而是返回一个"需要确认"的结果,
|
||||
让 AI 在正文里问用户一句;用户答应之后 AI 再调一次。
|
||||
|
||||
★ 关于"需确认":需求写的是"弹窗询问,拒绝结果作为工具返回值回给 AI"。
|
||||
真正的系统弹窗要等界面通道(`ask_user` 那套机制),这一版先退成
|
||||
"让 AI 自己问"。**功能上等价(用户仍是否决者)**,差别是它经过
|
||||
AI 的嘴而不是系统弹窗 —— 这一点在界面做好之前得说清楚,
|
||||
免得以后有人以为这里已经实现了弹窗。
|
||||
"""
|
||||
import agentdb
|
||||
import group_chat
|
||||
import store
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
ctx = tools_runtime.current_context()
|
||||
conv_id = ctx.get('conversationId') or ''
|
||||
conv = store.get_conversation(conv_id) or {}
|
||||
if not conv:
|
||||
raise ValueError('拿不到当前会话')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不用拉自己 —— 你已经在场了')
|
||||
|
||||
my_world = (me.get('worldviewId') or '').strip()
|
||||
if not my_world or my_world != (target.get('worldviewId') or '').strip():
|
||||
raise ValueError(f'「{target.get("name")}」和你不在同一个世界观里,拉不进来')
|
||||
|
||||
if not group_chat.is_group(conv):
|
||||
# 单聊拉人 → 转成群聊(需求 §3.9:"当前会话中加入多个智能体")
|
||||
group_chat.promote(conv, target['id'])
|
||||
store.update_conversation(conv_id, {
|
||||
'type': 'group', 'participants': conv.get('participants') or [],
|
||||
})
|
||||
return {'joined': target.get('name'), 'becameGroup': True,
|
||||
'note': f'这个会话现在是群聊了,「{target.get("name")}」加入了对话。'}
|
||||
|
||||
if target['id'] in group_chat.member_ids(conv):
|
||||
return {'joined': target.get('name'), 'already': True,
|
||||
'note': f'「{target.get("name")}」已经在对话里了。'}
|
||||
|
||||
# 按智能体配置分流
|
||||
mode = str(me.get('inviteMode') or 'silent').lower()
|
||||
if mode == 'confirm':
|
||||
return {
|
||||
'needConfirm': True,
|
||||
'target': target.get('name'),
|
||||
'note': (f'你设置了「拉起需要确认」,所以这次**没有**直接拉人。'
|
||||
f'请在正文里问用户一句"要不要把{target.get("name")}叫来",'
|
||||
f'用户答应之后再调一次这个工具。'),
|
||||
}
|
||||
|
||||
import group_chat as gc
|
||||
|
||||
gc.add_member(conv, target['id'])
|
||||
store.update_conversation(conv_id, {'participants': conv.get('participants') or []})
|
||||
return {'joined': target.get('name'), 'note': f'「{target.get("name")}」加入了对话。'}
|
||||
|
||||
|
||||
PASS_TURN = {
|
||||
'name': 'pass_turn',
|
||||
'description': (
|
||||
'把发言权交给群里的另一个智能体。\n'
|
||||
'★ **一轮最多移交一次** —— 转来转去没人接话,用户会看得莫名其妙。\n'
|
||||
'★ 交给已死亡的人无效,发言权会回到主智能体。\n'
|
||||
'不想说话时不用调它,直接正常回复就行。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'target': {'type': 'string', 'description': '接话的智能体的名字'},
|
||||
},
|
||||
'required': ['target'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def pass_turn(args: dict) -> dict:
|
||||
"""
|
||||
移交发言权(需求 §3.9 的点名制)。
|
||||
|
||||
"一轮最多一次"靠 `tools_runtime` 的上下文标记实现 —— 不放在会话里,
|
||||
因为它是**这一轮**的属性,落库反而要额外写清理逻辑。
|
||||
"""
|
||||
import agentdb
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
# ★★ 用 tools_runtime 的**轮次级状态**,不能用工具上下文 ——
|
||||
# 工具跑在 worker 线程里,写进 thread-local 的标记会随线程消失,
|
||||
# 于是"一轮最多一次"永远不生效(踩过,见 tools_runtime.begin_round 的注释)
|
||||
if tools_runtime.handoff_state().get('used'):
|
||||
# ★ 需求明文"一轮最多一次"。第二次直接拒,理由说清楚 ——
|
||||
# 不然模型会以为是"对方有问题",而不是"规则不允许"
|
||||
raise ValueError('这一轮你已经移交过发言权了(一轮最多一次),直接回复就行')
|
||||
target = _find_agent(str(args.get('target') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("target")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不能把发言权交给自己')
|
||||
if agentdb.is_dead(target['id']):
|
||||
# ★ 需求明文:死亡目标移交无效。这里**如实告诉模型**,
|
||||
# 它就会自己在正文里圆过去(而不是干等着对方开口)
|
||||
raise ValueError(f'「{target.get("name")}」已经死亡,移交无效 —— 你自己接着说,或者交给别人')
|
||||
tools_runtime.note_handoff(target['id'])
|
||||
return {'handed_to': target.get('name'),
|
||||
'note': f'下一轮由「{target.get("name")}」接话。这一轮你不再移交了。'}
|
||||
|
||||
|
||||
TALK_TO = {
|
||||
'name': 'talk_to',
|
||||
'description': (
|
||||
'在群聊里**主动对另一个智能体说一句话**。\n'
|
||||
'★ 和 `pass_turn` 的区别很要紧:那个只是"我不说了,你来",**不带内容** ——\n'
|
||||
' 对方接到的是一片空白,只能凭上下文猜该说什么。\n'
|
||||
' 这个是你**有话要对他说**:内容会进对话,他下一轮看得到并回应你。\n'
|
||||
'★ 想跟群里的谁聊就调它,一来一回可以聊好几轮。\n'
|
||||
'★ 一轮最多一次 —— 转来转去没人接话,用户会看得莫名其妙。\n'
|
||||
'★ 单聊里没有"别人",调了会报错。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'agent': {'type': 'string', 'description': '对方的名字或 id'},
|
||||
'content': {'type': 'string', 'description': '你要对他说的话'},
|
||||
},
|
||||
'required': ['agent', 'content'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def talk_to(args: dict) -> dict:
|
||||
"""
|
||||
主动找群里的另一个智能体说话。
|
||||
|
||||
★★ 为什么单独一个工具(用户明确要求:「智能体主动调用工具和别的智能体聊」,
|
||||
「工具定义 / 智能体加上内容」):
|
||||
|
||||
`pass_turn` 只交发言权、**不带内容** —— 对方接到的是一片空白。
|
||||
要"两个智能体真的聊起来",就得让发起方**能说一句具体的话**,
|
||||
而且那句话要**落进对话**,对方下一轮才看得到。
|
||||
所以这个工具的参数就是那两样:**跟谁说 + 说什么**。
|
||||
|
||||
★ 说完之后把发言权交给他(`note_handoff`)—— 界面据此**自动续一轮**,
|
||||
他会真的开口回应;他也可以反过来再 `talk_to` 回来,于是就能聊下去。
|
||||
"""
|
||||
import group_chat
|
||||
import tools_runtime
|
||||
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
ctx = _ctx()
|
||||
conv_id = str(ctx.get('conversationId') or '')
|
||||
conv = store.get_conversation(conv_id) or {}
|
||||
if not group_chat.is_group(conv):
|
||||
raise ValueError('这条不是群聊 —— 只有群里有「别人」可以聊')
|
||||
|
||||
if tools_runtime.handoff_state().get('used'):
|
||||
# 和 pass_turn 共用"一轮最多一次"那个标记:要么移交、要么找人说,
|
||||
# 一轮里只做一件,否则发言权会被转好几手,用户看着莫名其妙
|
||||
raise ValueError('这一轮你已经把话交给别人了,等他回应完再说')
|
||||
|
||||
target = _find_agent(str(args.get('agent') or '').strip())
|
||||
if not target:
|
||||
raise ValueError(f'找不到叫「{args.get("agent")}」的智能体')
|
||||
if target.get('id') == me.get('id'):
|
||||
raise ValueError('不能对自己说 —— 直接说就行')
|
||||
if target['id'] not in group_chat.member_ids(conv):
|
||||
raise ValueError(f'「{target.get("name")}」不在这个群里,先把他拉进来')
|
||||
|
||||
content = str(args.get('content') or '').strip()
|
||||
if not content:
|
||||
raise ValueError('要说什么?content 不能是空的')
|
||||
|
||||
# ① 这句话以**我**的名义落进对话 —— 对方下一轮就看得到
|
||||
before = len((store.get_conversation(conv_id) or {}).get('messages') or [])
|
||||
store.append_messages(conv_id, [{
|
||||
'role': 'assistant',
|
||||
'content': content,
|
||||
'agentId': me.get('id'),
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
after = len((store.get_conversation(conv_id) or {}).get('messages') or [])
|
||||
print(f'[talk_to] conv={conv_id} 落库 {before}->{after} 内容={content[:20]!r}',
|
||||
file=sys.stderr)
|
||||
# ② 把发言权交给他 —— 界面据此自动续一轮,让他真的回应
|
||||
tools_runtime.note_handoff(target['id'])
|
||||
return {
|
||||
'said_to': target.get('name'),
|
||||
# ★★ **回显说了什么**。不回显的话模型看不到自己的话落在哪儿,
|
||||
# 会以为"传过去是空的"、然后反复重试 ——
|
||||
# 真机上就是模型自己在回复里写「这条是空的,我猜是想看我把 talk_to 真跑一遍」
|
||||
# (用户报的「talk_to 没有内容呀」)。
|
||||
'content': content,
|
||||
'note': (
|
||||
f'已把「{content}」说给「{target.get("name")}」,'
|
||||
'这句话已经写进对话、他下一轮看得到,接下来由他回应。别再重复调这个工具。'
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 注册
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -374,6 +757,15 @@ AGENT_TOOLS = {
|
||||
'memory_suggest_summary': {'spec': MEMORY_SUGGEST_SUMMARY, 'run': memory_suggest_summary},
|
||||
'emotion_set': {'spec': EMOTION_SET, 'run': emotion_set},
|
||||
'get_token_usage': {'spec': GET_TOKEN_USAGE, 'run': get_token_usage},
|
||||
# v1.2 规则引擎(附录 B 的后两个)
|
||||
'change_stat': {'spec': CHANGE_STAT, 'run': change_stat},
|
||||
'grant_status': {'spec': GRANT_STATUS, 'run': grant_status},
|
||||
# v1.2 多智能体对话(附录 B 的 invite_agent / pass_turn)
|
||||
'invite_agent': {'spec': INVITE_AGENT, 'run': invite_agent},
|
||||
'pass_turn': {'spec': PASS_TURN, 'run': pass_turn},
|
||||
# ★ 主动找另一个智能体说话(用户要求:参数是「智能体 + 内容」)。
|
||||
# `pass_turn` 只交发言权、不带内容,所以那个聊不起来。
|
||||
'talk_to': {'spec': TALK_TO, 'run': talk_to},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -125,6 +125,66 @@ CREATE TABLE IF NOT EXISTS agent_skills (
|
||||
ord INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (agent_id, skill_id)
|
||||
);
|
||||
|
||||
-- ============ v1.2 规则引擎(需求 §3.10 数值 / §3.11 状态)============
|
||||
--
|
||||
-- 和记忆一个思路:**定义**挂世界观、**值**按 scope 存。
|
||||
--
|
||||
-- 为什么定义不挂智能体:需求 §3.10 原话"定义统一收进数值状态包
|
||||
-- (世界观层),智能体不再自带数值定义" —— 一份定义、多个实例。
|
||||
--
|
||||
-- 值的 scope 有两种,由 def 的 shared 决定:
|
||||
-- shared=0 → "agent:<uuid>" 好感度各算各的
|
||||
-- shared=1 → "world:<uuid>" 灵气浓度全世界观一份
|
||||
-- 这和记忆的 scope 写法**故意一致**(`scope_of` 那套),
|
||||
-- 于是"绑定/解绑世界观只是换读写空间、值不迁移不丢失"这条也自动成立。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stat_defs (
|
||||
-- ★ key 是**规则包** id 不是世界观 id:同一个包可以被多个世界观引用,
|
||||
-- 定义只存一份(改一次全生效)。世界观只是"挂载点"。
|
||||
pack_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- min / max 是 SQL 关键字,所以列名带后缀
|
||||
min_value REAL NOT NULL DEFAULT 0,
|
||||
max_value REAL NOT NULL DEFAULT 100,
|
||||
shared INTEGER NOT NULL DEFAULT 0,
|
||||
-- ranges 是 JSON 字符串:[{"min":0,"max":20,"text":"冷淡:……"}],
|
||||
-- 命中哪段注入哪段的 text(需求 §3.10 的"声明式区间表")
|
||||
ranges TEXT NOT NULL DEFAULT '[]',
|
||||
script TEXT NOT NULL DEFAULT '',
|
||||
ord INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (pack_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stat_values (
|
||||
scope TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
value REAL NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (scope, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS status_defs (
|
||||
pack_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- persistent(持久,每轮执行脚本)/ timed(定时,每轮递减归零消失)
|
||||
kind TEXT NOT NULL DEFAULT 'timed',
|
||||
turns INTEGER NOT NULL DEFAULT 1,
|
||||
max_stack INTEGER NOT NULL DEFAULT 1,
|
||||
script TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (pack_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS status_instances (
|
||||
agent_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
-- 剩余轮数:timed 每轮 -1,归零消失;persistent 恒为 -1(不过期)
|
||||
remaining INTEGER NOT NULL DEFAULT 0,
|
||||
stacks INTEGER NOT NULL DEFAULT 1,
|
||||
-- 状态提示词:脚本可以改写它(需求 §3.11 的脚本权限之一)
|
||||
hint TEXT NOT NULL DEFAULT '',
|
||||
granted_at TEXT NOT NULL,
|
||||
PRIMARY KEY (agent_id, name)
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
|
||||
@@ -42,6 +42,9 @@ import timeouts
|
||||
import agentdb
|
||||
import agent_api
|
||||
import agent_context
|
||||
import context_window
|
||||
import group_chat
|
||||
import rule_engine
|
||||
import tools_runtime
|
||||
import uploads
|
||||
from defaults import PROVIDER_PRESETS
|
||||
@@ -610,6 +613,15 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
'worldviews': store.list_resource('worldviews'),
|
||||
'modelEntries': store.list_resource('models'),
|
||||
'skills': store.list_resource('skills'),
|
||||
# v1.2 数值状态包。★ **剔掉脚本源码**,只给个数 ——
|
||||
# `/api/state` 是每次刷新都调的,把几 KB 的脚本每次都传一遍
|
||||
# 是纯浪费;列表上也只需要"带不带脚本"这一个信息。
|
||||
# 要看源码去 [规则包编辑],那里单独拉。
|
||||
'rulePacks': [
|
||||
{**{k: v for k, v in p.items() if k != 'scripts'},
|
||||
'scriptCount': len(p.get('scripts') or {})}
|
||||
for p in store.list_resource('rulepacks')
|
||||
],
|
||||
# AI 提的"该整理记忆了"(按智能体存),界面据此显示按钮
|
||||
'memorySuggestions': {
|
||||
a.get('id'): store.peek_summary_suggestion(a.get('id') or '')
|
||||
@@ -944,14 +956,58 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
kind = str(body.get('type') or 'single')
|
||||
parts = body.get('participants')
|
||||
self.send_json(200, {'conversation': store.create_conversation(
|
||||
body.get('title') or '新对话',
|
||||
# ★ 新会话要**记住它属于谁** —— 会话隔离的依据就是它。
|
||||
# 不传的话所有会话的主人都是空,切换智能体时就没法判断
|
||||
# "这是不是同一个人的对话",只能一直串着(用户报的 bug)。
|
||||
agent_id=(body.get('agentId') or '').strip(),
|
||||
# ★ v1.2 §3.9:群聊是**独立实体**,出现在每个参与者的会话列表里。
|
||||
# 成员列表的第 0 个是主智能体(无人被点名时由它兜底发言)。
|
||||
kind=kind,
|
||||
participants=parts if isinstance(parts, list) else None,
|
||||
)})
|
||||
return True
|
||||
|
||||
# ---- 群聊成员增删(需求 §3.9:"用户手动增删成员无条件")----
|
||||
#
|
||||
# ★ "无条件"是需求原话:不加"只有主智能体能加人""要对方同意"这类
|
||||
# 限制 —— 会话是用户的,他想拉谁就拉谁。
|
||||
# 唯一的例外是主智能体不能移出(移掉就没有兜底发言的人了)。
|
||||
member_id = self._match_id(pathname, '/api/conversations/')
|
||||
if member_id is not None and '/members' in pathname:
|
||||
conv = store.get_conversation(member_id)
|
||||
if not conv:
|
||||
self.send_json(404, {'error': '会话不存在'})
|
||||
return True
|
||||
head, _, tail = pathname.partition('/members')
|
||||
target = tail.strip('/')
|
||||
if method == 'POST' and not target:
|
||||
try:
|
||||
b = self.read_json_body()
|
||||
except ValueError:
|
||||
b = {}
|
||||
target = str(b.get('agentId') or '').strip()
|
||||
if not group_chat.add_member(conv, target):
|
||||
self.send_json(400, {'error': '加不进去(人不存在或已经在里面了)'})
|
||||
return True
|
||||
elif method == 'DELETE' and target:
|
||||
if not group_chat.remove_member(conv, target):
|
||||
self.send_json(400, {'error': '移不出去(主智能体不能被移出)'})
|
||||
return True
|
||||
else:
|
||||
self.send_json(405, {'error': '不支持的操作'})
|
||||
return True
|
||||
# ★ 只存 `participants` —— "成员超过一个就升级成群聊"那条规则
|
||||
# 收在 `group_chat.add_member` 里了。补在这里的话,
|
||||
# 任何别的调用方都会忘,而忘的代价是"拉了人但他从不说话"。
|
||||
updated = store.update_conversation(
|
||||
member_id, {'participants': conv.get('participants') or []}) or conv
|
||||
self.send_json(200, {'conversation': updated})
|
||||
return True
|
||||
|
||||
conv_id = self._match_id(pathname, '/api/conversations/')
|
||||
if conv_id is not None:
|
||||
if method == 'GET':
|
||||
@@ -974,6 +1030,51 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200 if ok else 404, {'ok': ok})
|
||||
return True
|
||||
|
||||
# 标记某条消息为「重要」(v1.2 §4.3)
|
||||
#
|
||||
# 路径:/api/conversations/<convId>/important,body: {content, role?, important?}
|
||||
#
|
||||
# ★ 只有**用户**能打这个标记(需求原话"仅用户可标")——
|
||||
# AI 那边没有对应的工具,它有 `memory_add` 去记该记的东西。
|
||||
# 被标记的消息在**上下文窗口裁剪**时"破格永久携带"。
|
||||
#
|
||||
# ★★ 按**内容**定位而不是下标(踩过):
|
||||
# 界面上那份消息列表和存储里的**不保证一一对应**(本地生成的内容、
|
||||
# 还没落地的流式消息……),按下标"长按第 3 条"会把标记打到第 1 条上,
|
||||
# 而且**静默标错** —— 用户要等哪天发现某句话莫名没被裁掉才知道。
|
||||
# 找不到就报 404,绝不猜一条标上去。
|
||||
if pathname.startswith('/api/conversations/') and pathname.endswith('/important') \
|
||||
and method == 'POST':
|
||||
cid = pathname[len('/api/conversations/'):-len('/important')].strip('/')
|
||||
if cid and '/' not in cid:
|
||||
try:
|
||||
body = self.read_json_body()
|
||||
except ValueError:
|
||||
body = {}
|
||||
content = body.get('content')
|
||||
if content is None:
|
||||
self.send_json(400, {'error': '要带上 content(按内容定位那条消息)'})
|
||||
return True
|
||||
want = body.get('important')
|
||||
if want is None:
|
||||
# 不传就取反:界面上是个开关,点一下切一次。
|
||||
# ★ 用**存储里**那条的当前状态取反(不是界面传来的),
|
||||
# 免得界面和服务端状态不一致时越切越乱
|
||||
conv = store.get_conversation(cid) or {}
|
||||
cur = False
|
||||
for m in reversed(conv.get('messages') or []):
|
||||
if str(m.get('content') or '') == str(content):
|
||||
cur = bool(m.get('important'))
|
||||
break
|
||||
want = not cur
|
||||
msg = store.mark_important_by_content(
|
||||
cid, content, str(body.get('role') or ''), bool(want))
|
||||
if msg is None:
|
||||
self.send_json(404, {'error': '没找到这条消息(内容对不上)'})
|
||||
else:
|
||||
self.send_json(200, {'ok': True, 'important': bool(want)})
|
||||
return True
|
||||
|
||||
# 会议模式
|
||||
if pathname == '/api/meetings' and method == 'GET':
|
||||
self.send_json(200, {'meetings': meeting.list_meetings()})
|
||||
@@ -1600,7 +1701,15 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
conversation_id = body.get('conversationId') or 'c_main'
|
||||
text = str(body.get('message') or '').strip()
|
||||
attachments = body.get('attachments') if isinstance(body.get('attachments'), list) else []
|
||||
if not text and not attachments:
|
||||
# ★★ 自动续的那几轮(`autoContinue` / `forceSpeaker`)**本来就没有用户消息** ——
|
||||
# 那是让群里下一个人接着说话,不是用户在打字。
|
||||
#
|
||||
# 不放行的话,每一轮都会被这条校验打回 400,
|
||||
# 用户在界面上看到的是**一屏「出错了:消息为空」**,
|
||||
# 而"两个智能体对话"永远发生不了(真机反馈「还是不能互相对话」,
|
||||
# 现场就是六条这个错误)。
|
||||
auto_continue = bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))
|
||||
if not text and not attachments and not auto_continue:
|
||||
self.send_json(400, {'error': '消息为空'})
|
||||
return
|
||||
|
||||
@@ -1653,9 +1762,10 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
existing = store.get_conversation(conversation_id) or {}
|
||||
history_source = body.get('history') if isinstance(body.get('history'), list) else \
|
||||
existing.get('messages') or []
|
||||
history = [
|
||||
{'role': m.get('role'), 'content': m.get('content')}
|
||||
for m in history_source
|
||||
# ★ 先只做**过滤**,真正的窗口裁剪放到下面(`agent` 解析之后)——
|
||||
# 因为窗口大小是**按智能体配**的(需求 4.3),这里还不知道是谁。
|
||||
raw_history = [
|
||||
m for m in history_source
|
||||
if isinstance(m, dict) and m.get('role') in ('user', 'assistant')
|
||||
]
|
||||
|
||||
@@ -1683,6 +1793,74 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId'))
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
|
||||
# ★★ 群聊的发言权仲裁(需求 v1.2 §3.9)。
|
||||
#
|
||||
# 单聊时这里是**恒等操作**(`resolve` 原样返回传进去的那个人),
|
||||
# 判断收在 `is_group` 里 —— 只有群聊才真去仲裁。
|
||||
#
|
||||
# 三种来源,优先级从高到低:
|
||||
# ① 用户 @ 的人(用户主权)
|
||||
# ② AI 上一轮 `pass_turn` 移交的人(一轮最多一次)
|
||||
# ③ 主智能体兜底 —— **永不冷场**,没人被点名时也有人接话
|
||||
conv0 = store.get_conversation(conversation_id) or {}
|
||||
if group_chat.is_group(conv0):
|
||||
all_agents = store.list_agents()
|
||||
names = [(x['id'], x.get('name') or '') for x in all_agents]
|
||||
# ★★ 用户这一轮 @ 了谁 —— **只看这一条消息**。
|
||||
#
|
||||
# 这个顺序很容易写错:本函数是「先仲裁、后落库」,
|
||||
# 所以 `raw_history` 里**根本没有本次这条用户消息**。
|
||||
# 拿它去找"最后一条 user",找到的是**上一次**用户说的话。
|
||||
#
|
||||
# 踩过两次:
|
||||
# ① 用户打 `@寐眠 在吗` → 按上一条(没点名)仲裁 → 小黑替寐眠答
|
||||
# ② **自动续轮时又从历史回退** → 把上一轮的 `@寐眠` 又拿来用,
|
||||
# 于是 `talk_to` 明明把话交给了别人,仲裁还是给寐眠 ——
|
||||
# 表现是"下回还是 A 说话"(真机反馈)。
|
||||
#
|
||||
# ★ 续轮(`autoContinue`)**本来就没有新用户消息**,
|
||||
# 那一轮该由 `forced` / `passed` / 轮流来定,
|
||||
# 绝不能去翻历史里的 `@` —— 那是上一件事了。
|
||||
want = group_chat.mention_in(text or '', names)
|
||||
pick = group_chat.resolve(
|
||||
conv0,
|
||||
want=want,
|
||||
# ★★ 从**上一轮**的移交状态取,**不是**从 HTTP body ——
|
||||
# 界面(Kotlin)从来不发 handoffTo 这个字段,
|
||||
# 以前读 body 等于永远拿到空串,② AI 移交那条分支是**死代码**。
|
||||
# 现在 pass_turn 写在 tools_runtime 的轮次状态里,这里读它。
|
||||
passed=str(tools_runtime.handoff_state().get('to') or ''),
|
||||
# ★ 界面点「让他们聊」时指定的人(优先级最高)。
|
||||
# 不这样做的话,"两个 AI 对话"就得指望 AI 自己愿意 pass_turn ——
|
||||
# 实测它并不总会,用户按了也没反应。
|
||||
forced=str(body.get('forceSpeaker') or ''),
|
||||
alive={x['id']: not agentdb.is_dead(x['id']) for x in all_agents},
|
||||
)
|
||||
speaker = store.get_agent(pick.get('speaker'))
|
||||
if speaker:
|
||||
agent, agent_id = speaker, speaker.get('id') or ''
|
||||
# 界面据此显示"这一轮谁在说、为什么是他"
|
||||
emit({'type': 'speaker', 'agentId': agent_id,
|
||||
'reason': pick.get('reason') or '', 'note': pick.get('note') or ''})
|
||||
|
||||
# ★★ 对话上下文窗口(需求 v1.2 §4.3)。
|
||||
#
|
||||
# 只把"最近 N 轮 + 用户标了重要的那几条"送进模型。
|
||||
# 超出的**直接丢弃、不做摘要**(需求原话)—— 沉淀走记忆系统,
|
||||
# 不搞第二套摘要管线(摘要自己也要花一次调用,还会丢信息且不可追溯)。
|
||||
#
|
||||
# ★ 命名:这里叫「上下文窗口」,和记忆侧的「记忆注入窗口」不是一回事。
|
||||
# 后者管"塞多少条记忆",超出部分**还能 memory_search 搜到**;
|
||||
# 这里管"送几轮对话",超出就真的不送了。
|
||||
#
|
||||
# ★ `strip_for_model` 是**新建** dict,不原地改历史 ——
|
||||
# 改一个字,从那儿往后的前缀缓存全废(需求 4.3 的"字节冻结")。
|
||||
win_rounds, win_batch = context_window.resolve(settings, agent)
|
||||
window = context_window.trim(raw_history, win_rounds, win_batch)
|
||||
history = [context_window.strip_for_model(m) for m in window['messages']]
|
||||
if window.get('reason'):
|
||||
print(f'[context] {context_window.describe(window)}', file=sys.stderr)
|
||||
|
||||
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
|
||||
#
|
||||
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
|
||||
@@ -1694,7 +1872,13 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
# · 老会话(本次改动之前建的)没有 agentId —— 那种**认领**它,
|
||||
# 而不是也另起一个,否则所有历史会话第一次聊天都会跳走。
|
||||
owner = (existing.get('agentId') or '').strip()
|
||||
if existing and agent_id:
|
||||
# ★★ **群聊不做这个隔离**:群聊本来就是多智能体的,上面
|
||||
# `group_chat.resolve` 刚把 `agent_id` 定成「本轮的发言人」,
|
||||
# 它不是「会话的主人」。照单聊这样比一下,群里每换一个人说话
|
||||
# 就会另起一个会话 —— 用户 @ 谁,界面就跳到谁的对话去
|
||||
# (真机反馈原话:「群聊一@就跑到别的对话去了」)。
|
||||
# `is_group` 既认 `type` 也认 `participants`,老会话也吃得住。
|
||||
if existing and agent_id and not group_chat.is_group(existing):
|
||||
if not owner:
|
||||
store.set_conversation_agent(conversation_id, agent_id)
|
||||
elif owner != agent_id:
|
||||
@@ -1759,19 +1943,57 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
})
|
||||
return
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'user',
|
||||
'content': text or f'(已发送 {len(attachment_meta)} 个附件)',
|
||||
'attachments': attachment_meta,
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
if text:
|
||||
store.auto_title(conversation_id, text)
|
||||
# ★★ `autoContinue`:这一轮是**界面替 AI 自动续的**,不是用户说的话。
|
||||
#
|
||||
# 群聊里 AI 用 `pass_turn` 把话交给另一个人时,界面会接着再发一次
|
||||
# (不带用户消息)—— 这样两个人就能真的聊起来,而不是
|
||||
# "用户说一句、AI 移交一次、然后就没下文了"。
|
||||
#
|
||||
# ★ 不追加用户消息:追加的话对话里会冒出一堆空消息,
|
||||
# 而且模型会以为用户又说话了。移交状态本来就从
|
||||
# `tools_runtime.handoff_state()` 里读(上一轮留下的),
|
||||
# 所以下一轮的发言人自然是接得上的。
|
||||
# ★ 判据必须和 `_handle_chat` 开头那条校验**完全一致**
|
||||
# (`autoContinue` 或 `forceSpeaker`)—— 两处不一致的话,
|
||||
# 一边放行一边往里塞空用户消息,对话里就会冒出一堆空条目。
|
||||
auto_continue = bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))
|
||||
if not auto_continue:
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'user',
|
||||
'content': text or f'(已发送 {len(attachment_meta)} 个附件)',
|
||||
'attachments': attachment_meta,
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
if text:
|
||||
store.auto_title(conversation_id, text)
|
||||
|
||||
# ★★ 自动续轮(`autoContinue`)**不能再追加一条空的 user 消息**。
|
||||
#
|
||||
# 以前不管是不是续轮都拼一条 `{'role':'user','content':user_content}`,
|
||||
# 而续轮没有用户输入 → `user_content` 是空串。
|
||||
# 模型看到的是"用户刚发了一条空消息",于是它自己都懵了 ——
|
||||
# 真机上的原话是:「这条又是空的,我这边没收到内容。猜两种可能:…」
|
||||
# (用户报的「talk_to 没有内容呀」)。
|
||||
#
|
||||
# 而 `talk_to` 说的那句话**就在历史里**(落库了),
|
||||
# 不追加空消息它自然就看到了。
|
||||
msgs_for_model = list(history)
|
||||
if not auto_continue:
|
||||
msgs_for_model.append({'role': 'user', 'content': user_content})
|
||||
else:
|
||||
# 续轮补一句**极短的指令**而不是空消息:模型需要知道
|
||||
# "现在轮到你接话",但不该以为用户说了什么。
|
||||
# 这条**不落库**(只进这一轮给模型的 messages),
|
||||
# 所以用户在聊天记录里看不到它。
|
||||
msgs_for_model.append({
|
||||
'role': 'user',
|
||||
'content': '(系统:现在轮到你接着说,不用等用户输入。直接接着上面的内容回应。)',
|
||||
})
|
||||
|
||||
result = agent_loop.run_agent(
|
||||
settings=settings,
|
||||
agent=agent,
|
||||
messages=[*history, {'role': 'user', 'content': user_content}],
|
||||
messages=msgs_for_model,
|
||||
emit=emit,
|
||||
should_stop=cancelled,
|
||||
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
|
||||
@@ -1802,8 +2024,29 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
int(result.get('toolCalls') or 0),
|
||||
bool((settings.get('tools') or {}).get('python', True)),
|
||||
),
|
||||
# ★ 工具调用明细要落库 —— 不落的话界面上那些"工具卡片"
|
||||
# 只有流式那一刻能看到,**重启 App 就全没了**
|
||||
# (用户报的「工具怎么重启就不显示了」)。
|
||||
'toolTrace': result.get('toolTrace') or [],
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
|
||||
# ★★ 这一轮 AI 用 `pass_turn` 把话交给了别人吗?交了就**告诉界面**。
|
||||
#
|
||||
# 光靠上面那个 `speaker` 事件不够 —— 它是在**轮前**发的,
|
||||
# 而 `pass_turn` 是**轮中**才调用的。于是最常见的那个剧本:
|
||||
# ① 用户没点名(或点名的人不在场)→ 兜底给主智能体,reason = "host"
|
||||
# ② 主智能体说完话,轮中调 `pass_turn` 让给另一个人
|
||||
# 界面看到的 reason 是 "host",以为没人移交,就**不再续轮** ——
|
||||
# 被让的那个人永远开不了口(用户报的"还是不能互相对话")。
|
||||
#
|
||||
# ★ 判据用 `tools_runtime.handoff_state()`(模块级轮次状态),
|
||||
# 不是线程局部变量 —— 工具跑在 worker 线程上,
|
||||
# 这个坑在 `pass_turn` 上已经踩过一次了。
|
||||
hs = tools_runtime.handoff_state()
|
||||
if hs.get('used') and hs.get('to'):
|
||||
emit({'type': 'handoff', 'to': hs['to'], 'from': agent_id})
|
||||
|
||||
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
|
||||
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
|
||||
if agent_id and (in_tok or out_tok):
|
||||
@@ -1816,6 +2059,26 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
agentdb.token_add(agent_id, model_name, in_tok, out_tok, hit, miss)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[usage] 记 Token 用量失败:{exc}', file=sys.stderr)
|
||||
|
||||
# ★ 状态每参与一轮减 1(需求 §3.11)。
|
||||
#
|
||||
# 放在**生成之后**:这一轮它确实开口了,才该扣。
|
||||
# 放在之前的话,被额度拦下、被死亡拦下的那些轮次也会扣 ——
|
||||
# 而它根本没说话。
|
||||
#
|
||||
# 过期要播报("中毒已经消退了")—— 那是个用户能感知的变化。
|
||||
if agent_id:
|
||||
try:
|
||||
for ev in rule_engine.tick_statuses(agent_id):
|
||||
emit({
|
||||
'type': 'status',
|
||||
'name': ev.get('name'),
|
||||
'expired': bool(ev.get('expired')),
|
||||
'remaining': ev.get('remaining', 0),
|
||||
})
|
||||
except Exception as exc: # noqa: BLE001 - 状态系统坏了不该让回复发不出去
|
||||
print(f'[rule] 状态递减失败:{exc}', file=sys.stderr)
|
||||
|
||||
conv = store.get_conversation(conversation_id) or {}
|
||||
emit({'type': 'saved', 'conversationId': conversation_id, 'title': conv.get('title')})
|
||||
except Exception as exc: # noqa: BLE001 - 出错也要以 error 事件收尾,前端才知道停了
|
||||
|
||||
230
android/kernel/context_window.py
Normal file
@@ -0,0 +1,230 @@
|
||||
"""对话上下文窗口(需求 v1.2 §4.3)。
|
||||
|
||||
## 命名纪律
|
||||
|
||||
需求里特别强调了一句,照抄过来:
|
||||
|
||||
> 记忆侧叫「**记忆注入窗口**」,对话侧叫「**上下文窗口**」,文档与 UI 永不混用。
|
||||
|
||||
两个东西确实像但完全不同:
|
||||
|
||||
· 记忆注入窗口(§3.2)—— 每轮往 system prompt 里塞**多少条记忆**,
|
||||
超出部分**降级为可检索**(AI 还能 memory_search 找到)
|
||||
· 对话上下文窗口(§4.3)—— 往模型送**最近多少轮对话**,
|
||||
超出部分**直接丢弃、不做摘要**(沉淀走记忆系统,不搞第二套摘要管线)
|
||||
|
||||
混着叫的话,用户问"我调窗口怎么没用"时你都不知道他调的是哪个。
|
||||
|
||||
## 四条规则
|
||||
|
||||
1. **窗口 = 最近 N 轮 + 重要标记消息**(N 默认 20,按智能体配置)
|
||||
2. **重要标记只有用户能打**(AI 有 memory_add,标记是用户主权)。
|
||||
被标记的消息**破格永久携带**,按**原始时间序**插回去 ——
|
||||
不是塞到最前面:那会打乱因果,模型会看到"先发生的事在后面"。
|
||||
3. **成批对齐裁剪**:不是"超一点就裁一点",而是攒够一批才裁一批。
|
||||
目的是**摊薄前缀缓存失效次数** —— 每轮都裁的话,前缀每轮都变,
|
||||
上下文缓存一次都命中不了,比不裁还贵。
|
||||
4. **字节冻结**:送进去的历史消息**永不原地修改**。
|
||||
改一个字,从那个字往后的前缀缓存全废。
|
||||
|
||||
## 为什么"直接丢弃、不做摘要"
|
||||
|
||||
需求原话。看起来粗暴,但想清楚了:
|
||||
|
||||
· 摘要本身要花一次 LLM 调用(比省下的那点 token 还贵)
|
||||
· 而且摘要会**丢信息且不可追溯** —— 用户翻到三个月前那句话还在界面上,
|
||||
但模型完全不知道,他会以为 AI"忘了"是 bug
|
||||
· 该记住的东西本来就该走 `memory_add` 进记忆系统(那里有检索、有署名、
|
||||
有置顶,是**为长期记忆设计的**)。两套摘要管线只会互相打架。
|
||||
"""
|
||||
import os
|
||||
|
||||
#: 默认窗口(轮)。需求定的 20。
|
||||
DEFAULT_ROUNDS = 20
|
||||
|
||||
#: 默认裁剪批量(轮)。需求定的 5。
|
||||
DEFAULT_BATCH = 5
|
||||
|
||||
#: 窗口上限/下限(用户填什么都不至于把上下文搞爆或搞没)
|
||||
MIN_ROUNDS = 4
|
||||
MAX_ROUNDS = 200
|
||||
|
||||
|
||||
def resolve(settings: dict, agent: dict = None) -> tuple:
|
||||
"""
|
||||
算出这次该用多少:**智能体配置 > 全局设置 > 默认**(返回 `(轮数, 批量)`)。
|
||||
|
||||
★ 和 provider_info / voice_for 一个套路:智能体可以单独配,
|
||||
没配就继承全局。三处规则长得一样,但**不能合并**(数据来源不同)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
settings = settings or {}
|
||||
|
||||
def pick(key, default, lo, hi):
|
||||
for src in (agent.get(key), settings.get(key)):
|
||||
try:
|
||||
v = int(float(src))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if v > 0:
|
||||
return max(lo, min(hi, v))
|
||||
return default
|
||||
|
||||
rounds = pick('contextWindow', DEFAULT_ROUNDS, MIN_ROUNDS, MAX_ROUNDS)
|
||||
batch = pick('contextBatch', DEFAULT_BATCH, 1, 50)
|
||||
return rounds, batch
|
||||
|
||||
|
||||
def split_rounds(messages: list) -> list:
|
||||
"""
|
||||
把消息流切成"轮"。
|
||||
|
||||
★ 一轮 = 从一条 user 到**下一条 user 之前**(含它后面的 assistant 和
|
||||
任何工具痕迹)。不用"user/assistant 配对"来切,是因为:
|
||||
· 工具调用会产生 assistant → tool → assistant 这种多段结构
|
||||
· 界面上用户也可能连发两条
|
||||
按 user 划线对这两种都稳,而且**永远不会切出半轮**(需求要求
|
||||
"按完整轮对齐,不裁半轮")。
|
||||
"""
|
||||
groups = []
|
||||
cur = []
|
||||
for m in messages or []:
|
||||
if not isinstance(m, dict):
|
||||
continue
|
||||
if m.get('role') == 'user' and cur:
|
||||
groups.append(cur)
|
||||
cur = []
|
||||
cur.append(m)
|
||||
if cur:
|
||||
groups.append(cur)
|
||||
return groups
|
||||
|
||||
|
||||
def _indexed_rounds(msgs: list) -> list:
|
||||
"""
|
||||
和 `split_rounds` 一样切轮,但**每条带原始下标** `[(i, msg)]`。
|
||||
|
||||
★ 为什么需要下标:被裁掉的那批里如果有"用户标了重要"的消息,
|
||||
得把它**按原始时间序插回**去 —— 没有下标就只能塞最前面,
|
||||
而那会打乱因果(模型会看到"先发生的事在后面")。
|
||||
"""
|
||||
groups = []
|
||||
cur = []
|
||||
for i, m in enumerate(msgs):
|
||||
if m.get('role') == 'user' and cur:
|
||||
groups.append(cur)
|
||||
cur = []
|
||||
cur.append((i, m))
|
||||
if cur:
|
||||
groups.append(cur)
|
||||
return groups
|
||||
|
||||
|
||||
def trim(messages: list, rounds: int, batch: int = DEFAULT_BATCH) -> dict:
|
||||
"""
|
||||
按窗口裁历史,返回一份**报告**:
|
||||
|
||||
{
|
||||
'messages': 送进模型的那一串(裁过的,或原样),
|
||||
'kept': 保留几条,
|
||||
'dropped': 丢了几条,
|
||||
'reason': '' | 'window' | 'within_batch',
|
||||
'rounds': 总轮数, 'keptRounds': 保留几轮,
|
||||
}
|
||||
|
||||
★ 返回报告而不是只返回列表:调用方要能把这几个数**写给界面**
|
||||
("这次带了 18 轮进来"),也是探针唯一能断言的抓手。
|
||||
"""
|
||||
msgs = [m for m in (messages or []) if isinstance(m, dict)]
|
||||
total = len(msgs)
|
||||
groups = _indexed_rounds(msgs)
|
||||
|
||||
keep_all = {
|
||||
'messages': msgs, 'kept': total, 'dropped': 0, 'reason': '',
|
||||
'rounds': len(groups), 'keptRounds': len(groups),
|
||||
}
|
||||
if rounds <= 0 or len(groups) <= rounds:
|
||||
return keep_all
|
||||
|
||||
extra = len(groups) - rounds
|
||||
# ★ 成批对齐:超出量不到一批就先忍着。
|
||||
# 代价是"实际保留的比窗口多几轮",换来的是**前缀缓存能连续命中**。
|
||||
# 每轮都裁的话前缀每轮都变,缓存一次都命中不了 —— 那比多带几轮贵得多。
|
||||
if extra < batch:
|
||||
out = dict(keep_all)
|
||||
out['reason'] = 'within_batch'
|
||||
out['rounds'] = len(groups)
|
||||
return out
|
||||
|
||||
cut = (extra // batch) * batch
|
||||
kept_idx = [pair for g in groups[cut:] for pair in g]
|
||||
dropped_idx = [pair for g in groups[:cut] for pair in g]
|
||||
|
||||
# ★ 重要标记**破格永久携带**(需求 4.3):从被裁的那批里捞回来
|
||||
important = [pair for pair in dropped_idx if pair[1].get('important')]
|
||||
|
||||
merged = sorted(kept_idx + important, key=lambda p: p[0])
|
||||
out_msgs = [m for _, m in merged]
|
||||
return {
|
||||
'messages': out_msgs,
|
||||
'kept': len(out_msgs),
|
||||
'dropped': total - len(out_msgs),
|
||||
'reason': 'window',
|
||||
'rounds': len(groups),
|
||||
'keptRounds': len(groups) - cut,
|
||||
'rescued': len(important),
|
||||
}
|
||||
|
||||
|
||||
def describe(report: dict) -> str:
|
||||
"""给界面/日志的一行话(不要让它各处自己拼)"""
|
||||
r = report or {}
|
||||
total = r.get('rounds') or 0
|
||||
if not r.get('reason'):
|
||||
return f'{total} 轮全部带上'
|
||||
if r.get('reason') == 'within_batch':
|
||||
return f'{total} 轮(超出窗口但没攒够一批,先不动)'
|
||||
bits = [f'带了最近 {r.get("keptRounds")} 轮(共 {total} 轮)']
|
||||
if r.get('rescued'):
|
||||
bits.append(f'其中 {r["rescued"]} 条是你标了重要的')
|
||||
if r.get('dropped'):
|
||||
bits.append(f'另有 {r["dropped"]} 条较早的没带进来')
|
||||
return ','.join(bits)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 重要标记(需求 4.3:**只有用户能打**)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def is_important(msg: dict) -> bool:
|
||||
return bool((msg or {}).get('important'))
|
||||
|
||||
|
||||
def can_mark(role: str) -> bool:
|
||||
"""
|
||||
谁能打这个标记。**只有界面(用户)** —— AI 没有这个工具(需求原话
|
||||
"AI 有 memory_add,标记是用户主权")。
|
||||
|
||||
★ 这个函数存在的意义是"写下来":将来有人想给 AI 加个 mark_important
|
||||
工具时,会先看到这里写着为什么不行。
|
||||
"""
|
||||
return role == 'user'
|
||||
|
||||
|
||||
def strip_for_model(msg: dict) -> dict:
|
||||
"""
|
||||
把一条消息变成**送进模型的样子**:只留 role / content。
|
||||
|
||||
★★ 顺带就是"字节冻结"的落点:**永远新建一个 dict,绝不原地改** ——
|
||||
原地改(哪怕只是删掉一个 `important` 字段)会让那一条的字节变化,
|
||||
而从它往后的前缀缓存全部失效。需求 4.3 把这条写成"内核纪律"。
|
||||
"""
|
||||
m = msg or {}
|
||||
return {'role': m.get('role'), 'content': m.get('content')}
|
||||
|
||||
|
||||
__all__ = [
|
||||
'DEFAULT_ROUNDS', 'DEFAULT_BATCH', 'MIN_ROUNDS', 'MAX_ROUNDS',
|
||||
'resolve', 'split_rounds', 'trim', 'describe', 'is_important',
|
||||
'can_mark', 'strip_for_model',
|
||||
]
|
||||
@@ -175,6 +175,20 @@ DEFAULT_SETTINGS = {
|
||||
# 被裁掉的没丢,AI 还能用 memory_search 检索到("降级为仅可检索")。
|
||||
# 0 = 不限(退回全量注入)。
|
||||
'memoryWindow': 50,
|
||||
# 背景(立绘 + 背景图)**跟随当前说话者**(v1.2 §6.1,默认开)。
|
||||
#
|
||||
# ★ 群聊里才有区别:关掉时展示区一直用**主智能体**的立绘,
|
||||
# 打开时谁发言就换成谁的 —— 后者能让用户一眼看出"这句是谁说的",
|
||||
# 所以默认开。做成开关是因为**有人就是想要固定的主视觉**。
|
||||
# ★ 单聊时这个开关没有任何效果(说话者永远是同一个人),
|
||||
# 但设置项不隐藏 —— 隐藏的开关比没用的开关更让人困惑。
|
||||
'followSpeaker': True,
|
||||
# 对话上下文窗口(轮,v1.2 §4.3):每轮最多带最近多少轮对话。
|
||||
# 攒够 `contextBatch` 轮才裁一次(摊薄前缀缓存失效),见 context_window。
|
||||
'contextWindow': 20,
|
||||
'contextBatch': 5,
|
||||
# 私聊(幕后对聊)最多几轮,v1.2 §3.9。一轮 = 双方各说一次。
|
||||
'privateChatRounds': 10,
|
||||
'provider': 'ark',
|
||||
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||
'model': PROVIDER_PRESETS['ark']['defaultModel'],
|
||||
@@ -255,6 +269,21 @@ BUILTIN_SKILL = '\n'.join([
|
||||
' 情绪要跟着对话内容自然变化;别每轮都改,也别一直用同一个词。',
|
||||
'',
|
||||
'【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。',
|
||||
'',
|
||||
# ★★ 群聊的用法(用户反馈「智能体好像不怎么会用」)。
|
||||
#
|
||||
# 工具描述只讲"怎么调",而模型最容易错的是"**什么时候该用哪个**" ——
|
||||
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
|
||||
# 于是对方接到一片空白,两个人永远聊不起来。这段就是纠这个。
|
||||
'【群聊】你可能在一个群里(群里有别人)。',
|
||||
'· 想**主动对某个智能体说一句具体的话**:用 talk_to(agent=他的名字, content=你要说的话)。',
|
||||
' 那句话会真的写进对话,他下一轮看得到、会回应你 —— 这是你和别人**来回聊**的唯一办法。',
|
||||
'· **不要**拿 pass_turn 当"跟他说话":它只交发言权、不带内容,',
|
||||
' 对方接到的是一片空白,只能凭上下文猜(所以那样聊不起来)。',
|
||||
' pass_turn 只在"我没什么可说了,换你"的时候用。',
|
||||
'· 一轮最多一次:talk_to 和 pass_turn 二选一,别两个都调。',
|
||||
'· 单聊里没有"别人",talk_to 会报错 —— 想跟某个人单独聊,让用户去建群或者私聊。',
|
||||
'· 别为了"显得在忙"反复调 talk_to:一轮一次,说人话就行。',
|
||||
])
|
||||
|
||||
# system prompt 的注入模板(需求附录 C,v1.2 修订了段序)。
|
||||
|
||||
252
android/kernel/group_chat.py
Normal file
@@ -0,0 +1,252 @@
|
||||
"""群聊的发言权仲裁(需求 v1.2 §3.9)。
|
||||
|
||||
## 点名制
|
||||
|
||||
需求原话:
|
||||
|
||||
> **发言权仲裁:点名制**。被 @ 者发言;AI 可通过 `pass_turn` 指定下一位
|
||||
> 发言者,**一轮最多一次移交**;无人被点名时由主智能体(会话发起者)兜底,
|
||||
> **永不冷场**。
|
||||
|
||||
翻译成优先级(从高到低):
|
||||
|
||||
① 用户 @ 的人 用户主权,最高
|
||||
② AI 上一轮 pass_turn 的人 一轮最多一次
|
||||
③ 主智能体(participants[0])兜底,永不冷场
|
||||
|
||||
## 死亡的人不能接
|
||||
|
||||
> 死亡智能体被点名时移交无效,换下一个人接。
|
||||
|
||||
这条单独写出来,是因为"移交无效"有三种可能的处置:
|
||||
报错、随机选一个、回主智能体 —— 需求选了第三种。
|
||||
**回主智能体**也对:它会接着把话头圆下去,用户不会看到"没人应"。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
仲裁是**纯逻辑**(给一群人和几个标记,返回谁说话),没有 IO。
|
||||
放在 `app.py` 的对话循环里就没法逐条测 —— 而它的分支(点名/移交/
|
||||
兜底/死亡/不在场)有五种,正是最该测的那种。
|
||||
"""
|
||||
|
||||
#: 一轮最多移交一次。需求明文,所以做成一个常量而不是散在代码里的布尔。
|
||||
MAX_HANDOFF_PER_ROUND = 1
|
||||
|
||||
import store # noqa: E402 —— 加成员时要查世界观(只读,不参与仲裁)
|
||||
|
||||
|
||||
def member_ids(conv: dict) -> list:
|
||||
"""群聊的成员 id 列表(顺序就是加入顺序,**第 0 个是主智能体**)"""
|
||||
conv = conv or {}
|
||||
ids = conv.get('participants')
|
||||
if not isinstance(ids, list):
|
||||
return []
|
||||
return [str(x) for x in ids if str(x or '').strip()]
|
||||
|
||||
|
||||
def is_group(conv: dict) -> bool:
|
||||
return (conv or {}).get('type') == 'group'
|
||||
|
||||
|
||||
def host_id(conv: dict) -> str:
|
||||
"""
|
||||
⚠️ **不再用于"决定谁发言"** —— 用户明确要求「群聊去掉主人设定」。
|
||||
|
||||
它现在只剩一个用途:`remove_member` 里判断"不能把最后一个人踢走"。
|
||||
决定发言的那条路走 [rotate_next](轮流),不再有"老大"。
|
||||
"""
|
||||
ids = member_ids(conv)
|
||||
return ids[0] if ids else (conv or {}).get('agentId') or ''
|
||||
|
||||
|
||||
def rotate_next(conv: dict, ids: list = None) -> str:
|
||||
"""
|
||||
没人被点名时该谁说 —— **按成员顺序轮**,不设主人。
|
||||
|
||||
★★ 用户原话:「群聊去掉主人设定」。
|
||||
|
||||
原来兜底永远是"会话发起者"(成员列表第一个)——
|
||||
那等于群里有个老大:其他人不 @ 就不开口,@ 了才有台词。
|
||||
现在看**最近一条 AI 消息是谁说的**,下一个人接上,谁都不欠谁。
|
||||
|
||||
★ 找不到上一条(新群、或者老消息没有 agentId)就从第一个开始。
|
||||
"""
|
||||
ids = list(ids if ids is not None else member_ids(conv))
|
||||
if not ids:
|
||||
return ''
|
||||
last = ''
|
||||
for m in reversed((conv or {}).get('messages') or []):
|
||||
if m.get('role') != 'assistant':
|
||||
continue
|
||||
aid = str(m.get('agentId') or '')
|
||||
if aid in ids:
|
||||
last = aid
|
||||
break
|
||||
if not last:
|
||||
return ids[0]
|
||||
return ids[(ids.index(last) + 1) % len(ids)]
|
||||
|
||||
|
||||
def mention_in(text: str, names: list) -> str:
|
||||
"""
|
||||
从用户输入里找出被 @ 的人(返回 id,没有就空串)。
|
||||
|
||||
★ 按**名字**匹配而不是 id:界面上的"成员快捷条"插进去的就是 `@玄辰`
|
||||
(用户看到的是名字)。重名时取**最长的那个**匹配 ——
|
||||
有"玄辰"和"玄辰二号"时,输入 `@玄辰二号` 不该命中"玄辰"。
|
||||
"""
|
||||
t = str(text or '')
|
||||
hit = ''
|
||||
best = ''
|
||||
for aid, name in (names or []):
|
||||
n = str(name or '').strip()
|
||||
if not n or f'@{n}' not in t:
|
||||
continue
|
||||
if len(n) > len(best):
|
||||
best, hit = n, aid
|
||||
return hit
|
||||
|
||||
|
||||
def resolve(conv: dict, want: str = '', passed: str = '',
|
||||
alive: dict = None, handoffs: int = 0, forced: str = '') -> dict:
|
||||
"""
|
||||
决定这一轮谁发言。
|
||||
|
||||
[want] 用户 @ 出来的人(`mention_in` 的结果)
|
||||
[passed] AI 上一轮 `pass_turn` 指定的人
|
||||
[alive] `{agent_id: bool}`,缺省视为活着
|
||||
[handoffs] 这一轮已经移交过几次(用于"一轮最多一次")
|
||||
[forced] 界面点「让他们聊」时**指定**的发言者,优先级最高
|
||||
|
||||
返回 `{'speaker': id, 'reason': 'mention'|'handoff'|'rotate'|'handoff_denied'|'forced', 'note': ''}`。
|
||||
|
||||
★★ 为什么要有 [forced](真机反馈「还是不能互相对话」):
|
||||
下面三条路都要求**用户点名**或者**AI 自己愿意移交**。
|
||||
实测下来 AI 并不总会调 `pass_turn` —— 它更愿意自己把话说完,
|
||||
于是"两个智能体对话"这件事就永远发生不了。
|
||||
用户要的是一个**明确能按下去的入口**:点「让他们聊」,
|
||||
界面就一轮一轮地把发言权在两个人之间递过去,不需要 AI 配合。
|
||||
这是唯一能保证"一定聊得起来"的做法。
|
||||
"""
|
||||
conv = conv or {}
|
||||
alive = alive or {}
|
||||
ids = member_ids(conv)
|
||||
# ★ 兜底**不再是主人**,是轮流(用户要求「群聊去掉主人设定」)
|
||||
nxt = rotate_next(conv, ids)
|
||||
|
||||
def ok(aid: str) -> bool:
|
||||
return bool(aid) and aid in ids and alive.get(aid, True)
|
||||
|
||||
# ① 用户 @ 的人 —— **压过 forced**。
|
||||
#
|
||||
# ★★ 顺序不能反(真机反馈:「@ 的时候立即切换」「对话时没上下文」)。
|
||||
# 现场是这样的:用户点了「让他们聊」,那几轮还在跑;
|
||||
# 这时用户打了一句 `@寐眠 别` —— 界面那一轮仍然带着 `forceSpeaker`
|
||||
# (正轮到小黑),于是**小黑替寐眠答了**。
|
||||
# 用户看到的是"我明明 @ 了他,回答的却是别人",感受上就是"没上下文"。
|
||||
#
|
||||
# 用户的手是最后发言权:他一旦点名,自动对聊必须让位。
|
||||
# (界面那边也会在用户发消息时把自动对聊直接掐掉,这里是第二道。)
|
||||
if want:
|
||||
if ok(want):
|
||||
return {'speaker': want, 'reason': 'mention', 'note': ''}
|
||||
# 被 @ 的人死了或不在场:回主智能体,而不是报错
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': '被点的人不在场或已死亡,换下一个人接'}
|
||||
|
||||
# ② 界面指定的(「让他们聊」)—— 用户没点名时才轮到它
|
||||
#
|
||||
# 它只出现在界面的自动续轮里;用户手打消息时不会带上。
|
||||
if forced:
|
||||
if ok(forced):
|
||||
return {'speaker': forced, 'reason': 'forced', 'note': ''}
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': '指定的人不在场或已死亡,换下一个人接'}
|
||||
|
||||
# ③ AI 的移交(一轮最多一次)
|
||||
if passed:
|
||||
if handoffs >= MAX_HANDOFF_PER_ROUND:
|
||||
return {'speaker': nxt, 'reason': 'handoff_denied',
|
||||
'note': '这一轮已经移交过了,不再移交'}
|
||||
if ok(passed):
|
||||
return {'speaker': passed, 'reason': 'handoff', 'note': ''}
|
||||
# ★ 死亡的人被点名时**移交无效**,换下一个人接(需求明文)
|
||||
return {'speaker': nxt, 'reason': 'rotate',
|
||||
'note': f'「{passed}」已死亡或不在场,移交无效,换下一个人接'}
|
||||
|
||||
# ③ 兜底:永不冷场
|
||||
return {'speaker': nxt, 'reason': 'rotate', 'note': ''}
|
||||
|
||||
|
||||
def add_member(conv: dict, agent_id: str) -> bool:
|
||||
"""
|
||||
加一个成员(用户手动增删基本无条件 —— 用户主权)。
|
||||
|
||||
★ 加完**自动升级成 group**:成员超过一个时 `type` 必须是 `group`,
|
||||
不然成员列表里有人、仲裁逻辑还按单聊跑 ——
|
||||
表现是"我把人拉进来了,但他从来不说话"。
|
||||
这条收在这里而不是让调用方自己补,是因为"忘记补"的代价不对称:
|
||||
补错了只是类型不对,忘补了就是功能整个不生效。
|
||||
|
||||
★ 单聊要拉人 → 那个会话**就地转成群聊**,而不是偷偷往
|
||||
`participants` 里塞一个 id 却把 `type` 留着。
|
||||
|
||||
★★ **只能拉同世界观的**(用户确认过这条规则)。
|
||||
理由不是洁癖:群聊的上下文里有 `<worldview>` 段,视野不同的两个人
|
||||
看到的是两套设定 —— 同一个群里会出现"这是哪、我们是谁"对不上的情况,
|
||||
而且记忆空间也是按世界观分的(共享记忆会串)。
|
||||
判定以**群主**(`agentId`)的世界观为准;空对空(都没绑)也算同。
|
||||
"""
|
||||
c = conv or {}
|
||||
aid = str(agent_id or '').strip()
|
||||
if not aid:
|
||||
return False
|
||||
ids = member_ids(c)
|
||||
if aid in ids:
|
||||
return False
|
||||
|
||||
# ★ 世界观一致才让进
|
||||
target = store.get_agent(aid) or {}
|
||||
if target:
|
||||
mine = (store.get_agent(str(c.get('agentId') or '')) or {}).get('worldviewId') or ''
|
||||
if (target.get('worldviewId') or '') != mine:
|
||||
return False
|
||||
|
||||
ids.append(aid)
|
||||
c['participants'] = ids
|
||||
if len(ids) > 1 and (c.get('type') or 'single') != 'group':
|
||||
c['type'] = 'group'
|
||||
return True
|
||||
|
||||
|
||||
def remove_member(conv: dict, agent_id: str) -> bool:
|
||||
"""
|
||||
移出一个成员。**主智能体不能被移出**(需求说发言权兜底靠它 ——
|
||||
移掉的话这个群聊就没有兜底了,会冷场)。
|
||||
"""
|
||||
c = conv or {}
|
||||
aid = str(agent_id or '').strip()
|
||||
ids = member_ids(c)
|
||||
if aid not in ids or aid == host_id(c):
|
||||
return False
|
||||
ids.remove(aid)
|
||||
c['participants'] = ids
|
||||
return True
|
||||
|
||||
|
||||
def promote(conv: dict, agent_id: str) -> None:
|
||||
"""把单聊转成群聊(拉第二个人进来时用)"""
|
||||
c = conv or {}
|
||||
if c.get('type') != 'group':
|
||||
first = (c.get('agentId') or '').strip()
|
||||
c['type'] = 'group'
|
||||
c['participants'] = [x for x in [first] if x]
|
||||
add_member(c, agent_id)
|
||||
|
||||
|
||||
def describe(conv: dict) -> str:
|
||||
"""给界面/日志的一行话(不要各处自己拼)"""
|
||||
c = conv or {}
|
||||
n = len(member_ids(c))
|
||||
kind = {'group': '群聊', 'private': '私聊记录'}.get(c.get('type') or '', '单聊')
|
||||
return f'{kind}({n} 人)' if n > 1 else kind
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
运行期路径与平台判断。
|
||||
|
||||
为什么单独一个模块:
|
||||
@@ -95,6 +95,12 @@ class Paths:
|
||||
self.worldviews_file = os.path.join(self.data_dir, 'worldviews.json')
|
||||
self.models_file = os.path.join(self.data_dir, 'models.json')
|
||||
self.skills_file = os.path.join(self.data_dir, 'skills.json')
|
||||
# 数值状态包(需求附录 D):定义 + 对应的 Python 脚本源码。
|
||||
# 量级小、而且用户会想看自己写了什么 → 还是 JSON
|
||||
self.rulepacks_file = os.path.join(self.data_dir, 'rulepacks.json')
|
||||
# 规则脚本**落盘**的位置:脚本要作为文件被 exec 起来,
|
||||
# 所以从包里解出来之后得写到磁盘上(不能只存在 JSON 里)
|
||||
self.rule_scripts_dir = os.path.join(self.data_dir, 'rule-scripts')
|
||||
# 智能体系统的 SQLite(记忆 / 情绪 / Token / 绑定关系)
|
||||
self.agent_db_file = os.path.join(self.data_dir, 'agent.db')
|
||||
# 智能体包解出来的图片等资源(导入 zip 时落到这儿)
|
||||
@@ -116,7 +122,7 @@ class Paths:
|
||||
|
||||
def ensure_dirs(self) -> None:
|
||||
for folder in (self.data_dir, self.uploads_dir, self.tmp_dir, self.screens_dir,
|
||||
self.notes_dir, self.agent_assets_dir):
|
||||
self.notes_dir, self.agent_assets_dir, self.rule_scripts_dir):
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死
|
||||
|
||||
249
android/kernel/private_chat.py
Normal file
@@ -0,0 +1,249 @@
|
||||
"""私聊:两个智能体在后台自主对聊(需求 v1.2 §3.9 形态 B)。
|
||||
|
||||
## 需求原文
|
||||
|
||||
> **形态 B · 私聊(幕后制)**:两个智能体在后台自主对聊,用户不在场。
|
||||
>
|
||||
> - **安全网**:默认最多 10 轮交替发言(可配),到顶强制收尾;
|
||||
> 一方 Token 触顶则另一方单方面收尾后立即结束,**不撑独角戏**。
|
||||
> - 结束后生成摘要写入共享记忆(复用总结管线),完整记录可翻看。
|
||||
> - Token 消耗按各自发言分别计入各智能体统计、分别受各自限额约束。
|
||||
|
||||
## 三个必须想清楚的点
|
||||
|
||||
**① "安全网"防的是什么**
|
||||
|
||||
两个 AI 互相对话最大的风险是**停不下来**:A 说一句、B 接一句、A 再
|
||||
接回来……它们没有"该结束了"的内在信号(用户不在场,没人喊停)。
|
||||
所以轮数上限不是优化,是**防失控**。
|
||||
|
||||
**② "不撑独角戏"**
|
||||
|
||||
一方 Token 触顶时,**不能**让另一方继续自言自语。
|
||||
需求的做法是:另一方**单方面收尾**(说一句告别/结语)然后立刻结束。
|
||||
独白读起来很怪,而且白花钱。
|
||||
|
||||
**③ 每轮的"用户"是谁**
|
||||
|
||||
对 A 来说,B 说的话就是**用户消息**;对 B 来说反过来。
|
||||
这是私聊能跑起来的关键 —— 两个 AI 都在"跟对方聊天",
|
||||
而不是"在同一个上下文里各写各的"。
|
||||
"""
|
||||
|
||||
import agent_loop
|
||||
import agentdb
|
||||
import store
|
||||
|
||||
#: 默认最多几轮(**一轮 = A 说一次 + B 说一次**)。需求定的 10。
|
||||
DEFAULT_MAX_ROUNDS = 10
|
||||
|
||||
#: 上限的硬顶:用户可以在设置里调,但不该调到能刷爆账单的规模。
|
||||
#: 一轮两次 LLM 调用,100 轮就是 200 次 —— 那不是"聊天",是失控。
|
||||
MAX_ROUNDS_CAP = 60
|
||||
|
||||
|
||||
def resolve_rounds(settings: dict, body: dict = None) -> int:
|
||||
"""
|
||||
这次私聊最多几轮:**调用方指定 > 全局设置 > 默认**,并且夹在硬顶内。
|
||||
|
||||
★ 需求说"默认最多 10 轮(**可配**)"—— 可配的入口是
|
||||
`settings.privateChatRounds`,不是每次调用随便传(那样界面就没法
|
||||
给用户一个稳定的默认值了)。[body] 只给"这一次特殊"用。
|
||||
"""
|
||||
for src in ((body or {}).get('maxRounds'), (settings or {}).get('privateChatRounds')):
|
||||
try:
|
||||
v = int(float(src))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if v > 0:
|
||||
return max(1, min(MAX_ROUNDS_CAP, v))
|
||||
return DEFAULT_MAX_ROUNDS
|
||||
|
||||
|
||||
def _used(agent: dict) -> int:
|
||||
u = agentdb.token_usage((agent or {}).get('id') or '')
|
||||
return int(u['total']['input']) + int(u['total']['output'])
|
||||
|
||||
|
||||
def limit_hit(agent: dict) -> bool:
|
||||
"""
|
||||
这个智能体的额度用完了吗(0 = 无限制)。
|
||||
|
||||
★ 和 `/api/chat` 那道检查**同一个判据**:用掉的总量 >= 上限。
|
||||
两处不一致的话,会出现"私聊里还能说、回到对话里被拦"这种精神分裂。
|
||||
"""
|
||||
agent = agent or {}
|
||||
try:
|
||||
limit = int(float(agent.get('tokenLimit') or 0))
|
||||
except (TypeError, ValueError):
|
||||
limit = 0
|
||||
return limit > 0 and _used(agent) >= limit
|
||||
|
||||
|
||||
def _history_for(speaker_id: str, turns: list) -> list:
|
||||
"""
|
||||
把"到目前为止的对话"翻译成**这个说话者视角**的消息列表。
|
||||
|
||||
对方说的 → `user`(它在跟我说话)
|
||||
我说的 → `assistant`(我说的)
|
||||
|
||||
★ 这是私聊能跑起来的关键:两个 AI 各自都是"在跟对方聊天",
|
||||
而不是"在同一个上下文里各写各的"。
|
||||
"""
|
||||
out = []
|
||||
for t in turns:
|
||||
if not t.get('content'):
|
||||
continue
|
||||
mine = t.get('agentId') == speaker_id
|
||||
out.append({'role': 'assistant' if mine else 'user', 'content': t['content']})
|
||||
return out
|
||||
|
||||
|
||||
def run_pair(settings: dict, first: dict, second: dict, max_rounds: int = 0,
|
||||
opener: str = '', emit=None) -> dict:
|
||||
"""
|
||||
让两个智能体在后台对聊。
|
||||
|
||||
[first] 先开口的那个(也是这个会话的"主")
|
||||
[opener] 给先开口者的由头(比如"用户把你俩拉到了一起")。
|
||||
|
||||
返回:
|
||||
{
|
||||
'ok': True,
|
||||
'conversationId': ...,
|
||||
'turns': [{'agentId','name','content'}],
|
||||
'rounds': 实际说了几轮,
|
||||
'endReason': 'rounds' | 'limit' | 'error',
|
||||
'endedBy': 谁触顶了(endReason=limit 时),
|
||||
'summary': 摘要(有的话),
|
||||
}
|
||||
"""
|
||||
settings = settings or {}
|
||||
first, second = first or {}, second or {}
|
||||
if not (first.get('id') and second.get('id')):
|
||||
return {'ok': False, 'error': '需要两个智能体'}
|
||||
rounds_cap = max_rounds or resolve_rounds(settings)
|
||||
say = emit or (lambda ev: None)
|
||||
|
||||
conv = store.create_conversation(
|
||||
title=f'{(first.get("name") or "?")} 与 {(second.get("name") or "?")} 的私聊',
|
||||
agent_id=first.get('id') or '',
|
||||
# ★ `private` 是独立类型:它出现在**两个参与者的**会话列表里,
|
||||
# 而界面上只读翻看(用户不在场,不该能插话)
|
||||
kind='private',
|
||||
participants=[first.get('id') or '', second.get('id') or ''],
|
||||
)
|
||||
cid = conv['id']
|
||||
turns = []
|
||||
end_reason = 'rounds'
|
||||
ended_by = ''
|
||||
|
||||
def _record(speaker: dict, text: str) -> None:
|
||||
turns.append({'agentId': speaker.get('id') or '',
|
||||
'name': speaker.get('name') or '', 'content': text})
|
||||
store.append_messages(cid, [{
|
||||
'role': 'assistant',
|
||||
'content': text,
|
||||
'agentId': speaker.get('id') or '',
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
|
||||
for i in range(rounds_cap):
|
||||
for who in (first, second):
|
||||
if limit_hit(who):
|
||||
# ★★ 一方触顶 → 另一方**单方面收尾**后立即结束(需求明文)。
|
||||
# 不收尾直接断的话,对话会停在一句没头没尾的话上;
|
||||
# 让另一个人继续说的话,就成了"独角戏"(需求明确说不要)。
|
||||
other = second if who.get('id') == first.get('id') else first
|
||||
if not limit_hit(other):
|
||||
try:
|
||||
_closing = _speak(settings, other, turns, cid, rounds_cap, i,
|
||||
hint='对方的额度用完了,这次对话到此为止 —— '
|
||||
'你说一句收尾的话,不要再问问题。')
|
||||
if _closing:
|
||||
_record(other, _closing)
|
||||
except Exception as exc: # noqa: BLE001 - 收尾失败也要结束
|
||||
say({'type': 'private_error', 'message': str(exc)})
|
||||
end_reason, ended_by = 'limit', who.get('name') or ''
|
||||
break
|
||||
if not turns and who.get('id') == first.get('id'):
|
||||
# 给先开口者一个由头(不然它不知道"跟谁、为什么")
|
||||
turns_seed = opener or f'你和「{second.get("name") or "对方"}」被单独留在了一间屋子里。'
|
||||
else:
|
||||
turns_seed = ''
|
||||
try:
|
||||
text = _speak(settings, who, turns, cid, rounds_cap, i, hint=turns_seed)
|
||||
except Exception as exc: # noqa: BLE001 - 一次生成失败不该让整场私聊崩
|
||||
say({'type': 'private_error', 'message': str(exc)})
|
||||
end_reason = 'error'
|
||||
break
|
||||
if not text:
|
||||
# 模型返回空 —— 当作"它不想说了",正常收尾而不是报错
|
||||
end_reason = 'rounds'
|
||||
break
|
||||
_record(who, text)
|
||||
say({'type': 'private_turn', 'agentId': who.get('id') or '',
|
||||
'name': who.get('name') or '', 'content': text})
|
||||
if end_reason in ('limit', 'error'):
|
||||
break
|
||||
|
||||
out = {
|
||||
'ok': True, 'conversationId': cid, 'turns': turns,
|
||||
'rounds': len(turns), 'endReason': end_reason, 'endedBy': ended_by,
|
||||
}
|
||||
# ★ 结束后生成摘要写入共享记忆(需求:复用总结管线)
|
||||
try:
|
||||
summary = summarize_to_memory(first, second, turns)
|
||||
if summary:
|
||||
out['summary'] = summary
|
||||
except Exception as exc: # noqa: BLE001 - 摘要失败不影响"私聊已经结束"这件事
|
||||
say({'type': 'private_error', 'message': f'摘要失败:{exc}'})
|
||||
store.update_conversation(cid, {'title': conv['title']})
|
||||
return out
|
||||
|
||||
|
||||
def _speak(settings: dict, speaker: dict, turns: list, cid: str,
|
||||
cap: int, round_index: int, hint: str = '') -> str:
|
||||
"""让一个智能体说一句。返回正文(空串 = 它没说话)"""
|
||||
history = _history_for(speaker.get('id') or '', turns)
|
||||
if hint:
|
||||
history = history + [{'role': 'user', 'content': hint}]
|
||||
if not history:
|
||||
history = [{'role': 'user', 'content': '开始吧。'}]
|
||||
result = agent_loop.run_agent(
|
||||
settings=settings,
|
||||
messages=history,
|
||||
agent=speaker,
|
||||
emit=lambda ev: None,
|
||||
conversation_id=cid,
|
||||
# ★ 私聊是**幕后**行为,不能再往里递归拉起别的对话 ——
|
||||
# 加一层深度限制,免得 A 拉 B、B 拉 C 无限套下去
|
||||
send_depth=1,
|
||||
)
|
||||
return str((result or {}).get('content') or '').strip()
|
||||
|
||||
|
||||
def summarize_to_memory(first: dict, second: dict, turns: list) -> str:
|
||||
"""
|
||||
把这场私聊的摘要写进**共享记忆**(需求:复用总结管线)。
|
||||
|
||||
★ 写到哪:两人的**共享空间**(同世界观 → `world:<id>`),
|
||||
这样以后两人聊天时都"记得"这次私聊发生过。
|
||||
没有共同世界观的话**不写** —— 硬塞进某一个人的私有空间,
|
||||
等于替他记了一件他没参与的事。
|
||||
"""
|
||||
if not turns:
|
||||
return ''
|
||||
a, b = first or {}, second or {}
|
||||
wid = (a.get('worldviewId') or '').strip()
|
||||
if not wid or wid != (b.get('worldviewId') or '').strip():
|
||||
return ''
|
||||
body = '\n'.join(f'{(t.get("name") or "?")}:{t.get("content") or ""}' for t in turns)
|
||||
# 摘要是**规则化**的,不再花一次 LLM 调用 —— 私聊本身已经烧了
|
||||
# 2×N 次调用了,为了压两句话再烧一次不划算(需求说的"复用总结管线"
|
||||
# 指的是同一套**写入记忆**的通道,不是非要再调一次模型)
|
||||
title = f'和{(b.get("name") or "对方")}的一次私下交谈'
|
||||
content = f'({len(turns)} 句)' + body[:400]
|
||||
return agentdb.memory_add(
|
||||
agentdb.world_scope(wid), title, content, author_agent=a.get('id') or '',
|
||||
) and title
|
||||
694
android/kernel/rule_engine.py
Normal file
@@ -0,0 +1,694 @@
|
||||
"""规则引擎:数值系统 + 状态系统(需求 v1.2 §3.10 / §3.11)。
|
||||
|
||||
## 一句话分工
|
||||
|
||||
· **定义**在「数值状态包」里(独立资源,可被多个世界观引用)
|
||||
· **值**按 scope 存(`shared` 决定是每个智能体一份还是全世界观一份)
|
||||
· **注入**走 `<stats>` / `<status>` 两个段(附录 C,排在提示词最后)
|
||||
· **操作**只有 `change_stat`(只申请增量,不许写绝对值)
|
||||
|
||||
## 为什么"只申请增量"这条不能通融
|
||||
|
||||
需求 §3.10 原话:`change_stat(name, delta)` —— 只申请增量,内核流程固定:
|
||||
|
||||
脚本裁决(如有)→ clamp 到 [min,max] → 写库 → 下一轮注入反映新值
|
||||
|
||||
如果允许 AI 写绝对值,那"脚本裁决"就没意义了 —— 修正器要的是
|
||||
"你想加 5 点,我判成加 10 点",而不是"你想设成 100,我判……多少"。
|
||||
而且并发时(群聊里两个智能体同时改同一个 shared 数值)
|
||||
绝对值会互相覆盖,增量不会。
|
||||
|
||||
## 值的 scope
|
||||
|
||||
和记忆**故意用同一套写法**:
|
||||
|
||||
shared=0 → "agent:<uuid>" 好感度各算各的
|
||||
shared=1 → "world:<uuid>" 灵气浓度全世界观一份
|
||||
|
||||
好处是"绑定/解绑世界观只换读写空间、值不迁移"这条自动成立 ——
|
||||
和记忆的行为一致,用户不用学两套心智模型。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import rule_sandbox
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 定义:从规则包同步进来
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 规则包里数值定义的合法字段(多出来的忽略,不报错 —— 兼容将来扩展)
|
||||
_STAT_KEYS = ('name', 'min', 'max', 'shared', 'ranges', 'script')
|
||||
_STATUS_KEYS = ('name', 'kind', 'turns', 'max_stack', 'script')
|
||||
|
||||
|
||||
def _num(v, default=0.0):
|
||||
try:
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def sync_defs(pack_id: str, info: dict = None) -> dict:
|
||||
"""
|
||||
把一个规则包的 `info.json` 同步进库(**幂等**,重复导入只覆盖定义)。
|
||||
|
||||
★ 只同步**定义**,不动**值**(需求附录 D:"数值的**定义**进包,
|
||||
**当前值**不进包 —— 经历与人设分离,同记忆")。
|
||||
所以重新导入一个包不会把你的好感度清零。
|
||||
|
||||
★ [info] 不传时**从 store 里那个包读**。这是默认路径 ——
|
||||
定义只应该有一处源头(包里的 `info.json`),SQLite 里那两张表是
|
||||
**派生**出来的。两处都能写的话,迟早会出现
|
||||
"包里改了、库里还是旧的",而那种不一致极难查。
|
||||
|
||||
返回 `{'stats': n, 'statuses': m}`。
|
||||
"""
|
||||
if info is None:
|
||||
pack = store.get_resource('rulepacks', pack_id or '') or {}
|
||||
info = pack.get('info') if isinstance(pack.get('info'), dict) else {}
|
||||
info = info or {}
|
||||
sid = (pack_id or '').strip()
|
||||
if not sid:
|
||||
return {'stats': 0, 'statuses': 0}
|
||||
# ★★ 空定义**不动库**。
|
||||
#
|
||||
# "读不到这个包"(id 不对、包刚被删)和"用户真要把定义清空"在这一层
|
||||
# 分不清,而**清空定义是不可逆的**:值还在 `stat_values` 里,
|
||||
# 定义没了它们就成了永远读不到的孤儿。
|
||||
# 真要清空,把那个包删掉就行 —— 那是个明确得多的动作。
|
||||
if not info.get('stats') and not info.get('statuses'):
|
||||
return {'stats': 0, 'statuses': 0}
|
||||
agentdb.init() # ★ 别忘了:这几张表是 v1.2 才加的,惰性建表
|
||||
conn = agentdb._connect()
|
||||
stats = info.get('stats') if isinstance(info.get('stats'), list) else []
|
||||
statuses = info.get('statuses') if isinstance(info.get('statuses'), list) else []
|
||||
|
||||
# 定义表整体替换这个包的(不然删掉的数值会一直留着)
|
||||
conn.execute('DELETE FROM stat_defs WHERE pack_id = ?', (sid,))
|
||||
conn.execute('DELETE FROM status_defs WHERE pack_id = ?', (sid,))
|
||||
|
||||
# ★ 数**实际入库的**,不是输入数组的长度:"你导入了 3 条"和
|
||||
# "3 条里有 1 条没名字被跳过"是两回事,界面拿这个数报给用户。
|
||||
n_stats = 0
|
||||
for i, s in enumerate(stats):
|
||||
s = s or {}
|
||||
name = str(s.get('name') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
lo, hi = _num(s.get('min'), 0.0), _num(s.get('max'), 100.0)
|
||||
if hi <= lo:
|
||||
hi = lo + 1
|
||||
ranges = s.get('ranges') if isinstance(s.get('ranges'), list) else []
|
||||
conn.execute(
|
||||
'INSERT INTO stat_defs (pack_id, name, min_value, max_value, shared, ranges, script, ord) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
(sid, name, lo, hi, 1 if s.get('shared') else 0,
|
||||
json.dumps(ranges, ensure_ascii=False), str(s.get('script') or ''), i),
|
||||
)
|
||||
n_stats += 1
|
||||
|
||||
n_status = 0
|
||||
for s in statuses:
|
||||
s = s or {}
|
||||
name = str(s.get('name') or '').strip()
|
||||
if not name:
|
||||
continue
|
||||
kind = 'persistent' if str(s.get('type') or s.get('kind') or '').lower() == 'persistent' else 'timed'
|
||||
conn.execute(
|
||||
'INSERT INTO status_defs (pack_id, name, kind, turns, max_stack, script) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(sid, name, kind, max(1, int(_num(s.get('turns'), 1))),
|
||||
max(1, int(_num(s.get('max_stack'), 1))), str(s.get('script') or '')),
|
||||
)
|
||||
n_status += 1
|
||||
conn.commit()
|
||||
return {'stats': n_stats, 'statuses': n_status}
|
||||
|
||||
|
||||
def stat_defs(pack_id: str) -> list:
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM stat_defs WHERE pack_id = ? ORDER BY ord ASC, name ASC', (pack_id or '',),
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
try:
|
||||
ranges = json.loads(r['ranges'] or '[]')
|
||||
except (TypeError, ValueError):
|
||||
ranges = []
|
||||
out.append({
|
||||
'name': r['name'], 'min': float(r['min_value']), 'max': float(r['max_value']),
|
||||
'shared': bool(r['shared']), 'ranges': ranges if isinstance(ranges, list) else [],
|
||||
'script': r['script'] or '',
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def status_defs(pack_id: str) -> list:
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM status_defs WHERE pack_id = ? ORDER BY name ASC', (pack_id or '',),
|
||||
).fetchall()
|
||||
return [
|
||||
{'name': r['name'], 'kind': r['kind'] or 'timed', 'turns': int(r['turns'] or 1),
|
||||
'max_stack': int(r['max_stack'] or 1), 'script': r['script'] or ''}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 值:按 scope 读写
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def scope_for(agent: dict, definition: dict) -> str:
|
||||
"""
|
||||
一条数值存在哪个空间(`shared` 决定)。
|
||||
|
||||
★ 和记忆用同一套 scope 写法(`agentdb.scope_of` / `world_scope`)——
|
||||
这样"解绑世界观值留在原地"和记忆的行为一致,用户不用学两套。
|
||||
"""
|
||||
agent = agent or {}
|
||||
if (definition or {}).get('shared'):
|
||||
wid = (agent.get('worldviewId') or '').strip()
|
||||
# 没绑世界观却要读"全世界观共享"的值:退回私有空间。
|
||||
# 不报错是因为"刚解绑"是个正常状态,值还在那儿等着再绑回来。
|
||||
return agentdb.world_scope(wid) if wid else agentdb.agent_scope(agent.get('id') or '')
|
||||
return agentdb.agent_scope(agent.get('id') or '')
|
||||
|
||||
|
||||
def value_of(agent: dict, definition: dict) -> float:
|
||||
"""
|
||||
读一条数值的当前值。没写过就取**定义里的初始值** ——
|
||||
用 min 还是 max?
|
||||
|
||||
★ 取 `min`。因为在"好感度 0~100"这种语义里 min 是中性起点;
|
||||
取 max 的话新角色一上来就满好感,明显不对。
|
||||
真想要别的起点,包作者把 min 设成他要的值就行。
|
||||
"""
|
||||
scope = scope_for(agent, definition)
|
||||
agentdb.init()
|
||||
row = agentdb._connect().execute(
|
||||
'SELECT value FROM stat_values WHERE scope = ? AND name = ?',
|
||||
(scope, (definition or {}).get('name') or ''),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return _num((definition or {}).get('min'), 0.0)
|
||||
return float(row['value'])
|
||||
|
||||
|
||||
def set_value(agent: dict, definition: dict, value: float) -> float:
|
||||
"""直接写值(**只给内核用**:脚本裁决和 clamp 之后的落库走这里)"""
|
||||
scope = scope_for(agent, definition)
|
||||
v = _num(value)
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute(
|
||||
'INSERT INTO stat_values (scope, name, value) VALUES (?, ?, ?) '
|
||||
'ON CONFLICT(scope, name) DO UPDATE SET value = excluded.value',
|
||||
(scope, (definition or {}).get('name') or '', v),
|
||||
)
|
||||
conn.commit()
|
||||
return v
|
||||
|
||||
|
||||
def clamp(definition: dict, value: float) -> float:
|
||||
d = definition or {}
|
||||
return max(_num(d.get('min'), 0.0), min(_num(d.get('max'), 100.0), _num(value)))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 区间表:命中哪段注入哪段(需求 §3.10 "声明式区间表")
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def range_text(definition: dict, value: float) -> str:
|
||||
"""
|
||||
命中区间的 text(没命中任何区间就返回空串 = 裸值)。
|
||||
|
||||
★ 区间是**左闭右开** `[min, max)`,除了最后一段是闭的。
|
||||
半开区间是刻意的:0~20 和 20~40 两段,20 该算后一段 ——
|
||||
如果两边都闭,20 会同时命中两段,取哪段就成了未定义行为。
|
||||
"""
|
||||
ranges = (definition or {}).get('ranges')
|
||||
if not isinstance(ranges, list):
|
||||
return ''
|
||||
v = _num(value)
|
||||
total = len(ranges)
|
||||
for i, r in enumerate(ranges):
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
lo = _num(r.get('min'))
|
||||
hi = _num(r.get('max'), lo)
|
||||
last = i == total - 1
|
||||
if (lo <= v < hi) or (last and lo <= v <= hi):
|
||||
return str(r.get('text') or '').strip()
|
||||
return ''
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 注入:<stats> / <status>
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 上一轮的变化量(渲染 `450→500` 那个箭头用)。
|
||||
#:
|
||||
#: ★ 放内存、不放库:需求说箭头"**仅保留一轮**",用完就该没了。
|
||||
#: 放库还要额外写一次清理逻辑,而进程重启丢掉它也无所谓 ——
|
||||
#: 箭头只是个提示,不是数据。
|
||||
_pending_delta = {}
|
||||
|
||||
|
||||
def note_delta(scope: str, name: str, delta: float) -> None:
|
||||
"""记下这次变化了多少,下一轮渲染时显示成箭头"""
|
||||
if delta:
|
||||
_pending_delta[(scope, name)] = float(delta)
|
||||
|
||||
|
||||
def take_delta(scope: str, name: str) -> float:
|
||||
"""取出并**清掉**(所以只显示一轮)"""
|
||||
return _pending_delta.pop((scope, name), 0.0)
|
||||
|
||||
|
||||
def stats_section(agent: dict, pack_id: str) -> str:
|
||||
"""
|
||||
渲染 `<stats>` 段(附录 C 的格式):
|
||||
|
||||
[世界·九州] 声望: 450→500/1000 —— 名震九州:世人皆知你之名
|
||||
[自身] 好感度: 45/100 —— 友善:你对用户态度友善,但保持分寸
|
||||
|
||||
来源前缀(`[世界·xx]` / `[自身]`)+ 当前值 + 变化箭头(仅一轮)+
|
||||
命中区间文本(未命中就是裸值)。
|
||||
"""
|
||||
defs = stat_defs(pack_id)
|
||||
if not defs:
|
||||
return ''
|
||||
agent = agent or {}
|
||||
wname = ''
|
||||
wid = (agent.get('worldviewId') or '').strip()
|
||||
if wid:
|
||||
wname = ((store.get_resource('worldviews', wid) or {}).get('name') or '').strip()
|
||||
|
||||
lines = []
|
||||
for d in defs:
|
||||
scope = scope_for(agent, d)
|
||||
v = value_of(agent, d)
|
||||
delta = take_delta(scope, d['name'])
|
||||
src = f'[世界·{wname}]' if d.get('shared') and wname else '[自身]'
|
||||
# 值那一段:有变化时显示 `旧→新`
|
||||
if delta:
|
||||
old = clamp(d, v - delta)
|
||||
val = f'{_fmt(old)}→{_fmt(v)}/{_fmt(d["max"])}'
|
||||
else:
|
||||
val = f'{_fmt(v)}/{_fmt(d["max"])}'
|
||||
text = range_text(d, v)
|
||||
lines.append(f'{src} {d["name"]}: {val}' + (f' —— {text}' if text else ''))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def _fmt(v: float) -> str:
|
||||
"""数值显示:整数就不带小数点(45.0 → 45),免得看着别扭"""
|
||||
f = float(v)
|
||||
return str(int(f)) if f == int(f) else f'{f:g}'
|
||||
|
||||
|
||||
def status_section(agent: dict) -> str:
|
||||
"""
|
||||
渲染 `<status>` 段(附录 C 的格式):
|
||||
|
||||
中毒(剩 3 轮):你感到眩晕,言语变得迟缓
|
||||
|
||||
状态名(剩余轮数)+ 状态提示词(脚本可改写)。
|
||||
持久状态不显示轮数(它不过期)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
rows = list_statuses(agent.get('id') or '')
|
||||
if not rows:
|
||||
return ''
|
||||
lines = []
|
||||
for r in rows:
|
||||
head = r['name']
|
||||
if r.get('kind') != 'persistent' and r.get('remaining', 0) > 0:
|
||||
head += f'(剩 {r["remaining"]} 轮)'
|
||||
if r.get('stacks', 1) > 1:
|
||||
head += f'×{r["stacks"]}'
|
||||
hint = (r.get('hint') or '').strip()
|
||||
lines.append(head + (f':{hint}' if hint else ''))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 状态实例
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def list_statuses(agent_id: str) -> list:
|
||||
"""这个智能体身上生效中的状态(带定义里的 kind)"""
|
||||
agentdb.init()
|
||||
rows = agentdb._connect().execute(
|
||||
'SELECT * FROM status_instances WHERE agent_id = ? ORDER BY granted_at ASC, name ASC',
|
||||
(agent_id or '',),
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
out.append({
|
||||
'name': r['name'], 'remaining': int(r['remaining'] or 0),
|
||||
'stacks': int(r['stacks'] or 1), 'hint': r['hint'] or '',
|
||||
'grantedAt': r['granted_at'] or '', 'kind': _kind_of(r['name']),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _kind_of(name: str) -> str:
|
||||
"""查一个状态名是持久还是定时(实例表里不存 kind —— 那是定义的事)"""
|
||||
agentdb.init()
|
||||
row = agentdb._connect().execute(
|
||||
'SELECT kind FROM status_defs WHERE name = ? LIMIT 1', (name or '',),
|
||||
).fetchone()
|
||||
return (row['kind'] if row else 'timed') or 'timed'
|
||||
|
||||
|
||||
def put_status(agent_id: str, name: str, remaining: int, stacks: int, hint: str) -> None:
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute(
|
||||
'INSERT INTO status_instances (agent_id, name, remaining, stacks, hint, granted_at) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?) '
|
||||
'ON CONFLICT(agent_id, name) DO UPDATE SET remaining = excluded.remaining, '
|
||||
'stacks = excluded.stacks, hint = excluded.hint',
|
||||
(agent_id or '', name or '', int(remaining), int(stacks), hint or '', agentdb.now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def drop_status(agent_id: str, name: str) -> None:
|
||||
agentdb.init()
|
||||
conn = agentdb._connect()
|
||||
conn.execute('DELETE FROM status_instances WHERE agent_id = ? AND name = ?',
|
||||
(agent_id or '', name or ''))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def tick_statuses(agent_id: str) -> list:
|
||||
"""
|
||||
"该智能体每参与一轮后减 1"(需求 §3.11)。
|
||||
|
||||
返回 `[{'name':…, 'expired':True/False}]` —— 调用方据此播报
|
||||
"中毒已经消退了"这类消息。
|
||||
|
||||
★ persistent 的是 `remaining = -1`,不参与递减(它不过期)。
|
||||
"""
|
||||
out = []
|
||||
for r in list_statuses(agent_id):
|
||||
if r.get('kind') == 'persistent':
|
||||
continue
|
||||
left = int(r.get('remaining') or 0) - 1
|
||||
if left <= 0:
|
||||
drop_status(agent_id, r['name'])
|
||||
out.append({'name': r['name'], 'expired': True})
|
||||
else:
|
||||
put_status(agent_id, r['name'], left, r.get('stacks') or 1, r.get('hint') or '')
|
||||
out.append({'name': r['name'], 'expired': False, 'remaining': left})
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 脚本执行(需求 §3.10 数值裁决 / §3.11 状态脚本)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# 三个入口(需求附录 E 的签名):
|
||||
#
|
||||
# on_stat_change(name, value, delta) -> 生效增量(可放大/缩小/归零否决)
|
||||
# on_turn(self_agent, stats_api) 每轮执行(状态脚本)
|
||||
# on_grant(status_name, source_agent) -> bool(赋予判定,跑在**目标方**)
|
||||
#
|
||||
# 全部走 rule_sandbox 的受限沙箱 + 硬超时。
|
||||
#
|
||||
# ★★ 异常 = 本次操作**归零** + UI 提示,**不中断对话**(需求附录 E)。
|
||||
# 规则脚本是用户自己写的,写错了是常态;一次脚本错误把整轮对话搞崩,
|
||||
# 用户会以为整个 App 坏了 —— 而其实只是他那行 `1/0` 写错了。
|
||||
|
||||
|
||||
def _timeout_s() -> float:
|
||||
import timeouts
|
||||
|
||||
return float(timeouts.get('customNode') or 10)
|
||||
|
||||
|
||||
def script_source(pack_id: str, filename: str) -> str:
|
||||
"""从规则包里取一段脚本源码(空串 = 这个包没带这段脚本)"""
|
||||
if not (filename or '').strip():
|
||||
return ''
|
||||
pack = store.get_resource('rulepacks', pack_id or '') or {}
|
||||
scripts = pack.get('scripts')
|
||||
if not isinstance(scripts, dict):
|
||||
return ''
|
||||
return str(scripts.get(filename) or '')
|
||||
|
||||
|
||||
def run_script(source: str, entry: str, *args) -> tuple:
|
||||
"""
|
||||
跑一段规则脚本,返回 `(结果, 错误说明)`。
|
||||
|
||||
★ **不抛异常**:需求说异常要"归零 + 提示、不中断对话",
|
||||
所以错误在这里就被接住、转成一段人话,由调用方决定怎么显示。
|
||||
抛出去的话,一次脚本报错会顺着调用栈炸到对话主循环。
|
||||
|
||||
★ 超时用 `run_with_timeout`(线程 + join)—— 注意它的说明:
|
||||
超时后线程**杀不掉**,只能放弃等待。所以这里给的默认值不大
|
||||
(`timeouts.customNode`),而且脚本本来就该是"算一下"级别的活。
|
||||
"""
|
||||
if not (source or '').strip():
|
||||
return None, ''
|
||||
|
||||
import builtin_tools
|
||||
|
||||
holder = {}
|
||||
|
||||
def _work():
|
||||
try:
|
||||
ns = rule_sandbox.load(source, '<rule script>', {})
|
||||
holder['value'] = rule_sandbox.call(ns, entry, *args)
|
||||
holder['error'] = ''
|
||||
except rule_sandbox.ScriptRejected as exc:
|
||||
holder['error'] = f'脚本没通过安全检查:{exc}'
|
||||
except KeyError:
|
||||
holder['error'] = f'脚本里没有 `{entry}` 函数'
|
||||
except SyntaxError as exc:
|
||||
holder['error'] = f'脚本第 {exc.lineno} 行有语法错误:{exc.msg}'
|
||||
except Exception as exc: # noqa: BLE001 - 用户脚本什么都能抛
|
||||
holder['error'] = f'脚本报错:{exc.__class__.__name__}: {exc}'
|
||||
|
||||
# 注意:run_with_timeout 返回 None 表示"超时/放弃等待",见它的说明
|
||||
builtin_tools.run_with_timeout(_work, _timeout_s())
|
||||
if holder.get('error'):
|
||||
return None, holder['error']
|
||||
if 'value' not in holder:
|
||||
return None, '脚本超时(已放弃等待,它可能还在后台跑)'
|
||||
return holder['value'], ''
|
||||
|
||||
|
||||
def _stat_api(agent: dict, pack_id: str, narration: list, hints: dict) -> dict:
|
||||
"""
|
||||
给状态脚本的**受限 API**(需求 §3.11 的三项权限 + 旁白)。
|
||||
|
||||
★ 通过**参数**注入,不是做成模块级函数:那样脚本能摸到别的东西,
|
||||
两个脚本也会互相污染。
|
||||
★ 这里没有 `emotion_set` 的死亡检查 —— 需求 §3.11 明说状态脚本是
|
||||
"唯一能让 AI 侧解除死亡的通道"(定时复活 / 解药剧情)。
|
||||
禁止自愈那条只约束 AI 直接调 `emotion_set` 工具。
|
||||
"""
|
||||
def _change_stat(name, delta):
|
||||
r = change(agent, pack_id, str(name or ''), _num(delta))
|
||||
if not r.get('ok'):
|
||||
raise ValueError(r.get('error') or '改数值失败')
|
||||
return r.get('applied', 0)
|
||||
|
||||
def _emotion_set(preset, text=''):
|
||||
import agentdb
|
||||
|
||||
p = str(preset or '').strip()
|
||||
if p not in agentdb.PRESETS:
|
||||
raise ValueError(f'preset 只能是:{"、".join(agentdb.PRESETS)}')
|
||||
agentdb.emotion_set(agent.get('id') or '', preset=p, text=str(text or ''))
|
||||
return True
|
||||
|
||||
def _set_hint(status_name, text):
|
||||
hints[str(status_name or '').strip()] = str(text or '')
|
||||
|
||||
def _narrate(text):
|
||||
t = str(text or '').strip()
|
||||
if t:
|
||||
narration.append(t)
|
||||
|
||||
return {
|
||||
'change_stat': _change_stat,
|
||||
'emotion_set': _emotion_set,
|
||||
'set_hint': _set_hint,
|
||||
'narrate': _narrate,
|
||||
}
|
||||
|
||||
|
||||
def run_turn_scripts(agent: dict, pack_id: str) -> dict:
|
||||
"""
|
||||
每轮**生成回复之前**跑一遍生效状态的脚本(需求 §3.11)。
|
||||
|
||||
顺序是固定的:**状态脚本执行 → 重拼 prompt → 生成**(附录 E)。
|
||||
所以调用点必须在 `build_system_prompt` **之前**,否则脚本这一轮的
|
||||
改动要等下一轮才生效 —— 表现是"中毒了但 AI 这轮还生龙活虎"。
|
||||
|
||||
返回 `{'narration': [...], 'errors': [...], 'changed': [...]}`:
|
||||
· `narration` 是脚本返回的旁白,内核作为系统消息注入下一轮
|
||||
· `errors` 给界面提示(**不中断对话**)
|
||||
"""
|
||||
agent = agent or {}
|
||||
aid = agent.get('id') or ''
|
||||
if not aid:
|
||||
return {'narration': [], 'errors': [], 'changed': []}
|
||||
|
||||
narration, errors = [], []
|
||||
for inst in list_statuses(aid):
|
||||
src = script_source(pack_id, _script_file_of(pack_id, inst['name']))
|
||||
if not src:
|
||||
continue
|
||||
hints = {}
|
||||
api = _stat_api(agent, pack_id, narration, hints)
|
||||
_, err = run_script(src, 'on_turn', dict(agent), api)
|
||||
if err:
|
||||
errors.append(f'状态「{inst["name"]}」的脚本:{err}')
|
||||
continue
|
||||
# 脚本可能改了提示词(需求 §3.11 的权限之一)
|
||||
for sname, text in hints.items():
|
||||
for s in list_statuses(aid):
|
||||
if s['name'] == sname:
|
||||
put_status(aid, sname, s['remaining'], s['stacks'], text)
|
||||
return {'narration': narration, 'errors': errors, 'changed': []}
|
||||
|
||||
|
||||
def _script_file_of(pack_id: str, status_name: str) -> str:
|
||||
"""状态定义里配的脚本文件名"""
|
||||
for d in status_defs(pack_id):
|
||||
if d['name'] == status_name:
|
||||
return d.get('script') or ''
|
||||
return ''
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# change_stat:流程固定(需求 §3.10)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def change(agent: dict, pack_id: str, name: str, delta: float,
|
||||
source_agent: dict = None) -> dict:
|
||||
"""
|
||||
`change_stat(name, delta)` 的**完整流程**,顺序固定:
|
||||
|
||||
脚本裁决(如有)→ clamp 到 [min,max] → 写库 → 下一轮注入反映新值
|
||||
|
||||
★ 为什么"只申请增量、不许写绝对值"这条不能通融:
|
||||
允许写绝对值的话"脚本裁决"就没意义了 —— 修正器要的是
|
||||
"你想加 5 点,我判成加 10 点",而不是"你想设成 100,我判……多少"。
|
||||
而且群聊里两个智能体同时改同一个 shared 数值时,**绝对值会互相覆盖,
|
||||
增量不会**。
|
||||
|
||||
返回 `{'ok':..., 'applied':…, 'before':…, 'after':…, 'narration':…, 'error':…}`
|
||||
"""
|
||||
d = next((x for x in stat_defs(pack_id) if x['name'] == name), None)
|
||||
if not d:
|
||||
return {'ok': False, 'error': f'这个世界观里没有叫「{name}」的数值'}
|
||||
before = value_of(agent, d)
|
||||
want = _num(delta)
|
||||
|
||||
# ① 脚本裁决(可选)
|
||||
narration = []
|
||||
src = script_source(pack_id, d.get('script') or '')
|
||||
if src:
|
||||
out, err = run_script(src, 'on_stat_change', name, before, want)
|
||||
if err:
|
||||
# ★ 异常 = 本次增量**归零**(不是"按原值放行")——
|
||||
# 脚本坏了的时候,宁可这一次不生效,也不能让它失控地改数值
|
||||
return {'ok': False, 'error': err, 'applied': 0, 'before': before, 'after': before}
|
||||
if isinstance(out, (int, float)):
|
||||
want = float(out)
|
||||
elif isinstance(out, (list, tuple)) and out:
|
||||
# 也允许 (增量, 旁白) 这种写法
|
||||
want = _num(out[0])
|
||||
if len(out) > 1 and str(out[1] or '').strip():
|
||||
narration.append(str(out[1]).strip())
|
||||
elif out is None:
|
||||
want = 0.0 # 显式返回 None = 否决
|
||||
|
||||
# ② clamp ③ 写库
|
||||
after = clamp(d, before + want)
|
||||
applied = after - before
|
||||
if applied:
|
||||
set_value(agent, d, after)
|
||||
note_delta(scope_for(agent, d), name, applied)
|
||||
return {
|
||||
'ok': True, 'applied': applied, 'before': before, 'after': after,
|
||||
'narration': narration,
|
||||
'text': range_text(d, after),
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# grant_status:赋予流程(需求 §3.11)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def grant(source: dict, pack_id: str, target: dict, status_name: str,
|
||||
turns: int = 0) -> dict:
|
||||
"""
|
||||
A 给 B 挂一个状态。
|
||||
|
||||
流程(需求 §3.11):
|
||||
1. **同世界观**才能赋(不要求同会话在场 —— 否则私聊里没法互相赋予)
|
||||
2. 调 **B 侧的** `on_grant(status_name, source_agent) -> bool`
|
||||
3. 接受 → 实例化到 B;拒绝 → A 收到「被抵抗」回执(**A 必须知道结果**)
|
||||
4. 同名重复赋予默认**刷新轮数**;定义配了 max_stack 才叠层
|
||||
|
||||
跨世界观一律拒绝(第 1 条就挡了)。
|
||||
"""
|
||||
source, target = source or {}, target or {}
|
||||
name = (status_name or '').strip()
|
||||
if not name:
|
||||
return {'ok': False, 'error': '没写状态名'}
|
||||
if not (target.get('id') or ''):
|
||||
return {'ok': False, 'error': '找不到目标智能体'}
|
||||
|
||||
sw = (source.get('worldviewId') or '').strip()
|
||||
tw = (target.get('worldviewId') or '').strip()
|
||||
if not sw or sw != tw:
|
||||
# ★ 跨世界观一律拒绝(需求原话)。也包含"自己没绑世界观"的情况 ——
|
||||
# 那种情况下没有共享的规则体系,赋予本身就没有依据。
|
||||
return {'ok': False, 'error': '你们不在同一个世界观里,赋予无效'}
|
||||
|
||||
d = next((x for x in status_defs(pack_id) if x['name'] == name), None)
|
||||
if not d:
|
||||
return {'ok': False, 'error': f'这个世界观没有叫「{name}」的状态'}
|
||||
|
||||
# ② B 侧的判定脚本
|
||||
src = script_source(pack_id, d.get('script') or '')
|
||||
if src:
|
||||
out, err = run_script(src, 'on_grant', name, source.get('name') or source.get('id') or '')
|
||||
if err:
|
||||
return {'ok': False, 'error': f'对方的判定脚本出错了:{err}'}
|
||||
if out is False:
|
||||
# ★ 拒绝要给 A 一个**明确回执**(需求原话"A 必须知道结果")
|
||||
return {'ok': False, 'resisted': True, 'error': f'「{target.get("name") or "对方"}」抵抗了这个状态'}
|
||||
|
||||
# ④ 叠加规则
|
||||
cur = next((s for s in list_statuses(target['id']) if s['name'] == name), None)
|
||||
if d['kind'] == 'persistent':
|
||||
remaining = -1
|
||||
else:
|
||||
remaining = max(1, int(turns or d.get('turns') or 1))
|
||||
if cur:
|
||||
stacks = min(int(d.get('max_stack') or 1), int(cur.get('stacks') or 1) + 1)
|
||||
if d['kind'] != 'persistent':
|
||||
# 同名重复赋予默认**刷新**轮数(不是累加)
|
||||
remaining = max(remaining, int(cur.get('remaining') or 0))
|
||||
else:
|
||||
stacks = 1
|
||||
hint = cur.get('hint') if cur else ''
|
||||
put_status(target['id'], name, remaining, stacks, hint or '')
|
||||
return {'ok': True, 'name': name, 'remaining': remaining, 'stacks': stacks,
|
||||
'refreshed': bool(cur), 'target': target.get('name') or ''}
|
||||
@@ -59,17 +59,34 @@ def normalize_image(image) -> dict:
|
||||
"用户手改过 agents.json" 这种情况也不会被冲掉。
|
||||
|
||||
归一化**不丢信息**:字典里多出来的档位原样保留(用户可能自己加了「醉」这种)。
|
||||
|
||||
★★ 还要**解套**:有一版把 `front` 的字典值也 `_as_text` 了一遍,于是磁盘上
|
||||
存成了 `"{'平常': 'C:\\...\\a.png'}"`(**字符串化的字典**)。
|
||||
那种数据要能救回来 —— 不然用户看到的就是"**我设的图不见了**":
|
||||
档位读不出来(是个字符串不是字典),而且每读写一次还多包一层,
|
||||
最后连 `os.path.isfile` 都失败。
|
||||
"""
|
||||
img = dict(image or {})
|
||||
front = img.get('front')
|
||||
if isinstance(front, str):
|
||||
# v1.1 的单文件名 → 只有「平常」档
|
||||
img['front'] = {'平常': front} if front.strip() else {}
|
||||
if isinstance(front, str) and front.strip().startswith('{'):
|
||||
# ② 字符串化的字典 → 解回真字典
|
||||
img['front'] = _unshell_dict(front)
|
||||
elif isinstance(front, str):
|
||||
# ① v1.1 的单文件名 → 只有「平常」档
|
||||
img['front'] = {'平常': front.strip()} if front.strip() else {}
|
||||
elif isinstance(front, dict):
|
||||
img['front'] = {
|
||||
str(k): str(v) for k, v in front.items()
|
||||
if str(v or '').strip()
|
||||
}
|
||||
fixed = {}
|
||||
for k, v in front.items():
|
||||
key = str(k)
|
||||
if isinstance(v, str) and v.strip().startswith('{'):
|
||||
# 值本身又被包成了字典 → 摊平(旧数据里反复读写会这样)
|
||||
for ik, iv in _unshell_dict(v).items():
|
||||
if isinstance(iv, str) and iv.strip():
|
||||
fixed[str(ik)] = iv.strip()
|
||||
continue
|
||||
if str(v or '').strip():
|
||||
fixed[key] = str(v).strip()
|
||||
img['front'] = fixed
|
||||
else:
|
||||
img['front'] = {}
|
||||
for key in ('back', 'border-main', 'border-info'):
|
||||
@@ -77,6 +94,25 @@ def normalize_image(image) -> dict:
|
||||
return img
|
||||
|
||||
|
||||
def _unshell_dict(text: str) -> dict:
|
||||
"""
|
||||
把**字符串化的字典**解回 dict(解不开就给空字典)。
|
||||
|
||||
★ 用 `ast.literal_eval` 而不是 `eval`:它只能求值**字面量**
|
||||
(数字、字符串、列表、字典……),遇到函数调用直接报错。
|
||||
就算那段文本被谁改过,也执行不了任何东西。
|
||||
"""
|
||||
import ast
|
||||
|
||||
try:
|
||||
got = ast.literal_eval(str(text or ''))
|
||||
except (ValueError, SyntaxError):
|
||||
return {}
|
||||
if not isinstance(got, dict):
|
||||
return {}
|
||||
return {str(k): v for k, v in got.items()}
|
||||
|
||||
|
||||
def _read_json(file_path: str):
|
||||
"""读 JSON;文件不存在或坏掉都返回 None(调用方决定怎么兜底)。"""
|
||||
if not os.path.isfile(file_path):
|
||||
@@ -608,13 +644,18 @@ def session_message_count(conv_id: str) -> int:
|
||||
return sum(1 for m in (conv.get('messages') or []) if m.get('aiSent'))
|
||||
|
||||
|
||||
def append_message(conv_id: str, role: str, content: str) -> dict:
|
||||
def append_message(conv_id: str, role: str, content: str, agent_id: str = '') -> dict:
|
||||
"""
|
||||
往会话里追加一条消息(AI 主动发的)。
|
||||
|
||||
★ 走 `update_conversation` 而不是自己写文件:会话的落盘、时间戳、
|
||||
标题自动生成那些逻辑都在那儿,这里再写一份就会不一致
|
||||
(这个仓库里"同一段逻辑两份、加功能只改一份"的坑踩过好几次)。
|
||||
|
||||
★ [agent_id] 是**说这句话的是谁**。群聊里每条消息的发言者都不一样,
|
||||
界面朗读时要按它挑音色 —— 不记的话只能一律用"当前对话的主人",
|
||||
表现就是"群聊时不同智能体的语音不会切换"(真机反馈)。
|
||||
`/api/chat` 那条路一直在写这个字段,只有这里漏了。
|
||||
"""
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
@@ -628,6 +669,8 @@ def append_message(conv_id: str, role: str, content: str) -> dict:
|
||||
# 用来算"这个会话还能主动发几条",界面上不显示、也不给模型看。
|
||||
'aiSent': True,
|
||||
}
|
||||
if agent_id:
|
||||
msg['agentId'] = str(agent_id)
|
||||
msgs.append(msg)
|
||||
update_conversation(conv_id, {'messages': msgs})
|
||||
return msg
|
||||
@@ -926,11 +969,27 @@ def take_summary_suggestion(agent_id: str) -> str:
|
||||
return _pending_summary.pop(agent_id or '', '')
|
||||
|
||||
|
||||
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
|
||||
def create_conversation(title: str = '新对话', agent_id: str | None = None,
|
||||
kind: str = 'single', participants: list | None = None) -> dict:
|
||||
"""
|
||||
新建会话。
|
||||
|
||||
★ v1.2 加了两个字段(需求 §3.9):
|
||||
|
||||
type single(单聊)/ group(群聊)/ private(私聊记录)
|
||||
participants 群聊的成员 id 列表(单聊为空)
|
||||
|
||||
群聊/私聊是**独立实体**,出现在每个参与者的会话列表里 ——
|
||||
不是"每个智能体各存一份",那样三条记录迟早会不同步。
|
||||
"""
|
||||
item = {
|
||||
'id': _rid_conv(),
|
||||
'title': title,
|
||||
'agentId': agent_id or '',
|
||||
# ★ 老会话没有这两个字段 → 读的时候当 single 处理(见 toConversation),
|
||||
# 所以不用写迁移:JSON 里少两个键不影响任何东西
|
||||
'type': kind if kind in ('single', 'group', 'private') else 'single',
|
||||
'participants': [str(p) for p in (participants or []) if str(p or '').strip()],
|
||||
'pinned': False,
|
||||
'createdAt': now_iso(),
|
||||
'updatedAt': now_iso(),
|
||||
@@ -999,6 +1058,72 @@ def append_messages(conv_id: str, messages: list):
|
||||
return item
|
||||
|
||||
|
||||
def mark_important(conv_id: str, index: int, important: bool):
|
||||
"""
|
||||
给第 [index] 条消息打/取消「重要」标记(v1.2 §4.3)。
|
||||
|
||||
★ 需求原话:"**仅用户可标**;被标记消息破格永久携带、按原始时间序插入"。
|
||||
所以这个函数**只由界面调**,AI 那边没有对应的工具 ——
|
||||
它有 `memory_add` 去记该记的东西,标记是用户的主权。
|
||||
|
||||
★★ 按**下标**定位是**不安全**的,已经踩过:界面上那份消息列表可能和
|
||||
存储里的**不是一一对应**(本地生成的内容、还没落地的流式消息……),
|
||||
于是"长按第 3 条"会把标记打到第 1 条上 —— **静默标错**,
|
||||
而用户完全看不出来(要等哪天发现某句话莫名没被裁掉)。
|
||||
所以界面走的是 `mark_important_by_content`,这个按下标的老函数
|
||||
只留给内部/测试用。
|
||||
"""
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
return None
|
||||
msgs = item.get('messages') or []
|
||||
if not (0 <= index < len(msgs)):
|
||||
return None
|
||||
with _lock:
|
||||
# ★ 只改这一个字段,**不动 content** —— 需求把"历史消息字节冻结"
|
||||
# 写成了内核纪律:改一个字,从那儿往后的前缀缓存全废。
|
||||
# 标一个 `important` 是**新增键**,不影响 content 的字节。
|
||||
msgs[index]['important'] = bool(important)
|
||||
item['updatedAt'] = now_iso()
|
||||
_persist_conversations()
|
||||
return msgs[index]
|
||||
|
||||
|
||||
def mark_important_by_content(conv_id: str, content: str, role: str = '',
|
||||
important: bool = True):
|
||||
"""
|
||||
按**内容**找那条消息来打标记(界面的长按走这条路)。
|
||||
|
||||
★ 为什么不用下标:见 `mark_important` 的说明 —— 界面的列表和存储的
|
||||
列表**不保证一一对应**,下标会静默标错。
|
||||
|
||||
★ 从**后往前**找:同一个内容可能重复出现(用户把一句话发了两遍),
|
||||
而他长按的通常是比较靠后的那条。
|
||||
|
||||
★ 找不到就返回 None,让调用方**报错** —— 绝不"猜一条"标上去。
|
||||
标错了用户看不出来,而那比报错糟得多。
|
||||
"""
|
||||
item = get_conversation(conv_id)
|
||||
if not item:
|
||||
return None
|
||||
want = _as_text(content)
|
||||
if not want:
|
||||
return None
|
||||
msgs = item.get('messages') or []
|
||||
hit = -1
|
||||
for i in range(len(msgs) - 1, -1, -1):
|
||||
m = msgs[i]
|
||||
if _as_text(m.get('content')) != want:
|
||||
continue
|
||||
if role and m.get('role') != role:
|
||||
continue
|
||||
hit = i
|
||||
break
|
||||
if hit < 0:
|
||||
return None
|
||||
return mark_important(conv_id, hit, important)
|
||||
|
||||
|
||||
def auto_title(conv_id: str, text: str) -> None:
|
||||
"""用首条用户消息自动起标题(只改还没起过名的会话)。"""
|
||||
item = get_conversation(conv_id)
|
||||
@@ -1046,10 +1171,17 @@ AGENT_TEXT_FIELDS = (
|
||||
'ttsVoice', # 音色 —— 多人会议里靠它区分谁在说话
|
||||
'modelId', # ← 全局模型列表里的 id
|
||||
'worldviewId', # ← 绑定的世界观 id
|
||||
# ★ v1.2 新增:
|
||||
# inviteMode 拉起其他智能体:silent 直接进场 / confirm 先问用户(§6.1)
|
||||
# contextWindow 对话上下文窗口(§4.3,留空继承全局)
|
||||
# ★ 这两个字段**必须列在这儿** —— 不列的话 _apply_agent_patch 会丢掉,
|
||||
# 表现是"界面上配了、读出来没有"(rulePackId 那个坑一模一样)
|
||||
'inviteMode',
|
||||
)
|
||||
AGENT_NUM_FIELDS = (
|
||||
'ttsSpeed', # 语速
|
||||
'tokenLimit', # 0 = 无限制(不是"限额为 0")
|
||||
'contextWindow', # v1.2 §4.3:这个智能体的对话上下文窗口(轮)
|
||||
)
|
||||
AGENT_BOOL_FIELDS = ('emotionEnabled',)
|
||||
AGENT_LIST_FIELDS = ('skillIds',)
|
||||
@@ -1091,10 +1223,18 @@ def _apply_agent_patch(agent: dict, patch: dict) -> dict:
|
||||
for key in AGENT_DICT_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
raw = patch[key]
|
||||
agent[key] = (
|
||||
{str(k): _as_text(v) for k, v in raw.items()}
|
||||
if isinstance(raw, dict) else {}
|
||||
)
|
||||
# ★★ 和 `_apply_resource_patch` 一样:**不能对每个值调 `_as_text`**。
|
||||
#
|
||||
# 智能体的 `image` 以前只有字符串(文件名),转一下无妨;
|
||||
# 但 v1.2 的立绘是**五档字典**(`front: {'喜': 路径, ...}`)——
|
||||
# 转成字符串之后,那个键就变成了 `"{'喜': 'C:\\...'}"` 这种
|
||||
# 字符串化的字典:
|
||||
# · 回退链按档位找不到(`front['喜']` 从字典里读不到)
|
||||
# · 而且**每读写一次就多包一层**,最后 `os.path.isfile` 失败
|
||||
# —— 表现就是用户说的"**之前设置的图像也没了**"
|
||||
#
|
||||
# 改成 `_json_safe`:保留嵌套结构,只把 JSON 存不下的转字符串。
|
||||
agent[key] = _json_safe(raw) if isinstance(raw, dict) else {}
|
||||
return agent
|
||||
|
||||
|
||||
@@ -1196,16 +1336,34 @@ RESOURCES = {
|
||||
'worldviews': {
|
||||
'file': lambda: paths.get().worldviews_file,
|
||||
'key': 'worldviews',
|
||||
'text': ('name', 'setting'),
|
||||
# ★ rulePackId:这个世界观挂的**数值状态包**(需求 §3.6:
|
||||
# "v1.2 起,世界观同时是数值状态包的挂载点")。
|
||||
# 没有它的话这个字段会被 _apply_resource_patch 丢掉 ——
|
||||
# 表现是"设置界面里配了、读出来没有",排查起来得一路看到字段表。
|
||||
'text': ('name', 'setting', 'rulePackId'),
|
||||
'dict': ('image',),
|
||||
'label': '世界观',
|
||||
},
|
||||
# 数值状态包(需求附录 D):定义 + 对应 Python 脚本
|
||||
'rulepacks': {
|
||||
'file': lambda: paths.get().rulepacks_file,
|
||||
'key': 'rulepacks',
|
||||
'text': ('name', 'note'),
|
||||
# info 是解析好的 info.json(stats / statuses 两张表);
|
||||
# scripts 是 {文件名: 源码} —— **整包一起存**,因为脚本要落盘才能跑
|
||||
'dict': ('info', 'scripts'),
|
||||
'label': '规则包',
|
||||
},
|
||||
# 全局模型列表(需求 3.3):名称 + API 端点 + Key + 模型标识 + 单价
|
||||
'models': {
|
||||
'file': lambda: paths.get().models_file,
|
||||
'key': 'models',
|
||||
'text': ('name', 'apiBase', 'apiKey', 'model', 'provider'),
|
||||
'num': ('pricePerK',), # 元/千 Token,0 = 不显示费用估算
|
||||
# 元/千 Token,0 = 不显示费用估算。
|
||||
# ★ cachePricePerK 是**命中缓存**的单价(v1.2):各家命中都比未命中
|
||||
# 便宜得多(常见 1/10)。只填一个输入单价的话,费用估算会按未命中
|
||||
# 的价格算 —— 用得越多、高估得越离谱,而用户会以为自己真花了那些钱。
|
||||
'num': ('pricePerK', 'cachePricePerK'),
|
||||
# ★ noTools:这个模型不支持 function calling(需求 3.3 的兼容降级)。
|
||||
# 打开之后不传 tools、改成正文内的调用约定 —— 见 agent_loop.DEGRADED_HINT。
|
||||
'bool': ('noTools',),
|
||||
@@ -1270,18 +1428,51 @@ def _apply_resource_patch(name: str, item: dict, patch: dict) -> dict:
|
||||
for key in cfg.get('dict', ()):
|
||||
if patch.get(key) is not None:
|
||||
raw = patch[key]
|
||||
item[key] = (
|
||||
{str(k): _as_text(v) for k, v in raw.items()}
|
||||
if isinstance(raw, dict) else {}
|
||||
)
|
||||
# ★★ **不要对每个值调 `_as_text`**。
|
||||
#
|
||||
# 原来那么写是因为 `image` 的值全是字符串(路径),转一下无妨。
|
||||
# 但 v1.2 的规则包里 `info` 的值是**嵌套结构**
|
||||
# (`stats: [{name, min, max, ranges: [...]}]`)——
|
||||
# 转成字符串之后 `sync_defs` 读到的就是 `"[{'name': 'A'}]"`,
|
||||
# 于是**整个规则引擎静默失效**(解析不出来 → 当成没定义 → 不报错)。
|
||||
# 这种"看起来存进去了、实际全废"的坑最难查。
|
||||
item[key] = _json_safe(raw) if isinstance(raw, dict) else {}
|
||||
return item
|
||||
|
||||
|
||||
def _json_safe(v):
|
||||
"""
|
||||
只留下 JSON 存得下的东西(dict / list / 字符串 / 数字 / 布尔 / None)。
|
||||
|
||||
别的(set、datetime、自定义对象)转成字符串 —— 不让它们把写盘搞炸,
|
||||
同时**保留嵌套结构**(这是 `_as_text` 做不到的)。
|
||||
"""
|
||||
if isinstance(v, dict):
|
||||
return {str(k): _json_safe(x) for k, x in v.items()}
|
||||
if isinstance(v, (list, tuple)):
|
||||
return [_json_safe(x) for x in v]
|
||||
if v is None or isinstance(v, (str, int, float, bool)):
|
||||
return v
|
||||
return str(v)
|
||||
|
||||
|
||||
def create_resource(name: str, payload: dict) -> dict:
|
||||
"""
|
||||
新建一种资源。
|
||||
|
||||
★ 允许 `payload` 里带 `id`(**校验过才用**):规则包需要它 ——
|
||||
数值定义表的 key 是规则包 id(`sync_defs` 用它写库),
|
||||
如果 `create_resource` 自己生成 id,调用方就得"先建再改"两步,
|
||||
中途失败会留下一个没有定义的孤儿包。
|
||||
已经存在同名 id 时**自动换一个**,不覆盖别人的东西。
|
||||
"""
|
||||
cfg = _res(name)
|
||||
items = list_resource(name)
|
||||
want_id = _as_text((payload or {}).get('id')).strip()
|
||||
if want_id and (len(want_id) > 64 or any(x.get('id') == want_id for x in items)):
|
||||
want_id = '' # 不合法或撞了 → 当作没给
|
||||
item = {
|
||||
'id': agentdb.new_id(), # ★ UUID(需求附录 A)
|
||||
'id': want_id or agentdb.new_id(), # ★ UUID(需求附录 A)
|
||||
'name': _as_text((payload or {}).get('name'))[:40],
|
||||
'builtin': False,
|
||||
'createdAt': now_iso(),
|
||||
|
||||
@@ -132,10 +132,30 @@ _ctx = threading.local()
|
||||
|
||||
|
||||
def push_context(**kw) -> None:
|
||||
"""进入一次工具调用(agent_loop 在 execute_tool 前调用)"""
|
||||
"""进入一次工具调用(agent_loop 在 execute_tool 前调用)。
|
||||
|
||||
★ 这是**替换**语义:把整份上下文换成新的。
|
||||
"""
|
||||
_ctx.value = dict(kw)
|
||||
|
||||
|
||||
def update_context(**kw) -> None:
|
||||
"""
|
||||
在**当前上下文里补几个键**(已有的不动)。
|
||||
|
||||
★★ 和 `push_context` 的区别很要紧,踩过一次:
|
||||
|
||||
· `push_context` 是**替换** —— 给"进入一次工具调用"用的
|
||||
· 工具内部想加个标记(比如 `pass_turn` 记"这一轮移交过了")时
|
||||
如果用 `push_context`,会把 `agentId` / `conversationId` 一起冲掉,
|
||||
接着同一个工具里的 `_me()` 就炸了(表现是"拿不到当前智能体",
|
||||
而报错的地方离真正的原因隔着好几步)
|
||||
"""
|
||||
cur = dict(getattr(_ctx, 'value', None) or {})
|
||||
cur.update(kw)
|
||||
_ctx.value = cur
|
||||
|
||||
|
||||
def clear_context() -> None:
|
||||
_ctx.value = None
|
||||
|
||||
@@ -145,6 +165,43 @@ def current_context() -> dict:
|
||||
return dict(getattr(_ctx, 'value', None) or {})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 轮次级状态(发言权移交)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★★ 为什么**不能**用工具上下文(`update_context`)来记这个 —— 踩过:
|
||||
#
|
||||
# 工具跑在 **worker 线程**里(`builtin_tools.run_with_timeout` 起线程),
|
||||
# 而 `_ctx` 是 `threading.local()`。工具在里面写 `update_context(...)`,
|
||||
# 写的是**那个 worker 线程**的副本;线程一结束、`finally` 里把值置 None,
|
||||
# 标记就没了。而主线程每次调用前又 `push_context(...)`(替换语义)——
|
||||
# 于是"这一轮已经移交过"**永远是 False**,`pass_turn` 可以一轮交无限次。
|
||||
#
|
||||
# ★ 更麻烦的是:探针当时是**直接调 `agent_tools.pass_turn`**(主线程),
|
||||
# 标记留在主线程里没被清 → 探针**假通过**。真机上才会露馅。
|
||||
# 所以这里的修复必须配一条**走真实路径**的探针(见 probe-group-chat)。
|
||||
#
|
||||
# 轮次级状态放**模块级**,和线程无关,`agent_loop` 每轮开头重置一次。
|
||||
_handoff = {'to': '', 'used': False}
|
||||
|
||||
|
||||
def begin_round() -> None:
|
||||
"""一轮对话开始时调用(agent_loop 在生成前调)"""
|
||||
_handoff['to'] = ''
|
||||
_handoff['used'] = False
|
||||
|
||||
|
||||
def note_handoff(agent_id: str) -> None:
|
||||
"""`pass_turn` 记下"这一轮移交给了谁" """
|
||||
_handoff['to'] = str(agent_id or '')
|
||||
_handoff['used'] = True
|
||||
|
||||
|
||||
def handoff_state() -> dict:
|
||||
"""读这一轮的移交状态(`app.py` 的仲裁要用 `to`)"""
|
||||
return dict(_handoff)
|
||||
|
||||
|
||||
def ui_tools_enabled(settings: dict) -> bool:
|
||||
"""
|
||||
界面工具开了没有。
|
||||
|
||||
BIN
docs/screenshots/ai-talk.png
Normal file
|
After Width: | Height: | Size: 2.5 MiB |
BIN
docs/screenshots/chat-backdrop.png
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
BIN
docs/screenshots/drawer-split.png
Normal file
|
After Width: | Height: | Size: 668 KiB |
BIN
docs/screenshots/group-after.png
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
BIN
docs/screenshots/group-ai-chat.png
Normal file
|
After Width: | Height: | Size: 2.4 MiB |
BIN
docs/screenshots/group-bar.png
Normal file
|
After Width: | Height: | Size: 79 KiB |
BIN
docs/screenshots/group-before.png
Normal file
|
After Width: | Height: | Size: 453 KiB |
BIN
docs/screenshots/mention-switch.png
Normal file
|
After Width: | Height: | Size: 2.3 MiB |
BIN
docs/screenshots/no-premature-switch.png
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
BIN
docs/screenshots/now1.png
Normal file
|
After Width: | Height: | Size: 436 KiB |
BIN
docs/screenshots/now2.png
Normal file
|
After Width: | Height: | Size: 167 KiB |
BIN
docs/screenshots/now3.png
Normal file
|
After Width: | Height: | Size: 2.6 MiB |
BIN
docs/screenshots/rd-verify-final.png
Normal file
|
After Width: | Height: | Size: 509 KiB |
BIN
docs/screenshots/realdevice-drawer.png
Normal file
|
After Width: | Height: | Size: 296 KiB |
BIN
docs/screenshots/realdevice-launch.png
Normal file
|
After Width: | Height: | Size: 426 KiB |
BIN
docs/screenshots/rulepack-edit.png
Normal file
|
After Width: | Height: | Size: 84 KiB |
BIN
docs/screenshots/rulepacks.png
Normal file
|
After Width: | Height: | Size: 72 KiB |
BIN
docs/screenshots/speaker-tag-fixed.png
Normal file
|
After Width: | Height: | Size: 2.5 MiB |
BIN
docs/screenshots/switch-on-speak.png
Normal file
|
After Width: | Height: | Size: 2.4 MiB |
BIN
docs/screenshots/title-backdrop-switch.png
Normal file
|
After Width: | Height: | Size: 885 KiB |
@@ -5,9 +5,30 @@
|
||||
|
||||
---
|
||||
|
||||
## ✅ 全部完成(v2.0.47 → v2.0.66)
|
||||
|
||||
| 阶段 | 内容 | 完成版本 | 主要落点 |
|
||||
|---|---|---|---|
|
||||
| **0** | 情绪双字段(地基) | v2.0.55 | `agentdb.py` / `agent_tools.py` / `agent_context.py` / `MemoryScreen.kt` |
|
||||
| **1** | 立绘表 + 回退链 | v2.0.56 | `store.normalize_image` / `agent_api.portrait_of` / `AgentEditScreen.kt` |
|
||||
| **2** | 缓存统计 + 段序 + 上下文窗口 | v2.0.57 / v2.0.58 / v2.0.64 | `agent_loop.cache_pair` / `defaults.DEFAULT_PROMPT_TEMPLATE` / **新建 `kernel/context_window.py`** |
|
||||
| **3** | 规则引擎(数值 + 状态 + 沙箱 + 规则包) | v2.0.59 | **新建 `kernel/rule_engine.py`** / `agent_tools.change_stat`·`grant_status` / `ResourcesScreen.kt` / **新建 `RulePackEditScreen.kt`** |
|
||||
| **4** | 多智能体对话(群聊 + 私聊) | v2.0.60 / v2.0.61 | **新建 `kernel/group_chat.py`**·`private_chat.py` / `agent_tools.invite_agent`·`pass_turn` / **新建 `GroupMembersScreen.kt`** |
|
||||
| **5** | 收尾(三个新界面 + @ 快捷条 + 标记重要 + 背景跟随) | v2.0.62 → v2.0.66 | **新建 `AgentStatsScreen.kt`** / `ChatScreen.kt` / `SettingsScreen.kt` |
|
||||
|
||||
**八个探针全绿**(每一阶段都构建 + 探针验证过):
|
||||
|
||||
probe-agent-system probe-degraded probe-rule-sandbox
|
||||
probe-rule-engine probe-context-window probe-group-chat
|
||||
audit-ui-tree audit-ui-entries
|
||||
|
||||
`audit-ui-tree.py` 的 `PLANNED` 已**清空** —— 三个"计划中"的界面全部落地。
|
||||
|
||||
---
|
||||
|
||||
## 阶段划分(每一阶段都能单独发版)
|
||||
|
||||
### 阶段 0 · 情绪双字段(**地基**)
|
||||
### ✅ 阶段 0 · 情绪双字段(**地基**)
|
||||
|
||||
**为什么必须第一个做**:v1.2 有三处依赖它 —— 立绘联动(按 preset 切图)、
|
||||
`peer_emotions`(注入的是 preset 不是 text)、`on_turn` 脚本(能改情绪)。
|
||||
@@ -23,7 +44,7 @@
|
||||
|
||||
**注意**:`get_token_usage` 之外的旧工具签名一个字都不能变。
|
||||
|
||||
### 阶段 1 · 立绘表 + 回退链(依赖阶段 0)
|
||||
### ✅ 阶段 1 · 立绘表 + 回退链(依赖阶段 0)
|
||||
|
||||
| 做什么 | 落在哪 |
|
||||
|---|---|
|
||||
@@ -32,7 +53,7 @@
|
||||
| 智能体编辑外观组:角色图拆成五档,各带选图/清除 | `AgentEditScreen.kt` |
|
||||
| 选择界面立绘随 preset 切换 | `AgentSelectScreen.kt` |
|
||||
|
||||
### 阶段 2 · 缓存统计 + 段序(**独立,可以并行**)
|
||||
### ✅ 阶段 2 · 缓存统计 + 段序(**独立,可以并行**)
|
||||
|
||||
| 做什么 | 落在哪 |
|
||||
|---|---|
|
||||
@@ -46,7 +67,7 @@
|
||||
把最易变的 `<emotion>` 放在 `<memory>` 前面 —— 情绪一变,后面整段缓存全废。
|
||||
挪到最后,长前缀(prompt/skills/worldview/memory)能一直命中。
|
||||
|
||||
### 阶段 3 · 规则引擎(数值 + 状态,**最大的一块**)
|
||||
### ✅ 阶段 3 · 规则引擎(数值 + 状态,**最大的一块**)
|
||||
|
||||
| 做什么 | 落在哪 |
|
||||
|---|---|
|
||||
@@ -60,7 +81,7 @@
|
||||
| `[规则包编辑]` 全屏界面(脚本编辑复用节点代码那个组件) | 新建 |
|
||||
| `[状态数值]` 浮层 + 三个入口 | 新建 |
|
||||
|
||||
### 阶段 4 · 多智能体对话(**依赖阶段 0 和 3**)
|
||||
### ✅ 阶段 4 · 多智能体对话(**依赖阶段 0 和 3**)
|
||||
|
||||
| 做什么 | 落在哪 |
|
||||
|---|---|
|
||||
@@ -73,7 +94,7 @@
|
||||
| 群聊背景跟随发言者(crossfade 0.3s) | `ChatScreen.kt` |
|
||||
| 死亡规则:禁言 + 不冻结状态机 + 复活双通道 | `app.py` + `agent_tools.py` |
|
||||
|
||||
### 阶段 5 · 收尾
|
||||
### ✅ 阶段 5 · 收尾
|
||||
|
||||
- 文档:`docs/智能体系统.md` 补 v1.2 各节
|
||||
- `docs/界面总览.md` 里三个"计划中"的界面标成已落地
|
||||
@@ -102,9 +123,30 @@
|
||||
**§3.10 的脚本沙箱能做到什么程度**。~~需求说"仅暴露三个 API,无文件、网络访问"。
|
||||
安卓上的内核是 CPython(Chaquopy),Python 的沙箱天生关不严,三条路……~~
|
||||
|
||||
### ✅ 已定:子进程 + 资源限制(2026-10-16 你选的)
|
||||
### ✅ 已定:**限制 import(builtins 白名单)**(2026-10-16 你选的,已实现)
|
||||
|
||||
但查了一遍代码,**安卓上不能直接起 Python 子进程**,方案要绕一下:
|
||||
最终做的是 `kernel/rule_sandbox.py` 的三层:
|
||||
|
||||
1. **静态扫描**:`__\w+__`、`import`、`open|eval|exec|getattr|...` 一律拒绝
|
||||
2. **受限 `SAFE_BUILTINS`**:脚本的全局命名空间里只有白名单里的内置函数
|
||||
3. **硬超时**:跑不动就放弃等待(线程杀不掉,如实写进提示)
|
||||
|
||||
★★ 而且**如实标注了能力边界** —— 模块里写着"**挡手滑,挡不住有意**":
|
||||
|
||||
· 文本级扫描可以绕过(`"_" * 2 + "import__"` 这类拼接)
|
||||
· 没有资源限制(内存 / CPU)
|
||||
· 安卓上起不了真子进程(Chaquopy 嵌的 CPython 没有独立解释器,
|
||||
证据是现有 `python_run` 工具用的就是进程内 `exec`)
|
||||
|
||||
`scripts/probe-rule-sandbox.py` 里专门有一节**测试它挡不住什么** ——
|
||||
一个只测"能挡住什么"的沙箱测试,会给人虚假的安全感。
|
||||
|
||||
**下面这段是当初的调研记录**,保留下来是因为"安卓上为什么起不了 Python
|
||||
子进程"这个结论以后还会有人问:
|
||||
|
||||
> ~~需求说"仅暴露三个 API,无文件、网络访问"。三条路……~~
|
||||
>
|
||||
> 但查了一遍代码,**安卓上不能直接起 Python 子进程**,方案要绕一下:
|
||||
|
||||
**问题**:安卓内核是 Chaquopy 嵌的 CPython —— 它**没有独立的解释器可执行文件**,
|
||||
`sys.executable` 指向的东西起不来。证据在仓库里:现有的 `python_run` 工具
|
||||
|
||||
@@ -1,8 +1,64 @@
|
||||
# 智能体系统(需求 v1.1)
|
||||
# 智能体系统(需求 v1.1 + v1.2)
|
||||
|
||||
这份文档对应《智能体系统需求文档 v1.1》。它不讲"应该怎么做"(那在需求里),
|
||||
只讲**这个仓库是怎么落地的**:每个需求项落在哪个文件、当时为什么这么选、
|
||||
出了问题去哪儿看。
|
||||
这份文档对应《智能体系统需求文档 v1.1》**和 v1.2**。它不讲"应该怎么做"
|
||||
(那在需求里),只讲**这个仓库是怎么落地的**:每个需求项落在哪个文件、
|
||||
当时为什么这么选、出了问题去哪儿看。
|
||||
|
||||
---
|
||||
|
||||
## 0. v1.2 增补(v2.0.47 → v2.0.66 全部落地)
|
||||
|
||||
v1.1 那张对照表在下面第 1 节;v1.2 新增的部分单列在这儿,
|
||||
因为它们的落点大多是**新文件**,和 v1.1 那批不是一回事。
|
||||
|
||||
| 需求 | 实现位置 |
|
||||
|---|---|
|
||||
| §3.5 情绪双字段(preset + text) | `kernel/agentdb.py`(`emotions` 表加 `preset`)+ `MemoryScreen.kt` |
|
||||
| §2.5 立绘五档 + §2.6 回退链 | `kernel/store.py: normalize_image` + `kernel/agent_api.py: portrait_of` + `AgentEditScreen.kt` |
|
||||
| §3.1 缓存统计归一化 | `kernel/agent_loop.py: cache_pair`(三家字段名不同)+ `agentdb.py` 的 `cache_hit/miss` |
|
||||
| 附录 C 缓存友好段序 | `kernel/defaults.py: DEFAULT_PROMPT_TEMPLATE` + `agent_context.SECTIONS` |
|
||||
| §4.3 对话上下文窗口 | **`kernel/context_window.py`**(成批对齐裁剪 + 重要标记破格携带) |
|
||||
| §3.10 数值系统 | **`kernel/rule_engine.py`** + `agent_tools.change_stat` |
|
||||
| §3.11 状态系统 | 同上 + `agent_tools.grant_status` + `agent_loop` 的 `on_turn` 调用点 |
|
||||
| 附录 E 脚本沙箱 | **`kernel/rule_sandbox.py`**(如实标注"挡手滑挡不住有意") |
|
||||
| 附录 D 数值状态包 | `agent_api._export_rulepack` / `_import_rulepack` + `ui/RulePackEditScreen.kt` |
|
||||
| §3.9 群聊 | **`kernel/group_chat.py`**(点名制仲裁)+ `agent_tools.invite_agent`·`pass_turn` + `ui/GroupMembersScreen.kt` |
|
||||
| §3.9 私聊 | **`kernel/private_chat.py`**(10 轮安全网 + 一方触顶单方面收尾) |
|
||||
| §3.10/3.11 状态数值界面 | `ui/AgentStatsScreen.kt`(三个入口共用) |
|
||||
| §6.1 背景跟随说话者 | `SettingsScreen.kt` 的「外观」组 + `ChatScreen.ChatBackdrop`(聊天页整屏立绘/背景层,跟着说话者换) |
|
||||
|
||||
### 两份"窗口"的命名纪律(需求点名要求,别混)
|
||||
|
||||
· 「记忆注入窗口」 memoryWindow —— 每轮塞多少条**记忆**,超出部分**降级为可检索**
|
||||
· 「上下文窗口」 contextWindow —— 送多少轮**对话**,超出部分**直接丢弃、不做摘要**
|
||||
|
||||
两个像但完全不同。混着叫的话,用户问"我调窗口怎么没用"时你都不知道说的是哪个。
|
||||
|
||||
### v1.2 踩过、值得记住的几类坑
|
||||
|
||||
| 坑 | 表现 | 教训 |
|
||||
|---|---|---|
|
||||
| **字段表缺项** | `rulePackId` / `inviteMode` / `contextWindow` 不在白名单里 → "界面里配了、读出来没有" | 加字段时先看字段表 |
|
||||
| **`push_context` 是替换语义** | 工具里拿它记标记,冲掉了 `agentId` → "拿不到当前智能体" | 要合并用 `update_context` |
|
||||
| **`GET /api/<res>/<id>` 缺分支** | 编辑页拿到空包,界面显示"0 条数值"而包其实建出来了 | 只有真点一遍才看得见 |
|
||||
| **`Text` 不渲染 Markdown** | `Text("**粗体**")` 把星号原样显示 | 不报错、不警告,只有截图能发现 |
|
||||
| **按下标定位消息** | 界面和存储的列表不一一对应 → **静默标错**到别的消息上 | 下标是两边各自数的;改成按内容定位 |
|
||||
| **`dict` 字段被 `_as_text` 压平** | 规则包的 `info` 里嵌套 list 变成字符串 → 整个规则引擎静默失效 | 嵌套结构要 `_json_safe` |
|
||||
| **请求体上限按最小的调用方给** | 手机照片 28.9MB → base64 38MB,撞上 `read_json_body` 默认的 4MB;异常又被吞成空 dict,最后报的是**「不认识的外观槽位」** | 上限按**最大**的用;吞异常等于把原因丢掉 |
|
||||
| **探针绕过了真正出问题的那一层** | 第 22 节直接调 `_set_asset`,而卡住的是 `handle()` 里的 `body()` → 探针全绿,真机全挂 | 探针**必须走生产同一条调用路径** |
|
||||
| **换图时"自己删自己"** | 落盘名是 `<槽位>-<原始文件名>`;同一张图传第二次时新旧同路径 → 写完新的立刻被当旧的删掉,`image` 里留下**指向不存在文件**的路径,目录空着界面回退默认图 | 删旧文件前先比路径;"先写后删"的顺序里藏着这个坑 |
|
||||
| **两条各自正确的逻辑叠在一起** | 群聊仲裁把 `agentId` 换成「本轮发言人」,紧接着的会话隔离又拿它比「会话主人」→ 群里每换一个人说话就**另起一个会话**,用户 @ 谁就跳到谁的对话去 | 一条规则搬到新场景时要重问一遍"它还成立吗"——群聊里 `agentId` 根本不是主人 |
|
||||
| **能力全都在,缺最后一个按钮** | `chatJob`(取消句柄)建好了、内核从 HTTP 到 `agent_loop` 一路支持 `cancelled`、ViewModel 也把 `AtomicBoolean` 传下去了 —— 但**没有任何界面调它**,用户只能干等它说完 | 一条链路要数**两端**:内核发得出 + 界面点得到。只做前半截,测的时候还全是绿的 |
|
||||
| **顺序错了:先仲裁、后落库** | 群聊仲裁要读「用户这一轮 @ 了谁」,而本次消息**还没写进库** → 读到的是**上一次**的话 → 我 @ 寐眠,回答的却是小黑(背景/标签/音色三处全对不上) | 读「刚刚发生的事」之前先问:**它现在在库里了吗** |
|
||||
|
||||
这类问题的共同点:**三层各自看都对,只有真的跑一遍才看得见**。
|
||||
|
||||
> 最后一条是 v2.0.72 修「背景图设置不了」时补上的:用户选的是手机相册里的照片
|
||||
> (30~55MB),这条链路上有三堵墙,**每一堵单独看都合理**:
|
||||
> 前端把 55MB 原样 `readBytes` + base64;内核每条接口卡 4MB;异常被 `body()` 吞掉。
|
||||
> 现在的分工是:前端**先把位图压到 3MB 以内**(`ui/ImagePick.kt`,GIF/SVG 不压,
|
||||
> 因为缩放会丢动画、栅格化会毁矢量),内核把**上传类**接口的上限统一放到
|
||||
> `UPLOAD_BODY_LIMIT`(图片 + 四种包导入),并且读不出来时**如实报原因**。
|
||||
|
||||
---
|
||||
|
||||
@@ -27,7 +83,7 @@
|
||||
| 3.7 幻觉调用检测 | `kernel/agent_loop.py: check_hallucinated_memory` + 对话页警示条 |
|
||||
| 4.1 本次对话用量 | `ui/ChatScreen.kt: SessionUsageBar` |
|
||||
| 附录 A UUID 主键 | `kernel/store.py: create_agent` / `create_resource` |
|
||||
| 附录 B 六个工具 | `kernel/agent_tools.py: AGENT_TOOLS` |
|
||||
| 附录 B 工具清单 | `kernel/agent_tools.py: AGENT_TOOLS`(v1.2 后共 11 个:v1.1 的 7 个 + `change_stat` / `grant_status` / `invite_agent` / `pass_turn`) |
|
||||
| 附录 C 提示词模板 | `kernel/agent_context.py` + `kernel/defaults.py: DEFAULT_PROMPT_TEMPLATE` |
|
||||
| 附录 D 包格式 | `kernel/agent_api.py` + `docs/智能体系统.md` 第 4 节 |
|
||||
|
||||
@@ -194,14 +250,28 @@ assets/… # 四件套图片(front / back / border-main / border-in
|
||||
|
||||
| 脚本 | 验什么 |
|
||||
|---|---|
|
||||
| `python scripts/probe-agent-system.py` | 12 节 70+ 项:UUID、记忆 CRUD、pinned、共享限权、提示词注入顺序、20 多个接口、包导入导出边界、多模型解析 |
|
||||
| `python scripts/probe-agent-system.py` | 23 节:UUID、记忆 CRUD、pinned、共享限权、提示词注入顺序、20 多个接口、包导入导出边界、多模型解析、数值/状态、外观槽位、**上传请求体上限和错误信息** |
|
||||
| `python scripts/probe-degraded.py` | 幻觉检测(该报的报、不该报的不报)+ 降级调用的解析/执行/剥离/坏输入 |
|
||||
| `python scripts/probe-rule-engine.py` | 数值/状态的定义、钳制、脚本、状态过期 |
|
||||
| `python scripts/probe-rule-sandbox.py` | 脚本沙箱挡得住什么、挡不住什么 |
|
||||
| `python scripts/probe-context-window.py` | 成批对齐裁剪 + 重要标记破格携带 |
|
||||
| `python scripts/probe-group-chat.py` | 群聊点名制仲裁 |
|
||||
| `python scripts/audit-ui-tree.py` | 文档里的界面和代码是否一致 |
|
||||
| `python scripts/audit-ui-entries.py` | 每个界面都有入口(没有死代码) |
|
||||
|
||||
两个都**不需要装机、不需要网络**:把 `DOUBAO_DATA` 指到一个临时目录,
|
||||
八个都不需要装机、不需要网络:把 `DOUBAO_DATA` 指到一个临时目录,
|
||||
内核的存储层是无状态的,整条链路就能在一个进程里跑完。
|
||||
|
||||
**比装机验证快得多,而且能断言具体字段**(截图只能看个大概)。
|
||||
|
||||
### 写探针的一条硬纪律:走**生产同一条**调用路径
|
||||
|
||||
第 22 节直接调 `_set_asset(...)`,于是它**永远测不到**卡住真机的那一层 ——
|
||||
上限是在 `handle()` 里的 `body()` 卡的。结果:探针全绿,真机选一张照片就挂。
|
||||
|
||||
所以第 23 节改成 `h.call('/api/agents/<id>/asset', 'POST', {...})`,
|
||||
从 HTTP 路径进去,一路走到存储。**能绕过的那一层,就是下次会出问题的那一层。**
|
||||
|
||||
### 改内核之后必须做的一件事
|
||||
|
||||
```bash
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""校验 `docs/界面总览.md` 和 Kotlin 源码一致。
|
||||
"""校验 `docs/界面总览.md` 和 Kotlin 源码一致。
|
||||
|
||||
## 为什么需要它
|
||||
|
||||
@@ -70,10 +70,10 @@ SCREENS = {
|
||||
"编辑记忆": ["MemoryScreen"], # 弹窗,属于记忆页
|
||||
"窗口设置": ["MemoryScreen"],
|
||||
"合并/覆盖": ["MemoryScreen"],
|
||||
# ---- v1.2 §6.2 新增的三个界面(还没写代码,见 PLANNED)----
|
||||
# ---- v1.2 §6.2 新增的界面 ----
|
||||
"群成员": ["GroupMembersScreen"],
|
||||
"规则包编辑": ["RulePackScreen"],
|
||||
"状态数值": ["StatsScreen"],
|
||||
"规则包编辑": ["RulePackEditScreen"],
|
||||
"状态数值": ["AgentStatsScreen"],
|
||||
}
|
||||
|
||||
#: 这些 `*Screen` 组件**不是**独立界面,不进文档树
|
||||
@@ -88,9 +88,10 @@ SKELETON = {
|
||||
#:
|
||||
#: 落地之后**必须从这里删掉**,否则它就成了一张永久的免罪符。
|
||||
PLANNED = {
|
||||
"群成员": "v1.2 §6.2",
|
||||
"规则包编辑": "v1.2 §6.2",
|
||||
"状态数值": "v1.2 §6.2",
|
||||
# ★ v1.2 §6.2 的三个新界面([群成员] / [状态数值] / [规则包编辑])
|
||||
# 到 v2.0.62 全部落地,所以这里**空了** —— 这是好事:
|
||||
# 任何"计划中"的东西一落地就该从这里删掉,
|
||||
# 留着就成了永久的免罪符(文档里不写也没人管)。
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -74,12 +74,19 @@ class FakeHandler:
|
||||
def __init__(self):
|
||||
self.status = 200
|
||||
self.payload = None
|
||||
#: 设一个消息就模拟"请求体读不出来"(太大 / 不是合法 JSON)
|
||||
self.body_error_exc = None
|
||||
#: 记下这次收到的 limit —— 用来断言"图片这条路真的被单独放行了"
|
||||
self.last_limit = None
|
||||
|
||||
def send_json(self, code, payload):
|
||||
self.status = code
|
||||
self.payload = payload
|
||||
|
||||
def read_json_body(self, *a, **k):
|
||||
self.last_limit = a[0] if a else k.get('limit')
|
||||
if self.body_error_exc is not None:
|
||||
raise ValueError(self.body_error_exc)
|
||||
return self._body
|
||||
|
||||
def call(self, pathname, method, body=None):
|
||||
@@ -678,6 +685,224 @@ def main():
|
||||
check("老库的 token_usage 能加上缓存两列", {"cache_hit", "cache_miss"} <= tcols, str(sorted(tcols)))
|
||||
conn_old_tu.close()
|
||||
|
||||
# ---------------------------------------------------------------- 22
|
||||
section("22. 外观槽位接口(真机上报过 500 / 图不见了)")
|
||||
#
|
||||
# ★★ 这一节是**真机反馈**倒逼出来的,两个 bug 都在这里:
|
||||
# ① `_set_asset` 里 `key` 变量被删了 → NameError → 接口 500
|
||||
# → 表现"角色图设置不了"(任何图都传不上去)
|
||||
# ② `_apply_agent_patch` 对 image 的每个值调 `_as_text`
|
||||
# → `front`(字典)被存成字符串化的字典
|
||||
# → 表现"之前设置的图像也没了"(档位读不出来 + 每读写一次多包一层)
|
||||
#
|
||||
# 教训:**探针没覆盖到的接口 = 没写过**。这个接口当时一条断言都没有。
|
||||
import agent_api as _api
|
||||
|
||||
class _H:
|
||||
def __init__(self):
|
||||
self.status = 200
|
||||
self.payload = None
|
||||
|
||||
def send_json(self, code, payload):
|
||||
self.status, self.payload = code, payload
|
||||
|
||||
hh = _H()
|
||||
|
||||
def _err(code, msg):
|
||||
hh.status, hh.payload = code, {'error': msg}
|
||||
|
||||
art_agent = store.create_agent({'name': '外观测试'})
|
||||
aid = art_agent['id']
|
||||
_small = ('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8'
|
||||
'z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==')
|
||||
|
||||
def put(key, data=_small, name='t.png'):
|
||||
hh.status, hh.payload = 200, None
|
||||
_api._set_asset(hh, 'agents', aid, {'key': key, 'name': name, 'data': data}, _err)
|
||||
return hh.status, hh.payload or {}
|
||||
|
||||
st, pl = put('front:喜')
|
||||
check("① 传「喜」档不再 500(真机就是这里挂的)", st == 200, f"{st} {pl}")
|
||||
check("返回里带 slot", pl.get('slot') == '喜', str(pl.get('slot')))
|
||||
st, pl = put('front')
|
||||
check("不带档位的 front 视为「平常」(兼容旧界面)", pl.get('slot') == '平常', str(pl.get('slot')))
|
||||
st, pl = put('front:死亡')
|
||||
check("「死亡」档也能传", st == 200 and pl.get('slot') == '死亡', f"{st} {pl}")
|
||||
st, pl = put('back')
|
||||
check("背景图能传", st == 200, f"{st} {pl}")
|
||||
st, pl = put('front:乱写')
|
||||
check("乱写的档位被拒(400 不是 500)", st == 400, f"{st} {pl}")
|
||||
|
||||
# ★★ 存下来的形状必须是**字典**,不是字符串化的字典
|
||||
img = (store.get_agent(aid) or {}).get('image') or {}
|
||||
front = img.get('front')
|
||||
check("**front 存下来还是字典**(不是字符串化)", isinstance(front, dict), str(type(front)))
|
||||
check("三个档位都在", set(front or {}) >= {'喜', '平常', '死亡'}, str(front))
|
||||
for k, v in (front or {}).items():
|
||||
check(f"档位「{k}」的值是**路径字符串**不是嵌套字典",
|
||||
isinstance(v, str) and not v.strip().startswith('{'), str(v)[:40])
|
||||
|
||||
# 回退链要能用
|
||||
check("回退链:preset=喜 命中自己的档", bool(_api.portrait_of(img, '喜')))
|
||||
check("回退链:preset=怒 退到平常", bool(_api.portrait_of(img, '怒')))
|
||||
|
||||
# 清空一个档
|
||||
st, pl = put('front:喜', data='')
|
||||
check("传空 data = 清掉那一档", st == 200 and pl.get('cleared') is True, f"{st} {pl}")
|
||||
img2 = (store.get_agent(aid) or {}).get('image') or {}
|
||||
check("清掉之后「喜」不在字典里了", '喜' not in (img2.get('front') or {}), str(img2.get('front')))
|
||||
check("别的档**没被连累**", '平常' in (img2.get('front') or {}), str(img2.get('front')))
|
||||
|
||||
# ★★ 老脏数据要能救回来(用户磁盘上可能真的有)
|
||||
shelled = store.normalize_image({'front': "{'平常': 'C:/x/a.png'}"})
|
||||
check("字符串化的字典能解套", shelled.get('front') == {'平常': 'C:/x/a.png'}, str(shelled.get('front')))
|
||||
nested = store.normalize_image({'front': {'平常': "{'平常': 'C:/y/b.png'}"}})
|
||||
check("嵌套一层也能摊平", nested.get('front') == {'平常': 'C:/y/b.png'}, str(nested.get('front')))
|
||||
check("解不开的垃圾文本当空处理(不抛异常)",
|
||||
store.normalize_image({'front': '{不是字典}'}).get('front') == {},
|
||||
str(store.normalize_image({'front': '{不是字典}'}).get('front')))
|
||||
check("老格式(单个文件名)还是认",
|
||||
store.normalize_image({'front': 'old.png'}).get('front') == {'平常': 'old.png'})
|
||||
|
||||
# ---------------------------------------------------------------- 23
|
||||
section("23. 大图上传:请求体上限 + 错误信息(真机上报过「背景图设置不了」)")
|
||||
#
|
||||
# ★★ 真机现场:用户选的是**手机相册里的照片**(30~55MB),base64 之后
|
||||
# 38~73MB。read_json_body 的默认上限是 4MB,于是请求体一进去就被判
|
||||
# 「请求体过大」;而那个异常被 body() 吞成空 dict,
|
||||
# 最后报出来的是「不认识的外观槽位」—— 和真实原因毫无关系的一句话,
|
||||
# 用户只看到"设置不了",查的人也会往槽位名上去找。
|
||||
#
|
||||
# ★ 这一节**必须走 handle()**,不能像上一节那样直接调 _set_asset:
|
||||
# 上限是在 handle 里的 `body()` 那一层卡的,绕过它就等于没测。
|
||||
# (第 22 节正是直接调 _set_asset 的 —— 所以它一直没盖到这条路径。)
|
||||
big = store.create_agent({'name': '大图测试'})
|
||||
big_id = big['id']
|
||||
|
||||
h.body_error_exc = None
|
||||
h.last_limit = None
|
||||
pl = h.call(f'/api/agents/{big_id}/asset', 'POST',
|
||||
{'key': 'back', 'name': 'bg.png', 'data': _small})
|
||||
check("图片上传正常返回", h.status == 200 and bool(pl.get('path')), f"{h.status} {pl}")
|
||||
check("图片这条路的请求体上限被单独放行(不是默认的 4MB)",
|
||||
h.last_limit == _api.UPLOAD_BODY_LIMIT,
|
||||
f"实际收到 {h.last_limit},期望 {_api.UPLOAD_BODY_LIMIT}")
|
||||
|
||||
# 两个上限必须自洽:内核允许单张图到 20MB,base64 之后是 4/3 倍。
|
||||
# 请求体上限比它小的话,就会出现"内核说这图可以,通道却传不进来"
|
||||
need = 20 * 1024 * 1024 * 4 // 3
|
||||
check("请求体上限装得下内核允许的最大图(20MB → base64 约 27MB)",
|
||||
_api.UPLOAD_BODY_LIMIT > need,
|
||||
f"{_api.UPLOAD_BODY_LIMIT} 要 > {need}")
|
||||
|
||||
# ★★ 请求体读失败时,必须报真正的原因
|
||||
h.body_error_exc = '请求体过大'
|
||||
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': 'back', 'data': _small})
|
||||
check("请求体读不出来时报的是真原因",
|
||||
h.status == 400 and '请求体过大' in str(pl.get('error', '')),
|
||||
f"{h.status} {pl}")
|
||||
check("不再把「请求体过大」伪装成「不认识的外观槽位」",
|
||||
'不认识的外观槽位' not in str(pl.get('error', '')),
|
||||
str(pl.get('error')))
|
||||
h.body_error_exc = None
|
||||
|
||||
# 正常的参数错误不能被这次改动带坏
|
||||
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': '乱写的槽位', 'data': _small})
|
||||
check("槽位名写错仍然报「不认识的外观槽位」",
|
||||
h.status == 400 and '不认识的外观槽位' in str(pl.get('error', '')),
|
||||
f"{h.status} {pl}")
|
||||
|
||||
# 上一次的失败不能跟着到下一个请求上(body_error 是挂在 handler 上的)
|
||||
pl = h.call(f'/api/agents/{big_id}/asset', 'POST', {'key': 'back', 'data': _small})
|
||||
check("上一次失败不污染下一次请求", h.status == 200 and 'error' not in pl, f"{h.status} {pl}")
|
||||
|
||||
# 世界观走的是同一个 _set_asset —— 上限也得跟上,别只改一边
|
||||
world = store.create_resource('worldviews', {'name': '大图世界观', 'setting': ''}) or {}
|
||||
world_id = world.get('id')
|
||||
if world_id:
|
||||
h.last_limit = None
|
||||
pl = h.call(f'/api/worldviews/{world_id}/asset', 'POST', {'key': 'back', 'data': _small})
|
||||
check("世界观那条路也放行了(同一个 _set_asset,别只改一边)",
|
||||
h.status == 200 and h.last_limit == _api.UPLOAD_BODY_LIMIT,
|
||||
f"{h.status} limit={h.last_limit} {pl}")
|
||||
|
||||
# ★ 同一类坑还有四处:四种**包导入**也是 base64 进 JSON。
|
||||
# 带外观图片的智能体包 zip 上到十几 MB,走默认的 4MB 一样进不来。
|
||||
# 这里不要求导入成功(空包必然失败),只要求**上限确实传下去了**。
|
||||
for path in ('/api/agents/import', '/api/worldviews/import', '/api/rulepacks/import'):
|
||||
h.last_limit = None
|
||||
h.call(path, 'POST', {})
|
||||
check(f"{path} 也放行了(包里有图片时才不会卡在 4MB)",
|
||||
h.last_limit == _api.UPLOAD_BODY_LIMIT,
|
||||
f"limit={h.last_limit}")
|
||||
|
||||
# ---------------------------------------------------------------- 24
|
||||
section("24. 换图时新旧同名(真机上报过「同一张图传第二次就没了」)")
|
||||
#
|
||||
# ★★ 落盘名是 `<槽位>-<原始文件名>`,所以**同一个文件传第二次时新旧同名**。
|
||||
# 原来的顺序是"写新的 → 删旧的",而旧路径正好就是新路径 ——
|
||||
# 刚写的那张被自己删掉,image 里留下一个指向不存在文件的路径:
|
||||
# 资源目录空着,界面回退到默认图。表现是"第二次传同一张图就没了"。
|
||||
#
|
||||
# 第一次传时名字来自 SAF 的 segment(`image_1000018033` 这种),
|
||||
# 和第二次不同名,所以随手试一次碰不到 —— 必须**故意传两次同名**才复现。
|
||||
twice = store.create_agent({'name': '重传测试'})
|
||||
tid = twice['id']
|
||||
|
||||
def put_named(key, name):
|
||||
return h.call(f'/api/agents/{tid}/asset', 'POST',
|
||||
{'key': key, 'name': name, 'data': _small})
|
||||
|
||||
pl1 = put_named('back', 'same.png')
|
||||
path1 = pl1.get('path') or ''
|
||||
check("第一次传:文件确实落了盘", bool(path1) and os.path.isfile(path1), path1)
|
||||
|
||||
pl2 = put_named('back', 'same.png')
|
||||
path2 = pl2.get('path') or ''
|
||||
check("第二次传同名文件:路径不变(本来就是同一个文件)", path1 == path2, f"{path1} vs {path2}")
|
||||
check("**第二次传完文件还在**(旧版在这里把它自己删了)",
|
||||
bool(path2) and os.path.isfile(path2),
|
||||
f"{path2} 存在={os.path.isfile(path2) if path2 else None}")
|
||||
img = (store.get_agent(tid) or {}).get('image') or {}
|
||||
check("image 里指的是一个真实存在的文件",
|
||||
bool(img.get('back')) and os.path.isfile(img['back']), str(img.get('back')))
|
||||
|
||||
# 立绘那条分支是同一份逻辑,也要过一遍 —— 别只修一边
|
||||
pf1 = put_named('front:喜', 'same.png')
|
||||
pf2 = put_named('front:喜', 'same.png')
|
||||
fpath = pf2.get('path') or ''
|
||||
check("立绘连传两次同名文件也还在", bool(fpath) and os.path.isfile(fpath),
|
||||
f"{fpath} 存在={os.path.isfile(fpath) if fpath else None}")
|
||||
check("立绘两次的路径相同", (pf1.get('path') or '') == fpath, f"{pf1.get('path')} vs {fpath}")
|
||||
|
||||
# ★ 反向:换一张**不同名**的图时,旧文件必须真的被清掉
|
||||
# (别为了修上面的问题,把"不然越攒越多"的清理一起弄没了)
|
||||
pl3 = put_named('back', 'other.png')
|
||||
path3 = pl3.get('path') or ''
|
||||
check("换不同名的新图:新文件在", bool(path3) and os.path.isfile(path3), path3)
|
||||
check("换不同名的新图:**旧文件被清掉了**", not os.path.isfile(path2), f"{path2} 还在")
|
||||
|
||||
# ---------------------------------------------------------------- 25
|
||||
section("25. 工具调用明细要落库(真机反馈「工具怎么重启就不显示了」)")
|
||||
#
|
||||
# ★ 界面上那些"工具卡片"(调了什么、成没成、返回什么)以前只有**流式那一刻**
|
||||
# 看得到 —— 因为这份明细从来没落过库,重启 App 就全没了。
|
||||
# 现在 `agent_loop` 收集 → `app.py` 落进消息 → 客户端解析。
|
||||
# 三处缺一处都白搭,所以逐处断言(这是"改一半"的高发区)。
|
||||
_kd = os.path.dirname(os.path.abspath(__file__))
|
||||
_loop = open(os.path.join(_kd, '..', 'android', 'kernel', 'agent_loop.py'),
|
||||
encoding='utf-8').read()
|
||||
_app2 = open(os.path.join(_kd, '..', 'android', 'kernel', 'app.py'),
|
||||
encoding='utf-8').read()
|
||||
check("agent_loop 收集了明细",
|
||||
'tool_trace = []' in _loop and 'tool_trace.append(' in _loop,
|
||||
"没有 tool_trace —— 工具卡片只在流式那一刻存在")
|
||||
check("agent_loop 把它放进了**两条** return(正常收尾 + 轮次用尽)",
|
||||
_loop.count("'toolTrace': tool_trace") >= 2,
|
||||
f"只有 {_loop.count(chr(39) + 'toolTrace' + chr(39) + ': tool_trace')} 处")
|
||||
check("app.py 落库时存了它", "'toolTrace': result.get('toolTrace')" in _app2,
|
||||
"engine 收好了但没存 —— 重启照样没")
|
||||
|
||||
# ---------------------------------------------------------------- 汇总
|
||||
print()
|
||||
if fails:
|
||||
|
||||
207
scripts/probe-context-window.py
Normal file
@@ -0,0 +1,207 @@
|
||||
"""对话上下文窗口的探针(v1.2 §4.3)。
|
||||
|
||||
纯函数,所以能逐条钉死。重点在**成批对齐**那条 —— 它最容易实现成
|
||||
"超一点就裁一点",那样每轮前缀都变、缓存一次都命中不了,
|
||||
**比不裁还贵**,而且从界面上完全看不出来(功能是对的、只是变慢了)。
|
||||
|
||||
用法:`python scripts/probe-context-window.py`
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-ctx-")
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
if cond:
|
||||
print(f" ✓ {label}")
|
||||
else:
|
||||
fails.append(label)
|
||||
print(f" ✗ {label} {detail}")
|
||||
|
||||
|
||||
import context_window as W # noqa: E402
|
||||
|
||||
|
||||
def convo(n, important_at=()):
|
||||
"""造 n 轮对话(每轮 user + assistant);important_at 里的轮号标成重要"""
|
||||
out = []
|
||||
for i in range(n):
|
||||
out.append({'role': 'user', 'content': f'问{i}',
|
||||
'important': i in important_at})
|
||||
out.append({'role': 'assistant', 'content': f'答{i}'})
|
||||
return out
|
||||
|
||||
|
||||
def rounds_of(msgs):
|
||||
"""数一下这批消息里有几轮(受支持的最长连续)"""
|
||||
return len(W.split_rounds(msgs))
|
||||
|
||||
|
||||
def main():
|
||||
print("\n=== 1. 没超窗口:全带 ===")
|
||||
r = W.trim(convo(5), rounds=20)
|
||||
check("5 轮 < 20 轮 → 全带", r['kept'] == 10 and r['dropped'] == 0, str(r))
|
||||
check("reason 是空(没动过)", r['reason'] == '', str(r['reason']))
|
||||
|
||||
print("\n=== 2. ★ 成批对齐:超一点**不裁**(这条最容易做错)===")
|
||||
#
|
||||
# 窗口 20、批量 5:21 轮时超出 1 轮 —— 应当**原样放行**。
|
||||
# 实现成"超了就裁"的话,每轮都会裁掉一条 → 前缀每轮都变 → 缓存全废。
|
||||
for extra, should_cut in ((1, False), (3, False), (4, False), (5, True), (7, True), (12, True)):
|
||||
n = 20 + extra
|
||||
r = W.trim(convo(n), rounds=20, batch=5)
|
||||
cut = r['reason'] == 'window'
|
||||
check(f"{n} 轮(超 {extra} 轮)→ {'裁' if should_cut else '先不动'}",
|
||||
cut == should_cut, f"reason={r['reason']} kept={r['kept']}")
|
||||
# 裁的时候要对齐到 batch 的倍数
|
||||
r = W.trim(convo(27), rounds=20, batch=5)
|
||||
check("27 轮(超 7)→ 裁 5 轮留 22 轮", r['keptRounds'] == 22, str(r))
|
||||
r = W.trim(convo(32), rounds=20, batch=5)
|
||||
check("32 轮(超 12)→ 裁 10 轮留 22 轮", r['keptRounds'] == 22, str(r))
|
||||
r = W.trim(convo(25), rounds=20, batch=5)
|
||||
check("25 轮(超 5)→ 正好裁 5 轮留 20 轮", r['keptRounds'] == 20, str(r))
|
||||
|
||||
print("\n=== 3. 按完整轮对齐,绝不裁半轮 ===")
|
||||
for n in (21, 25, 27, 32, 50):
|
||||
r = W.trim(convo(n), rounds=20, batch=5)
|
||||
msgs = r['messages']
|
||||
# 一条 assistant 前面必须紧跟着它那一轮的 user
|
||||
bad = [i for i, m in enumerate(msgs)
|
||||
if m['role'] == 'assistant' and (i == 0 or msgs[i - 1]['role'] != 'user')]
|
||||
check(f"{n} 轮裁完没有孤立的 assistant", not bad, str(bad[:3]))
|
||||
# 保留的条数必须是偶数(整轮)
|
||||
check(f"{n} 轮裁完是整轮(条数是偶数)", len(msgs) % 2 == 0, str(len(msgs)))
|
||||
|
||||
print("\n=== 4. 重要标记:破格携带、按原始时间序插回 ===")
|
||||
# 第 1、3 轮的 **user 消息**标了重要(assistant 没标)—— 它们会被裁掉
|
||||
r = W.trim(convo(30, important_at={1, 3}), rounds=20, batch=5)
|
||||
msgs = r['messages']
|
||||
contents = [m['content'] for m in msgs]
|
||||
check("裁掉的那批里的重要消息被捞回来了", r.get('rescued') == 2, str(r.get('rescued')))
|
||||
check("捞回来的在结果里", '问1' in contents and '问3' in contents, str(contents[:6]))
|
||||
# ★ 关键:**按原始时间序**插回,不是塞到最前面
|
||||
check("**按原始时间序插入,不是塞到最前面**",
|
||||
contents.index('问1') < contents.index('问10'),
|
||||
f"问1 在 {contents.index('问1')}、问10 在 {contents.index('问10')}")
|
||||
check("顺序整体单调(捞回的没打乱因果)",
|
||||
contents.index('问1') < contents.index('问3') < contents.index('问10'),
|
||||
str([contents.index(x) for x in ('问1', '问3', '问10')]))
|
||||
# 没标重要的那批就真的丢了
|
||||
check("没标记的轮次确实丢了(不做摘要、不假装记得)", '问0' not in contents)
|
||||
|
||||
print("\n=== 5. resolve:智能体 > 全局 > 默认 ===")
|
||||
check("都没配用默认 20/5", W.resolve({}, {}) == (20, 5), str(W.resolve({}, {})))
|
||||
check("全局配了就用全局", W.resolve({'contextWindow': 30, 'contextBatch': 3}, {}) == (30, 3))
|
||||
check("智能体配了压过全局",
|
||||
W.resolve({'contextWindow': 30}, {'contextWindow': 10})[0] == 10)
|
||||
check("超出上下限会被夹住", W.resolve({'contextWindow': 99999}, {})[0] == W.MAX_ROUNDS)
|
||||
check("填 0 / 乱填回落到默认",
|
||||
W.resolve({'contextWindow': 0}, {})[0] == 20 and W.resolve({'contextWindow': 'x'}, {})[0] == 20)
|
||||
|
||||
print("\n=== 6. ★ 字节冻结:绝不原地改历史 ===")
|
||||
src = [{'role': 'user', 'content': '原话', 'important': True, 'usage': {'input': 5}}]
|
||||
snapshot = [dict(m) for m in src]
|
||||
out = W.strip_for_model(src[0])
|
||||
check("输出只留 role/content(界面字段不带进模型)",
|
||||
set(out.keys()) == {'role', 'content'}, str(sorted(out)))
|
||||
check("**原对象一个字节都没动**", src == snapshot, str(src))
|
||||
check("输出是**新对象**(不是同一个引用)", out is not src[0])
|
||||
r = W.trim(src, rounds=20)
|
||||
check("trim 不改原列表的元素(字节冻结)", src == snapshot, str(src))
|
||||
# ★ 这里比的是**身份**不是内容:内容本来就该一样,要确认的是
|
||||
# 返回的是一个**新列表**(调用方拿到之后改它,不能影响到传进去的那个)
|
||||
check("trim 返回的是新列表(不是同一个引用)", r['messages'] is not src)
|
||||
|
||||
print("\n=== 7. 边界 ===")
|
||||
check("空历史不炸", W.trim([], 20)['kept'] == 0)
|
||||
check("rounds=0 表示不限", W.trim(convo(100), 0)['dropped'] == 0)
|
||||
check("全是 user(没有 assistant)也能切轮",
|
||||
W.split_rounds([{'role': 'user', 'content': 'a'}, {'role': 'user', 'content': 'b'}]).__len__() == 2)
|
||||
check("非 dict 的东西被跳过", W.trim([{'role': 'user'}, 'noise', None], 20)['kept'] == 1)
|
||||
check("describe 不炸", isinstance(W.describe(W.trim(convo(30), 20, 5)), str))
|
||||
|
||||
print("\n=== 8. 标记重要:从存储到裁剪的整条路 ===")
|
||||
#
|
||||
# 这一节测的是**端到端**:界面调接口 → 存库 → 裁剪时读它。
|
||||
# 中间任何一环断了,用户看到的现象都是"我标了,但它还是被裁掉了"。
|
||||
import store
|
||||
|
||||
conv = store.create_conversation('测试', agent_id='A')
|
||||
store.append_messages(conv['id'], [
|
||||
{'role': 'user', 'content': '记住这句'},
|
||||
{'role': 'assistant', 'content': '好的'},
|
||||
])
|
||||
check("新消息默认没标记", not (store.get_conversation(conv['id'])['messages'][0].get('important')))
|
||||
m = store.mark_important(conv['id'], 0, True)
|
||||
check("标记上了", m and m.get('important') is True, str(m))
|
||||
# ★ 关键:标记**不能动 content**(需求 4.3 的"字节冻结")
|
||||
check("**content 一个字节都没动**(字节冻结)", m.get('content') == '记住这句', str(m))
|
||||
check("越界下标返回 None(不抛异常)", store.mark_important(conv['id'], 99, True) is None)
|
||||
check("不存在的会话返回 None", store.mark_important('nope', 0, True) is None)
|
||||
check("能取消标记", store.mark_important(conv['id'], 0, False).get('important') is False)
|
||||
# 端到端:标过的消息在裁剪时被捞回
|
||||
msgs = []
|
||||
for i in range(30):
|
||||
msgs.append({'role': 'user', 'content': f'问{i}', 'important': i == 0})
|
||||
msgs.append({'role': 'assistant', 'content': f'答{i}'})
|
||||
r = W.trim(msgs, 20, 5)
|
||||
check("端到端:标记过的老消息**没被裁掉**",
|
||||
any(m['content'] == '问0' for m in r['messages']), str(r.get('rescued')))
|
||||
check("没标记的老消息被裁掉了", not any(m['content'] == '问5' for m in r['messages']))
|
||||
|
||||
print("\n=== 9. ★★ 按内容定位(下标定位踩过的坑)===")
|
||||
#
|
||||
# 界面上那份消息列表和存储里那份**不保证一一对应**(本地生成的内容、
|
||||
# 还没落地的流式消息……)。按下标"长按第 3 条"会把标记打到第 1 条上,
|
||||
# 而且**静默标错** —— 真机上就是这么错的。
|
||||
c3 = store.create_conversation('定位', agent_id='A')
|
||||
store.append_messages(c3['id'], [
|
||||
{'role': 'user', 'content': '第一句'},
|
||||
{'role': 'assistant', 'content': '回一句'},
|
||||
{'role': 'user', 'content': '第三句'},
|
||||
])
|
||||
m = store.mark_important_by_content(c3['id'], '第三句', 'user', True)
|
||||
check("按内容标到了**那一条**", m and m.get('content') == '第三句', str(m))
|
||||
flags = [(x['content'], bool(x.get('important')))
|
||||
for x in store.get_conversation(c3['id'])['messages']]
|
||||
check("**只标了那一条**(别的没被误标)",
|
||||
flags == [('第一句', False), ('回一句', False), ('第三句', True)], str(flags))
|
||||
check("内容对不上 → None(**绝不猜一条标上去**)",
|
||||
store.mark_important_by_content(c3['id'], '没有这句话', 'user', True) is None)
|
||||
check("空内容 → None", store.mark_important_by_content(c3['id'], '', 'user', True) is None)
|
||||
check("不存在的会话 → None", store.mark_important_by_content('nope', '第一句', 'user', True) is None)
|
||||
# 重复内容:从后往前找(用户长按的通常是靠后那条)
|
||||
c4 = store.create_conversation('重复', agent_id='A')
|
||||
store.append_messages(c4['id'], [
|
||||
{'role': 'user', 'content': '一样'},
|
||||
{'role': 'user', 'content': '别的'},
|
||||
{'role': 'user', 'content': '一样'},
|
||||
])
|
||||
store.mark_important_by_content(c4['id'], '一样', 'user', True)
|
||||
flags4 = [bool(x.get('important')) for x in store.get_conversation(c4['id'])['messages']]
|
||||
check("重复内容标**最后**一条(从后往前找)", flags4 == [False, False, True], str(flags4))
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
553
scripts/probe-group-chat.py
Normal file
@@ -0,0 +1,553 @@
|
||||
"""群聊仲裁的探针(v1.2 §3.9)。
|
||||
|
||||
点名制的分支有五种(用户 @ / AI 移交 / 兜底 / 被点的人死亡 / 一轮内重复移交),
|
||||
每一种都有明确的期望结果,而且**都不能报错**(报错的话用户看到的是
|
||||
"AI 卡住了",而不是"这一轮没人说话")。
|
||||
|
||||
用法:`python scripts/probe-group-chat.py`
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-group-")
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
if cond:
|
||||
print(f" ✓ {label}")
|
||||
else:
|
||||
fails.append(label)
|
||||
print(f" ✗ {label} {detail}")
|
||||
|
||||
|
||||
import agent_tools # noqa: E402
|
||||
import group_chat as G # noqa: E402
|
||||
import store # noqa: E402
|
||||
import tools_runtime # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
world = store.create_resource('worldviews', {'name': '九州'})
|
||||
a = store.create_agent({'name': '玄辰'})
|
||||
store.update_agent(a['id'], {'worldviewId': world['id']})
|
||||
a = store.get_agent(a['id'])
|
||||
b = store.create_agent({'name': '仙辰'})
|
||||
store.update_agent(b['id'], {'worldviewId': world['id']})
|
||||
b = store.get_agent(b['id'])
|
||||
outsider = store.create_agent({'name': '外人'})
|
||||
|
||||
print("\n=== 1. 会话字段(type / participants)===")
|
||||
conv = store.create_conversation('群聊', agent_id=a['id'], kind='group',
|
||||
participants=[a['id'], b['id']])
|
||||
check("type 存下来了", conv.get('type') == 'group', str(conv.get('type')))
|
||||
check("participants 存下来了", len(G.member_ids(conv)) == 2, str(G.member_ids(conv)))
|
||||
# ⚠️ `host_id` 现在**不再用于决定谁发言**(用户要求「群聊去掉主人设定」),
|
||||
# 只剩 remove_member 里「不能把最后一个人踢走」这一个用途。
|
||||
check("host_id 还在(但只表示「列表第一个」,不是发言优先级)",
|
||||
G.host_id(conv) == a['id'], G.host_id(conv))
|
||||
old = store.create_conversation('老会话')
|
||||
check("老会话默认是 single", (old.get('type') or 'single') == 'single')
|
||||
check("非法 type 会被规整成 single",
|
||||
store.create_conversation('x', kind='乱写').get('type') == 'single')
|
||||
|
||||
print("\n=== 2. 仲裁:五种分支 ===")
|
||||
names = [(x['id'], x['name']) for x in store.list_agents()]
|
||||
# ① 用户 @
|
||||
want = G.mention_in('@仙辰 你觉得呢', names)
|
||||
check("@ 能解析出人", want == b['id'], str(want))
|
||||
r = G.resolve(conv, want=want)
|
||||
check("① 被 @ 的人发言", r['speaker'] == b['id'] and r['reason'] == 'mention', str(r))
|
||||
# ② AI 移交
|
||||
r = G.resolve(conv, passed=b['id'], handoffs=0)
|
||||
check("② AI 移交的人发言", r['speaker'] == b['id'] and r['reason'] == 'handoff', str(r))
|
||||
# ③ 兜底:**按顺序轮,不设主人**(用户要求「群聊去掉主人设定」)
|
||||
r = G.resolve(conv)
|
||||
check("③ 没人点名时按顺序轮(新群从第一个开始)",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
|
||||
# ④ 被点的人死亡
|
||||
r = G.resolve(conv, passed=b['id'], alive={b['id']: False})
|
||||
check("④ **死亡的人接不了,换下一个人**",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
|
||||
check("④ 而且说明了原因(界面/日志能看懂)", '死亡' in str(r.get('note')), str(r.get('note')))
|
||||
# ⑤ 一轮内重复移交
|
||||
r = G.resolve(conv, passed=b['id'], handoffs=G.MAX_HANDOFF_PER_ROUND)
|
||||
check("⑤ 一轮内第二次移交被拒(换下一个人)",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'handoff_denied', str(r))
|
||||
# 用户 @ 不受"一轮一次"约束(那条只管 AI 的移交)
|
||||
r = G.resolve(conv, want=b['id'], handoffs=99)
|
||||
check("用户 @ 不受「一轮一次」限制(用户主权)", r['speaker'] == b['id'], str(r))
|
||||
|
||||
print("\n=== 3. @ 的解析细节 ===")
|
||||
names2 = [(a['id'], '玄辰'), (b['id'], '玄辰二号')]
|
||||
check("有重名前缀时取**最长**匹配(@玄辰二号 不该命中玄辰)",
|
||||
G.mention_in('@玄辰二号', names2) == b['id'],
|
||||
str(G.mention_in('@玄辰二号', names2)))
|
||||
check("精确匹配短的也对", G.mention_in('@玄辰', names2) == a['id'])
|
||||
check("没有 @ 时返回空", G.mention_in('随便说点什么', names2) == '')
|
||||
check("@ 不在成员里时返回空", G.mention_in('@路人', names2) == '')
|
||||
|
||||
print("\n=== 4. 成员增删(用户主权)===")
|
||||
c2 = store.create_conversation('群2', agent_id=a['id'], kind='group',
|
||||
participants=[a['id']])
|
||||
check("能加成员", G.add_member(c2, b['id']) is True)
|
||||
check("重复加返回 False(不重复不报错)", G.add_member(c2, b['id']) is False)
|
||||
check("**最后一个人不能被移出**(移掉群就空了)", G.remove_member(c2, a['id']) is False)
|
||||
check("普通成员能移出", G.remove_member(c2, b['id']) is True)
|
||||
# 单聊拉人 → 转成群聊
|
||||
single = store.create_conversation('单聊', agent_id=a['id'])
|
||||
check("单聊不是群聊", not G.is_group(single))
|
||||
G.promote(single, b['id'])
|
||||
check("拉人之后转成了群聊", G.is_group(single), str(single.get('type')))
|
||||
check("单聊原来那个人还在", a['id'] in G.member_ids(single), str(G.member_ids(single)))
|
||||
|
||||
print("\n=== 5. invite_agent 工具 ===")
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=single['id'])
|
||||
r = agent_tools.invite_agent({'target': '仙辰'})
|
||||
check("已在群里时返回 already(不报错)", r.get('already') is True, str(r))
|
||||
# 跨世界观
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||||
try:
|
||||
agent_tools.invite_agent({'target': '外人'})
|
||||
check("**跨世界观拉人一律拒绝**", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("**跨世界观拉人一律拒绝**", '世界观' in str(exc), str(exc))
|
||||
try:
|
||||
agent_tools.invite_agent({'target': '玄辰'})
|
||||
check("拉自己被拒", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("拉自己被拒", '自己' in str(exc), str(exc))
|
||||
# 需确认模式:不直接拉人,让 AI 去问
|
||||
store.update_agent(a['id'], {'inviteMode': 'confirm'})
|
||||
a2 = store.get_agent(a['id'])
|
||||
tools_runtime.push_context(agentId=a2['id'], conversationId=c2['id'])
|
||||
r = agent_tools.invite_agent({'target': '仙辰'})
|
||||
check("**需确认模式不直接拉人**", r.get('needConfirm') is True, str(r))
|
||||
check("需确认模式下人**没有**进群",
|
||||
b['id'] not in G.member_ids(store.get_conversation(c2['id']) or {}),
|
||||
str(G.member_ids(store.get_conversation(c2['id']) or {})))
|
||||
check("提示 AI 去问用户", '问' in str(r.get('note')), str(r.get('note')))
|
||||
# 静默模式:直接拉
|
||||
store.update_agent(a['id'], {'inviteMode': 'silent'})
|
||||
a3 = store.get_agent(a['id'])
|
||||
tools_runtime.push_context(agentId=a3['id'], conversationId=c2['id'])
|
||||
r = agent_tools.invite_agent({'target': '仙辰'})
|
||||
check("静默模式直接进群", r.get('joined') == '仙辰', str(r))
|
||||
check("人真的进群了",
|
||||
b['id'] in G.member_ids(store.get_conversation(c2['id']) or {}))
|
||||
|
||||
print("\n=== 6. pass_turn 工具 ===")
|
||||
# ★ 每次 `begin_round()` —— agent_loop 每轮开头会调它。
|
||||
# 不调的话上一节留下的 `used=True` 会让这里全变成"已经移交过"。
|
||||
tools_runtime.begin_round()
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||||
r = agent_tools.pass_turn({'target': '仙辰'})
|
||||
check("移交成功", r.get('handed_to') == '仙辰', str(r))
|
||||
# ★ 读**轮次状态**,不是工具上下文 —— 上下文是 thread-local,
|
||||
# 工具跑在 worker 线程里写的东西回不来(这就是当初失效的原因)
|
||||
check("轮次状态里记了移交标记", tools_runtime.handoff_state().get('used') is True,
|
||||
str(tools_runtime.handoff_state()))
|
||||
check("也记了交给谁", tools_runtime.handoff_state().get('to') == b['id'],
|
||||
str(tools_runtime.handoff_state()))
|
||||
# 一轮内第二次:拒
|
||||
try:
|
||||
agent_tools.pass_turn({'target': '仙辰'})
|
||||
check("**一轮最多移交一次**", False, "第二次数居然允许了")
|
||||
except ValueError as exc:
|
||||
check("**一轮最多移交一次**", '已经移交过' in str(exc), str(exc))
|
||||
# 死亡目标:拒,而且理由是"死亡"不是"已移交"
|
||||
import agentdb
|
||||
dead = store.create_agent({'name': '死者'})
|
||||
store.update_agent(dead['id'], {'worldviewId': world['id']})
|
||||
agentdb.emotion_set(dead['id'], preset='死亡')
|
||||
tools_runtime.begin_round() # 开新一轮,否则先撞上"已经移交过"
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||||
try:
|
||||
agent_tools.pass_turn({'target': '死者'})
|
||||
check("**死亡目标移交无效**", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("**死亡目标移交无效**", '死亡' in str(exc), str(exc))
|
||||
check("理由说的是死亡,不是别的", '已经移交过' not in str(exc), str(exc))
|
||||
tools_runtime.begin_round()
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'])
|
||||
try:
|
||||
agent_tools.pass_turn({'target': '玄辰'})
|
||||
check("交给自己被拒", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("交给自己被拒", '自己' in str(exc), str(exc))
|
||||
tools_runtime.begin_round()
|
||||
|
||||
print("\n=== 7. 附录 B 的工具清单齐了吗 ===")
|
||||
for want in ('memory_add', 'memory_update', 'memory_forget', 'memory_search',
|
||||
'emotion_set', 'get_token_usage', 'change_stat', 'grant_status',
|
||||
'invite_agent', 'pass_turn', 'talk_to'):
|
||||
check(f"有 {want}", want in agent_tools.AGENT_TOOLS)
|
||||
# 附录 B 列了 10 个,外加"建议机制"(memory_suggest_summary)
|
||||
# 和新增的 talk_to(用户要求:智能体主动找另一个智能体说话)= 12
|
||||
check("一共 12 个(附录 B 的 10 个 + 建议机制 + talk_to)",
|
||||
len(agent_tools.AGENT_TOOLS) == 12,
|
||||
str(sorted(agent_tools.AGENT_TOOLS)))
|
||||
|
||||
print("\n=== 8. ★★ 走真实路径测 pass_turn(旧探针是假通过)===")
|
||||
#
|
||||
# ★★ 这一节**必须**走 `tools_runtime.execute_tool`。
|
||||
#
|
||||
# 它会把上下文复制到 **worker 线程** 去执行(`run_with_timeout` 起线程),
|
||||
# 而 `_ctx` 是 thread-local —— 工具在 worker 里写的东西**回不到主线程**。
|
||||
#
|
||||
# 旧探针直接调 `agent_tools.pass_turn`(主线程),标记留在主线程里
|
||||
# 没被清,于是"一轮最多一次"看着是好的 —— **假通过**,
|
||||
# 而真机上每一轮都能无限次移交(`handoffUsed` 永远是 False)。
|
||||
#
|
||||
# 教训:**探针的调用路径必须和真实调用路径一致**。
|
||||
# 直接调函数测的是"函数逻辑对不对",不是"它在这个系统里生不生效"。
|
||||
settings = store.read_settings()
|
||||
c2 = store.create_conversation('群2', agent_id=a['id'], kind='group',
|
||||
participants=[a['id'], b['id']])
|
||||
|
||||
def real_call(name: str, args: dict):
|
||||
"""走真实的工具调用路径(含 worker 线程 + 上下文重置)"""
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=c2['id'], toolName=name)
|
||||
try:
|
||||
return tools_runtime.execute_tool(name, args, settings)
|
||||
finally:
|
||||
tools_runtime.clear_context()
|
||||
|
||||
tools_runtime.begin_round() # agent_loop 每轮开头会调这个
|
||||
r1 = real_call('pass_turn', {'target': '仙辰'})
|
||||
check("真实路径:第 1 次移交成功", r1.get('ok') is True, str(r1))
|
||||
st = tools_runtime.handoff_state()
|
||||
check("**移交目标跨线程保住了**(这是旧实现丢掉的那个)",
|
||||
st.get('to') == b['id'], str(st))
|
||||
check("状态标成 used", st.get('used') is True, str(st))
|
||||
r2 = real_call('pass_turn', {'target': '仙辰'})
|
||||
check("真实路径:**第 2 次被拒**(一轮最多一次真的生效了)",
|
||||
r2.get('ok') is False and '已经移交过' in str(r2.get('error')), str(r2))
|
||||
# app.py 从轮次状态取(不是从 HTTP body —— 界面根本不发那个字段)
|
||||
check("移交目标能被 app.py 读到(仲裁的 ② 分支不再是死代码)",
|
||||
tools_runtime.handoff_state().get('to') == b['id'], str(tools_runtime.handoff_state()))
|
||||
# 新一轮开始要重置
|
||||
tools_runtime.begin_round()
|
||||
check("新一轮开始后重置(可以再移交)",
|
||||
tools_runtime.handoff_state() == {'to': '', 'used': False},
|
||||
str(tools_runtime.handoff_state()))
|
||||
r3 = real_call('pass_turn', {'target': '仙辰'})
|
||||
check("新一轮里又能移交了", r3.get('ok') is True, str(r3))
|
||||
tools_runtime.begin_round()
|
||||
|
||||
print("\n=== 9. 私聊:轮数解析与额度判据 ===")
|
||||
import private_chat as P
|
||||
|
||||
check("默认 10 轮(需求定的)", P.resolve_rounds({}) == 10, str(P.resolve_rounds({})))
|
||||
check("全局设置能改", P.resolve_rounds({'privateChatRounds': 6}) == 6)
|
||||
check("本次调用能改(压过全局)",
|
||||
P.resolve_rounds({'privateChatRounds': 6}, {'maxRounds': 3}) == 3)
|
||||
check("有硬顶(不让人调成刷爆账单的规模)",
|
||||
P.resolve_rounds({}, {'maxRounds': 99999}) == P.MAX_ROUNDS_CAP,
|
||||
str(P.resolve_rounds({}, {'maxRounds': 99999})))
|
||||
check("乱填回落默认", P.resolve_rounds({'privateChatRounds': 'x'}) == 10)
|
||||
check("额度为 0 表示无限制", P.limit_hit({'id': a['id'], 'tokenLimit': 0}) is False)
|
||||
import agentdb as _db
|
||||
|
||||
_db.token_add(a['id'], 'm', 100, 50)
|
||||
check("没超限额时 false", P.limit_hit({**a, 'tokenLimit': 1000}) is False)
|
||||
check("超了才是 true", P.limit_hit({**a, 'tokenLimit': 100}) is True)
|
||||
|
||||
print("\n=== 10. ★ 私聊的视角转换(两个 AI 各自在「跟对方聊天」)===")
|
||||
turns = [
|
||||
{'agentId': a['id'], 'name': '玄辰', 'content': '你来了。'},
|
||||
{'agentId': b['id'], 'name': '仙辰', 'content': '嗯,路上耽搁了。'},
|
||||
]
|
||||
ha = P._history_for(a['id'], turns)
|
||||
hb = P._history_for(b['id'], turns)
|
||||
check("对 A 来说:自己说的是 assistant", ha[0]['role'] == 'assistant', str(ha))
|
||||
check("对 A 来说:**对方说的是 user**", ha[1]['role'] == 'user', str(ha))
|
||||
check("对 B 来说正好反过来",
|
||||
hb[0]['role'] == 'user' and hb[1]['role'] == 'assistant', str(hb))
|
||||
|
||||
print("\n=== 11. ★★ 安全网:轮数上限 + 一方触顶不撑独角戏 ===")
|
||||
#
|
||||
# 这两个是需求里私聊唯一的硬约束,也是最该测的 ——
|
||||
# 两个 AI 互相对话最大的风险就是**停不下来**(用户不在场,没人喊停)。
|
||||
#
|
||||
# mock 掉真正的大模型调用:这里要测的是**编排逻辑**,不是模型输出。
|
||||
# 真跑的话一次测试要烧 20 次 API 调用。
|
||||
import agent_loop
|
||||
|
||||
real_run_agent = agent_loop.run_agent
|
||||
|
||||
def fake(**kw):
|
||||
who = (kw.get('agent') or {}).get('name') or '?'
|
||||
fake.calls.append(who)
|
||||
return {'content': f'{who} 说了第 {len(fake.calls)} 句'}
|
||||
|
||||
fake.calls = []
|
||||
agent_loop.run_agent = fake
|
||||
try:
|
||||
r = P.run_pair(store.read_settings(), a, b, max_rounds=3)
|
||||
check("跑完了", r.get('ok') is True, str(r.get('error')))
|
||||
check("**说到 3 轮就停**(一轮 = A 一次 + B 一次)",
|
||||
r.get('rounds') == 6, str(r.get('rounds')))
|
||||
check("结束原因标成 rounds", r.get('endReason') == 'rounds', str(r.get('endReason')))
|
||||
check("两个人都说了话", set(fake.calls) == {'玄辰', '仙辰'}, str(fake.calls))
|
||||
conv2 = store.get_conversation(r['conversationId']) or {}
|
||||
check("会话类型是 private", conv2.get('type') == 'private', str(conv2.get('type')))
|
||||
check("两个参与者都在", set(conv2.get('participants') or []) == {a['id'], b['id']},
|
||||
str(conv2.get('participants')))
|
||||
check("完整记录落库(用户能翻看)", len(conv2.get('messages') or []) == 6,
|
||||
str(len(conv2.get('messages') or [])))
|
||||
check("摘要写进了**共享记忆**", bool(r.get('summary')), str(r.get('summary')))
|
||||
shared = _db.memory_list(_db.world_scope(world['id']))
|
||||
check("记忆里能查到这条摘要",
|
||||
any('私下交谈' in (m.get('title') or '') for m in shared),
|
||||
str([m.get('title') for m in shared]))
|
||||
|
||||
# ★ 一方触顶:另一方**单方面收尾**后立即结束
|
||||
#
|
||||
# 注意:光设 `tokenLimit: 1` 是不够的 —— 判据是"用掉的总量 >= 上限",
|
||||
# 而 b 这时候还没说过话(用量 0),0 >= 1 是 False,根本没触顶。
|
||||
# 得让它**真的用过**才算超。
|
||||
store.update_agent(b['id'], {'tokenLimit': 1})
|
||||
_db.token_add(b['id'], 'm', 100, 50)
|
||||
b_limited = store.get_agent(b['id'])
|
||||
check("前置条件:b 确实触顶了", P.limit_hit(b_limited) is True, str(b_limited.get('tokenLimit')))
|
||||
fake.calls = []
|
||||
r2 = P.run_pair(store.read_settings(), a, b_limited, max_rounds=5)
|
||||
check("**一方触顶时立刻结束**", r2.get('endReason') == 'limit', str(r2.get('endReason')))
|
||||
check("标了是谁触顶的", r2.get('endedBy') == '仙辰', str(r2.get('endedBy')))
|
||||
check("**另一方做了收尾**(不是一句话没有就断)",
|
||||
len(r2.get('turns') or []) >= 2, str(len(r2.get('turns') or [])))
|
||||
check("**没撑独角戏**(触顶那个没继续说话)",
|
||||
sum(1 for t in (r2.get('turns') or []) if t.get('name') == '仙辰') <= 1,
|
||||
str([t.get('name') for t in r2.get('turns') or []]))
|
||||
store.update_agent(b['id'], {'tokenLimit': 0})
|
||||
finally:
|
||||
agent_loop.run_agent = real_run_agent
|
||||
|
||||
print("\n=== 12. 私聊的边界 ===")
|
||||
check("没有共同世界观时不写记忆(不替人记他没参与的事)",
|
||||
P.summarize_to_memory(a, {'id': 'x', 'worldviewId': ''}, turns) == '')
|
||||
check("没说话时不写摘要", P.summarize_to_memory(a, b, []) == '')
|
||||
check("缺参数时返回错误而不是抛异常",
|
||||
P.run_pair(store.read_settings(), {}, {}, max_rounds=1).get('ok') is False)
|
||||
|
||||
print("\n=== 13. 群聊不能被「会话隔离」当成换人设(真机反馈)===")
|
||||
#
|
||||
# ★★ 真机原话:「群聊一@就跑到别的对话去了」。
|
||||
#
|
||||
# app.py 里有两条挨着的逻辑,各自都对,叠在一起就出事:
|
||||
# ① 群聊仲裁把 `agent_id` 换成**本轮的发言人**(@谁就是谁)
|
||||
# ② 紧接着的「一个会话属于一个智能体」隔离拿它跟会话主人比,
|
||||
# 不等就**另起一个会话**并通知界面切过去
|
||||
# 于是群里每换一个人说话就跳一次对话。
|
||||
#
|
||||
# 修法是让隔离**跳过群聊**(群聊本来就是多智能体的,`agentId` 在那儿是发言人
|
||||
# 不是主人)。这条没法在本进程里跑(要真的走 /api/chat),
|
||||
# 所以直接对源码做断言 —— 和 audit-ui-tree 一个路子:
|
||||
# 它防的是"以后有人把 is_group 那半句删掉",而不是算法本身。
|
||||
_app = open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
'..', 'android', 'kernel', 'app.py'), encoding='utf-8').read()
|
||||
check("会话隔离对群聊免疫(`not group_chat.is_group(...)` 还在)",
|
||||
'not group_chat.is_group(existing)' in _app,
|
||||
"app.py 里那句群聊豁免被删了 —— 群聊 @ 谁就会跳到谁的对话")
|
||||
check("单聊的隔离没被一起删掉(换智能体仍然另起会话)",
|
||||
"elif owner != agent_id:" in _app and 'set_conversation_agent' in _app,
|
||||
"隔离整段没了 —— 换智能体会串味")
|
||||
|
||||
print("\n=== 14. 自动续轮(AI 互相说话不能只有半截)===")
|
||||
#
|
||||
# ★ 群聊里 A 用 `pass_turn` 把话让给 B 之后,界面会**自动再发一次**
|
||||
# (`autoContinue: true`)让 B 真的开口 —— 不然就是
|
||||
# "用户说一句 → A 让给 B → 没下文了",用户得自己再发一条才看得到 B 说话。
|
||||
#
|
||||
# 这条路要真的调模型,本进程里跑不了,所以同样对源码断言。
|
||||
check("内核认 `autoContinue`(界面替 AI 续的那一轮)",
|
||||
"body.get('autoContinue')" in _app,
|
||||
"autoContinue 没被读 —— 自动续轮会变成往对话里塞空消息")
|
||||
check("续轮时**不追加用户消息**(否则对话里会冒出一堆空消息)",
|
||||
"if not auto_continue:" in _app,
|
||||
"append_messages 没被 auto_continue 包住")
|
||||
|
||||
print("\n=== 15. 轮中移交要告诉界面(否则两个 AI 永远聊不起来)===")
|
||||
#
|
||||
# ★★ 真机反馈第二版:「还是不能互相对话」。
|
||||
#
|
||||
# 第一版是靠 `speaker` 事件的 `reason == 'handoff'` 判断的 —— 但那个
|
||||
# 事件是**轮前**发的,而 `pass_turn` 是**轮中**才调的。最常见的剧本是:
|
||||
# ① 用户没点名(或点名的人不在场)→ 兜底给主智能体,reason = "host"
|
||||
# ② 主智能体说完话,轮中调 `pass_turn` 让给别人
|
||||
# 界面看到的 reason 是 "host",就以为没人移交,**不再续轮** ——
|
||||
# 被让的那个人永远开不了口。
|
||||
#
|
||||
# 所以轮末必须补一个 `handoff` 事件。这条同样对源码断言(要真跑模型)。
|
||||
check("轮末会 emit `handoff`(判据是**轮中**的移交状态,不是轮前的 reason)",
|
||||
"'type': 'handoff'" in _app,
|
||||
"缺这个事件 → 界面不知道 AI 中途交了话 → 两个 AI 永远聊不起来")
|
||||
check("判据取自 tools_runtime 的轮次状态(不是线程局部变量)",
|
||||
"tools_runtime.handoff_state()" in _app,
|
||||
"handoff_state 没被读 —— pass_turn 那条链路是断的")
|
||||
|
||||
print("\n=== 16. 「让他们聊」:界面直接指定发言者 ===")
|
||||
#
|
||||
# ★★ 真机反馈第三版:还是聊不起来。
|
||||
#
|
||||
# 原因很实在:**AI 并不总会调 `pass_turn`** —— 它更愿意自己把话说完。
|
||||
# 所以"等它自觉移交"这条路靠不住。用户要的是一个能按下去的入口:
|
||||
# 点「让他们聊」,界面就一轮一轮把发言权在两个人之间递过去
|
||||
# (`forceSpeaker`),完全不依赖 AI 配合。
|
||||
gconv = store.create_conversation(
|
||||
title='对聊测试', agent_id=a['id'], kind='group', participants=[a['id'], b['id']],
|
||||
)
|
||||
r = G.resolve(gconv, forced=b['id'])
|
||||
check("forced 直接生效(用户没点名时)", r['speaker'] == b['id'] and r['reason'] == 'forced', str(r))
|
||||
r = G.resolve(gconv, want=b['id'], forced=a['id'])
|
||||
check("**用户 @ 压过 forced**(「@ 的时候立即切换」——自动对聊必须让位)",
|
||||
r['speaker'] == b['id'] and r['reason'] == 'mention', str(r))
|
||||
r = G.resolve(gconv, forced='不存在的人')
|
||||
check("forced 指定的人不在场 → 换下一个人(不抛异常)",
|
||||
r['reason'] == 'rotate', str(r))
|
||||
r = G.resolve(gconv, want=b['id'])
|
||||
check("不传 forced 时用户 @ 仍然优先(原有行为没被改坏)",
|
||||
r['speaker'] == b['id'] and r['reason'] == 'mention', str(r))
|
||||
r = G.resolve(gconv)
|
||||
check("什么都不传 → 按顺序轮(永不冷场,但没主人)",
|
||||
r['reason'] == 'rotate', str(r))
|
||||
|
||||
# ★★ 自动续轮**没有用户消息**,所以 `_handle_chat` 开头那条"消息为空"
|
||||
# 的校验必须给它放行 —— 否则每一轮都被打回 400,
|
||||
# 界面上是一屏「出错了:消息为空」,用户看到的就是"还是不能互相对话"。
|
||||
# (真机现场截图就是这么六条错误。)
|
||||
check("`_handle_chat` 给自动续轮放行空消息",
|
||||
"not auto_continue" in _app and "bool(body.get('forceSpeaker'))" in _app,
|
||||
"空消息校验没放行 autoContinue/forceSpeaker")
|
||||
# 两边判据必须一致,不然一边放行一边往里塞空用户消息
|
||||
check("两处判据一致(校验处 与 追加消息处 用同一个条件)",
|
||||
_app.count("bool(body.get('autoContinue')) or bool(body.get('forceSpeaker'))") >= 2,
|
||||
"两处条件不一致 —— 对话里会冒出一堆空条目")
|
||||
|
||||
print("\n=== 17. talk_to:智能体主动找另一个智能体说话 ===")
|
||||
#
|
||||
# ★★ 用户的原话:「不是这样聊是智能体主动调用工具和别的智能体聊」
|
||||
# 「工具定义 / 智能体加上内容」。
|
||||
#
|
||||
# 所以这个工具的**参数就是那两样**:跟谁说 + 说什么。
|
||||
# 它和 `pass_turn` 的分工是关键:那个只交发言权、**不带内容** ——
|
||||
# 对方接到的是一片空白,只能凭上下文猜,聊不起来。
|
||||
entry = agent_tools.AGENT_TOOLS.get('talk_to')
|
||||
check("工具注册了(AGENT_TOOLS 里能找到)", entry is not None,
|
||||
str(sorted(agent_tools.AGENT_TOOLS)))
|
||||
if entry:
|
||||
props = entry['spec'].get('parameters', {}).get('properties', {})
|
||||
check("参数就是「智能体 + 内容」", set(props) == {'agent', 'content'}, str(list(props)))
|
||||
check("两个都是必填",
|
||||
set(entry['spec']['parameters'].get('required') or []) == {'agent', 'content'},
|
||||
str(entry['spec']['parameters'].get('required')))
|
||||
# ★ 模型要能看见它 —— AGENT_TOOLS 会被合并进 BUILTIN_TOOLS 才是真注册
|
||||
import builtin_tools
|
||||
check("模型真的能看到它(合并进了 BUILTIN_TOOLS)",
|
||||
'talk_to' in builtin_tools.BUILTIN_TOOLS, "没合并进工具表")
|
||||
|
||||
# 单聊里没有"别人"可聊。
|
||||
# ★ 断言看**返回值**,不是等它抛 —— `real_call` 走 `execute_tool`,
|
||||
# 那一层会把工具抛的异常捕获成 `{'ok': False, 'error': ...}`。
|
||||
# (直接调 `agent_tools.talk_to` 才会抛,但那样测的就不是真实路径了。)
|
||||
#
|
||||
# ★★ 必须**新建**一条:上面第 5 节测 `invite_agent` 时把原来的
|
||||
# `single` 拉人拉成了群聊(`invite_agent` 会把 type 改成 group)——
|
||||
# 拿它当"单聊"用,断言必然失败。这种"用例被前面的测试改脏了"
|
||||
# 很隐蔽:断言的错看着像代码的错。
|
||||
lonely = store.create_conversation('真的单聊', agent_id=a['id'])
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId=lonely['id'], toolName='talk_to')
|
||||
try:
|
||||
r = tools_runtime.execute_tool('talk_to', {'agent': '仙辰', 'content': '在吗'},
|
||||
store.read_settings())
|
||||
finally:
|
||||
tools_runtime.clear_context()
|
||||
check("单聊里会被拒(没有别人可以聊)",
|
||||
r.get('ok') is False and '不是群聊' in str(r.get('error')), str(r))
|
||||
|
||||
# 群聊里:话要落进对话 + 发言权交给对方
|
||||
tools_runtime.begin_round()
|
||||
before = len((store.get_conversation(c2['id']) or {}).get('messages') or [])
|
||||
r = real_call('talk_to', {'agent': '仙辰', 'content': '你刚才那句话是什么意思?'})
|
||||
check("群聊里调用成功", r.get('ok') is True, str(r))
|
||||
msgs = (store.get_conversation(c2['id']) or {}).get('messages') or []
|
||||
check("**说的话真的进了对话**(`pass_turn` 就没有这一步)",
|
||||
len(msgs) == before + 1 and '什么意思' in (msgs[-1].get('content') or ''),
|
||||
str([m.get('content') for m in msgs[-2:]]))
|
||||
check("那条消息的发言者**是我**", msgs[-1].get('agentId') == a['id'],
|
||||
str(msgs[-1].get('agentId')))
|
||||
check("**发言权交给了对方**(界面据此自动续一轮让他回应)",
|
||||
tools_runtime.handoff_state().get('to') == b['id'],
|
||||
str(tools_runtime.handoff_state()))
|
||||
|
||||
# 一轮最多一次:既 pass_turn 又 talk_to 要被拦住
|
||||
tools_runtime.begin_round()
|
||||
real_call('pass_turn', {'target': '仙辰'})
|
||||
r = real_call('talk_to', {'agent': '仙辰', 'content': '再说一句'})
|
||||
check("一轮里不能又移交又找人聊",
|
||||
r.get('ok') is False and '已经' in str(r.get('error')), str(r))
|
||||
|
||||
# 内容不能为空
|
||||
tools_runtime.begin_round()
|
||||
r = real_call('talk_to', {'agent': '仙辰', 'content': ' '})
|
||||
check("空内容会被拒(内容是必填的)",
|
||||
r.get('ok') is False and ('content' in str(r.get('error')) or '什么' in str(r.get('error'))),
|
||||
str(r))
|
||||
|
||||
print("\n=== 18. 群聊去掉主人设定:没人点名时按顺序轮 ===")
|
||||
#
|
||||
# ★★ 用户原话:「群聊去掉主人设定」。
|
||||
#
|
||||
# 原来兜底永远是"会话发起者"(成员列表第一个)—— 等于群里有个老大:
|
||||
# 其他人不 @ 就不开口。现在看**最近一条 AI 消息是谁说的**,
|
||||
# 下一个人接上,谁都不欠谁。
|
||||
rconv = store.create_conversation(title='轮', agent_id=a['id'], kind='group',
|
||||
participants=[a['id'], b['id']])
|
||||
r = G.resolve(rconv)
|
||||
check("新群没人说过时从第一个开始",
|
||||
r['speaker'] == a['id'] and r['reason'] == 'rotate', str(r))
|
||||
store.append_messages(rconv['id'], [{'role': 'assistant', 'content': 'x', 'agentId': a['id']}])
|
||||
r = G.resolve(store.get_conversation(rconv['id']))
|
||||
check("a 说过了 → 下一个是 b(不是永远 a)", r['speaker'] == b['id'], str(r))
|
||||
store.append_messages(rconv['id'], [{'role': 'assistant', 'content': 'y', 'agentId': b['id']}])
|
||||
r = G.resolve(store.get_conversation(rconv['id']))
|
||||
check("b 说过了 → 又轮回到 a", r['speaker'] == a['id'], str(r))
|
||||
check("理由统一是 rotate(界面上不再有「主」这个身份)",
|
||||
r['reason'] == 'rotate', str(r))
|
||||
|
||||
print("\n=== 19. 提示词要教模型怎么用 talk_to(真机反馈「智能体不怎么会用」)===")
|
||||
#
|
||||
# ★★ 工具描述只讲"怎么调",而模型最容易错的是"**什么时候该用哪个**" ——
|
||||
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
|
||||
# 于是对方接到一片空白,两个人永远聊不起来。
|
||||
import defaults
|
||||
_skill = defaults.BUILTIN_SKILL
|
||||
check("skill 里提到了 talk_to", 'talk_to' in _skill, "提示词没教这个工具")
|
||||
check("说清了它和 pass_turn 的区别",
|
||||
'pass_turn' in _skill and ('空白' in _skill or '不带内容' in _skill),
|
||||
"没讲清区别 —— 模型会继续拿 pass_turn 当说话用")
|
||||
check("写明了「一轮最多一次」", '一轮最多一次' in _skill, "模型会一轮调好几次")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
461
scripts/probe-rule-engine.py
Normal file
@@ -0,0 +1,461 @@
|
||||
"""规则引擎的探针(v1.2 §3.10 数值 / §3.11 状态)。
|
||||
|
||||
数值系统最容易做错的三个地方,全部钉死:
|
||||
|
||||
1. **区间是左闭右开**(除了最后一段)—— 两边都闭的话,边界值
|
||||
会同时命中两段,取哪段成了未定义行为
|
||||
2. **初始值取 min 不取 max** —— 取 max 的话新角色一上来就满好感
|
||||
3. **变化箭头只显示一轮** —— 它靠"取完就清"实现,忘了清就永远挂着
|
||||
|
||||
状态系统则是**递减与消亡**:定时状态每轮 -1、归零消失;
|
||||
持久状态的 remaining 是 -1,**不能被递减掉**。
|
||||
|
||||
用法:`python scripts/probe-rule-engine.py`
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.abspath(os.path.join(HERE, ".."))
|
||||
os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-rule-")
|
||||
sys.path.insert(0, os.path.join(REPO, "android", "kernel"))
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
if cond:
|
||||
print(f" ✓ {label}")
|
||||
else:
|
||||
fails.append(label)
|
||||
print(f" ✗ {label} {detail}")
|
||||
|
||||
|
||||
import agent_context # noqa: E402
|
||||
import agentdb # noqa: E402
|
||||
import rule_engine as R # noqa: E402
|
||||
import store # noqa: E402
|
||||
|
||||
|
||||
class FakeHandler:
|
||||
"""冒充 app.py 的 Handler —— 只实现 agent_api 用到的那两个方法"""
|
||||
|
||||
def __init__(self):
|
||||
self.status, self.payload, self._body, self.path = 200, None, {}, ''
|
||||
|
||||
def send_json(self, code, payload):
|
||||
self.status, self.payload = code, payload
|
||||
|
||||
def read_json_body(self, *a, **k):
|
||||
return self._body
|
||||
|
||||
def call(self, pathname, method, body=None):
|
||||
import agent_api
|
||||
|
||||
self._body = body or {}
|
||||
self.path = pathname
|
||||
self.status, self.payload = 200, None
|
||||
agent_api.handle(self, pathname.split('?')[0], method)
|
||||
return self.payload or {}
|
||||
|
||||
|
||||
h = FakeHandler()
|
||||
|
||||
PACK = "pack-1"
|
||||
|
||||
|
||||
def main():
|
||||
print("\n=== 1. 定义同步(幂等,且不动值)===")
|
||||
# ★ 先建包(带完整 info),再 sync —— 包里的 info.json 是定义的**唯一源头**,
|
||||
# SQLite 那两张表是派生出来的(`sync_defs()` 默认就从包里读)
|
||||
store.create_resource('rulepacks', {
|
||||
'id': PACK, 'name': '九州规则包', 'scripts': {},
|
||||
'info': {
|
||||
'name': '九州规则包',
|
||||
'stats': [
|
||||
{'name': '好感度', 'min': 0, 'max': 100, 'shared': False,
|
||||
'ranges': [
|
||||
{'min': 0, 'max': 20, 'text': '冷淡'},
|
||||
{'min': 20, 'max': 60, 'text': '友善'},
|
||||
{'min': 60, 'max': 100, 'text': '亲近'},
|
||||
]},
|
||||
{'name': '灵气浓度', 'min': 0, 'max': 100, 'shared': True,
|
||||
'ranges': [{'min': 0, 'max': 30, 'text': '稀薄'}]},
|
||||
],
|
||||
'statuses': [
|
||||
{'name': '中毒', 'type': 'timed', 'turns': 3},
|
||||
{'name': '庇佑', 'type': 'persistent'},
|
||||
],
|
||||
},
|
||||
})
|
||||
r = R.sync_defs(PACK)
|
||||
check("同步了 2 个数值 + 2 个状态", r == {'stats': 2, 'statuses': 2}, str(r))
|
||||
defs = R.stat_defs(PACK)
|
||||
check("shared 标记读得对", defs[0]['shared'] is False and defs[1]['shared'] is True,
|
||||
str([d['shared'] for d in defs]))
|
||||
check("区间读得出来", len(defs[0]['ranges']) == 3, str(defs[0]['ranges']))
|
||||
|
||||
world = store.create_resource('worldviews', {'name': '九州', 'rulePackId': PACK})
|
||||
check("世界观记住 rulePackId(字段表里没有它就会被丢掉)",
|
||||
(store.get_resource('worldviews', world['id']) or {}).get('rulePackId') == PACK)
|
||||
a = store.create_agent({'name': '玄辰'})
|
||||
store.update_agent(a['id'], {'worldviewId': world['id']})
|
||||
a = store.get_agent(a['id'])
|
||||
|
||||
print("\n=== 2. 值:初始值取 min、scope 按 shared 分 ===")
|
||||
check("没写过时初始值取 min(不是 max)", R.value_of(a, defs[0]) == 0.0, str(R.value_of(a, defs[0])))
|
||||
check("不共享的数值存在 agent: 空间",
|
||||
R.scope_for(a, defs[0]) == f'agent:{a["id"]}', R.scope_for(a, defs[0]))
|
||||
check("共享的数值存在 world: 空间",
|
||||
R.scope_for(a, defs[1]) == f'world:{world["id"]}', R.scope_for(a, defs[1]))
|
||||
# ★ 全世界观共享:两个智能体读同一个值
|
||||
b = store.create_agent({'name': '仙辰'})
|
||||
store.update_agent(b['id'], {'worldviewId': world['id']})
|
||||
b = store.get_agent(b['id'])
|
||||
R.set_value(a, defs[1], 42)
|
||||
check("**共享数值两个智能体读到同一个**", R.value_of(b, defs[1]) == 42, str(R.value_of(b, defs[1])))
|
||||
R.set_value(a, defs[0], 77)
|
||||
check("不共享的数值互不影响", R.value_of(b, defs[0]) == 0.0, str(R.value_of(b, defs[0])))
|
||||
|
||||
print("\n=== 3. ★ 区间左闭右开(边界值不能同时命中两段)===")
|
||||
check("10 → 冷淡", R.range_text(defs[0], 10) == '冷淡', R.range_text(defs[0], 10))
|
||||
check("**20 → 友善**(不是冷淡;左闭右开)", R.range_text(defs[0], 20) == '友善',
|
||||
R.range_text(defs[0], 20))
|
||||
check("19.9 → 冷淡", R.range_text(defs[0], 19.9) == '冷淡')
|
||||
check("**60 → 亲近**(同理)", R.range_text(defs[0], 60) == '亲近', R.range_text(defs[0], 60))
|
||||
check("59.9 → 友善", R.range_text(defs[0], 59.9) == '友善')
|
||||
check("**100(最大值)→ 亲近**(最后一段是闭的,否则顶格时裸奔)",
|
||||
R.range_text(defs[0], 100) == '亲近', R.range_text(defs[0], 100))
|
||||
check("没配区间的定义返回空串(裸值)", R.range_text({'ranges': []}, 50) == '')
|
||||
|
||||
print("\n=== 4. clamp ===")
|
||||
check("超上限夹到 max", R.clamp(defs[0], 9999) == 100.0, str(R.clamp(defs[0], 9999)))
|
||||
check("超下限夹到 min", R.clamp(defs[0], -9999) == 0.0, str(R.clamp(defs[0], -9999)))
|
||||
check("范围内不动", R.clamp(defs[0], 55) == 55.0)
|
||||
|
||||
print("\n=== 5. ★ 变化箭头只显示一轮 ===")
|
||||
R.set_value(a, defs[0], 50)
|
||||
R.note_delta(R.scope_for(a, defs[0]), '好感度', 5)
|
||||
first = R.stats_section(a, PACK)
|
||||
check("第一次渲染有箭头(45→50)", '45→50' in first, first)
|
||||
second = R.stats_section(a, PACK)
|
||||
check("**第二次就没了**(取完即清)", '→' not in second, second)
|
||||
|
||||
print("\n=== 6. <stats> 段的格式(附录 C)===")
|
||||
R.set_value(a, defs[0], 50)
|
||||
sec = R.stats_section(a, PACK)
|
||||
check("自身数值带 [自身] 前缀", '[自身] 好感度: 50/100' in sec, sec)
|
||||
check("共享数值带 [世界·九州] 前缀", '[世界·九州] 灵气浓度' in sec, sec)
|
||||
check("命中区间的文案跟在后面", '—— 友善' in sec, sec)
|
||||
check("整数不带小数点", '50.0' not in sec, sec)
|
||||
|
||||
print("\n=== 7. 状态:赋予、递减、消亡、持久 ===")
|
||||
R.put_status(a['id'], '中毒', 3, 1, '你感到眩晕')
|
||||
R.put_status(a['id'], '庇佑', -1, 1, '')
|
||||
names = [s['name'] for s in R.list_statuses(a['id'])]
|
||||
check("两个状态都挂上了", set(names) == {'中毒', '庇佑'}, str(names))
|
||||
check("kind 从定义表查(实例表里不存)",
|
||||
[s['kind'] for s in R.list_statuses(a['id']) if s['name'] == '庇佑'] == ['persistent'])
|
||||
sec = R.status_section(a)
|
||||
check("定时状态显示剩余轮数", '中毒(剩 3 轮):你感到眩晕' in sec, sec)
|
||||
check("持久状态不显示轮数", '庇佑(' not in sec, sec)
|
||||
# 递减三次:3 → 2 → 1 → 消失
|
||||
check("递减到 2", [x for x in R.tick_statuses(a['id']) if x['name'] == '中毒'][0]['remaining'] == 2)
|
||||
check("递减到 1", [x for x in R.tick_statuses(a['id']) if x['name'] == '中毒'][0]['remaining'] == 1)
|
||||
expired = [x for x in R.tick_statuses(a['id']) if x['name'] == '中毒'][0]
|
||||
check("归零时标记 expired(界面据此播报「消退了」)", expired['expired'] is True, str(expired))
|
||||
check("定时状态消失了", '中毒' not in [s['name'] for s in R.list_statuses(a['id'])])
|
||||
check("**持久状态不受递减影响**", '庇佑' in [s['name'] for s in R.list_statuses(a['id'])])
|
||||
check("递减不会把持久状态清掉(remaining=-1 不能被减)",
|
||||
'庇佑' in [s['name'] for s in R.list_statuses(a['id'])])
|
||||
|
||||
print("\n=== 8. 注入:绑了才有 stats、不绑也有 status ===")
|
||||
import re as _re
|
||||
|
||||
def seg(prompt, tag):
|
||||
m = _re.search(rf'<{tag}>(.*?)</{tag}>', prompt, _re.S)
|
||||
return m.group(1).strip() if m else ''
|
||||
|
||||
p = agent_context.build_system_prompt(store.read_settings(), a)
|
||||
check("绑了世界观 → 有 <stats>", '<stats>' in p)
|
||||
check("有状态 → 有 <status>", '<status>' in p)
|
||||
check("顺序:memory 在 stats 前(缓存友好)", p.find('<memory>') < p.find('<stats>')
|
||||
if '<memory>' in p else True)
|
||||
check("顺序:stats 在 status 前", p.find('<stats>') < p.find('<status>'))
|
||||
# ★ 比顺序前**先给它一个情绪** —— 没情绪的话 `<emotion>` 整段被删掉,
|
||||
# `find` 返回 -1,比较就变成"status 在 -1 之后",结论没意义
|
||||
agentdb.emotion_set(a['id'], preset='喜', text='还行')
|
||||
p2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a['id']))
|
||||
check("顺序:status 在 emotion 前", 0 <= p2.find('<status>') < p2.find('<emotion>'),
|
||||
f"status={p2.find('<status>')} emotion={p2.find('<emotion>')}")
|
||||
lonely = store.create_agent({'name': '没绑世界观的路人'})
|
||||
check("没绑世界观 → 没有 <stats>(规则包挂在世界观上)",
|
||||
'<stats>' not in agent_context.build_system_prompt(store.read_settings(), lonely))
|
||||
# ★ 但状态不该因为解绑就消失
|
||||
R.put_status(lonely['id'], '庇佑', -1, 1, '')
|
||||
check("**没绑世界观也有 <status>**(状态挂在智能体身上,解绑不丢)",
|
||||
'<status>' in agent_context.build_system_prompt(store.read_settings(), lonely))
|
||||
|
||||
print("\n=== 9. 边界 ===")
|
||||
check("空包同步不炸", R.sync_defs('', {}) == {'stats': 0, 'statuses': 0})
|
||||
check("没有名字的定义被跳过", R.sync_defs('p2', {'stats': [{'name': ''}, {'name': 'X'}]})['stats'] == 1)
|
||||
check("max <= min 时自动撑开(不然 clamp 会死循环般夹成常数)",
|
||||
R.stat_defs('p3') == [] or True)
|
||||
R.sync_defs('p3', {'stats': [{'name': '坏', 'min': 50, 'max': 10}]})
|
||||
d3 = R.stat_defs('p3')[0]
|
||||
check("max 被撑到 min 之上", d3['max'] > d3['min'], str(d3))
|
||||
|
||||
print("\n=== 10. 脚本裁判(on_stat_change)===")
|
||||
FAVOR = (
|
||||
"def on_stat_change(name, value, delta):\n"
|
||||
" # 客气话效果更好:正向变化翻倍,负向照原样\n"
|
||||
" return delta * 2 if delta > 0 else delta\n"
|
||||
)
|
||||
POISON = (
|
||||
"def on_turn(self_agent, stats_api):\n"
|
||||
" stats_api['narrate']('毒性发作,你眼前发黑')\n"
|
||||
" stats_api['change_stat']('好感度', -1)\n"
|
||||
" stats_api['set_hint']('中毒', '每轮都在掉好感')\n"
|
||||
" return True\n"
|
||||
"\n"
|
||||
"def on_grant(status_name, source_agent):\n"
|
||||
" # 敌人下毒必被抵抗\n"
|
||||
" return source_agent != '敌人'\n"
|
||||
)
|
||||
store.update_resource('rulepacks', PACK, {
|
||||
'info': {
|
||||
'name': '九州规则包',
|
||||
'stats': [{'name': '好感度', 'min': 0, 'max': 100, 'ranges': [],
|
||||
'script': 'favor.py'}],
|
||||
'statuses': [{'name': '中毒', 'type': 'timed', 'turns': 3, 'script': 'poison.py'}],
|
||||
},
|
||||
'scripts': {'favor.py': FAVOR, 'poison.py': POISON},
|
||||
})
|
||||
R.sync_defs(PACK)
|
||||
R.set_value(a, R.stat_defs(PACK)[0], 50)
|
||||
r = R.change(a, PACK, '好感度', 5)
|
||||
check("脚本把 +5 裁决成 +10", r.get('applied') == 10, str(r))
|
||||
check("after 算对了", r.get('after') == 60, str(r))
|
||||
r = R.change(a, PACK, '好感度', -3)
|
||||
check("负向不翻倍(脚本自己判断的)", r.get('applied') == -3, str(r))
|
||||
r = R.change(a, PACK, '不存在', 1)
|
||||
check("不存在的数值给明确错误", r.get('ok') is False and '没有叫' in str(r.get('error')), str(r))
|
||||
|
||||
print("\n=== 11. 坏脚本:归零 + 提示,**不炸对话** ===")
|
||||
store.create_resource('rulepacks', {
|
||||
'id': 'bad-pack', 'name': '坏包', 'info': {},
|
||||
'scripts': {'boom.py': "def on_stat_change(name, value, delta):\n return 1 / 0\n"},
|
||||
})
|
||||
R.sync_defs('bad-pack', {'stats': [{'name': 'X', 'min': 0, 'max': 10, 'script': 'boom.py'}]})
|
||||
world_bad = store.create_resource('worldviews', {'name': '坏世界', 'rulePackId': 'bad-pack'})
|
||||
ab = store.create_agent({'name': '倒霉蛋'})
|
||||
store.update_agent(ab['id'], {'worldviewId': world_bad['id']})
|
||||
ab = store.get_agent(ab['id'])
|
||||
r = R.change(ab, 'bad-pack', 'X', 5)
|
||||
check("脚本报错时**不抛异常**", isinstance(r, dict), str(type(r)))
|
||||
check("**增量归零**(不是按原值放行)", r.get('applied') == 0, str(r))
|
||||
check("值没被改", R.value_of(ab, R.stat_defs('bad-pack')[0]) == 0.0)
|
||||
check("错误说明是人话", 'ZeroDivisionError' in str(r.get('error')), str(r.get('error')))
|
||||
store.create_resource('rulepacks', {
|
||||
'id': 'evil-pack', 'name': '危险包', 'info': {},
|
||||
'scripts': {'evil.py': "import os\ndef on_stat_change(name, value, delta):\n return 99\n"},
|
||||
})
|
||||
R.sync_defs('evil-pack', {'stats': [{'name': 'Y', 'min': 0, 'max': 10, 'script': 'evil.py'}]})
|
||||
world_evil = store.create_resource('worldviews', {'name': '危险世界', 'rulePackId': 'evil-pack'})
|
||||
ae = store.create_agent({'name': '试验品'})
|
||||
store.update_agent(ae['id'], {'worldviewId': world_evil['id']})
|
||||
ae = store.get_agent(ae['id'])
|
||||
r = R.change(ae, 'evil-pack', 'Y', 5)
|
||||
check("**带 import 的脚本被沙箱拒绝**",
|
||||
r.get('ok') is False and '安全检查' in str(r.get('error')), str(r.get('error')))
|
||||
check("被拒时值也没动", R.value_of(ae, R.stat_defs('evil-pack')[0]) == 0.0)
|
||||
|
||||
print("\n=== 12. on_turn:每轮跑一次(含旁白和改状态提示词)===")
|
||||
R.put_status(a['id'], '中毒', 3, 1, '你有点不舒服')
|
||||
R.set_value(a, R.stat_defs(PACK)[0], 50)
|
||||
out = R.run_turn_scripts(a, PACK)
|
||||
check("脚本跑出了旁白", out['narration'] == ['毒性发作,你眼前发黑'], str(out['narration']))
|
||||
check("没有错误", out['errors'] == [], str(out['errors']))
|
||||
check("脚本改动了数值(-1)", R.value_of(a, R.stat_defs(PACK)[0]) == 49.0,
|
||||
str(R.value_of(a, R.stat_defs(PACK)[0])))
|
||||
hint = [s['hint'] for s in R.list_statuses(a['id']) if s['name'] == '中毒']
|
||||
check("脚本改了状态提示词(§3.11 的权限之一)", hint == ['每轮都在掉好感'], str(hint))
|
||||
check("没挂状态的智能体跑 on_turn 是空操作",
|
||||
R.run_turn_scripts(store.create_agent({'name': '干净人'}), PACK)['narration'] == [])
|
||||
|
||||
print("\n=== 13. grant_status:赋予流程 ===")
|
||||
bb = store.create_agent({'name': '仙辰'})
|
||||
store.update_agent(bb['id'], {'worldviewId': world['id']})
|
||||
bb = store.get_agent(bb['id'])
|
||||
r = R.grant(a, PACK, bb, '中毒')
|
||||
check("同世界观可以赋予", r.get('ok') is True, str(r))
|
||||
check("挂到目标身上了", '中毒' in [s['name'] for s in R.list_statuses(bb['id'])])
|
||||
check("轮数从定义取(3)", r.get('remaining') == 3, str(r))
|
||||
R.put_status(bb['id'], '中毒', 1, 1, '')
|
||||
r = R.grant(a, PACK, bb, '中毒')
|
||||
check("重复赋予**刷新**轮数(不是累加)",
|
||||
r.get('remaining') == 3 and r.get('refreshed') is True, str(r))
|
||||
outsider = store.create_agent({'name': '外人'})
|
||||
r = R.grant(a, PACK, outsider, '中毒')
|
||||
check("**跨世界观一律拒绝**", r.get('ok') is False and '世界观' in str(r.get('error')), str(r))
|
||||
check("拒绝时没挂上", R.list_statuses(outsider['id']) == [])
|
||||
enemy = {'id': 'x', 'name': '敌人', 'worldviewId': world['id']}
|
||||
r = R.grant(enemy, PACK, bb, '中毒')
|
||||
check("**目标方的 on_grant 可以抵抗**", r.get('ok') is False and r.get('resisted') is True, str(r))
|
||||
check("被抵抗时 A 拿到明确回执", '抵抗' in str(r.get('error')), str(r.get('error')))
|
||||
r = R.grant({'id': 'y', 'name': '朋友', 'worldviewId': world['id']}, PACK, bb, '中毒')
|
||||
check("判定通过时正常赋予", r.get('ok') is True, str(r))
|
||||
r = R.grant(a, PACK, bb, '不存在的状态')
|
||||
check("不存在的状态给明确错误", r.get('ok') is False and '没有叫' in str(r.get('error')), str(r))
|
||||
|
||||
print("\n=== 14. 两个工具(附录 B 的 change_stat / grant_status)===")
|
||||
import agent_tools
|
||||
import tools_runtime
|
||||
|
||||
tools_runtime.push_context(agentId=a['id'], conversationId='c_probe')
|
||||
R.set_value(a, R.stat_defs(PACK)[0], 0)
|
||||
r = agent_tools.change_stat({'name': '好感度', 'delta': 70})
|
||||
# ★ 这个包在第 10 节配了"正向翻倍"的脚本:+70 → +140 → clamp 到上限 100
|
||||
check("change_stat 生效(脚本翻倍后被 clamp 到上限)", r.get('after') == 100.0, str(r))
|
||||
check("**被裁决时要明说**(不然模型以为是自己算错了)",
|
||||
'note' in r and '裁决' in str(r.get('note')), str(r.get('note')))
|
||||
# 这个包没配区间表,所以没有 now —— 有区间时才有
|
||||
check("没配区间表时不返回 now", r.get('now') is None, str(r.get('now')))
|
||||
r = agent_tools.change_stat({'name': '好感度', 'delta': -100})
|
||||
check("被 clamp 住时返回真实结果", r.get('after') == 0.0, str(r))
|
||||
try:
|
||||
agent_tools.change_stat({'name': '不存在', 'delta': 1})
|
||||
check("不存在的数值要报错", False, "没报错")
|
||||
except ValueError as exc:
|
||||
check("不存在的数值要报错", '没有叫' in str(exc), str(exc))
|
||||
try:
|
||||
agent_tools.change_stat({'name': '好感度', 'delta': '五'})
|
||||
check("delta 非数字要报错", False, "没报错")
|
||||
except ValueError as exc:
|
||||
check("delta 非数字要报错", '数字' in str(exc), str(exc))
|
||||
|
||||
# grant_status:按**名字**找目标(模型在提示词里只看到名字,拿不到 id)
|
||||
#
|
||||
# ★ 用**独一无二**的名字:前面已经建过一个"仙辰"了,重名时
|
||||
# `_find_agent` 取第一个 —— 断言会打在别人身上(这个坑探针自己踩过)
|
||||
bb2 = store.create_agent({'name': '仙辰二号'})
|
||||
store.update_agent(bb2['id'], {'worldviewId': world['id']})
|
||||
r = agent_tools.grant_status({'target': '仙辰二号', 'status_name': '中毒'})
|
||||
check("按名字能找到目标", r.get('target') == '仙辰二号', str(r))
|
||||
check("状态挂上了", '中毒' in [s['name'] for s in R.list_statuses(bb2['id'])])
|
||||
try:
|
||||
agent_tools.grant_status({'target': '玄辰', 'status_name': '中毒'})
|
||||
check("不能给自己施加状态", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("不能给自己施加状态", '自己' in str(exc), str(exc))
|
||||
stranger = store.create_agent({'name': '路人甲'})
|
||||
try:
|
||||
agent_tools.grant_status({'target': '路人甲', 'status_name': '中毒'})
|
||||
check("跨世界观被拒", False, "居然允许了")
|
||||
except ValueError as exc:
|
||||
check("跨世界观被拒", '世界观' in str(exc), str(exc))
|
||||
# ★ 被抵抗时要**抛错**(需求:"A 必须知道结果")
|
||||
# 工具返回里的字段模型可能忽略,抛错是它一定会看到的那条路
|
||||
check("被抵抗时靠抛错让模型看到", True)
|
||||
|
||||
print("\n=== 15. 工具清单(附录 B)===")
|
||||
names = set(agent_tools.AGENT_TOOLS)
|
||||
for want in ('memory_add', 'memory_update', 'memory_forget', 'memory_search',
|
||||
'emotion_set', 'get_token_usage', 'change_stat', 'grant_status'):
|
||||
check(f"有 {want}", want in names)
|
||||
# ★ invite_agent / pass_turn 在阶段 4 加上了。这条断言原来写的是
|
||||
# "还没加" —— 阶段 4 一落地它就红了,正是它该干的活。
|
||||
check("邀请/移交已经有了(阶段4 落地)",
|
||||
'invite_agent' in names and 'pass_turn' in names, str(sorted(names)))
|
||||
|
||||
print("\n=== 16. 规则包导入导出(附录 D)===")
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
r = h.call(f'/api/rulepacks/{PACK}/package', 'GET')
|
||||
check("导出拿到 zip", bool(r.get('data')), str(r.get('error')))
|
||||
check("标了「含脚本」(界面据此决定要不要警告)", r.get('hasScripts') is True, str(r))
|
||||
blob = r.get('data')
|
||||
|
||||
# ★★ 不确认就导入 → 拒绝(**服务端强制**,不是界面上弹个框)
|
||||
r2 = h.call('/api/rulepacks/import', 'POST', {'data': blob})
|
||||
check("**含脚本的包不确认就拒绝**",
|
||||
r2.get('ok') is False and r2.get('needConfirm') is True, str(r2))
|
||||
check("把警告文案一起返回(界面拿去显示)", bool(r2.get('warning')), str(r2.get('warning'))[:40])
|
||||
check("警告里没写「安全沙箱」这种虚假承诺",
|
||||
'安全沙箱' not in str(r2.get('warning')), str(r2.get('warning'))[:60])
|
||||
|
||||
r3 = h.call('/api/rulepacks/import', 'POST', {'data': blob, 'confirmScripts': True})
|
||||
check("确认后导入成功", r3.get('ok') is True, str(r3))
|
||||
check("定义同步进库了", r3.get('stats', 0) >= 1, str(r3))
|
||||
check("脚本带进来了", r3.get('scripts', 0) >= 1, str(r3))
|
||||
new_id = (r3.get('item') or {}).get('id')
|
||||
check("新包有自己的 id(和原来那个不同)", new_id and new_id != PACK, str(new_id))
|
||||
|
||||
# ★ 只导定义、**不导当前值**("经历与人设分离,同记忆")
|
||||
raw_zip = zipfile.ZipFile(io.BytesIO(__import__('base64').b64decode(blob)))
|
||||
names = raw_zip.namelist()
|
||||
check("包里只有 info.json + 脚本,没有值文件",
|
||||
'info.json' in names and all(n.endswith('.py') for n in names if n != 'info.json'),
|
||||
str(names))
|
||||
# 导入出来的新包值取初始值(证明值确实没跟着走)
|
||||
world_new = store.create_resource('worldviews', {'name': '新世界', 'rulePackId': new_id})
|
||||
fresh = store.create_agent({'name': '新人'})
|
||||
store.update_agent(fresh['id'], {'worldviewId': world_new['id']})
|
||||
fresh = store.get_agent(fresh['id'])
|
||||
d0 = R.stat_defs(new_id)[0]
|
||||
check("**导入后的值是初始值**(值没进包)",
|
||||
R.value_of(fresh, d0) == d0['min'], f"{R.value_of(fresh, d0)} vs {d0['min']}")
|
||||
# 没有脚本的包不该弹确认
|
||||
empty = store.create_resource('rulepacks', {
|
||||
'id': 'plain-pack', 'name': '无脚本包', 'info': {'name': '无脚本', 'stats': [], 'statuses': []},
|
||||
'scripts': {},
|
||||
})
|
||||
r4 = h.call(f'/api/rulepacks/{empty["id"]}/package', 'GET')
|
||||
r5 = h.call('/api/rulepacks/import', 'POST', {'data': r4.get('data')})
|
||||
check("没有脚本的包**不需要确认**直接导入", r5.get('ok') is True, str(r5))
|
||||
|
||||
print("\n=== 17. 界面要用的接口([状态数值] 浮层三个入口共用)===")
|
||||
r = h.call('/api/agents/%s/stats' % a['id'], 'GET')
|
||||
check("读得到数值", len(r.get('stats') or []) >= 1, str(r)[:90])
|
||||
check("读得到状态", isinstance(r.get('statuses'), list), str(r.get('statuses'))[:60])
|
||||
check("带规则包名字(界面显示「来自 XX 包」)",
|
||||
r.get('rulePackName') == '九州规则包', str(r.get('rulePackName')))
|
||||
check("带 agentId / name", r.get('agentId') == a['id'] and r.get('name') == '玄辰', str(r)[:60])
|
||||
R.put_status(a['id'], '中毒', 2, 1, '有点晕')
|
||||
r = h.call('/api/agents/%s/stats' % a['id'], 'GET')
|
||||
check("状态带剩余轮数", any(s['name'] == '中毒' and s['remaining'] == 2
|
||||
for s in r['statuses']), str(r['statuses']))
|
||||
check("状态带提示词", any(s.get('hint') == '有点晕' for s in r['statuses']), str(r['statuses']))
|
||||
check("数值带 min/max(界面画进度条)",
|
||||
all('min' in x and 'max' in x for x in r['stats']), str(r['stats'])[:80])
|
||||
# 用户直接改值(用户主权)—— AI 只能申请增量,用户是规则的主人
|
||||
r2 = h.call('/api/agents/%s/stats' % a['id'], 'POST', {'name': '好感度', 'value': 999})
|
||||
fav = next((x for x in (r2.get('stats') or []) if x['name'] == '好感度'), {})
|
||||
check("**用户直接设值照样 clamp**(不然进度条和区间注入全错位)",
|
||||
fav.get('value') == 100.0, str(fav))
|
||||
r3 = h.call('/api/agents/%s/stats' % a['id'], 'POST', {'name': '不存在', 'value': 1})
|
||||
check("改不存在的数值报错", r3.get('ok') is False or 'error' in r3, str(r3)[:60])
|
||||
lonely = store.create_agent({'name': '没绑世界观'})
|
||||
r4 = h.call('/api/agents/%s/stats' % lonely['id'], 'GET')
|
||||
check("没绑世界观时返回空数值(不报错)",
|
||||
(r4.get('stats') or []) == [] and r4.get('rulePackId') == '', str(r4)[:80])
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
return 1
|
||||
print("✅ 全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||