Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e62dd7b87b | |||
| 8ccf009958 | |||
| ff1c2e3400 | |||
| bea9debe15 | |||
| 8ac14bdaa2 | |||
| f84c68762b |
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 265
|
||||
versionName = "2.0.65"
|
||||
versionCode = 271
|
||||
versionName = "2.0.71"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.util.Base64
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
@@ -203,6 +203,8 @@ fun AgentEditScreen(
|
||||
pickImage.launch(arrayOf("image/*"))
|
||||
},
|
||||
onClear = { vm.uploadAgentAsset(draft.id, "front:$preset", "", "") },
|
||||
// 立绘空着时显示内置默认人物 —— 那正是回退链的最后一级
|
||||
showDefaultPerson = true,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
}
|
||||
@@ -319,6 +321,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") },
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 技能 ---------------- */
|
||||
@@ -543,6 +557,15 @@ private fun AssetRow(
|
||||
path: String,
|
||||
onPick: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
/**
|
||||
* 空的时候要不要显示**内置默认人物**的缩略图。
|
||||
*
|
||||
* ★ 只有**立绘**该显示它(那正是回退链的最后一级)。
|
||||
* 背景图 / 边框为空时显示一张**人物照**是误导 ——
|
||||
* 用户会以为"我没设背景,怎么有个女的"(截图反馈过)。
|
||||
* 那三个空着就画一个空框 + 一个「空」字,如实表达"这里什么都没有"。
|
||||
*/
|
||||
showDefaultPerson: Boolean = false,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
@@ -554,14 +577,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,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
@@ -228,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 },
|
||||
)
|
||||
}
|
||||
@@ -578,15 +591,19 @@ 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() }
|
||||
// ★「新建群聊」(v1.2 §3.9):以前只有「[群成员] → 加人」能建群,
|
||||
// 那条路藏得太深 —— 用户想拉几个人一起聊,得先想到去成员页。
|
||||
// 放抽屉里是因为它和「开启新话题」是同一类动作(都是"开一个新的")。
|
||||
DrawerItem(Icons.Filled.Group, "新建群聊") {
|
||||
vm.drawerOpen = false
|
||||
vm.newGroupTopic()
|
||||
}
|
||||
DrawerItem(Icons.Filled.AutoAwesome, "智能体") {
|
||||
// ★ 抽屉这一项进的是**选择界面**(需求 2.1 的入口页),
|
||||
// 管理(新建/编辑/导入导出)在那个页面的「管理」里
|
||||
@@ -599,26 +616,13 @@ 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))
|
||||
SectionLabel("对话", Modifier.padding(start = 22.dp, top = 22.dp, bottom = 6.dp))
|
||||
|
||||
LazyColumn(Modifier.weight(1f)) {
|
||||
items(vm.state.conversations.size) { i ->
|
||||
@@ -676,11 +680,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))
|
||||
|
||||
@@ -193,6 +193,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() 这一处
|
||||
@@ -603,7 +604,120 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
fun importPackage(kind: String, base64: String, textJson: String) { viewModelScope.launch {
|
||||
/**
|
||||
* 内核给这条对话"换了归属"时的说明(非空 = 界面上提示一句)。
|
||||
*
|
||||
* ★ 它是个**用户能感知**的变化:对话突然换了个身份。
|
||||
* 不提示的话用户会以为自己点错了什么。显示一次就清掉。
|
||||
*/
|
||||
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 {
|
||||
withContext(Dispatchers.IO) {
|
||||
when (kind) {
|
||||
@@ -1524,9 +1638,36 @@ 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
|
||||
}
|
||||
is StreamEvent.Failure -> {
|
||||
// ★ 额度用完不是"出错了",是**一个需要你决定的状态**:
|
||||
|
||||
@@ -280,7 +280,8 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
tagline.endsWith("?") || tagline.contains(","))
|
||||
val greeting =
|
||||
if (looksLikeSentence) tagline else "嗨,我是${agent?.name ?: "豆包"},有什么可以帮你的吗?"
|
||||
item { AppearOnce { HeroSection(greeting) } }
|
||||
item { AppearOnce { ChatPortrait(vm) } }
|
||||
item { AppearOnce { HeroText(greeting) } }
|
||||
}
|
||||
items(vm.messages.size) { index ->
|
||||
AppearOnce(offsetY = 10.dp) {
|
||||
@@ -318,7 +319,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 结束了 —— **屏幕中间一个横幅,写着关闭原因**。
|
||||
*
|
||||
@@ -339,6 +348,21 @@ 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):点头像 = @ 点名,被点的人这一轮一定发言
|
||||
GroupQuickBar(vm)
|
||||
SessionUsageBar(vm)
|
||||
@@ -552,18 +576,11 @@ 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))
|
||||
@@ -575,6 +592,63 @@ private fun HeroSection(greeting: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 聊天页顶部的立绘(v1.2 §6.1)。
|
||||
*
|
||||
* ★ **跟随说话者**(设置里可关,默认开):群聊时谁发言就换成谁的立绘 ——
|
||||
* 一眼看出"这句是谁说的"。关掉时固定用主智能体(成员列表第一个)。
|
||||
*
|
||||
* ★ 0.3 秒的 crossfade:立绘是**情绪驱动**的,可能一轮换一次;
|
||||
* 硬切会让人以为界面闪了一下。0.3s 刚好够看出"换了",又不拖沓。
|
||||
* (这也正是需求里点名的 0.3s —— 和群聊背景跟随共用同一套缓动,
|
||||
* 两处各写一个数字的话,将来改一处必漏另一处。)
|
||||
*/
|
||||
@Composable
|
||||
private fun ChatPortrait(vm: AppViewModel) {
|
||||
val conv = vm.state.conversations.firstOrNull { it.id == vm.activeConversationId }
|
||||
// 谁在说话:跟随开着 && 是群聊 → 用**内核仲裁出来的**那一位;否则当前智能体
|
||||
val who = if (vm.state.settings.followSpeaker && conv?.isGroup == true &&
|
||||
vm.currentSpeakerId.isNotBlank()
|
||||
) {
|
||||
vm.state.agents.firstOrNull { it.id == vm.currentSpeakerId } ?: vm.activeAgent
|
||||
} else {
|
||||
vm.activeAgent
|
||||
}
|
||||
val art = who?.image?.portrait.orEmpty()
|
||||
// ★ 用 key(art) + AnimatedContent:图变了才做过渡,
|
||||
// 没变时(比如只是又聊了一句)不该白做一次动画
|
||||
androidx.compose.animation.Crossfade(
|
||||
targetState = art,
|
||||
animationSpec = androidx.compose.animation.core.tween(300),
|
||||
label = "portrait",
|
||||
) { path ->
|
||||
Box(
|
||||
Modifier.size(168.dp).clip(CircleShape).background(doubaoHeroRing()),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (path.isNotBlank()) {
|
||||
AssetImage(path, Modifier.size(168.dp), contentScale = ContentScale.Crop)
|
||||
} else {
|
||||
Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(96.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
// ★ 没配立绘时**说清楚 + 给入口**。
|
||||
//
|
||||
// 回退链最后一级就是"内置默认人物"(需求 §2.6),所以显示这张图**没错** ——
|
||||
// 但界面上一个字都不说的话,用户只会觉得"立绘功能没生效",
|
||||
// 而不知道**得自己去传**(内置那四个示例智能体默认都没有图)。
|
||||
if (art.isBlank() && who != null) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"还没有立绘 · 点这里去传一张",
|
||||
fontSize = 11.sp,
|
||||
color = Doubao.Blue,
|
||||
modifier = Modifier.clickable { vm.openAgentEdit(who) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 消息 ------------------------------ */
|
||||
|
||||
@Composable
|
||||
@@ -1222,4 +1296,15 @@ private fun GroupQuickBar(vm: AppViewModel) {
|
||||
}
|
||||
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),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -149,6 +149,57 @@ fun GroupMembersScreen(
|
||||
"在聊天页的输入框上方点成员头像就是 @ 点名 —— " +
|
||||
"被点的人这一轮一定发言。没人被点时由主智能体兜底,不会冷场。",
|
||||
)
|
||||
|
||||
// ★「让他们私下聊聊」(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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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.content.Intent
|
||||
import android.net.Uri
|
||||
@@ -512,6 +512,47 @@ 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) },
|
||||
)
|
||||
}
|
||||
|
||||
SettingsCard("个人资料") {
|
||||
FormLabel("昵称")
|
||||
FormField(
|
||||
@@ -1270,3 +1311,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 @@
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
@@ -1208,6 +1208,11 @@ 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(':')
|
||||
|
||||
@@ -329,6 +329,10 @@ 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()
|
||||
|
||||
@@ -352,6 +356,10 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
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)
|
||||
|
||||
@@ -630,8 +630,10 @@ def pass_turn(args: dict) -> dict:
|
||||
me = _me()
|
||||
if not me:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
ctx = tools_runtime.current_context()
|
||||
if ctx.get('handoffUsed'):
|
||||
# ★★ 用 tools_runtime 的**轮次级状态**,不能用工具上下文 ——
|
||||
# 工具跑在 worker 线程里,写进 thread-local 的标记会随线程消失,
|
||||
# 于是"一轮最多一次"永远不生效(踩过,见 tools_runtime.begin_round 的注释)
|
||||
if tools_runtime.handoff_state().get('used'):
|
||||
# ★ 需求明文"一轮最多一次"。第二次直接拒,理由说清楚 ——
|
||||
# 不然模型会以为是"对方有问题",而不是"规则不允许"
|
||||
raise ValueError('这一轮你已经移交过发言权了(一轮最多一次),直接回复就行')
|
||||
@@ -644,9 +646,7 @@ def pass_turn(args: dict) -> dict:
|
||||
# ★ 需求明文:死亡目标移交无效。这里**如实告诉模型**,
|
||||
# 它就会自己在正文里圆过去(而不是干等着对方开口)
|
||||
raise ValueError(f'「{target.get("name")}」已经死亡,移交无效 —— 你自己接着说,或者交给别人')
|
||||
# ★ 用 update_context 而不是 push_context —— 后者是**替换**语义,
|
||||
# 会把 agentId / conversationId 一起冲掉,接着这个工具里的 _me() 就炸了
|
||||
tools_runtime.update_context(handoffTo=target['id'], handoffUsed=True)
|
||||
tools_runtime.note_handoff(target['id'])
|
||||
return {'handed_to': target.get('name'),
|
||||
'note': f'下一轮由「{target.get("name")}」接话。这一轮你不再移交了。'}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
HTTP 路由:把 Node 版 server/src/index.mjs 的接口逐条搬到 stdlib 上。
|
||||
|
||||
用的是 http.server.ThreadingHTTPServer + BaseHTTPRequestHandler:
|
||||
@@ -1807,7 +1807,11 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
pick = group_chat.resolve(
|
||||
conv0,
|
||||
want=group_chat.mention_in(last_user, names),
|
||||
passed=str(body.get('handoffTo') or ''),
|
||||
# ★★ 从**上一轮**的移交状态取,**不是**从 HTTP body ——
|
||||
# 界面(Kotlin)从来不发 handoffTo 这个字段,
|
||||
# 以前读 body 等于永远拿到空串,② AI 移交那条分支是**死代码**。
|
||||
# 现在 pass_turn 写在 tools_runtime 的轮次状态里,这里读它。
|
||||
passed=str(tools_runtime.handoff_state().get('to') or ''),
|
||||
alive={x['id']: not agentdb.is_dead(x['id']) for x in all_agents},
|
||||
)
|
||||
speaker = store.get_agent(pick.get('speaker'))
|
||||
|
||||
@@ -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'],
|
||||
|
||||
@@ -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):
|
||||
@@ -1180,10 +1216,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
|
||||
|
||||
|
||||
|
||||
@@ -165,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:
|
||||
"""
|
||||
界面工具开了没有。
|
||||
|
||||
@@ -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,51 @@
|
||||
# 智能体系统(需求 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.ChatPortrait`(crossfade 0.3s) |
|
||||
|
||||
### 两份"窗口"的命名纪律(需求点名要求,别混)
|
||||
|
||||
· 「记忆注入窗口」 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` |
|
||||
|
||||
这类问题的共同点:**三层各自看都对,只有真的跑一遍才看得见**。
|
||||
|
||||
---
|
||||
|
||||
@@ -27,7 +70,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 节 |
|
||||
|
||||
|
||||
@@ -678,6 +678,85 @@ 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'})
|
||||
|
||||
# ---------------------------------------------------------------- 汇总
|
||||
print()
|
||||
if fails:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""群聊仲裁的探针(v1.2 §3.9)。
|
||||
"""群聊仲裁的探针(v1.2 §3.9)。
|
||||
|
||||
点名制的分支有五种(用户 @ / AI 移交 / 兜底 / 被点的人死亡 / 一轮内重复移交),
|
||||
每一种都有明确的期望结果,而且**都不能报错**(报错的话用户看到的是
|
||||
@@ -144,13 +144,18 @@ def main():
|
||||
b['id'] in G.member_ids(store.get_conversation(c2['id']) or {}))
|
||||
|
||||
print("\n=== 6. pass_turn 工具 ===")
|
||||
# ★ 每次都 push 完整上下文 —— `push_context` 是**替换**语义,
|
||||
# 只补一个键会把 agentId / conversationId 冲掉(这个坑踩过)
|
||||
# ★ 每次 `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))
|
||||
check("上下文里记了移交标记", tools_runtime.current_context().get('handoffUsed') is True)
|
||||
check("也记了交给谁", tools_runtime.current_context().get('handoffTo') == b['id'])
|
||||
# ★ 读**轮次状态**,不是工具上下文 —— 上下文是 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': '仙辰'})
|
||||
@@ -162,6 +167,7 @@ def main():
|
||||
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': '死者'})
|
||||
@@ -169,11 +175,14 @@ def main():
|
||||
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',
|
||||
@@ -184,7 +193,54 @@ def main():
|
||||
check("一共 11 个(附录 B 的 10 个 + 建议机制)", len(agent_tools.AGENT_TOOLS) == 11,
|
||||
str(sorted(agent_tools.AGENT_TOOLS)))
|
||||
|
||||
print("\n=== 8. 私聊:轮数解析与额度判据 ===")
|
||||
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({})))
|
||||
@@ -202,7 +258,7 @@ def main():
|
||||
check("没超限额时 false", P.limit_hit({**a, 'tokenLimit': 1000}) is False)
|
||||
check("超了才是 true", P.limit_hit({**a, 'tokenLimit': 100}) is True)
|
||||
|
||||
print("\n=== 9. ★ 私聊的视角转换(两个 AI 各自在「跟对方聊天」)===")
|
||||
print("\n=== 10. ★ 私聊的视角转换(两个 AI 各自在「跟对方聊天」)===")
|
||||
turns = [
|
||||
{'agentId': a['id'], 'name': '玄辰', 'content': '你来了。'},
|
||||
{'agentId': b['id'], 'name': '仙辰', 'content': '嗯,路上耽搁了。'},
|
||||
@@ -214,7 +270,7 @@ def main():
|
||||
check("对 B 来说正好反过来",
|
||||
hb[0]['role'] == 'user' and hb[1]['role'] == 'assistant', str(hb))
|
||||
|
||||
print("\n=== 10. ★★ 安全网:轮数上限 + 一方触顶不撑独角戏 ===")
|
||||
print("\n=== 11. ★★ 安全网:轮数上限 + 一方触顶不撑独角戏 ===")
|
||||
#
|
||||
# 这两个是需求里私聊唯一的硬约束,也是最该测的 ——
|
||||
# 两个 AI 互相对话最大的风险就是**停不下来**(用户不在场,没人喊停)。
|
||||
@@ -273,7 +329,7 @@ def main():
|
||||
finally:
|
||||
agent_loop.run_agent = real_run_agent
|
||||
|
||||
print("\n=== 11. 私聊的边界 ===")
|
||||
print("\n=== 12. 私聊的边界 ===")
|
||||
check("没有共同世界观时不写记忆(不替人记他没参与的事)",
|
||||
P.summarize_to_memory(a, {'id': 'x', 'worldviewId': ''}, turns) == '')
|
||||
check("没说话时不写摘要", P.summarize_to_memory(a, b, []) == '')
|
||||
|
||||
Reference in New Issue
Block a user