diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AgentSelectScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentSelectScreen.kt new file mode 100644 index 0000000..2491f94 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AgentSelectScreen.kt @@ -0,0 +1,460 @@ +package com.doubao.lynxclone.ui + +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.LinearOutSlowInEasing +import androidx.compose.animation.core.tween +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.doubao.lynxclone.R +import com.doubao.lynxclone.data.AgentImage +import com.doubao.lynxclone.data.Agent +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +/* + * 智能体选择界面(需求第二章)。 + * + * ## 布局(需求 2.1) + * + * 左侧:智能体列表(纵向、当前项高亮) + * 右侧:角色展示区,**四层叠加**: + * ① 背景图(铺满)② 主体边框(框住展示区)③ 角色图(居中)④ 介绍边框(围住介绍文本) + * + * ## 切换动画(需求 2.3,定稿参数) + * + * ① 旧角色图渐出 + 侧移 0.3s ease-in + * ② 间隔 0.5s + * ③ 边框/背景/介绍 滑出滑入 0.4s ease-in-out + * ④ 新角色图渐入 + 侧移到位 0.3s ease-out + * 合计约 1.5s。 + * + * **方向**:目标在当前**之下**(列表靠后)→ 向左切换;**之上** → 向右。 + * + * **连续快速切换立即打断**:靠 `LaunchedEffect(选中的 id)` —— 换目标时 + * 上一个协程直接被取消,而 `Animatable` 会**停在当前值**,所以新动画 + * 是从眼前的画面接着走的,不会闪回。这正是需求要的"从当前视觉状态 + * 直接过渡到最新目标,不做排队"。 + * + * ## ★ 默认资源回退(需求 2.6) + * + * 角色图缺 → 内置默认人物;背景缺 → 内置默认背景;边框缺 → **简单方框**。 + * 回退优先级:`smartInfo.json 指定 → 包内同名 → 内置默认`。 + * 前两级在内核导入时就落定了(存的是绝对路径),所以这里只做最后一级。 + * + * ★ "任何智能体至少能以「默认人物 + 默认背景 + 方框边框」正常展示" —— + * 所以**每个槽位都必须有兜底**,不能出现空白展示区。 + */ + +/* -------------------------------------------------------------------------- */ +/* 动画参数(需求 2.3 说"收进全局配置") */ +/* -------------------------------------------------------------------------- */ + +private const val T_FRONT_OUT = 300 // ① 旧角色图出 +private const val T_GAP = 500 // ② 间隔 +private const val T_FRAME = 400 // ③ 边框/背景/介绍(滑出 + 滑入各一半) +private const val T_FRONT_IN = 300 // ④ 新角色图进 + +/** 侧移幅度占展示区宽度的比例。需求只说"侧移",幅度大了像翻页、小了看不出来 */ +private const val SHIFT = 0.10f + +@Composable +fun AgentSelectScreen( + agents: List, + activeId: String, + /** 选中并进入它的对话界面(需求 2.1:完成选择后进入对应智能体的对话界面) */ + onEnter: (Agent) -> Unit, + /** 「更多」→ Token 用量详情(需求 2.4) */ + onMore: (Agent) -> Unit, + /** 管理(新建 / 编辑 / 导入导出)—— 需求文档之外,但少了它用户没法加自己的智能体 */ + onManage: () -> Unit, + onBack: () -> Unit, +) { + if (agents.isEmpty()) { + Column(Modifier.fillMaxSize().background(doubaoBg()), verticalArrangement = Arrangement.Center) { + Text("还没有智能体", Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = doubaoText()) + Spacer(Modifier.height(12.dp)) + Text("点右上角「管理」新建或导入一个", Modifier.fillMaxWidth(), + textAlign = TextAlign.Center, fontSize = 12.sp, color = doubaoTextSecondary()) + Spacer(Modifier.height(20.dp)) + Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + TopAction("去管理", onClick = onManage) + } + } + return + } + + val startIndex = agents.indexOfFirst { it.id == activeId }.coerceAtLeast(0) + var picked by remember(agents.size) { mutableStateOf(startIndex) } + // `shown` 是**画面上正在显示**的那个;picked 变了之后要等动画走到第③阶段才换它 + var shown by remember(agents.size) { mutableStateOf(startIndex) } + val shownAgent = agents.getOrNull(shown) ?: agents.first() + val pickedAgent = agents.getOrNull(picked) ?: agents.first() + + val frontAlpha = remember { Animatable(1f) } + val frontShift = remember { Animatable(0f) } + val frameAlpha = remember { Animatable(1f) } + val frameShift = remember { Animatable(0f) } + val listState = rememberLazyListState() + + LaunchedEffect(picked, agents.size) { + if (picked == shown) return@LaunchedEffect + // 目标在列表靠后 = 向左切换(新内容从右边进来) + val dir = if (picked > shown) 1f else -1f + + // ① 旧角色图渐出 + 侧移 + launch { frontAlpha.animateTo(0f, tween(T_FRONT_OUT, easing = FastOutSlowInEasing)) } + frontShift.animateTo(-dir * SHIFT, tween(T_FRONT_OUT, easing = FastOutSlowInEasing)) + + // ② 间隔(需求明确定义了这一段留白) + delay(T_GAP.toLong()) + + // ③ 边框 / 背景 / 介绍:滑出 → 换数据 → 滑入 + val half = T_FRAME / 2 + launch { frameAlpha.animateTo(0f, tween(half, easing = FastOutSlowInEasing)) } + frameShift.animateTo(-dir * SHIFT, tween(half, easing = FastOutSlowInEasing)) + shown = picked + launch { frameAlpha.animateTo(1f, tween(half, easing = LinearOutSlowInEasing)) } + frameShift.animateTo(0f, tween(half, easing = LinearOutSlowInEasing)) + + // ④ 新角色图渐入 + 侧移到位 + frontShift.snapTo(dir * SHIFT) + launch { frontAlpha.animateTo(1f, tween(T_FRONT_IN, easing = LinearOutSlowInEasing)) } + frontShift.animateTo(0f, tween(T_FRONT_IN, easing = LinearOutSlowInEasing)) + } + + // 选中的那项滚进视野(列表长了之后不滚的话用户看不到自己选了谁) + LaunchedEffect(picked) { + runCatching { listState.animateScrollToItem(picked) } + } + + Column(Modifier.fillMaxSize().background(doubaoBg())) { + // ---------------- 顶栏 ---------------- + Row( + Modifier.fillMaxWidth().padding(horizontal = 6.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + "← 返回", + fontSize = 14.sp, + color = Doubao.Blue, + modifier = Modifier.clip(RoundedCornerShape(8.dp)) + .clickable { onBack() }.padding(horizontal = 10.dp, vertical = 8.dp), + ) + Spacer(Modifier.weight(1f)) + Text( + "选择智能体", + fontSize = 17.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + ) + Spacer(Modifier.weight(1f)) + TopTextAction("管理", onClick = onManage) + } + + // ---------------- 展示区 ---------------- + Box( + Modifier + .fillMaxWidth() + .weight(1f) + .padding(horizontal = 8.dp) + .clip(RoundedCornerShape(18.dp)), + ) { + // ① 背景图(最底层,铺满)—— 缺就用内置默认背景 + ArtworkFill(shownAgent.image.back, R.drawable.agent_default_background) + + // ② 左侧列表(浮在背景上) + AgentList( + agents = agents, + picked = picked, + onPick = { picked = it }, + state = listState, + modifier = Modifier.width(96.dp).fillMaxHeight().padding(8.dp), + ) + + // ③ 角色图(居中)。★ 它和右侧的边框/介绍一起跟着 frameShift 动 + Box( + Modifier + .fillMaxSize() + .padding(start = 96.dp, end = 10.dp, top = 10.dp, bottom = 10.dp), + ) { + Box( + Modifier + .fillMaxSize() + .offset(x = (frameShift.value * 180).dp) + .alpha(frameAlpha.value), + ) { + // ③-1 角色图 + Box( + Modifier.fillMaxSize().offset(x = (frontShift.value * 200).dp), + ) { + ArtworkFill( + shownAgent.image.front, + R.drawable.agent_default_character, + alpha = frontAlpha.value, + scale = ContentScale.Fit, + ) + } + + // ③-2 介绍边框 + 介绍文本(需求 2.1 的第 4 层) + IntroCard( + agent = shownAgent, + modifier = Modifier + .align(Alignment.BottomEnd) + .padding(end = 6.dp, bottom = 10.dp) + .width(200.dp), + ) + + // ③-3 主体边框(画在最上层,纯装饰) + MainBorder(shownAgent.image.borderMain) + } + } + + // ④ 「更多」按钮(需求 2.4:圆形、竖排三点、在角色图附近)→ Token 用量 + Box( + Modifier + .align(Alignment.TopEnd) + .padding(top = 10.dp, end = 12.dp) + .size(34.dp) + .clip(CircleShape) + .background(Color(0xCC1B2430)) + .clickable { onMore(shownAgent) }, + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Filled.MoreVert, + contentDescription = "用量详情", + tint = Color(0xFFE8EAED), + modifier = Modifier.size(20.dp), + ) + } + } + + // ---------------- 底部:进入对话 ---------------- + Row( + Modifier.fillMaxWidth().padding(12.dp), + horizontalArrangement = Arrangement.Center, + ) { + Box( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(26.dp)) + .background( + Brush.horizontalGradient(listOf(Color(0xFF2B7BFF), Color(0xFF5B9BFF))), + ) + .clickable { onEnter(pickedAgent) } + .padding(vertical = 14.dp), + contentAlignment = Alignment.Center, + ) { + Text( + "开始对话", + fontSize = 16.sp, + fontWeight = FontWeight.Medium, + color = Color.White, + ) + } + } + } +} + +/* -------------------------------------------------------------------------- */ +/* 四层的具体画法 */ +/* -------------------------------------------------------------------------- */ + +/** 铺满一层图;没有就用内置默认(需求 2.6 的最后一级回退) */ +@Composable +private fun ArtworkFill( + path: String, + fallbackRes: Int, + alpha: Float = 1f, + scale: ContentScale = ContentScale.Crop, +) { + Box(Modifier.fillMaxSize().alpha(alpha)) { + AssetImage( + path = path, + modifier = Modifier.fillMaxSize(), + contentScale = scale, + fallback = { + // ★ 内置默认图:**必须画出来**,不能是空白 —— + // 需求原话"任何智能体至少能以默认人物+默认背景+方框边框正常展示" + Image( + painter = painterResource(fallbackRes), + contentDescription = null, + modifier = Modifier.fillMaxSize(), + contentScale = scale, + ) + }, + ) + } +} + +/** 主体边框。缺的时候用**简单方框**(纯色细线矩形)兜底 */ +@Composable +private fun MainBorder(path: String) { + val shape = RoundedCornerShape(18.dp) + if (canShowImage(path)) { + AssetImage( + path = path, + modifier = Modifier.fillMaxSize(), + contentScale = ContentScale.FillBounds, + fallback = { SimpleFrame(shape) }, + ) + } else { + SimpleFrame(shape) + } +} + +@Composable +private fun SimpleFrame(shape: RoundedCornerShape) { + Box( + Modifier + .fillMaxSize() + .border(1.dp, Doubao.Blue.copy(alpha = 0.45f), shape), + ) +} + +/** + * 介绍卡片(需求 2.1 的"介绍边框 + 介绍文本")。 + * + * 文本来自 `description`;缺失时**只显示智能体名**(需求原文)。 + */ +@Composable +private fun IntroCard(agent: Agent, modifier: Modifier = Modifier) { + Column( + modifier + .clip(RoundedCornerShape(14.dp)) + .background(Color(0xE6FFFDF5)) + .border(1.dp, Color(0x66B9A46A), RoundedCornerShape(14.dp)) + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + Text( + agent.name, + fontSize = 15.sp, + fontWeight = FontWeight.Medium, + color = Color(0xFF2A2419), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + val desc = agent.description.trim().ifBlank { agent.greeting.trim() } + if (desc.isNotBlank()) { + Spacer(Modifier.height(6.dp)) + Text( + desc, + fontSize = 11.sp, + lineHeight = 16.sp, + color = Color(0xFF4A4232), + maxLines = 6, + overflow = TextOverflow.Ellipsis, + ) + } + } +} + +/** 左侧列表:一张卡片 = 缩略图 + 名字;当前项高亮 */ +@Composable +private fun AgentList( + agents: List, + picked: Int, + onPick: (Int) -> Unit, + state: androidx.compose.foundation.lazy.LazyListState, + modifier: Modifier = Modifier, +) { + LazyColumn(modifier, state = state, verticalArrangement = Arrangement.spacedBy(8.dp)) { + itemsIndexed(agents) { index, agent -> + val on = index == picked + Column( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(if (on) Color(0xCC2B7BFF) else Color(0x99101820)) + .border( + width = if (on) 1.5.dp else 0.5.dp, + color = if (on) Color(0xFFFFE08A) else Color(0x33FFFFFF), + shape = RoundedCornerShape(12.dp), + ) + .clickable { onPick(index) } + .padding(4.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Box( + Modifier + .fillMaxWidth() + .height(52.dp) + .clip(RoundedCornerShape(9.dp)) + .background(Color(0x33FFFFFF)), + ) { + // 缩略图:也用角色图(缺就默认人物)—— 和右侧是同一套回退。 + // ★ alignment = TopCenter:角色图是竖长的,居中裁剪只会 + // 裁出"腰到大腿",一排缩略图全是裤子 + AssetImage( + path = agent.image.front, + modifier = Modifier.fillMaxSize(), + contentScale = ContentScale.Crop, + alignment = Alignment.TopCenter, + fallback = { + Image( + painter = painterResource(R.drawable.agent_default_character), + contentDescription = null, + modifier = Modifier.fillMaxSize(), + contentScale = ContentScale.Crop, + alignment = Alignment.TopCenter, + ) + }, + ) + } + Spacer(Modifier.height(3.dp)) + Text( + agent.name.ifBlank { "未命名" }, + fontSize = 11.sp, + color = Color.White, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center, + ) + } + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt index d6a3b6f..7c687ab 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt @@ -72,6 +72,43 @@ fun AppRoot( val vm = rememberAppViewModel(client) LaunchedEffect(Unit) { vm.refresh() } + /* ---------------- 记忆的导入 / 导出(SAF)---------------- + * + * ★ 为什么用系统的文件选择器而不是自己写路径:安卓 11+ 已经不给 + * App 随便写公共目录了,SAF 是唯一"用户想存哪就存哪"的正路 + * (会议导出、节点导出都是这条路,见 MeetingsScreen)。 + * ★ 编码固定 UTF-8:记忆里有中文,用默认编码在别的机器上会变乱码。 + */ + val ctx = androidx.compose.ui.platform.LocalContext.current + var pendingExport by remember { mutableStateOf(null) } + val createMemoryDoc = androidx.activity.compose.rememberLauncherForActivityResult( + androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/json"), + ) { uri -> + val text = pendingExport + pendingExport = null + if (uri != null && text != null) { + runCatching { + ctx.contentResolver.openOutputStream(uri)?.use { it.write(text.toByteArray(Charsets.UTF_8)) } + }.onFailure { vm.showHint("导出失败:${it.message ?: "写不进去"}") } + .onSuccess { vm.showHint("记忆已导出") } + } + } + val importMemoryDoc = androidx.activity.compose.rememberLauncherForActivityResult( + androidx.activity.result.contract.ActivityResultContracts.OpenDocument(), + ) { uri -> + if (uri != null) { + runCatching { + ctx.contentResolver.openInputStream(uri)?.use { input -> + input.readBytes().toString(Charsets.UTF_8) + } ?: "" + }.onSuccess { text -> + // ★ 默认**合并**(需求 3.4 定的默认值):按标题去重、保留现有。 + // 覆盖是破坏性的,不该是默认 —— 用户点错一次就全没了。 + if (text.isNotBlank()) vm.importMemories(text, "merge") + }.onFailure { vm.showHint("读不出这个文件") } + } + } + // 提示条 2.5 秒后自动消失 LaunchedEffect(vm.hint) { if (vm.hint.isNotBlank()) { @@ -104,6 +141,15 @@ fun AppRoot( Screen.Settings -> SettingsScreen(vm) Screen.Skills -> SkillsScreen(vm) Screen.Agents -> AgentsScreen(vm) + // 智能体选择界面(需求第二章):左列表 + 右角色展示 + 切换动画 + Screen.AgentSelect -> AgentSelectScreen( + agents = vm.agents, + activeId = vm.state.settings.activeAgentId, + onEnter = { vm.enterAgent(it.id) }, + onMore = { vm.openTokenUsage(it.id) }, + onManage = { vm.screen = Screen.Agents }, + onBack = { vm.screen = Screen.Chat }, + ) Screen.Meetings -> MeetingsScreen(vm) Screen.Terminal -> TerminalScreen(vm, termuxReady, termuxStatus, onInstallTermux) } @@ -188,6 +234,54 @@ fun AppRoot( ) } + // 「用量」详情 —— 选择界面上的「更多」按钮(需求 2.4 / 3.1) + AnimatedVisibility( + visible = vm.tokenUsageOpen, + enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)), + exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)), + ) { + TokenUsageScreen( + usage = vm.tokenUsage, + onReset = { vm.tokenUsage?.agentId?.takeIf { it.isNotBlank() }?.let { vm.resetTokenUsage(it) } }, + onBack = { vm.closeTokenUsage() }, + ) + } + + // 「记忆」管理(需求 3.2 的"用户手动编辑兜底") + AnimatedVisibility( + visible = vm.memoryAgentId.isNotBlank(), + enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)), + exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)), + ) { + MemoryScreen( + space = vm.memorySpace, + agentName = vm.agents.firstOrNull { it.id == vm.memoryAgentId }?.name ?: "", + loading = vm.memoryLoading, + hint = vm.memoryHint, + onSetEmotion = { vm.setEmotion(it) }, + onAdd = { t, c -> vm.addMemory(t, c) }, + onUpdate = { id, t, c -> vm.updateMemory(id, t, c) }, + onDelete = { vm.deleteMemory(it) }, + onTogglePin = { id, p -> vm.toggleMemoryPin(id, p) }, + onSummarize = { vm.summarizeMemories() }, + onExport = { vm.exportMemories { text -> pendingExport = text } }, + onImportClick = { importMemoryDoc.launch(arrayOf("application/json", "text/plain", "*/*")) }, + onBack = { vm.closeMemories() }, + ) + } + + // 拿到 JSON 之后再弹存盘对话框(先有内容才能给文件名,顺序不能反) + LaunchedEffect(pendingExport) { + val text = pendingExport ?: return@LaunchedEffect + if (text.isNotBlank()) { + runCatching { + createMemoryDoc.launch( + "${vm.agents.firstOrNull { it.id == vm.memoryAgentId }?.name ?: "agent"}-记忆.json", + ) + } + } + } + // 「超时」—— 所有超时都能调(入口在设置页) AnimatedVisibility( visible = vm.timeoutsOpen, @@ -305,7 +399,9 @@ private fun DrawerOverlay(vm: AppViewModel) { SectionLabel("功能", Modifier.padding(horizontal = 20.dp, vertical = 6.dp)) DrawerItem(Icons.Filled.AddComment, "开启新话题") { vm.newTopic() } DrawerItem(Icons.Filled.AutoAwesome, "智能体") { - vm.screen = Screen.Agents; vm.drawerOpen = false + // ★ 抽屉这一项进的是**选择界面**(需求 2.1 的入口页), + // 管理(新建/编辑/导入导出)在那个页面的「管理」里 + vm.screen = Screen.AgentSelect; vm.drawerOpen = false } // 「笔记」—— 用户要能查看 AI 替他记了什么 DrawerItem(Icons.Filled.EditNote, "笔记") { diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt index d8e2c1d..6c43d29 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt @@ -27,8 +27,8 @@ import org.json.JSONArray import org.json.JSONObject import java.util.concurrent.atomic.AtomicBoolean -/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应) */ -enum class Screen { Chat, Profile, Settings, Skills, Agents, Terminal, Meetings } +/** 页面路由(跟原来 Lynx 版的 7 个页面一一对应;AgentSelect 是需求 v1.1 新增的选择页) */ +enum class Screen { Chat, Profile, Settings, Skills, Agents, AgentSelect, Terminal, Meetings } /** * 全局状态。界面只读这里的状态、只调这里的方法,网络全在 KernelClient 里。 @@ -138,8 +138,184 @@ class AppViewModel(val client: KernelClient) : ViewModel() { } } - /* -------------------- 超时(全部可调)-------------------- */ + /* -------------------- 智能体系统(需求 v1.1)-------------------- */ + /** + * 选择界面上"开始对话":把这个人设为当前,然后回聊天页。 + * + * ★ 需求 2.1 的定位是"选择智能体的入口页,**完成选择后进入对话界面**"—— + * 所以这里既切人设也切页面,用户不用自己再点一次返回。 + */ + fun enterAgent(agentId: String) { + useAgent(agentId) + screen = Screen.Chat + } + + /** 用量详情(选择界面「更多」按钮,需求 3.1) */ + var tokenUsage by mutableStateOf(null) + private set + + var tokenUsageOpen by mutableStateOf(false) + private set + + fun openTokenUsage(agentId: String) { + tokenUsageOpen = true + tokenUsage = null + viewModelScope.launch { + tokenUsage = runCatching { + withContext(Dispatchers.IO) { client.tokenUsage(agentId) } + }.getOrNull() + } + } + + fun closeTokenUsage() { + tokenUsageOpen = false + } + + /** 清零(需求 3.1 的"管理操作",界面会先弹一次确认) */ + fun resetTokenUsage(agentId: String) { + viewModelScope.launch { + tokenUsage = runCatching { + withContext(Dispatchers.IO) { client.resetTokenUsage(agentId) } + }.getOrNull() ?: tokenUsage + } + } + + /** 记忆空间(列表 + 情绪 + AI 的建议) */ + var memorySpace by mutableStateOf(null) + private set + + /** 正在看谁的记忆(null = 没打开) */ + var memoryAgentId by mutableStateOf("") + private set + + var memoryLoading by mutableStateOf(false) + private set + + /** AI 整理记忆的结果提示("12 条 → 7 条"这种) */ + var memoryHint by mutableStateOf("") + private set + + fun openMemories(agentId: String) { + memoryAgentId = agentId + memoryHint = "" + refreshMemories() + } + + fun closeMemories() { + memoryAgentId = "" + memorySpace = null + } + + fun refreshMemories() { + val id = memoryAgentId + if (id.isBlank()) return + memoryLoading = true + viewModelScope.launch { + memorySpace = runCatching { + withContext(Dispatchers.IO) { client.memories(id) } + }.getOrNull() + memoryLoading = false + } + } + + fun setEmotion(text: String) { + val id = memoryAgentId + if (id.isBlank()) return + viewModelScope.launch { + runCatching { withContext(Dispatchers.IO) { client.setEmotion(id, text) } } + refreshMemories() + } + } + + fun addMemory(title: String, content: String) { + val id = memoryAgentId + if (id.isBlank()) return + viewModelScope.launch { + runCatching { withContext(Dispatchers.IO) { client.addMemory(id, title, content) } } + refreshMemories() + } + } + + fun updateMemory(mid: String, title: String?, content: String?) { + viewModelScope.launch { + runCatching { withContext(Dispatchers.IO) { client.updateMemory(mid, title, content) } } + refreshMemories() + } + } + + fun deleteMemory(mid: String) { + viewModelScope.launch { + runCatching { withContext(Dispatchers.IO) { client.deleteMemory(mid) } } + refreshMemories() + } + } + + fun toggleMemoryPin(mid: String, pinned: Boolean) { + viewModelScope.launch { + runCatching { withContext(Dispatchers.IO) { client.pinMemory(mid, pinned) } } + refreshMemories() + } + } + + /** + * 让 AI 整理一次记忆(需求 3.2)。 + * + * ★ 这是**一次真的 LLM 调用**(会花 Token、要等几秒),所以界面上要给人反馈 —— + * 按钮按下之后显示"整理中…",回来之后报"12 条 → 7 条"。 + */ + fun summarizeMemories() { + val id = memoryAgentId + if (id.isBlank()) return + memoryLoading = true + memoryHint = "" + viewModelScope.launch { + val res = runCatching { + withContext(Dispatchers.IO) { client.summarizeMemories(id) } + }.getOrNull() + memoryHint = when { + res == null -> "整理失败(看内核日志)" + res.optBoolean("summarized") -> + "整理好了:${res.optInt("before")} 条 → ${res.optInt("after")} 条" + + if (res.optInt("keptPinned") > 0) "(保留了 ${res.optInt("keptPinned")} 条「必须保留」)" else "" + else -> res.optString("error").ifBlank { res.optString("reason").ifBlank { "没有可整理的记忆" } } + } + memoryLoading = false + refreshMemories() + refresh() // 用量变了,「更多」里要跟着变 + } + } + + fun exportMemories(onDone: (String) -> Unit) { + val id = memoryAgentId + if (id.isBlank()) return + viewModelScope.launch { + val text = runCatching { + withContext(Dispatchers.IO) { client.exportMemories(id) } + }.getOrNull() + if (text.isNullOrBlank()) showHint("导出失败") else onDone(text) + } + } + + fun importMemories(json: String, mode: String) { + val id = memoryAgentId + if (id.isBlank()) return + memoryLoading = true + viewModelScope.launch { + val res = runCatching { + withContext(Dispatchers.IO) { client.importMemories(id, json, mode) } + }.getOrNull() + memoryHint = if (res == null) "导入失败" else { + val err = res.optString("error") + if (err.isNotBlank()) err + else "导入完成:新增 ${res.optInt("added")} 条,跳过重名 ${res.optInt("skipped")} 条" + } + memoryLoading = false + refreshMemories() + } + } + + /* -------------------- 超时(全部可调)-------------------- */ /** * 超时清单 + 当前值。 * diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AssetImage.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AssetImage.kt new file mode 100644 index 0000000..28bf989 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AssetImage.kt @@ -0,0 +1,226 @@ +package com.doubao.lynxclone.ui + +import android.graphics.BitmapFactory +import android.graphics.ImageDecoder +import android.graphics.drawable.Drawable +import android.os.Build +import android.util.Log +import android.widget.ImageView +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.unit.sp +import androidx.compose.ui.viewinterop.AndroidView +import java.io.File + +/* + * 显示智能体/世界观包里的图片资源。 + * + * ## ★ 为什么不用 Coil / Glide + * + * 项目一直坚持**零第三方依赖**(安卓端构建要能离线完成、APK 也不要多几百 KB)。 + * 而这里要的东西其实很窄:显示一个已知路径的本地图片。 + * Android 原生的三套 API 正好够: + * + * · PNG / JPG → `BitmapFactory.decodeFile`(所有版本) + * · GIF 动图 → `ImageDecoder.decodeDrawable`(API 28+,低版本退化成静态第一帧) + * · SVG → 原生**解不了**,走 WebView(项目里已经大量在用 WebView) + * + * ## 为什么静态图不统一走 ImageView + * + * 因为 Compose 的 `Image(bitmap)` 在裁剪/圆角/缩放上比 `AndroidView` 包一层 + * 可控得多(`Modifier.clip` / `ContentScale` 直接生效),而 GIF 又必须用 + * `Drawable`(Compose 没有原生的动图 Painter,accompanist 是第三方)。 + * 所以按扩展名分流:常见的静态图走低成本那条,动图才付出 AndroidView 的代价。 + * + * ## 缺失资源的回退(需求 2.6) + * + * 回退是**调用方**的事(`AgentArtwork` 里判的),这里只负责"路径给了就画"。 + * 给空路径、文件不存在,这里返回 false 让调用方决定显示什么。 + */ + +private const val TAG = "DoubaoImage" + +/** 这个文件是哪种图(按扩展名,和内核 uploads.py 一个思路) */ +private enum class ImageKind { Static, Gif, Svg, Unknown } + +private fun kindOf(path: String): ImageKind = when (File(path).extension.lowercase()) { + "gif" -> ImageKind.Gif + "svg" -> ImageKind.Svg + "png", "jpg", "jpeg", "webp", "bmp" -> ImageKind.Static + else -> ImageKind.Unknown +} + +/** + * 画一张本地图片。 + * + * @param path 绝对路径(内核给的就是绝对路径) + * @param fallback 画不出来时显示什么(通常是默认图或一个占位框) + */ +@Composable +fun AssetImage( + path: String, + modifier: Modifier = Modifier, + contentScale: ContentScale = ContentScale.Fit, + /** + * 裁剪时对齐哪儿。 + * + * ★ 缩略图必须给 `TopCenter`:角色图是**竖长**的(头在上半部分), + * 居中对齐裁出来的是"腰到大腿"——列表里一排裤子,谁也认不出是谁。 + */ + alignment: Alignment = Alignment.Center, + fallback: @Composable () -> Unit = {}, +) { + val file = remember(path) { if (path.isBlank()) null else File(path) } + if (file == null || !file.isFile) { + Box(modifier, contentAlignment = Alignment.Center) { fallback() } + return + } + + when (kindOf(path)) { + ImageKind.Svg -> SvgImage(file, modifier) + ImageKind.Gif -> DrawableImage(file, modifier, contentScale, alignment, fallback) + else -> StaticImage(file, modifier, contentScale, alignment, fallback) + } +} + +@Composable +private fun StaticImage( + file: File, + modifier: Modifier, + contentScale: ContentScale, + alignment: Alignment, + fallback: @Composable () -> Unit, +) { + // ★ remember(file.path):同一张图不重复解码。列表里滚动时这一下省很多。 + val bitmap = remember(file.path) { + runCatching { BitmapFactory.decodeFile(file.path) }.getOrNull() + } + if (bitmap == null) { + Box(modifier, contentAlignment = Alignment.Center) { fallback() } + return + } + Image( + bitmap = bitmap.asImageBitmap(), + contentDescription = null, + modifier = modifier, + contentScale = contentScale, + alignment = alignment, + ) +} + +/** + * 动图(GIF)。 + * + * ★ API 28 以下 `ImageDecoder` 不存在 —— 退回 `BitmapFactory` 拿第一帧, + * 至少不是空白。项目 minSdk 是 24,所以这条分支真的会走到。 + */ +@Composable +private fun DrawableImage( + file: File, + modifier: Modifier, + contentScale: ContentScale, + alignment: Alignment, + fallback: @Composable () -> Unit, +) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { + StaticImage(file, modifier, contentScale, alignment, fallback) + return + } + val drawable: Drawable? = remember(file.path) { + runCatching { + // ★ 宽度在 `info` 上(`ImageDecoder` 自己只有 setTargetSampleSize)—— + // 写成 `decoder.width` 是编译不过的 + ImageDecoder.decodeDrawable(ImageDecoder.createSource(file)) { decoder, info, _ -> + // 缩到 1024 以内:包里的图可能很大,全尺寸解码在低端机上会 OOM + val w = info.size.width + if (w > 1024) decoder.setTargetSampleSize(kotlin.math.round(w / 1024f).coerceAtLeast(1f).toInt()) + } + }.getOrNull() + } + if (drawable == null) { + Box(modifier, contentAlignment = Alignment.Center) { fallback() } + return + } + AndroidView( + modifier = modifier, + factory = { ctx -> + ImageView(ctx).apply { + setImageDrawable(drawable) + scaleType = when (contentScale) { + ContentScale.Crop -> ImageView.ScaleType.CENTER_CROP + ContentScale.FillBounds -> ImageView.ScaleType.FIT_XY + else -> ImageView.ScaleType.FIT_CENTER + } + } + }, + // 动图由 Drawable 自己驱动,不需要在 update 里做任何事; + // 但路径变了要换图 —— 这个 composable 的 key 已经是路径,重建即可。 + ) +} + +/** + * SVG。 + * + * ★ 原生解不了 SVG(`BitmapFactory` 直接返回 null),而引一个 SVG 库 + * 就破了"零第三方依赖"。项目里已经有成熟的 WebView 通道 + * (AI 界面就全靠它),所以这里用 WebView 单图显示。 + * + * ★ 关掉一切交互:它是**背景/装饰**,不能抢走列表的滑动和点击。 + */ +@Composable +private fun SvgImage(file: File, modifier: Modifier) { + AndroidView( + modifier = modifier, + factory = { ctx -> + android.webkit.WebView(ctx).apply { + setBackgroundColor(android.graphics.Color.TRANSPARENT) + settings.javaScriptEnabled = false + settings.allowFileAccess = true + isClickable = false + isFocusable = false + // 让触摸穿透到下面的列表(不然在列表里滑动会被 WebView 吃掉) + setOnTouchListener { _, _ -> false } + loadDataWithBaseURL( + "file://" + file.parent + "/", + """ + + """, + "text/html", "UTF-8", null, + ) + } + }, + ) +} + +/** 占位:没有图时显示一个淡淡的灰框 + 可选文字(需求 2.6 的"简单方框") */ +@Composable +fun ImagePlaceholder(modifier: Modifier = Modifier, text: String = "") { + Box( + modifier.then(Modifier.fillMaxSize()), + contentAlignment = Alignment.Center, + ) { + if (text.isNotBlank()) { + Text(text, fontSize = 10.sp, color = doubaoTextSecondary()) + } + } +} + +/** 图片能不能画出来(调用方据此决定要不要回退到默认资源) */ +fun canShowImage(path: String): Boolean { + if (path.isBlank()) return false + val f = File(path) + if (!f.isFile) { + Log.w(TAG, "图片不存在:$path") + return false + } + return true +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt index e92fcb7..e9fafa7 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt @@ -43,6 +43,7 @@ import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.AnnotatedString @@ -361,11 +362,15 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro HeaderIcon(Icons.Filled.Edit, "新话题") { vm.newTopic() } Spacer(Modifier.weight(1f)) - // 中间这块点开就是「模型」,和豆包一样(豆包点的是 Agent 名) + // 中间这块点开是**智能体选择界面**(需求 2.1:它是"选择智能体的入口页")。 + // + // ★ 以前点这里是「模型」面板 —— 但用户想"换个人聊"时点的是名字, + // 而模型是"换脑子"、不是"换人",两者混在一个入口里说不清。 + // 模型仍然在抽屉里有独立入口(那才是它该在的地方)。 Row( Modifier .clip(RoundedCornerShape(16.dp)) - .clickable { vm.modelPickerOpen = true } + .clickable { vm.screen = Screen.AgentSelect } .padding(horizontal = 8.dp, vertical = 2.dp), verticalAlignment = Alignment.CenterVertically, ) { @@ -373,7 +378,21 @@ private fun ChatHeader(vm: AppViewModel, agentName: String, speech: SpeechContro Modifier.size(24.dp).clip(CircleShape).background(doubaoHeroRing()), contentAlignment = Alignment.Center, ) { - Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp)) + // 有自定义角色图就显示它(需求 2.5 的资源回退在内核侧已经落定, + // 这里 path 为空就还是原来的图标) + val art = vm.activeAgent?.image?.front ?: "" + if (art.isNotBlank()) { + AssetImage( + path = art, + modifier = Modifier.fillMaxSize().clip(CircleShape), + contentScale = ContentScale.Crop, + fallback = { + Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp)) + }, + ) + } else { + Icon(Icons.Filled.Face, null, tint = Doubao.Blue, modifier = Modifier.size(17.dp)) + } } Spacer(Modifier.width(6.dp)) Text(agentName, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText()) diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/MemoryScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/MemoryScreen.kt new file mode 100644 index 0000000..a229b13 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/MemoryScreen.kt @@ -0,0 +1,348 @@ +package com.doubao.lynxclone.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.doubao.lynxclone.data.MemoryItem +import com.doubao.lynxclone.data.MemorySpace + +/* + * 记忆管理(需求 3.2 / 3.5)。 + * + * ## 这个界面存在的理由 + * + * 需求里记忆是"**混合制**":AI 通过工具自主读写,**用户手动编辑兜底**。 + * 没有这个界面,"兜底"就是空话 —— AI 记错了东西,用户只能干看着 + * (而他会记错:模型把"他喜欢猫"记成"他讨厌猫"这种事很常见)。 + * + * 顺带把三样东西一起放进来,因为它们都是"这个智能体的内在状态": + * · 情绪(需求 3.5:用户可手动编辑) + * · AI 提的"该整理记忆了"建议(需求 3.2:仅提示,用户确认才执行) + * · 导入 / 导出(需求 3.4) + * + * ## 共享记忆要**显式说明** + * + * 绑了世界观的智能体,记忆是和同世界观其他智能体**共用**的。 + * 界面上不写清楚的话,用户会以为"我给 A 记的东西怎么 B 也知道" —— + * 所以顶部有一条明显的提示。 + */ + +@Composable +fun MemoryScreen( + space: MemorySpace?, + agentName: String, + loading: Boolean, + hint: String, + onSetEmotion: (String) -> Unit, + onAdd: (String, String) -> Unit, + onUpdate: (String, String?, String?) -> Unit, + onDelete: (String) -> Unit, + onTogglePin: (String, Boolean) -> Unit, + onSummarize: () -> Unit, + onExport: () -> Unit, + onImportClick: () -> Unit, + onBack: () -> Unit, +) { + var editing by remember { mutableStateOf(null) } + var adding by remember { mutableStateOf(false) } + var emotionDraft by remember(space?.emotion) { mutableStateOf(space?.emotion ?: "") } + + FullScreen( + title = "记忆", + subtitle = buildString { + append(agentName.ifBlank { "智能体" }) + space?.let { + append(" · ") + append(if (it.shared) "世界观共享记忆" else "私有记忆") + append(" ${it.memories.size} 条") + } + if (loading) append(" · 处理中…") + }, + onBack = onBack, + actions = { + TopTextAction("导入", onClick = onImportClick) + }, + ) { + Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) { + // ---- 共享记忆提示(不写清楚用户会以为记忆串了)---- + if (space?.shared == true) { + Row( + Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 6.dp) + .clip(RoundedCornerShape(10.dp)) + .background(Color(0x14F29900)) + .padding(10.dp), + ) { + Text( + "这个智能体绑定了世界观,记忆是**和同世界观的其他智能体共用**的。\n" + + "它能改自己写的条目;改别人的(或删)需要你在这里手动操作。", + fontSize = 11.sp, + lineHeight = 16.sp, + color = Color(0xFF8A6100), + ) + } + } + + // ---- AI 的建议(需求 3.2:仅提示,用户确认才执行)---- + if (!space?.suggestion.isNullOrBlank()) { + Row( + Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 6.dp) + .clip(RoundedCornerShape(10.dp)) + .background(Doubao.Blue.copy(alpha = 0.08f)) + .padding(10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text("AI 觉得记忆该整理一下了", fontSize = 12.sp, color = Doubao.Blue) + Spacer(Modifier.height(2.dp)) + Text(space?.suggestion ?: "", fontSize = 11.sp, color = doubaoTextSecondary()) + } + Text( + "整理", + fontSize = 13.sp, + color = Color.White, + modifier = Modifier + .clip(RoundedCornerShape(14.dp)) + .background(Doubao.Blue) + .clickable(enabled = !loading) { onSummarize() } + .padding(horizontal = 12.dp, vertical = 6.dp), + ) + } + } + + if (hint.isNotBlank()) { + Text( + hint, + fontSize = 12.sp, + color = Doubao.Blue, + modifier = Modifier.padding(horizontal = 14.dp, vertical = 6.dp), + ) + } + + // ---- 情绪 ---- + SectionLabel("情绪") + Column( + Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp) + .clip(RoundedCornerShape(14.dp)) + .background(doubaoSurface()) + .padding(12.dp), + ) { + Text( + "AI 自己能改(emotion_set),你也可以在这里改。它每次对话都会被带进提示词。", + fontSize = 11.sp, + lineHeight = 16.sp, + color = doubaoTextSecondary(), + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = emotionDraft, + onValueChange = { emotionDraft = it }, + placeholder = { Text("比如:刚被夸了,有点得意", fontSize = 13.sp) }, + modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp), + textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp), + ) + Spacer(Modifier.height(6.dp)) + Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) { + TextButton( + onClick = { onSetEmotion(emotionDraft.trim()) }, + enabled = emotionDraft.trim() != (space?.emotion ?: ""), + ) { Text("保存情绪", fontSize = 13.sp) } + } + } + + // ---- 操作条 ---- + SectionLabel("记忆(按时间排,最新的在下面)") + Row( + Modifier.fillMaxWidth().padding(horizontal = 12.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + SmallAction("+ 加一条") { adding = true } + SmallAction(if (loading) "整理中…" else "AI 整理") { if (!loading) onSummarize() } + SmallAction("导出文件", onClick = onExport) + } + + Spacer(Modifier.height(8.dp)) + + // ---- 列表 ---- + val items = space?.memories ?: emptyList() + if (items.isEmpty()) { + Text( + if (loading) "读取中…" else "还没有记忆。AI 觉得有值得记住的事时会自己记下来。", + fontSize = 12.sp, + color = doubaoTextSecondary(), + modifier = Modifier.padding(horizontal = 14.dp, vertical = 16.dp), + ) + } + for (m in items) { + MemoryRow( + item = m, + onEdit = { editing = m }, + onDelete = { onDelete(m.id) }, + onTogglePin = { onTogglePin(m.id, !m.pinned) }, + ) + } + Spacer(Modifier.height(28.dp)) + } + } + + // ---- 编辑 / 新增 ---- + val target = editing + if (target != null || adding) { + MemoryEditDialog( + initial = target, + onDismiss = { editing = null; adding = false }, + onSave = { title, content -> + if (target == null) onAdd(title, content) else onUpdate(target.id, title, content) + editing = null + adding = false + }, + ) + } +} + +@Composable +private fun SmallAction(label: String, onClick: () -> Unit) { + Text( + label, + fontSize = 12.sp, + color = Doubao.Blue, + modifier = Modifier + .clip(RoundedCornerShape(14.dp)) + .background(Doubao.Blue.copy(alpha = 0.10f)) + .clickable { onClick() } + .padding(horizontal = 12.dp, vertical = 7.dp), + ) +} + +@Composable +private fun MemoryRow( + item: MemoryItem, + onEdit: () -> Unit, + onDelete: () -> Unit, + onTogglePin: () -> Unit, +) { + Column( + Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 4.dp) + .clip(RoundedCornerShape(12.dp)) + .background(doubaoSurface()) + .border( + width = if (item.pinned) 1.dp else 0.dp, + color = if (item.pinned) Color(0x66F29900) else Color.Transparent, + shape = RoundedCornerShape(12.dp), + ) + .padding(12.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + if (item.pinned) { + Text( + "必须保留", + fontSize = 9.sp, + color = Color(0xFF8A6100), + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .background(Color(0x22F29900)) + .padding(horizontal = 5.dp, vertical = 2.dp), + ) + Spacer(Modifier.width(6.dp)) + } + Text( + item.title.ifBlank { "(无标题)" }, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + modifier = Modifier.weight(1f), + ) + } + if (item.content.isNotBlank()) { + Spacer(Modifier.height(4.dp)) + Text(item.content, fontSize = 12.sp, lineHeight = 18.sp, color = doubaoTextSecondary()) + } + Spacer(Modifier.height(8.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + // ★「必须保留」是**用户**的权利(需求 3.2):标上之后 AI 总结时 + // 不参与合并、AI 自己也改不动 —— 所以这个开关只在界面上给 + RowAction(if (item.pinned) "取消保留" else "必须保留", onClick = onTogglePin) + RowAction("编辑", onClick = onEdit) + RowAction("删除", danger = true, onClick = onDelete) + } + } +} + +@Composable +private fun MemoryEditDialog( + initial: MemoryItem?, + onDismiss: () -> Unit, + onSave: (String, String) -> Unit, +) { + var title by remember { mutableStateOf(initial?.title ?: "") } + var content by remember { mutableStateOf(initial?.content ?: "") } + // ★ 单条记忆的编辑用弹窗是合适的(内容量小、就是两个输入框); + // 而"列表 / 多组配置"一律全屏 —— 见 AGENTS.md 那张表 + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(if (initial == null) "加一条记忆" else "编辑记忆", fontSize = 16.sp) }, + text = { + Column { + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text("标题", fontSize = 12.sp) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp), + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = content, + onValueChange = { content = it }, + label = { Text("内容", fontSize = 12.sp) }, + modifier = Modifier.fillMaxWidth().heightIn(min = 90.dp, max = 220.dp), + textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp), + ) + } + }, + confirmButton = { + TextButton( + onClick = { onSave(title.trim(), content.trim()) }, + enabled = title.isNotBlank() || content.isNotBlank(), + ) { Text("保存") } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } }, + ) +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/TokenUsageScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/TokenUsageScreen.kt new file mode 100644 index 0000000..5a61de0 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/TokenUsageScreen.kt @@ -0,0 +1,212 @@ +package com.doubao.lynxclone.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.doubao.lynxclone.data.TokenUsage + +/* + * Token 用量详情(需求 3.1 的展示入口:选择界面「更多」按钮)。 + * + * ## 展示什么 + * + * · 累计用量(**输入 / 输出分列**,需求明确要求不合并) + * · 限额进度(没限额就显示"无限制") + * · **按模型分行**(需求 3.1 的"按模型分桶",可看总数也可展开) + * · 配了单价才显示估算费用 —— 没配就只显示 Token 数,不瞎估 + * + * ## 不做历史曲线 + * + * 需求原话"当前不做曲线"(时间戳只是为将来预留)。 + * + * ## 做全屏而不是弹窗 + * + * 见 AGENTS.md「少用弹窗」。这里要放三四行数字 + 一张可能十几行的模型表, + * 弹窗装不下。 + */ + +@Composable +fun TokenUsageScreen( + usage: TokenUsage?, + onReset: () -> Unit, + onBack: () -> Unit, +) { + FullScreen( + title = "用量", + subtitle = usage?.name?.takeIf { it.isNotBlank() }?.let { "$it · 累计" } ?: "正在读取…", + onBack = onBack, + actions = { + if (usage != null && usage.total > 0) TopTextAction("清零", danger = true, onClick = onReset) + }, + ) { + if (usage == null) { + Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) { + Text("正在读取…", fontSize = 13.sp, color = doubaoTextSecondary()) + } + return@FullScreen + } + Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) { + // ---- 总览 ---- + Card { + Text("累计消耗", fontSize = 12.sp, color = doubaoTextSecondary()) + Spacer(Modifier.height(6.dp)) + Text( + fmtTokens(usage.total), + fontSize = 30.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + ) + Spacer(Modifier.height(10.dp)) + Row { + Metric("输入", usage.input) + Spacer(Modifier.width(24.dp)) + Metric("输出", usage.output) + } + if (usage.pricePerK > 0 && usage.cost != null) { + Spacer(Modifier.height(10.dp)) + Text( + "估算费用 ¥${"%.2f".format(usage.cost)}(按 ¥${usage.pricePerK}/千 Token)", + fontSize = 11.sp, + color = doubaoTextSecondary(), + ) + } + } + + // ---- 限额 ---- + Card { + if (usage.unlimited) { + Text("额度:无限制", fontSize = 14.sp, color = doubaoText()) + Spacer(Modifier.height(4.dp)) + Text( + "想限制他?在「管理 → 编辑」里填一个 Token 上限就行。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + ) + } else { + Text("额度", fontSize = 12.sp, color = doubaoTextSecondary()) + Spacer(Modifier.height(6.dp)) + Row(verticalAlignment = Alignment.Bottom) { + Text( + fmtTokens(usage.remaining ?: 0), + fontSize = 22.sp, + fontWeight = FontWeight.Medium, + color = if (usage.percent >= 1f) Color(0xFFD93025) else doubaoText(), + ) + Text( + " / ${fmtTokens(usage.limit)} 剩余", + fontSize = 12.sp, + color = doubaoTextSecondary(), + modifier = Modifier.padding(bottom = 3.dp), + ) + } + Spacer(Modifier.height(8.dp)) + // 进度条自己画(项目没有 material 的 LinearProgressIndicator 用法先例, + // 一条圆角 Box 更可控) + Box( + Modifier + .fillMaxWidth() + .height(6.dp) + .clip(RoundedCornerShape(3.dp)) + .background(Doubao.Border), + ) { + Box( + Modifier + .fillMaxWidth(usage.percent.toFloat().coerceIn(0f, 1f)) + .height(6.dp) + .clip(RoundedCornerShape(3.dp)) + .background(if (usage.percent >= 1f) Color(0xFFD93025) else Doubao.Blue), + ) + } + Spacer(Modifier.height(6.dp)) + Text( + if (usage.percent >= 1f) + "已经用完了 —— 下一轮会被拦住,并附一句告别。可以清零、调大限额或改成无限制。" + else "用满之后会拦住发送(记忆整理这类操作不受影响)。", + fontSize = 11.sp, + lineHeight = 16.sp, + color = if (usage.percent >= 1f) Color(0xFFD93025) else doubaoTextSecondary(), + ) + } + } + + // ---- 按模型分桶 ---- + Card { + Text("按模型", fontSize = 12.sp, color = doubaoTextSecondary()) + Spacer(Modifier.height(8.dp)) + if (usage.byModel.isEmpty()) { + Text("还没用过", fontSize = 13.sp, color = doubaoTextSecondary()) + } else { + for ((i, m) in usage.byModel.withIndex()) { + if (i > 0) Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text( + m.model, + fontSize = 13.sp, + color = doubaoText(), + modifier = Modifier.weight(1f), + ) + Text( + "入 ${fmtTokens(m.input)} · 出 ${fmtTokens(m.output)}", + fontSize = 12.sp, + color = doubaoTextSecondary(), + ) + } + } + } + } + + Spacer(Modifier.height(24.dp)) + } + } +} + +@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() } +} + +@Composable +private fun Metric(label: String, value: Long) { + Column { + Text(label, fontSize = 11.sp, color = doubaoTextSecondary()) + Text(fmtTokens(value), fontSize = 17.sp, fontWeight = FontWeight.Medium, color = doubaoText()) + } +} + +/** 大数字加千分位:`12345` → `12,345`。Token 数动辄五六位,不加看不清量级 */ +fun fmtTokens(n: Long): String { + val s = n.toString() + if (s.length <= 3) return s + val sb = StringBuilder() + for ((i, c) in s.withIndex()) { + if (i > 0 && (s.length - i) % 3 == 0) sb.append(',') + sb.append(c) + } + return sb.toString() +} diff --git a/android/app/src/main/res/drawable/agent_default_background.png b/android/app/src/main/res/drawable/agent_default_background.png new file mode 100644 index 0000000..dd15a0d Binary files /dev/null and b/android/app/src/main/res/drawable/agent_default_background.png differ diff --git a/android/app/src/main/res/drawable/agent_default_character.png b/android/app/src/main/res/drawable/agent_default_character.png new file mode 100644 index 0000000..bbf00bc Binary files /dev/null and b/android/app/src/main/res/drawable/agent_default_character.png differ diff --git a/android/kernel/agent_api.py b/android/kernel/agent_api.py new file mode 100644 index 0000000..6b9cb5e --- /dev/null +++ b/android/kernel/agent_api.py @@ -0,0 +1,871 @@ +"""智能体系统的 HTTP 接口(需求 v1.1)。 + +## 为什么单独一个模块 + +`app.py` 已经 1800 行,而这一批有二十多个接口。抽出来之后: + + · 路由写得下、看得清(一段一段对应需求的章节) + · `app.py` 只要在它的路由链里加一句 `agent_api.handle(...)` 就行 + · 这一批接口的**数据源**(`store` 的 JSON + `agentdb` 的 SQLite)也集中在一处, + 以后换存储只改这里 + +## 路由总表 + + GET/POST /api/agents 列表 / 新建 + PATCH/DELETE /api/agents/ 改 / 删 + GET /api/agents//memories 记忆列表 + POST /api/agents//memories 手动加一条 + POST /api/agents//memories/summarize AI 整理(一次独立 LLM 调用) + GET/POST /api/agents//memories/export|import 记忆 JSON 导出/导入 + GET /api/agents//suggestion AI 提的"该整理记忆了" + GET/PUT /api/agents//emotion 情绪 + POST /api/agents//skills 绑定 Skill(整体替换) + GET /api/agents//usage Token 用量 + POST /api/agents//usage/reset 清零 + GET /api/agents//package 导出智能体包(base64 zip) + POST /api/agents/import 导入智能体包 + PATCH/DELETE /api/memories/ 改 / 删一条 + POST /api/memories//pin 标记「必须保留」 + GET/POST /api/worldviews (+ /) 世界观 CRUD + GET/POST /api/model-entries (+ /) 全局模型列表 CRUD + GET/POST /api/skills (+ /) Skill CRUD + GET/POST /api/skills/export|import Skill JSON + GET/POST /api/worldviews//package|import + +★ `/api/model-entries` 而不是 `/api/models`:后者早就被"**拉上游**的可用模型列表" + 占了(`app.py` 的 `/api/models` 会去请求提供商的 `/v1/models`)。 + 两个东西完全不是一回事,不能共用一个路径。 +""" + +import base64 +import io +import json +import os +import re +import sys +import zipfile + +import agentdb +import paths +import store + +# --------------------------------------------------------------------------- # +# 小工具 +# --------------------------------------------------------------------------- # + +_SAFE_NAME = re.compile(r'[^\w.\-\u4e00-\u9fff]+') + + +def _safe_segment(name: str) -> str: + """ + 包里的文件名/目录名清洗。 + + ★ 防路径穿越:zip 里完全可以有一条叫 `../../settings.json` 的条目, + 照原样拼路径就会**写出数据目录之外**。所以只保留字母数字下划线 + 连字符点号和中文,其余一律换成下划线。 + """ + base = os.path.basename(str(name or '').replace('\\', '/')) + cleaned = _SAFE_NAME.sub('_', base).strip('._') + return cleaned[:80] or 'file' + + +def _asset_dir(owner_id: str) -> str: + d = os.path.join(paths.get().agent_assets_dir, _safe_segment(owner_id)) + os.makedirs(d, exist_ok=True) + return d + + +def _read_zip(data: bytes) -> dict: + """ + 解一个 zip,返回 `{相对路径: 字节}`。 + + ★ 只收**文件**、忽略目录;条目数/总大小有上限(防 zip 炸弹: + 一个 10KB 的 zip 能解出几十 GB)。 + """ + out = {} + total = 0 + with zipfile.ZipFile(io.BytesIO(data)) as z: + for info in z.infolist(): + if info.is_dir(): + continue + if len(out) >= 200: + raise ValueError('包里文件太多了(上限 200 个)') + total += info.file_size + if total > 60 * 1024 * 1024: + raise ValueError('包解出来太大了(上限 60MB)') + out[info.filename] = z.read(info) + return out + + +def _zip_of(files: dict) -> bytes: + buf = io.BytesIO() + with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as z: + for name, data in files.items(): + z.writestr(name, data) + return buf.getvalue() + + +def _pick_asset(files: dict, wanted: str): + """ + 按 `smartInfo.json` 里写的文件名找那个资源。 + + ★ 找不到时**退一步**按扩展名猜一个:用户手写的包经常是 + `"front": "角色图.png"` 但实际文件叫 `character.png` —— + 严格匹配的话整张图就白丢了,而"图没显示"用户只会觉得功能坏了。 + """ + if not wanted: + return None + want = os.path.basename(str(wanted).replace('\\', '/')).lower() + for name, data in files.items(): + if os.path.basename(name).lower() == want: + return name, data + stem, ext = os.path.splitext(want) + if not ext: + return None + for name, data in files.items(): + if os.path.splitext(name)[1].lower() == ext: + return name, data + return None + + +def _save_assets(owner_id: str, files: dict, image_spec: dict) -> dict: + """ + 把包里的四件套落到磁盘,返回新的 image 字段(**存绝对路径**)。 + + ★ 为什么存路径而不是存"包内文件名":包解完就没了(用户不会留着那个 zip), + 而界面每次都要显示它 —— 存文件名的话每次都得再去找一遍包。 + """ + out = {} + target_dir = _asset_dir(owner_id) + for key in ('front', 'back', 'border-main', 'border-info'): + hit = _pick_asset(files, (image_spec or {}).get(key)) + if not hit: + continue + name, data = hit + dest = os.path.join(target_dir, f'{key}-{_safe_segment(name)}') + with open(dest, 'wb') as fh: + fh.write(data) + out[key] = dest + return out + + +def _llm_once(settings: dict, agent: dict, system: str, user: str): + """ + 跑一次**独立**的 LLM 调用,返回 `(文本, usage)`。 + + 给"AI 整理记忆"用(需求 3.2:一次独立 LLM 调用)。 + ★ 不用工具、不开思考 —— 整理是个纯文本活,开思考只是白花时间和 token。 + """ + import providers + + provider = store.provider_info(settings, agent) + chunks = [] + usage = None + for ev in providers.stream_chat( + provider=provider.get('provider') or settings.get('provider'), + base_url=provider.get('baseUrl'), + api_key=settings.get('apiKey') or '', + model=provider.get('model'), + messages=[ + {'role': 'system', 'content': system}, + {'role': 'user', 'content': user}, + ], + temperature=0.2, + thinking_level='off', + ): + kind = ev.get('type') + if kind == 'text': + chunks.append(ev['text']) + elif kind == 'usage': + import agent_loop + + usage = agent_loop.add_usage(usage, ev.get('usage')) + return ''.join(chunks), usage + + +def _extract_json(text: str): + """ + 从模型回复里抠出 JSON。 + + ★ 必须容错:模型几乎总会把 JSON 包在 ```json 代码块里, + 直接 `json.loads` 十次有八次失败。而且失败的表现是"整理功能报错", + 用户根本不知道是模型多打了三个反引号。 + """ + raw = (text or '').strip() + fence = re.search(r'```(?:json)?\s*([\s\S]*?)```', raw) + if fence: + raw = fence.group(1).strip() + try: + return json.loads(raw) + except Exception: # noqa: BLE001 + pass + # 再退一步:从第一个 [ 或 { 到最后一个 ] 或 } + for left, right in (('[', ']'), ('{', '}')): + i, j = raw.find(left), raw.rfind(right) + if i >= 0 and j > i: + try: + return json.loads(raw[i:j + 1]) + except Exception: # noqa: BLE001 + continue + raise ValueError('模型没有返回能解析的 JSON') + + +# --------------------------------------------------------------------------- # +# 记忆 +# --------------------------------------------------------------------------- # + +def _memory_space(agent: dict) -> str: + return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '') + + +def _memory_payload(agent: dict) -> dict: + """一个记忆空间的完整视图(列表 + 情绪 + 用量),界面进页面时一次拿够""" + scope = _memory_space(agent) + items = agentdb.memory_list(scope) + return { + 'ok': True, + 'shared': bool(agent.get('worldviewId')), # 是不是共享空间(界面要提示) + 'worldviewId': agent.get('worldviewId') or '', + 'memories': items, + 'emotion': agentdb.emotion_get(agent.get('id') or ''), + 'suggestion': store.peek_summary_suggestion(agent.get('id') or ''), + } + + +MEMORY_SUMMARY_SYSTEM = '\n'.join([ + '你是一个记忆整理器。用户会给你一份记忆清单(JSON 数组),', + '你要把**零散、重复、可以合并**的条目压缩成更少、更完整的几条。', + '', + '规则:', + '1. 只输出一个 JSON 数组,每项 {"title": "...", "content": "..."},不要任何别的文字。', + '2. **不许编造**:只能合并和改写已有的信息,不能新增原始记忆里没有的事实。', + '3. 合并同类项:说同一件事的几条合成一条;时间上连续的经过可以并成一条。', + '4. 具体的数字、名字、日期**必须保留**("他每月话费 36"不能变成"他有话费支出")。', + '5. 条数控制在原来的 1/2 到 2/3;如果本来就不多(少于 8 条),原样返回即可。', + '6. 用中文,标题短(10 字以内),正文说清楚。', +]) + + +# --------------------------------------------------------------------------- # +# 路由 +# --------------------------------------------------------------------------- # + +def handle(handler, pathname: str, method: str) -> bool: + """ + 处理一个请求。返回 True = 已经响应过了。 + + [handler] 是 `app.py` 的那个 Handler 实例(借用它的 send_json / read_json_body)。 + """ + seg = [s for s in (pathname or '').split('/') if s] + # 全都是 /api/... 开头的 + if len(seg) < 2 or seg[0] != 'api': + return False + + def body(): + """ + 解析请求体。 + + ★ 做成**函数**而不是进来就解析:GET 请求没有 body,提前解析会抛异常。 + ★ 但注意:往下传的时候必须**调用它**(`body()`)—— + 直接把函数对象当 dict 传,报的是 `'function' object has no attribute 'get'`, + 而那个错看起来像"字段名写错了"。这里踩过一次。 + """ + try: + return handler.read_json_body() + except Exception: # noqa: BLE001 + return {} + + def err(code: int, msg: str): + handler.send_json(code, {'ok': False, 'error': msg}) + + try: + # ---------------- 智能体 ---------------- + if seg[1] == 'agents' and len(seg) == 2: + if method == 'GET': + handler.send_json(200, {'ok': True, 'agents': store.list_agents()}) + return True + if method == 'POST': + handler.send_json(200, {'ok': True, 'agent': store.create_agent(body())}) + return True + + if seg[1] == 'agents' and len(seg) == 3 and seg[2] == 'import' and method == 'POST': + return _import_agent(handler, body(), err) + + if seg[1] == 'agents' and len(seg) == 3: + aid = seg[2] + if method == 'PATCH': + updated = store.update_agent(aid, body()) + if updated is None: + err(404, '没有这个智能体') + else: + handler.send_json(200, {'ok': True, 'agent': updated}) + return True + if method == 'DELETE': + # ★ 内置智能体不给删:删了内核下次读 agents.json 会**重建**它, + # 用户看到"删了又回来"(界面也拦,但接口不能只靠界面拦) + target = store.get_agent(aid) + if target and target.get('builtin'): + err(400, '内置智能体不能删除(删了会被自动重建)') + return True + handler.send_json(200, {'ok': True, 'deleted': store.delete_agent(aid)}) + return True + + # ---------------- 记忆(挂在智能体下) ---------------- + if seg[1] == 'agents' and len(seg) >= 4 and seg[3] == 'memories': + return _memories(handler, method, seg, body, err) + + if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'suggestion': + agent = store.get_agent(seg[2]) + if not agent: + err(404, '没有这个智能体') + return True + handler.send_json(200, { + 'ok': True, + 'suggestion': store.peek_summary_suggestion(agent.get('id') or ''), + }) + return True + + if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'emotion': + agent = store.get_agent(seg[2]) + if not agent: + err(404, '没有这个智能体') + return True + if method == 'GET': + handler.send_json(200, {'ok': True, 'emotion': agentdb.emotion_get(agent['id'])}) + return True + if method in ('PUT', 'POST'): + emo = str(body().get('emotion') or '') + agentdb.emotion_set(agent['id'], emo[:200]) + handler.send_json(200, {'ok': True, 'emotion': emo[:200]}) + return True + + if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'skills': + agent = store.get_agent(seg[2]) + if not agent: + err(404, '没有这个智能体') + return True + if method == 'GET': + handler.send_json(200, {'ok': True, 'skillIds': agentdb.skills_of(agent['id'])}) + return True + if method in ('PUT', 'POST'): + ids = body().get('skillIds') or [] + agentdb.bind_skills(agent['id'], ids if isinstance(ids, list) else []) + handler.send_json(200, {'ok': True, 'skillIds': agentdb.skills_of(agent['id'])}) + return True + + # ---------------- Token 用量 ---------------- + if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'usage': + agent = store.get_agent(seg[2]) + if not agent: + err(404, '没有这个智能体') + return True + if method == 'GET': + handler.send_json(200, {'ok': True, **_usage_payload(agent)}) + return True + if method == 'POST': + agentdb.token_reset(agent['id']) + handler.send_json(200, {'ok': True, **_usage_payload(agent)}) + 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] == 'memories' and len(seg) == 3: + mid = seg[2] + item = agentdb.memory_get(mid) + if not item: + err(404, '没有这条记忆') + return True + if method == 'PATCH': + b = body() + # ★ 界面上改是**用户**在改,不受"只能改自己写的"限制 + # (那条限制是给 AI 的工具定的,见 agent_tools.py) + updated = agentdb.memory_update( + mid, + title=b.get('title') if 'title' in b else None, + content=b.get('content') if 'content' in b else None, + ) + handler.send_json(200, {'ok': True, 'memory': updated}) + return True + if method == 'DELETE': + agentdb.memory_forget(mid) + handler.send_json(200, {'ok': True, 'deleted': True}) + return True + + if seg[1] == 'memories' and len(seg) == 4 and seg[3] == 'pin' and method == 'POST': + ok = agentdb.memory_set_pinned(seg[2], bool(body().get('pinned', True))) + handler.send_json(200, {'ok': ok}) + return True + + # ---------------- 世界观 / 模型列表 / Skill ---------------- + res = _resource_route(handler, seg, method, body, err) + if res is not None: + return res + + except Exception as exc: # noqa: BLE001 - 接口层不能把内核带崩 + print(f'[agent_api] {pathname} 出错:{exc}', file=sys.stderr) + err(500, f'{type(exc).__name__}: {exc}') + return True + return False + + +# --------------------------------------------------------------------------- # +# 记忆的具体路由 +# --------------------------------------------------------------------------- # + +def _memories(handler, method: str, seg: list, body, err) -> bool: + agent = store.get_agent(seg[2]) + if not agent: + err(404, '没有这个智能体') + return True + tail = seg[4:] + + # /memories + if not tail: + if method == 'GET': + handler.send_json(200, _memory_payload(agent)) + return True + if method == 'POST': + b = body() + item = agentdb.memory_add( + scope=_memory_space(agent), + title=str(b.get('title') or ''), + content=str(b.get('content') or ''), + # 用户手动加的:author 记成自己(空 = 不是任何智能体写的) + author_agent=str(b.get('author_agent') or ''), + ) + handler.send_json(200, {'ok': True, 'memory': item}) + return True + + # /memories/summarize —— AI 整理(需求 3.2) + if tail == ['summarize'] and method == 'POST': + return _summarize(handler, agent, err) + + # /memories/export + if tail == ['export'] and method == 'GET': + payload = _memory_export(agent) + handler.send_json(200, {'ok': True, **payload}) + return True + + # /memories/import + if tail == ['import'] and method == 'POST': + return _memory_import(handler, agent, body(), err) + + return False + + +def _memory_export(agent: dict) -> dict: + """ + 导出成需求 3.4 那个格式。 + + ★ **不含 `author_agent`**:需求原话"导出不含 author_agent(导入后全部归属当前智能体)"。 + 带上它的话,把记忆导给另一个智能体之后,它会在共享空间里 + 顶着"别人写的"身份出现、连自己都改不了。 + """ + scope = _memory_space(agent) + items = [ + {'title': m.get('title') or '', 'content': m.get('content') or '', + 'pinned': bool(m.get('pinned'))} + for m in agentdb.memory_list(scope) + ] + return { + 'type': 'world-memory' if agent.get('worldviewId') else 'agent-memory', + 'version': 1, + 'name': agent.get('name') or '', + 'smartMemory': items, + 'Emotion': agentdb.emotion_get(agent.get('id') or ''), + } + + +def _memory_import(handler, agent: dict, body: dict, err) -> bool: + """ + 导入记忆(需求 3.4)。默认**合并**,可选**覆盖**。 + + 合并按**标题去重**:标题相同的跳过(保留现有的)。 + """ + payload = body.get('data') if isinstance(body.get('data'), dict) else body + if not isinstance(payload, dict) or 'smartMemory' not in payload: + err(400, '这不是一个记忆文件(缺少 smartMemory 字段)') + return True + if payload.get('type') and payload['type'] not in ('agent-memory', 'world-memory'): + err(400, f'不认识的文件类型:{payload.get("type")}') + return True + + incoming = payload.get('smartMemory') + if not isinstance(incoming, list): + err(400, 'smartMemory 必须是数组') + return True + + scope = _memory_space(agent) + mode = str(body.get('mode') or 'merge').lower() + before = len(agentdb.memory_list(scope)) + + if mode == 'replace': + agentdb.memory_replace_all(scope, incoming, keep_pinned=False) + added = len(agentdb.memory_list(scope)) - 0 + skipped = 0 + else: + existing = {(m.get('title') or '').strip() for m in agentdb.memory_list(scope)} + added = skipped = 0 + for it in incoming: + if not isinstance(it, dict): + continue + title = str(it.get('title') or '').strip() + if title and title in existing: + skipped += 1 + continue + agentdb.memory_add( + scope=scope, + title=title, + content=str(it.get('content') or ''), + author_agent=agent.get('id') or '', + ) + existing.add(title) + added += 1 + + emotion_kept = True + if mode == 'replace' and payload.get('Emotion') is not None: + # 覆盖模式连情绪一起换(需求 3.4);合并模式保留当前值 + agentdb.emotion_set(agent.get('id') or '', str(payload.get('Emotion') or '')) + emotion_kept = False + + return _send_json_ok(handler, { + 'mode': mode, + 'added': added, + 'skipped': skipped, + 'before': before, + 'after': len(agentdb.memory_list(scope)), + 'emotionReplaced': not emotion_kept, + }) + + +def _summarize(handler, agent: dict, err) -> bool: + """ + AI 整理记忆(需求 3.2)。 + + 流程:全部记忆 + pinned 清单一并给模型 → 拿回压缩后的列表 → + 整体写回(**pinned 的原样保留**)。 + + ★ Token 消耗计入该智能体统计(需求明确要求)。 + ★ **不受限额约束**(需求 3.1 的豁免条款)—— 额度用完了还得能整理记忆, + 否则用户的记忆就永远是一团乱麻、还解不开。 + """ + scope = _memory_space(agent) + items = agentdb.memory_list(scope) + if not items: + return _send_json_ok(handler, {'summarized': False, 'reason': '还没有记忆可以整理'}) + + settings = store.read_settings() + plain = [ + {'title': m.get('title') or '', 'content': m.get('content') or '', + 'pinned': bool(m.get('pinned'))} + for m in items + ] + try: + text, usage = _llm_once( + settings, agent, MEMORY_SUMMARY_SYSTEM, + json.dumps(plain, ensure_ascii=False, indent=1), + ) + merged = _extract_json(text) + except Exception as exc: # noqa: BLE001 + err(500, f'整理失败:{exc}') + return True + + if isinstance(merged, dict): + merged = merged.get('smartMemory') or merged.get('items') or [] + if not isinstance(merged, list): + err(500, '模型返回的不是列表') + return True + + # ★ pinned 的那几条**不能进这次替换**(需求 3.2:原样保留、不参与合并) + kept = [m for m in items if m.get('pinned')] + kept_titles = {(m.get('title') or '').strip() for m in kept} + clean = [ + {'title': str(x.get('title') or ''), 'content': str(x.get('content') or '')} + for x in merged + if isinstance(x, dict) and (x.get('title') or x.get('content')) + and (str(x.get('title') or '').strip() not in kept_titles) + ] + if not clean: + err(500, '模型返回的列表是空的,为了不丢数据这次不写回') + return True + + agentdb.memory_replace_all(scope, clean, keep_pinned=True) + + # 计入用量(记失败不影响结果) + try: + import agent_loop + + i, o = agent_loop.usage_pair(usage) + if i or o: + model = (store.provider_info(settings, agent) or {}).get('model') or '' + agentdb.token_add(agent.get('id') or '', model, i, o) + except Exception as exc: # noqa: BLE001 + print(f'[agent_api] 整理记忆的用量没记上:{exc}', file=sys.stderr) + + store.take_summary_suggestion(agent.get('id') or '') + return _send_json_ok(handler, { + 'summarized': True, + 'before': len(items), + 'after': len(agentdb.memory_list(scope)), + 'keptPinned': len(kept), + }) + + +# --------------------------------------------------------------------------- # +# 三种资源的通用路由 +# --------------------------------------------------------------------------- # + +_RES_PATH = { + 'worldviews': 'worldviews', + 'model-entries': 'models', + 'skills': 'skills', +} + + +def _resource_route(handler, seg: list, method: str, body, err): + if seg[1] not in _RES_PATH: + return None + name = _RES_PATH[seg[1]] + + # 包 / JSON 的导入导出(世界观包、Skill 文件) + if len(seg) == 3 and seg[2] == 'import' and method == 'POST': + return _resource_import(handler, name, body(), err) + if len(seg) == 4 and seg[3] == 'package' and method == 'GET': + return _resource_export(handler, name, seg[2], err) + if len(seg) == 4 and seg[3] == 'export' and method == 'GET': + return _resource_export(handler, name, seg[2], err) + + if len(seg) == 2: + if method == 'GET': + handler.send_json(200, {'ok': True, 'items': store.list_resource(name)}) + return True + if method == 'POST': + handler.send_json(200, {'ok': True, 'item': store.create_resource(name, body())}) + return True + + if len(seg) == 3: + rid = seg[2] + if method == 'PATCH': + updated = store.update_resource(name, rid, body()) + if updated is None: + err(404, '没有这一项') + else: + 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)}) + return True + return None + + +# --------------------------------------------------------------------------- # +# 导入导出 +# --------------------------------------------------------------------------- # + +def _usage_payload(agent: dict) -> dict: + usage = agentdb.token_usage(agent.get('id') or '') + try: + limit = int(float(agent.get('tokenLimit') or 0)) + except (TypeError, ValueError): + limit = 0 + used = usage['total']['input'] + usage['total']['output'] + # 单价(元/千 Token):在**全局模型列表**里配,填了才估费用 + price = 0.0 + mid = agent.get('modelId') or '' + if mid: + entry = store.get_resource('models', mid) or {} + try: + price = float(entry.get('pricePerK') or 0) + except (TypeError, ValueError): + price = 0.0 + return { + 'agentId': agent.get('id') or '', + 'name': agent.get('name') or '', + 'input': usage['total']['input'], + 'output': usage['total']['output'], + 'total': used, + 'byModel': usage['byModel'], + 'limit': limit, + 'remaining': None if limit <= 0 else max(0, limit - used), + 'pricePerK': price, + 'cost': round(used / 1000.0 * price, 4) if price > 0 else None, + } + + +def _export_agent(handler, agent_id: str, err) -> bool: + """导出智能体包(需求 2.5:zip,只含 smartInfo.json + 图片)""" + agent = store.get_agent(agent_id) + if not agent: + err(404, '没有这个智能体') + return True + files = {} + image = agent.get('image') or {} + for key, path in image.items(): + if not path or not os.path.isfile(path): + continue + try: + with open(path, 'rb') as fh: + files[f'{key}{os.path.splitext(path)[1]}'] = fh.read() + except OSError: + continue + # ★ 包里**不存内部 ID、不存模型引用、不存限额**(需求 2.5 的"包的边界约定") + info = { + 'name': agent.get('name') or '', + 'description': agent.get('description') or '', + 'prompt': agent.get('systemPrompt') or '', + 'image': {k: f'{k}{os.path.splitext(v)[1]}' for k, v in image.items() if v}, + } + files['smartInfo.json'] = json.dumps(info, ensure_ascii=False, indent=2).encode('utf-8') + blob = _zip_of(files) + return _send_json_ok(handler, { + 'fileName': f'{(agent.get("name") or "agent")}.zip', + 'data': base64.b64encode(blob).decode('ascii'), + 'bytes': len(blob), + }) + + +def _import_agent(handler, body, err) -> bool: + """ + 导入智能体包(需求 2.5)。 + + ★ **同一个包导入两次 = 两个互相独立的智能体**(需求原话)—— + 所以这里每次都 `create_agent` 生成新 UUID,不做"按名字去重"。 + ★ 模型引用 / 世界观绑定 / 限额这些**不进包**,导入后用默认值。 + """ + raw = body.get('data') or body.get('base64') 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 = None + for name in files: + if os.path.basename(name).lower() == 'smartinfo.json': + try: + info = json.loads(files[name].decode('utf-8')) + except Exception as exc: # noqa: BLE001 + err(400, f'smartInfo.json 解析失败:{exc}') + return True + break + if info is None: + err(400, '包里没有 smartInfo.json —— 这不是一个智能体包') + return True + + agent = store.create_agent({ + 'name': str(info.get('name') or '未命名').strip()[:24], + 'description': str(info.get('description') or ''), + 'systemPrompt': str(info.get('prompt') or ''), + 'avatar': 'custom', + }) + image = _save_assets(agent['id'], files, info.get('image') or {}) + if image: + agent = store.update_agent(agent['id'], {'image': image}) or agent + return _send_json_ok(handler, {'agent': agent, 'assets': len(image)}) + + +def _resource_export(handler, name: str, rid: str, err) -> bool: + item = store.get_resource(name, rid) + if not item: + err(404, '没有这一项') + return True + if name == 'skills': + # Skill 是**单个 JSON**(需求 3.7),不是 zip + payload = { + 'type': 'agent-skill', + 'version': 1, + 'name': item.get('name') or '', + 'content': item.get('content') or '', + } + return _send_json_ok(handler, { + 'fileName': f'{(item.get("name") or "skill")}.json', + 'json': json.dumps(payload, ensure_ascii=False, indent=2), + }) + # 世界观:zip,含 worldInfo.json + 图片 + files = {} + image = item.get('image') or {} + for key, path in image.items(): + if not path or not os.path.isfile(path): + continue + try: + with open(path, 'rb') as fh: + files[f'{key}{os.path.splitext(path)[1]}'] = fh.read() + except OSError: + continue + info = { + 'name': item.get('name') or '', + 'setting': item.get('setting') or '', + 'image': {k: f'{k}{os.path.splitext(v)[1]}' for k, v in image.items() if v}, + } + files['worldInfo.json'] = json.dumps(info, ensure_ascii=False, indent=2).encode('utf-8') + blob = _zip_of(files) + return _send_json_ok(handler, { + 'fileName': f'{(item.get("name") or "world")}.zip', + 'data': base64.b64encode(blob).decode('ascii'), + 'bytes': len(blob), + }) + + +def _resource_import(handler, name: str, body, err) -> bool: + if name == 'skills': + payload = body.get('data') if isinstance(body.get('data'), dict) else body + if isinstance(payload, str): + try: + payload = json.loads(payload) + except Exception: # noqa: BLE001 + err(400, '不是合法的 JSON') + return True + if not isinstance(payload, dict) or not (payload.get('content') or payload.get('name')): + err(400, '这不是一个 Skill 文件(缺 name / content)') + return True + if payload.get('type') and payload['type'] != 'agent-skill': + err(400, f'不认识的文件类型:{payload.get("type")}') + return True + item = store.create_resource('skills', { + 'name': payload.get('name') or '未命名 Skill', + 'content': payload.get('content') or '', + }) + return _send_json_ok(handler, {'item': item}) + + # 世界观包 + raw = body.get('data') or body.get('base64') or '' + if not raw: + err(400, '缺少包内容') + return True + try: + files = _read_zip(base64.b64decode(raw)) + except Exception as exc: # noqa: BLE001 + err(400, f'包读不出来:{exc}') + return True + info = None + for fname in files: + if os.path.basename(fname).lower() == 'worldinfo.json': + try: + info = json.loads(files[fname].decode('utf-8')) + except Exception as exc: # noqa: BLE001 + err(400, f'worldInfo.json 解析失败:{exc}') + return True + break + if info is None: + err(400, '包里没有 worldInfo.json —— 这不是一个世界观包') + return True + item = store.create_resource('worldviews', { + 'name': str(info.get('name') or '未命名').strip()[:40], + 'setting': str(info.get('setting') or ''), + }) + image = _save_assets(item['id'], files, info.get('image') or {}) + if image: + item = store.update_resource('worldviews', item['id'], {'image': image}) or item + return _send_json_ok(handler, {'item': item, 'assets': len(image)}) + + +def _send_json_ok(handler, payload: dict) -> bool: + handler.send_json(200, {'ok': True, **payload}) + return True diff --git a/android/kernel/agent_context.py b/android/kernel/agent_context.py new file mode 100644 index 0000000..31748c6 --- /dev/null +++ b/android/kernel/agent_context.py @@ -0,0 +1,205 @@ +"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。 + +## 这个模块只做一件事 + +把「人设 + Skill 手册 + 世界观 + 情绪 + 记忆 + 同伴情绪」按**固定顺序** +拼成一段 system prompt。 + +## 为什么单独一个模块,而不是写在 agent_loop 里 + +因为这里有**六种来源**,每一种都要判空、要查库/查 JSON、出错了还不能把 +整轮对话带崩。塞在 agent_loop 里会让那个函数变成两百行,而且没法单独测。 + +## 几条硬约定 + +**① 空段整段删掉。** +绑没绑世界观、有没有情绪、记没记过东西 —— 都是常态。 +不删的话每次对话都带着一堆空的 ``, +模型会以为"这里本来该有内容但我没看到",反而更容易瞎编。 + +**② 顺序固定:人设 → skills → worldview → emotion → memory → peer_emotions。** +见附录 C。顺序不是审美问题:记忆在情绪之后,模型读到"我现在有点烦" +再看记忆,语气才连贯;反过来它会先看到一堆事实、再看到情绪,像事后补的。 + +**③ 每轮重新拼。** +记忆和情绪随时会变(AI 自己就能改),拼一次缓存住的话, +用户会看到"我明明让它记住了,下一句它又忘了"。 + +**④ 查库失败一律当成"这段没有"。** +数据库被锁、文件损坏都不该让用户发不出消息。 +""" + +import re + +import agentdb +import store +from defaults import ( + BUILTIN_SKILL, + DEFAULT_MEMORY_LINE, + DEFAULT_PROMPT_TEMPLATE, +) + +# 模板里的段名(顺序就是渲染顺序)。加一段要同时改 defaults.DEFAULT_PROMPT_TEMPLATE。 +SECTIONS = ('skills', 'worldview', 'emotion', 'memory', 'peer_emotions') + + +def _safe(fn, fallback): + """ + 跑一个小查询,出错就当"没有"。 + + ★ 单独抽出来是因为这个模式在这里出现六次:**任何一处查库失败都不该 + 让整轮对话发不出去**(数据库锁了、agent.db 被删了、JSON 坏了)。 + """ + try: + return fn() + except Exception as exc: # noqa: BLE001 + print(f'[agent_context] 取上下文失败,按"没有"处理:{exc}', file=__import__('sys').stderr) + return fallback + + +# --------------------------------------------------------------------------- # +# 各段 +# --------------------------------------------------------------------------- # + +def build_skills(agent: dict) -> str: + """ + `` 段:内置手册 + 这个智能体绑定的自定义 Skill(**按绑定顺序**)。 + + 内置的那份永远在最前面 —— 它讲的是记忆/情绪这些**基础工具**怎么用, + 自定义 Skill 是额外的,放后面读起来才是"先会基本操作,再学扩展"。 + """ + parts = [BUILTIN_SKILL.strip()] if BUILTIN_SKILL.strip() else [] + agent_id = (agent or {}).get('id') or '' + if agent_id: + for sid in _safe(lambda: agentdb.skills_of(agent_id), []): + sk = _safe(lambda: store.get_resource('skills', sid), None) + if sk and (sk.get('content') or '').strip(): + parts.append(f'【{(sk.get("name") or "Skill").strip()}】\n{sk["content"].strip()}') + return '\n\n'.join(parts) + + +def build_worldview(agent: dict) -> str: + """`` 段:绑定的世界观设定文本(没绑就是空)""" + wid = (agent or {}).get('worldviewId') or '' + if not wid: + return '' + wv = _safe(lambda: store.get_resource('worldviews', wid), None) + return (wv or {}).get('setting', '').strip() + + +def memory_scope(agent: dict) -> str: + """这个智能体当前该读写哪个记忆空间(绑了世界观就是共享空间)""" + agent = agent or {} + return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '') + + +def build_emotion(agent: dict) -> str: + """`` 段:自己的情绪(**始终私有**,绑了世界观也不共享 —— 需求 3.5)""" + agent_id = (agent or {}).get('id') or '' + if not agent_id: + return '' + return (_safe(lambda: agentdb.emotion_get(agent_id), '') or '').strip() + + +def build_memory(agent: dict) -> str: + """ + `` 段:那个记忆空间的**全部条目**(标题 + 正文,需求 3.2 的"全量注入")。 + """ + scope = memory_scope(agent) + items = _safe(lambda: agentdb.memory_list(scope), []) + if not items: + return '' + tmpl = _safe( + lambda: (store.read_settings().get('memoryLine') or DEFAULT_MEMORY_LINE), + DEFAULT_MEMORY_LINE, + ) + lines = [] + for it in items: + title = (it.get('title') or '').strip() + content = (it.get('content') or '').strip() + try: + lines.append(tmpl.format(title=title, content=content)) + except (KeyError, IndexError): # 用户把模板改坏了:退回默认再试 + lines.append(DEFAULT_MEMORY_LINE.format(title=title, content=content)) + return '\n'.join(lines) + + +def build_peer_emotions(agent: dict) -> str: + """ + `` 段:**同世界观其他智能体**的名字 + 情绪(需求 3.5)。 + + ★ 三个条件全满足才有内容:绑了世界观、开了情绪感知开关、世界观下还有别人。 + 开关默认关(需求原话"默认关闭")—— 别人的情绪属于"角色内的隐私", + 默认让 AI 看到会让它们的表现互相串味。 + """ + agent = agent or {} + if not agent.get('worldviewId') or not agent.get('emotionEnabled'): + return '' + my_id = agent.get('id') or '' + wid = agent.get('worldviewId') or '' + others = [ + a for a in _safe(store.list_agents, []) + if a.get('worldviewId') == wid and a.get('id') != my_id + ] + rows = _safe( + lambda: agentdb.peer_emotions(wid, my_id, [a.get('id') for a in others]), + [], + ) + by_id = {a.get('id'): a for a in others} + parts = [] + for aid, emo in rows: + name = (by_id.get(aid) or {}).get('name') or '某人' + if (emo or '').strip(): + parts.append(f'{name}-{emo.strip()}') + return ';'.join(parts) + + +# --------------------------------------------------------------------------- # +# 拼装 +# --------------------------------------------------------------------------- # + +_RE_BLOCK = {name: re.compile(rf'<{name}>.*?', re.S) for name in SECTIONS} + + +def render(template: str, values: dict) -> str: + """ + 按模板渲染,**空的段整段删掉**。 + + ★ 先渲染 `{prompt}` 再处理段:人设里如果碰巧有 `` 这样的字 + (用户自己写的提示词里完全可能),会被当成段处理掉 —— 所以段的匹配 + 只在**模板**上做,不在渲染结果上做。 + """ + out = (template or DEFAULT_PROMPT_TEMPLATE).replace('{prompt}', (values.get('prompt') or '').strip()) + for name in SECTIONS: + block = _RE_BLOCK[name].search(out) + if not block: + continue + value = (values.get(name) or '').strip() + if value: + out = out[:block.start()] + f'<{name}>\n{value}\n' + out[block.end():] + else: + out = out[:block.start()] + out[block.end():] + # 段被删掉后会留下连续空行,压一压;别让提示词里出现四五行的空白 + out = re.sub(r'\n{3,}', '\n\n', out) + return out.strip() + + +def build_system_prompt(settings: dict, agent: dict) -> str: + """ + 这一轮要用的 system prompt。 + + [settings] 里可以覆盖:`promptTemplate`(整份模板)、`memoryLine`(记忆条目排版)。 + """ + agent = agent or {} + settings = settings or {} + prompt = (agent.get('systemPrompt') or '').strip() or (settings.get('systemPrompt') or '') + values = { + 'prompt': prompt, + 'skills': build_skills(agent), + 'worldview': build_worldview(agent), + 'emotion': build_emotion(agent), + 'memory': build_memory(agent), + 'peer_emotions': build_peer_emotions(agent), + } + template = (settings.get('promptTemplate') or '').strip() or DEFAULT_PROMPT_TEMPLATE + return render(template, values) diff --git a/android/kernel/agent_loop.py b/android/kernel/agent_loop.py index 4676dc8..a34932b 100644 --- a/android/kernel/agent_loop.py +++ b/android/kernel/agent_loop.py @@ -12,6 +12,7 @@ Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。 import json from typing import Callable, Optional +import agent_context import store import tools_runtime from providers import stream_chat @@ -19,6 +20,39 @@ from providers import stream_chat MAX_TOOL_RESULT_CHARS = 6000 +def add_usage(total, one) -> dict: + """ + 把一次调用的 usage 累加进总数。 + + ★ 各家的字段名不一样(OpenAI 系是 prompt_tokens / completion_tokens, + 兼容网关有时给 input_tokens / output_tokens),**两种都认** —— + 只认一种的话换个提供商统计就静默变成 0,而"统计是 0"极难被发现。 + """ + if not isinstance(one, dict): + return total or {} + out = dict(total or {}) + pairs = ( + ('prompt_tokens', 'prompt_tokens'), + ('completion_tokens', 'completion_tokens'), + ('total_tokens', 'total_tokens'), + ('input_tokens', 'prompt_tokens'), # 兼容写法 + ('output_tokens', 'completion_tokens'), # 兼容写法 + ) + for src, dst in pairs: + v = one.get(src) + if isinstance(v, (int, float)): + out[dst] = int(out.get(dst) or 0) + int(v) + if 'total_tokens' not in out: + out['total_tokens'] = int(out.get('prompt_tokens') or 0) + int(out.get('completion_tokens') or 0) + return out + + +def usage_pair(usage) -> tuple: + """从 usage 里取出 (输入, 输出)。给落库用 —— 字段名差异在这一处抹平""" + u = usage if isinstance(usage, dict) else {} + return int(u.get('prompt_tokens') or 0), int(u.get('completion_tokens') or 0) + + def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str: """工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。""" if isinstance(text, str): @@ -99,7 +133,15 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic tool_defs = tools_runtime.build_tool_defs(settings) max_rounds = _max_rounds(settings) mode = (settings.get('security') or {}).get('mode') or 'open' - system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or '' + # ★★ system prompt **每轮重新拼**(需求 3.2):人设 → skills → 世界观 → + # 情绪 → 记忆 → 同伴情绪,顺序固定(附录 C)。 + # + # 为什么不拼一次缓存住:记忆和情绪**随时会变**,而且 AI 自己就能改它们 + # (memory_add / emotion_set)。缓存住的表现是"我明明让它记住了, + # 下一句它又忘了"——这种 bug 用户会当成"记忆功能坏了"。 + # + # 拼法、判空、查库失败的兜底全在 agent_context.py 里。 + system_prompt = agent_context.build_system_prompt(settings, agent or {}) # ★★ 界面能力的用法**只在开关打开时才追加**。 # # 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**, @@ -192,7 +234,13 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic elif kind == 'tool_calls': tool_calls = event.get('toolCalls') or [] elif kind == 'usage': - usage = event.get('usage') + # ★★ **累加**而不是覆盖。 + # + # 多轮工具调用时每一轮上游都会来一个 usage,以前是直接赋值 —— + # 只留最后一轮。而消耗的大头恰恰在前面几轮(工具结果很长, + # 一轮就是几千 input token),丢掉之后统计出来的数字 + # 会少得离谱,用户会以为"怎么才用了这么点"。 + usage = add_usage(usage, event.get('usage')) if not tool_calls: emit({ diff --git a/android/kernel/agent_tools.py b/android/kernel/agent_tools.py new file mode 100644 index 0000000..6b3460d --- /dev/null +++ b/android/kernel/agent_tools.py @@ -0,0 +1,345 @@ +"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。 + +## 为什么是"内置工具"而不是 `tools/*.py` + +`tools/` 下的工具是**用户可改的 .py 文件**(内核启动时播种到手机上的可写目录)。 +这七个不一样: + + · 它们要读写 `agent.db`(记忆、情绪、Token 统计)—— 那是内核进程内的模块, + 电脑端的工具是**子进程**,根本 import 不到 + · 它们是系统的核心能力,不该被用户在 tools/ 里改坏(改坏了 AI 会"失忆", + 而且表现是"有时记得有时不记得",极难查) + +所以走 `builtin_tools.BUILTIN_TOOLS` 那条路(进程内、不进 tools/、不参与播种)。 + +## 限权规则(需求 3.6,**共享记忆里最重要的一条**) + +绑定了世界观的智能体共用一个记忆空间,于是"谁都能删"就成了问题: + + · `memory_add` —— 任何智能体都能往共享空间写(追加优先) + · `memory_forget` / `memory_update` —— **只能动自己写的**(按 author_agent 判定) + · `pinned` —— 用户标记"必须保留"的条目,AI 连自己的都改不动 + +改别人的条目只能由**用户在界面上手动做**。这条不做的话, +两个智能体互相删对方的记忆,用户会看到"记忆莫名其妙少了"。 +""" + +import sys + +import agentdb +import store + +# --------------------------------------------------------------------------- # +# 拿"我现在是谁" +# --------------------------------------------------------------------------- # + +def _ctx() -> dict: + """ + 当前这次工具调用的上下文(哪次对话、哪个智能体)。 + + ★ 局部 import:`tools_runtime` → `builtin_tools` → 这里,顶部 import 就成环了。 + """ + import tools_runtime + + return tools_runtime.current_context() or {} + + +def _me() -> dict: + """当前智能体(拿不到就返回空 dict —— 工具会据此报错,而不是瞎写)""" + ctx = _ctx() + agent = store.get_agent(ctx.get('agentId') or '') or {} + return agent + + +def _my_scope(agent: dict) -> str: + return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '') + + +def _shared(agent: dict) -> bool: + """是不是在共享空间里(绑了世界观就是)""" + return bool(agent.get('worldviewId')) + + +def _check_editable(item: dict, agent: dict) -> None: + """ + 能不能改/删这一条 —— 不能就抛错(**抛错而不是静默跳过**: + 静默的话模型以为改成功了,下一轮还按老样子说话)。 + """ + if item.get('pinned'): + raise ValueError( + '这条记忆被用户标记为「必须保留」,你改不了也删不掉。' + '如果它确实过时了,跟用户说一声让他自己处理。' + ) + if _shared(agent) and (item.get('author_agent') or '') != (agent.get('id') or ''): + raise ValueError( + '这条是**其他智能体**写进共享记忆的,你只能改/删自己写的。' + '需要修改它的话,跟用户说让他手动改。' + ) + + +# --------------------------------------------------------------------------- # +# 记忆 +# --------------------------------------------------------------------------- # + +MEMORY_ADD = { + 'name': 'memory_add', + 'description': ( + '记住一件事,**跨对话保留**。用户告诉你的重要事实、偏好、约定、他的项目,' + '都该记下来。记之前先看系统提示词里的记忆清单,已经记过的别再记一遍。' + '返回新条目的 id(以后要改/删它需要这个 id)。' + ), + 'parameters': { + 'type': 'object', + 'properties': { + 'title': {'type': 'string', 'description': '一句话标题(检索和整理时的锚点)'}, + 'content': {'type': 'string', 'description': '要记住的正文'}, + }, + 'required': ['title', 'content'], + }, +} + + +def memory_add(args: dict) -> dict: + agent = _me() + if not agent: + raise ValueError('拿不到当前智能体,无法写记忆') + title = str(args.get('title') or '').strip() + content = str(args.get('content') or '').strip() + if not title and not content: + raise ValueError('title 和 content 至少要有一个') + item = agentdb.memory_add( + scope=_my_scope(agent), + title=title, + content=content, + author_agent=agent.get('id') or '', + ) + return { + 'id': item['id'], + 'title': item['title'], + 'scope': '共享记忆(世界观)' if _shared(agent) else '你自己的记忆', + 'note': '已写入。不要只在正文里说"记住了"—— 你现在已经真的记住了,正常继续就行。', + } + + +MEMORY_UPDATE = { + 'name': 'memory_update', + 'description': ( + '修改一条已有的记忆(只改传进来的字段)。' + '只能改**你自己写的**、且没被用户标记为「必须保留」的条目。' + ), + 'parameters': { + 'type': 'object', + 'properties': { + 'id': {'type': 'string', 'description': '记忆的 id(memory_add 返回过,或记忆清单里带的)'}, + 'title': {'type': 'string', 'description': '新标题,不改就不传'}, + 'content': {'type': 'string', 'description': '新正文,不改就不传'}, + }, + 'required': ['id'], + }, +} + + +def memory_update(args: dict) -> dict: + agent = _me() + if not agent: + raise ValueError('拿不到当前智能体') + mid = str(args.get('id') or '').strip() + if not mid: + raise ValueError('id 不能为空') + item = agentdb.memory_get(mid) + # ★ 只允许改**自己这个记忆空间**里的条目:不然知道 id 就能改到别人的私有记忆 + if not item or item.get('scope') != _my_scope(agent): + raise ValueError('没找到这条记忆(id 不对,或者它不在你当前的记忆空间里)') + _check_editable(item, agent) + updated = agentdb.memory_update( + mid, + title=args.get('title') if 'title' in args else None, + content=args.get('content') if 'content' in args else None, + ) + return {'id': mid, 'title': (updated or {}).get('title', ''), 'note': '已更新。'} + + +MEMORY_FORGET = { + 'name': 'memory_forget', + 'description': ( + '删掉一条记忆。只能删**你自己写的**、且没被用户标记为「必须保留」的条目。' + '拿不准该不该删时,先问用户。' + ), + 'parameters': { + 'type': 'object', + 'properties': { + 'id': {'type': 'string', 'description': '要删的记忆 id'}, + }, + 'required': ['id'], + }, +} + + +def memory_forget(args: dict) -> dict: + agent = _me() + if not agent: + raise ValueError('拿不到当前智能体') + mid = str(args.get('id') or '').strip() + if not mid: + raise ValueError('id 不能为空') + item = agentdb.memory_get(mid) + if not item or item.get('scope') != _my_scope(agent): + raise ValueError('没找到这条记忆(id 不对,或者它不在你当前的记忆空间里)') + _check_editable(item, agent) + agentdb.memory_forget(mid) + return {'id': mid, 'forgotten': True, 'note': '已删除。'} + + +MEMORY_SEARCH = { + 'name': 'memory_search', + 'description': ( + '在自己的记忆库里检索。系统提示词里的记忆清单是**全量**的,' + '但条数多的时候你可能只想找相关的几条 —— 用这个按关键词查。' + ), + 'parameters': { + 'type': 'object', + 'properties': { + 'keyword': {'type': 'string', 'description': '关键词(标题和正文都会匹配)'}, + 'limit': {'type': 'number', 'description': '最多返回几条,默认 10'}, + }, + 'required': ['keyword'], + }, +} + + +def memory_search(args: dict) -> dict: + agent = _me() + if not agent: + raise ValueError('拿不到当前智能体') + kw = str(args.get('keyword') or '').strip() + if not kw: + raise ValueError('keyword 不能为空') + try: + limit = int(float(args.get('limit') or 10)) + except (TypeError, ValueError): + limit = 10 + rows = agentdb.memory_search(_my_scope(agent), kw, limit) + return { + 'keyword': kw, + 'count': len(rows), + 'items': [ + {'id': r['id'], 'title': r['title'], 'content': r['content']} for r in rows + ], + 'note': '' if rows else '没有匹配的记忆。别据此说"我完全不记得"—— 换个关键词再试一次。', + } + + +MEMORY_SUGGEST_SUMMARY = { + 'name': 'memory_suggest_summary', + 'description': ( + '**建议**用户整理一次记忆(把零散的合并成几条)。' + '你只负责建议,不执行 —— 用户点确认之后系统才会真的整理。' + '什么时候用:记忆条数明显变多、或者有好几条在说同一件事。' + ), + 'parameters': { + 'type': 'object', + 'properties': { + 'reason': {'type': 'string', 'description': '为什么建议整理(会显示给用户)'}, + }, + }, +} + + +def memory_suggest_summary(args: dict) -> dict: + agent = _me() + if not agent: + raise ValueError('拿不到当前智能体') + why = str(args.get('reason') or '').strip() or '记忆有点多了,想合并一下' + # ★ 只挂一个"建议"标记,**不执行总结**(需求 3.2:仅提示不执行)。 + # 界面看到这个标记会给用户一个「整理记忆」按钮。 + store.add_pending_summary_suggestion(agent.get('id') or '', why) + return { + 'suggested': True, + 'reason': why, + 'note': '已经建议了。**别再说"我整理好了"** —— 你只是提了个建议,' + '用户点确认之后才会真的整理。正文里正常说这件事就行。', + } + + +# --------------------------------------------------------------------------- # +# 情绪 +# --------------------------------------------------------------------------- # + +EMOTION_SET = { + 'name': 'emotion_set', + 'description': ( + '更新**你自己**当前的情绪状态(一小段话,比如"刚被夸了,有点得意")。' + '它会跟着你到下一次对话,也会显示在系统提示词里。' + '情绪要跟着对话内容自然变化,不用每轮都改。' + ), + 'parameters': { + 'type': 'object', + 'properties': { + 'emotion': {'type': 'string', 'description': '你现在的情绪'}, + }, + 'required': ['emotion'], + }, +} + + +def emotion_set(args: dict) -> dict: + agent = _me() + if not agent: + raise ValueError('拿不到当前智能体') + emo = str(args.get('emotion') or '').strip() + if not emo: + raise ValueError('emotion 不能为空(不想保留情绪的话直接别调用这个工具)') + agentdb.emotion_set(agent.get('id') or '', emo[:200]) + return {'emotion': emo[:200], 'note': '已更新你自己的情绪。'} + + +# --------------------------------------------------------------------------- # +# 用量 +# --------------------------------------------------------------------------- # + +GET_TOKEN_USAGE = { + 'name': 'get_token_usage', + 'description': ( + '查**你自己**累计用了多少 Token、还剩多少额度。' + '用户问"你还能说多少""用了多少"时用这个查真实数字,别猜。' + ), + 'parameters': {'type': 'object', 'properties': {}}, +} + + +def get_token_usage(args: dict) -> dict: + agent = _me() + if not agent: + raise ValueError('拿不到当前智能体') + usage = agentdb.token_usage(agent.get('id') or '') + limit = int(float(agent.get('tokenLimit') or 0)) + used = usage['total']['input'] + usage['total']['output'] + return { + 'used': used, + 'input': usage['total']['input'], + 'output': usage['total']['output'], + 'byModel': usage['byModel'], + 'limit': limit, + 'remaining': (None if limit <= 0 else max(0, limit - used)), + 'note': '额度无限制。' if limit <= 0 else f'还剩 {max(0, limit - used)} Token。', + } + + +# --------------------------------------------------------------------------- # +# 注册 +# --------------------------------------------------------------------------- # + +#: 名字 → {'spec': TOOL, 'run': fn}(形状和 builtin_tools.BUILTIN_TOOLS 一样) +AGENT_TOOLS = { + 'memory_add': {'spec': MEMORY_ADD, 'run': memory_add}, + 'memory_update': {'spec': MEMORY_UPDATE, 'run': memory_update}, + 'memory_forget': {'spec': MEMORY_FORGET, 'run': memory_forget}, + 'memory_search': {'spec': MEMORY_SEARCH, 'run': memory_search}, + 'memory_suggest_summary': {'spec': MEMORY_SUGGEST_SUMMARY, 'run': memory_suggest_summary}, + 'emotion_set': {'spec': EMOTION_SET, 'run': emotion_set}, + 'get_token_usage': {'spec': GET_TOKEN_USAGE, 'run': get_token_usage}, +} + + +def _unused(): # pragma: no cover - 只是让 sys 的 import 不被 lint 当成没用 + return sys diff --git a/android/kernel/agentdb.py b/android/kernel/agentdb.py new file mode 100644 index 0000000..e361402 --- /dev/null +++ b/android/kernel/agentdb.py @@ -0,0 +1,440 @@ +"""智能体系统的数据层:**记忆 / 情绪 / Token 统计 / 绑定关系**。 + +## 为什么这次用 SQLite,而别处(设置/会话/智能体)还是 JSON + +`store.py` 顶上写着"为什么用 JSON 而不是 SQLite",理由很实在: +**数据量极小**(几条会话、几个智能体),而且用户/开发者要能直接看到、改那些文件。 + +那个理由对**智能体本身**依然成立(就几个),所以它们还在 `agents.json` 里。 +但记忆不一样,三条都指向 SQLite: + + · 需求明确"记忆条目**无上限**",而**每轮对话都要全量注入** smartMemory —— + 几千条记忆塞进一个 JSON、每轮读盘再反序列化一遍,代价是实打实的 + · 要按关键词检索(`memory_search` 是 LIKE 查询) + · 要"只改一条""只删自己写的"这种**行级**操作 —— 在 JSON 里就是 + 读全量 → 改 → 写全量,多线程下一次并发写就可能把别人的改动盖掉 + +所以分界线是:**会持续增长、要按行操作或检索的数据 → SQLite; +少量、要人肉可读的配置 → JSON。** + +(另:这几张表**只属于智能体系统**,不和会话/设置混在一起 —— + `agent.db` 单独一个文件,删了就是"重置智能体系统",不会碰到聊天记录。) + +## 关联一律用 UUID + +见需求附录 A。`memories.author_agent`、`agent_skills.agent_id`、 +`token_usage.agent_id` 存的都是 UUID,`name` 只是显示名(可重复、可随便改)。 +""" + +import os +import sqlite3 +import threading +import uuid +from datetime import datetime, timezone + +import paths + +# --------------------------------------------------------------------------- # +# 连接 +# --------------------------------------------------------------------------- # +# +# ★ 每线程一个连接:sqlite3 的连接默认不能跨线程用,而内核是多线程的 +# (HTTP 每请求一线程 + 工具跑在又一个线程里)。 +# 用 threading.local() 而不是"一个全局连接 + 一把大锁":记忆检索可能在 +# 对话生成的过程中被调用,一把大锁会把整条链路串起来。 +_local = threading.local() +_init_done = False +_init_lock = threading.Lock() + + +def db_path() -> str: + """数据库文件的位置(跟着数据目录走,和 settings.json 同一层)""" + return os.path.join(os.path.dirname(paths.get().settings_file), 'agent.db') + + +def _connect() -> sqlite3.Connection: + conn = getattr(_local, 'conn', None) + if conn is not None: + return conn + os.makedirs(os.path.dirname(db_path()), exist_ok=True) + # check_same_thread=False 是安全的:这个连接只会被**创建它的那个线程**用到 + conn = sqlite3.connect(db_path(), check_same_thread=False, timeout=10) + conn.row_factory = sqlite3.Row + # WAL:读不挡写。安卓上内核同时有"对话在写记忆"和"界面在读列表"。 + try: + conn.execute('PRAGMA journal_mode=WAL') + conn.execute('PRAGMA synchronous=NORMAL') + except sqlite3.Error: + pass # 只读文件系统之类:不致命,退化成默认模式 + _local.conn = conn + return conn + + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS memories ( + id TEXT PRIMARY KEY, + scope TEXT NOT NULL, + title TEXT NOT NULL DEFAULT '', + content TEXT NOT NULL DEFAULT '', + pinned INTEGER NOT NULL DEFAULT 0, + author_agent TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope, created_at); + +CREATE TABLE IF NOT EXISTS emotions ( + agent_id TEXT PRIMARY KEY, + emotion TEXT NOT NULL DEFAULT '', + updated_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS token_usage ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + agent_id TEXT NOT NULL, + model TEXT NOT NULL DEFAULT '', + input INTEGER NOT NULL DEFAULT 0, + output INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_token_agent ON token_usage(agent_id); + +CREATE TABLE IF NOT EXISTS agent_skills ( + agent_id TEXT NOT NULL, + skill_id TEXT NOT NULL, + ord INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (agent_id, skill_id) +); +""" + + +def init() -> None: + """建表(幂等)。内核启动时调一次,各处也会惰性调。""" + global _init_done + if _init_done: + return + with _init_lock: + if _init_done: + return + conn = _connect() + conn.executescript(SCHEMA) + conn.commit() + _init_done = True + + +def reset_init() -> None: + """测试用:换过数据目录之后强制重新建表""" + global _init_done + _init_done = False + _local.__dict__.pop('conn', None) + + +def new_id() -> str: + """新实体的主键。**一律 UUID**(需求附录 A)""" + return str(uuid.uuid4()) + + +def now_iso() -> str: + """和 store.now_iso() 一样的格式(前端直接拿来排序/展示)""" + return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z') + + +# --------------------------------------------------------------------------- # +# scope:记忆是"智能体私有"还是"世界观共享" +# --------------------------------------------------------------------------- # +# +# ★ 用带前缀的字符串而不是两列(agent_id / worldview_id): +# 读的时候永远只关心"这一条属于哪个记忆空间",不需要分情况查两列; +# 而且以后加第三种空间(比如"全局公共记忆")不用改表结构。 + +def agent_scope(agent_id: str) -> str: + return f'agent:{agent_id or ""}' + + +def world_scope(worldview_id: str) -> str: + return f'world:{worldview_id or ""}' + + +def scope_of(agent_id: str, worldview_id: str = '') -> str: + """ + 这个智能体当前该读写哪个记忆空间。 + + 绑定世界观 → 共享空间;没绑定 → 自己的私有空间(需求 3.6)。 + """ + if worldview_id: + return world_scope(worldview_id) + return agent_scope(agent_id) + + +# --------------------------------------------------------------------------- # +# 记忆 +# --------------------------------------------------------------------------- # + +def memory_add(scope: str, title: str, content: str, author_agent: str = '') -> dict: + """新增一条。返回整条(带新生成的 UUID)""" + init() + item = { + 'id': new_id(), + 'scope': scope, + 'title': (title or '').strip(), + 'content': (content or '').strip(), + 'pinned': 0, + 'author_agent': author_agent or '', + 'created_at': now_iso(), + } + conn = _connect() + conn.execute( + 'INSERT INTO memories (id, scope, title, content, pinned, author_agent, created_at) ' + 'VALUES (:id, :scope, :title, :content, :pinned, :author_agent, :created_at)', + item, + ) + conn.commit() + return item + + +def memory_get(memory_id: str) -> dict | None: + init() + row = _connect().execute('SELECT * FROM memories WHERE id = ?', (memory_id,)).fetchone() + return dict(row) if row else None + + +def memory_list(scope: str) -> list: + """一个记忆空间的全部条目(**注入 system prompt 用的就是它**)""" + init() + rows = _connect().execute( + 'SELECT * FROM memories WHERE scope = ? ORDER BY created_at ASC', (scope,), + ).fetchall() + return [dict(r) for r in rows] + + +def memory_search(scope: str, keyword: str, limit: int = 20) -> list: + """ + 关键词检索(`memory_search` 工具)。 + + ★ 用 LIKE 而不是 FTS5:FTS5 对中文要额外的分词器,而这里的关键词 + 就是用户/模型给的整词,LIKE '%关键词%' 反而更符合直觉 + (搜"咖啡"能命中"喜欢喝咖啡")。条目量级(几千)下 LIKE 也够快。 + """ + init() + kw = (keyword or '').strip() + if not kw: + return [] + like = f'%{kw}%' + rows = _connect().execute( + 'SELECT * FROM memories WHERE scope = ? AND (title LIKE ? OR content LIKE ?) ' + 'ORDER BY pinned DESC, created_at DESC LIMIT ?', + (scope, like, like, max(1, min(200, int(limit)))), + ).fetchall() + return [dict(r) for r in rows] + + +def memory_update(memory_id: str, title: str = None, content: str = None) -> dict | None: + """改标题/正文(只改传进来的字段)""" + init() + cur = memory_get(memory_id) + if not cur: + return None + new_title = cur['title'] if title is None else (title or '').strip() + new_content = cur['content'] if content is None else (content or '').strip() + conn = _connect() + conn.execute( + 'UPDATE memories SET title = ?, content = ? WHERE id = ?', + (new_title, new_content, memory_id), + ) + conn.commit() + return memory_get(memory_id) + + +def memory_forget(memory_id: str) -> bool: + init() + conn = _connect() + cur = conn.execute('DELETE FROM memories WHERE id = ?', (memory_id,)) + conn.commit() + return cur.rowcount > 0 + + +def memory_set_pinned(memory_id: str, pinned: bool) -> bool: + """用户手动标记「必须保留」(AI 改不了这个,见需求 3.2)""" + init() + conn = _connect() + cur = conn.execute('UPDATE memories SET pinned = ? WHERE id = ?', (1 if pinned else 0, memory_id)) + conn.commit() + return cur.rowcount > 0 + + +def memory_replace_all(scope: str, items: list, keep_pinned: bool = True) -> int: + """ + **AI 总结**的写回:整个空间换成压缩后的那份。 + + ★ `keep_pinned=True` 时 pinned 条目**原样保留**、不参与替换 —— + 这是需求 3.2 里"pinned 保护"的落地:用户标了"必须保留"的东西, + 不能被一次总结合并掉。 + + 返回写回了多少条。 + """ + init() + conn = _connect() + kept = [] + if keep_pinned: + kept = [dict(r) for r in conn.execute( + 'SELECT * FROM memories WHERE scope = ? AND pinned = 1', (scope,), + ).fetchall()] + conn.execute('DELETE FROM memories WHERE scope = ?' + (' AND pinned = 0' if keep_pinned else ''), + (scope,)) + n = 0 + for it in items or []: + title = str((it or {}).get('title') or '').strip() + content = str((it or {}).get('content') or '').strip() + if not title and not content: + continue + conn.execute( + 'INSERT INTO memories (id, scope, title, content, pinned, author_agent, created_at) ' + 'VALUES (?, ?, ?, ?, 0, ?, ?)', + (new_id(), scope, title, content, str(it.get('author_agent') or ''), now_iso()), + ) + n += 1 + conn.commit() + return n + len(kept) + + +def memory_titles(scope: str) -> list: + """只要标题清单(注入时先拼标题,正文按需检索 —— 见注入模板)""" + init() + rows = _connect().execute( + 'SELECT title FROM memories WHERE scope = ? ORDER BY pinned DESC, created_at ASC', (scope,), + ).fetchall() + return [r['title'] for r in rows if r['title']] + + +# --------------------------------------------------------------------------- # +# 情绪(始终按智能体私有,即使绑定了世界观 —— 需求 3.5) +# --------------------------------------------------------------------------- # + +def emotion_get(agent_id: str) -> str: + init() + row = _connect().execute( + 'SELECT emotion FROM emotions WHERE agent_id = ?', (agent_id or '',), + ).fetchone() + return row['emotion'] if row else '' + + +def emotion_set(agent_id: str, emotion: str) -> str: + init() + conn = _connect() + conn.execute( + 'INSERT INTO emotions (agent_id, emotion, updated_at) VALUES (?, ?, ?) ' + 'ON CONFLICT(agent_id) DO UPDATE SET emotion = excluded.emotion, updated_at = excluded.updated_at', + (agent_id or '', emotion or '', now_iso()), + ) + conn.commit() + return emotion or '' + + +def peer_emotions(worldview_id: str, exclude_agent: str, agent_ids: list) -> list: + """ + 同世界观、**其他**智能体的「名字 + 情绪」(情绪感知开关打开时才注入)。 + + [agent_ids] 是绑定了这个世界观的全部智能体 id(由调用方从 agents.json 里挑, + 这里不碰 JSON —— 数据层只管数据库里有什么)。返回 [(agent_id, emotion)]。 + """ + init() + out = [] + for aid in agent_ids or []: + if not aid or aid == exclude_agent: + continue + out.append((aid, emotion_get(aid))) + return out + + +# --------------------------------------------------------------------------- # +# Token 统计 +# --------------------------------------------------------------------------- # + +def token_add(agent_id: str, model: str, input_tokens: int, output_tokens: int) -> None: + """ + 记一次消耗。 + + ★ 输入 / 输出**分开记**(需求 3.1),而且按**模型**分桶 —— + "按模型"是靠每行带 model 名做到的:桶是查询时 group by 出来的, + 不是提前建好的。这样换模型不会有"桶没建好"的问题。 + """ + init() + conn = _connect() + conn.execute( + 'INSERT INTO token_usage (agent_id, model, input, output, created_at) ' + 'VALUES (?, ?, ?, ?, ?)', + (agent_id or '', model or '', int(input_tokens or 0), int(output_tokens or 0), now_iso()), + ) + conn.commit() + + +def token_usage(agent_id: str) -> dict: + """ + 这个智能体的累计用量。 + + 返回 `{'total': {'input':..,'output':..}, 'byModel': [{'model':..,'input':..,'output':..}]}` + """ + init() + conn = _connect() + rows = conn.execute( + 'SELECT model, SUM(input) AS i, SUM(output) AS o FROM token_usage ' + 'WHERE agent_id = ? GROUP BY model ORDER BY (SUM(input) + SUM(output)) DESC', + (agent_id or '',), + ).fetchall() + by_model = [ + {'model': r['model'] or '(未知)', 'input': int(r['i'] or 0), 'output': int(r['o'] or 0)} + for r in rows + ] + return { + 'total': { + 'input': sum(m['input'] for m in by_model), + 'output': sum(m['output'] for m in by_model), + }, + 'byModel': by_model, + } + + +def token_reset(agent_id: str) -> int: + """按智能体清零(需求 3.1 的"管理操作")。返回清掉了几行""" + init() + conn = _connect() + cur = conn.execute('DELETE FROM token_usage WHERE agent_id = ?', (agent_id or '',)) + conn.commit() + return cur.rowcount + + +# --------------------------------------------------------------------------- # +# Skill 绑定 +# --------------------------------------------------------------------------- # + +def skills_of(agent_id: str) -> list: + """这个智能体绑定的自定义 Skill id(**按绑定顺序** —— 注入要按顺序拼)""" + init() + rows = _connect().execute( + 'SELECT skill_id FROM agent_skills WHERE agent_id = ? ORDER BY ord ASC, skill_id ASC', + (agent_id or '',), + ).fetchall() + return [r['skill_id'] for r in rows] + + +def bind_skills(agent_id: str, skill_ids: list) -> None: + """整体替换绑定关系(界面上的"勾选"就是一次整体替换,不用做增删接口)""" + init() + conn = _connect() + conn.execute('DELETE FROM agent_skills WHERE agent_id = ?', (agent_id or '',)) + for i, sid in enumerate(skill_ids or []): + if not sid: + continue + conn.execute( + 'INSERT OR REPLACE INTO agent_skills (agent_id, skill_id, ord) VALUES (?, ?, ?)', + (agent_id or '', sid, i), + ) + conn.commit() + + +def unbind_agent(agent_id: str) -> None: + """智能体被删掉时的清理(记忆**不删** —— 那是用户的数据,删了他会心疼)""" + init() + conn = _connect() + conn.execute('DELETE FROM agent_skills WHERE agent_id = ?', (agent_id or '',)) + conn.execute('DELETE FROM emotions WHERE agent_id = ?', (agent_id or '',)) + conn.commit() diff --git a/android/kernel/app.py b/android/kernel/app.py index 2bdf239..296cdc7 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -39,6 +39,9 @@ import providers import speech import store import timeouts +import agentdb +import agent_api +import agent_context import tools_runtime import uploads from defaults import PROVIDER_PRESETS @@ -579,6 +582,17 @@ class KernelHandler(BaseHTTPRequestHandler): 'mcpConfig': mcp_client.read_mcp_config(), 'conversations': store.list_conversations(), 'agents': store.list_agents(), + # ---- 智能体系统的另外三种资源(需求 v1.1)---- + # 都不大(几个到几十个),一次带给界面省得进页面再拉一次 + 'worldviews': store.list_resource('worldviews'), + 'modelEntries': store.list_resource('models'), + 'skills': store.list_resource('skills'), + # AI 提的"该整理记忆了"(按智能体存),界面据此显示按钮 + 'memorySuggestions': { + a.get('id'): store.peek_summary_suggestion(a.get('id') or '') + for a in store.list_agents() + if store.peek_summary_suggestion(a.get('id') or '') + }, 'toolNames': tool_names, 'suggestedAllow': tools_runtime.suggest_allowlist(tool_names), # 前端用它挑终端里的预设命令(安卓的 getprop / Windows 的 dir 不通用) @@ -1257,27 +1271,15 @@ class KernelHandler(BaseHTTPRequestHandler): self.send_json(200, {'ok': True}) return True - # 智能体 - if pathname == '/api/agents' and method == 'GET': - self.send_json(200, {'agents': store.list_agents()}) + # 智能体系统的接口(记忆 / 情绪 / Token / 世界观 / 模型列表 / Skill / 导入导出) + # + # ★ 全部集中在 agent_api.py 里 —— app.py 已经 1800 行,二十多个新接口 + # 塞进来会让这个文件彻底没法看。 + # ★ 老的 /api/agents 那三个路由**删掉了**(原来在下面),由这里统一处理: + # 留着就是两份实现,而新那份多了"内置智能体不能删"的保护 —— + # 两份并存的话,哪份生效取决于顺序,这种 bug 最难查。 + if agent_api.handle(self, pathname, method): return True - if pathname == '/api/agents' and method == 'POST': - body = self.read_json_body() - self.send_json(200, {'agent': store.create_agent(body)}) - return True - agent_id = self._match_id(pathname, '/api/agents/') - if agent_id is not None: - if method in ('PATCH', 'PUT'): - body = self.read_json_body() - agent = store.update_agent(agent_id, body) - if agent: - self.send_json(200, {'agent': agent}) - else: - self.send_json(404, {'error': '智能体不存在'}) - return True - if method == 'DELETE': - self.send_json(200 if store.delete_agent(agent_id) else 404, {'ok': True}) - return True # 附件 if pathname == '/api/upload' and method == 'POST': @@ -1426,7 +1428,19 @@ class KernelHandler(BaseHTTPRequestHandler): ) merged_agent = {'systemPrompt': sys_prompt, 'id': '', 'name': '判断器'} else: - base = (agent or {}).get('systemPrompt') or cfg.get('systemPrompt') or '' + # ★ 会议节点也走**同一套** system prompt 拼装(需求附录 C)。 + # + # 以前这里是自己拼的(`agent.systemPrompt or cfg.systemPrompt`), + # 于是同一个智能体在聊天里有记忆/情绪/世界观、在会议节点里没有 —— + # "引擎改了另一端必须跟上"这条在这个仓库里踩过好几次, + # 所以这次直接复用 agent_context,别再抄一份。 + # + # ★ 节点的额外要求 / 输出要求 / 变量说明仍然**追加在后面**: + # 它们是"这一轮的任务约束",比人设更具体,放最后模型才看得重。 + if agent: + base = agent_context.build_system_prompt(store.read_settings(), agent) + else: + base = cfg.get('systemPrompt') or '' parts = [base] if base.strip() else [] if extra: parts.append('【本次任务的额外要求】\n' + extra) @@ -1638,6 +1652,45 @@ class KernelHandler(BaseHTTPRequestHandler): has_image = any(p.get('type') == 'image_url' for p in parts) user_content = parts if (has_image or len(parts) > 1) else text agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId')) + agent_id = (agent or {}).get('id') or '' + + # ★★ Token 限额:**发起前**拦(需求 3.1)。 + # + # 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是 + # **已经攒下来的**用量,超了就根本不发这一轮。 + # + # ★ 拦在"写用户消息之前":拦住了还把用户那句话落库的话, + # 他会看到自己发的消息挂在那儿、AI 永远不回,以为卡住了。 + # + # ★ 豁免:记忆整理、导出这些**非对话生成**的操作不走这里 + # (它们有自己的接口),所以不会被限额挡住。 + try: + limit = int(float((agent or {}).get('tokenLimit') or 0)) + except (TypeError, ValueError): + limit = 0 + if limit > 0 and agent_id: + used = sum(agentdb.token_usage(agent_id)['total'].values()) + if used >= limit: + farewell = (settings.get('tokenLimitFarewell') or '我没力气再说话了……').strip() + store.append_messages(conversation_id, [{ + 'role': 'assistant', + 'content': farewell, + 'agentId': agent_id, + # ★ 标一下"这不是模型生成的":界面据此把它显示成提示样式, + # 而且重新生成时不会被当成一条正常的 AI 回复 + 'limitNotice': True, + 'at': store.now_iso(), + }]) + emit({ + 'type': 'error', + 'code': 'token_limit', + 'message': f'{(agent or {}).get("name") or "这个智能体"}的 Token 额度用完了', + 'used': used, + 'limit': limit, + 'farewell': farewell, + 'hint': '可以清零重新开始,或者把限额调大 / 改成无限制。', + }) + return store.append_messages(conversation_id, [{ 'role': 'user', @@ -1661,14 +1714,28 @@ class KernelHandler(BaseHTTPRequestHandler): send_depth=send_depth, ) + # ★ 这一轮的 Token 用量(需求 4.1:对话界面显示"本次对话"的用量)。 + # 按轮记在消息上,会话级用量是**加起来**算的 —— 这样"重新生成" + # 把上一条替换掉时,它的消耗也跟着消失,不会虚高。 + in_tok, out_tok = agent_loop.usage_pair(result.get('usage')) + model_name = (store.provider_info(settings, agent) or {}).get('model') or '' + store.append_messages(conversation_id, [{ 'role': 'assistant', 'content': result.get('content', ''), # 思维链也要落库,否则一刷新「思考过程」就没了 'reasoning': result.get('reasoning', '') or '', - 'agentId': (agent or {}).get('id') or '', + 'agentId': agent_id, + 'usage': {'input': in_tok, 'output': out_tok}, 'at': store.now_iso(), }]) + # ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。 + # 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。 + if agent_id and (in_tok or out_tok): + try: + agentdb.token_add(agent_id, model_name, in_tok, out_tok) + except Exception as exc: # noqa: BLE001 + print(f'[usage] 记 Token 用量失败:{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 事件收尾,前端才知道停了 diff --git a/android/kernel/builtin_tools.py b/android/kernel/builtin_tools.py index be7ea1e..ad9c9b0 100644 --- a/android/kernel/builtin_tools.py +++ b/android/kernel/builtin_tools.py @@ -344,3 +344,13 @@ BUILTIN_TOOLS = { 'shell': {'spec': SHELL_TOOL, 'run': shell_run}, 'python_run': {'spec': PYTHON_RUN_TOOL, 'run': python_run}, } + +# 智能体系统的工具(记忆 / 情绪 / 用量)也走**进程内**实现 —— 它们要读写 +# `agent.db`,而电脑端的文件工具是子进程,根本 import 不到内核模块。 +# +# ★ 合并进这一个字典而不是让 tools_runtime 从两处取: +# 发现工具、找入口、判"要不要豁免超时"全都只认 BUILTIN_TOOLS, +# 多一个来源就多一处"忘了查"的机会(加进来之后自动全部生效)。 +from agent_tools import AGENT_TOOLS # noqa: E402 + +BUILTIN_TOOLS.update(AGENT_TOOLS) diff --git a/android/kernel/defaults.py b/android/kernel/defaults.py index f3c69c6..35da733 100644 --- a/android/kernel/defaults.py +++ b/android/kernel/defaults.py @@ -222,6 +222,69 @@ DEFAULT_SETTINGS = { SECRET_KEYS = {'apiKey'} +# --------------------------------------------------------------------------- # +# 智能体系统(需求 v1.1) +# --------------------------------------------------------------------------- # + +# 内置 Skill:记忆 / 情绪 / 检索 / 用量这几个工具的**使用手册**(需求 3.7)。 +# +# ★ 为什么不把这些写进工具自己的 description: +# 工具的 description 只讲"这个工具怎么调",而 Skill 讲的是 +# "**什么时候该用、用完之后不许干什么**"—— 后者才是模型最容易犯错的地方 +# (最典型的是"只在嘴上说记住了、根本没调工具")。 +# 放在 段里,每个智能体都能看到;自定义 Skill 按同样的方式追加。 +BUILTIN_SKILL = '\n'.join([ + '【记忆】你有自己的记忆库,**跨对话保留**:', + '· 用户说了值得长期记住的事(称呼、偏好、重要事实、约定、他的项目),用 memory_add 记下来。', + '· 记之前先看上面的记忆清单 —— 已经记过的不要再记一遍,否则清单会越来越乱。', + '· 记错了/过时了用 memory_update 改;确实不该留的用 memory_forget 删(只能删你自己写的)。', + '· 清单里只有标题,需要正文细节时用 memory_search 检索。', + '★★ 绝对不要只在回复里说"我记住了"却不调用 memory_add。', + ' 说了要记就必须真的调工具;没调就别说这句话 —— 用户会当场发现你在骗他。', + '', + '【情绪】emotion_set 改的是**你自己**的情绪状态,下次对话还在。', + ' 情绪要跟着对话内容自然变化;别每轮都改,也别一直用同一个词。', + '', + '【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。', +]) + +# system prompt 的注入模板(需求附录 C)。 +# +# 顺序是**固定**的:人设 → skills → worldview → emotion → memory → peer_emotions。 +# 可以整段替换(存全局设置 promptTemplate),但占位符名字别改 —— +# agent_context.py 就是按这些名字找段落、空段整段删掉的。 +DEFAULT_PROMPT_TEMPLATE = '\n'.join([ + '{prompt}', + '', + '', + '{skills}', + '', + '', + '', + '{worldview}', + '', + '', + '', + '{emotion}', + '', + '', + '', + '{memory}', + '', + '', + '', + '{peer_emotions}', + '', +]) + +# 记忆注入时的条目模板(附录 C 的 `【标题1】内容1`)。 +# +# ★ 是**全量注入**(标题 + 正文都进去)—— 需求 3.2 的"主动记忆:smartMemory +# 全量注入 system prompt"。正文不进的话模型只知道"我记过这件事", +# 每次要用都得再检索一次,白花一轮。 +DEFAULT_MEMORY_LINE = '【{title}】{content}' + + # 内置智能体(前端有同名头像,靠 avatar 字段对应) DEFAULT_AGENTS = [ { diff --git a/android/kernel/doubao_entry.py b/android/kernel/doubao_entry.py index 377de3f..c371ae2 100644 --- a/android/kernel/doubao_entry.py +++ b/android/kernel/doubao_entry.py @@ -44,6 +44,11 @@ BUNDLED_TOOL_FILES = [ 'notifications.py', 'apps.py', 'volume.py', + # ★ web_search.py 以前漏在清单外(对拍脚本抓出来的)。 + # 它其实**照样会被播种**(构建脚本遍历整个 tools/ 目录, + # _seed_tools 又用那份源码整体补齐),所以功能上没缺 —— + # 但清单是"内置工具一览"的文档,和现实不一致就会误导下一个人。 + 'web_search.py', '_mcp_python_example.py', ] diff --git a/android/kernel/paths.py b/android/kernel/paths.py index 6336749..40713b1 100644 --- a/android/kernel/paths.py +++ b/android/kernel/paths.py @@ -86,6 +86,19 @@ class Paths: self.conversations_file = os.path.join(self.data_dir, 'conversations.json') self.agents_file = os.path.join(self.data_dir, 'agents.json') self.mcp_file = os.path.join(self.data_dir, 'mcp.servers.json') + # ---- 智能体系统的另外三种资源(需求 v1.1)---- + # + # ★ 和 agents.json 一样是 JSON、一人一个文件:它们的量级也是"几个到几十个", + # 而且要人肉可读(用户会想直接看自己建的世界观写成什么样)。 + # 会**持续增长**的那些(记忆 / 情绪 / Token 统计)在 agent.db 里, + # 分界线见 agentdb.py 的文件头。 + self.worldviews_file = os.path.join(self.data_dir, 'worldviews.json') + self.models_file = os.path.join(self.data_dir, 'models.json') + self.skills_file = os.path.join(self.data_dir, 'skills.json') + # 智能体系统的 SQLite(记忆 / 情绪 / Token / 绑定关系) + self.agent_db_file = os.path.join(self.data_dir, 'agent.db') + # 智能体包解出来的图片等资源(导入 zip 时落到这儿) + self.agent_assets_dir = os.path.join(self.data_dir, 'agent-assets') @staticmethod def _resolve_web_core(explicit: str | None) -> str: @@ -103,7 +116,7 @@ class Paths: def ensure_dirs(self) -> None: for folder in (self.data_dir, self.uploads_dir, self.tmp_dir, self.screens_dir, - self.notes_dir): + self.notes_dir, self.agent_assets_dir): try: os.makedirs(folder, exist_ok=True) except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死 diff --git a/android/kernel/store.py b/android/kernel/store.py index b1f77af..9b5db80 100644 --- a/android/kernel/store.py +++ b/android/kernel/store.py @@ -21,6 +21,7 @@ import uuid from datetime import datetime, timezone import paths +import agentdb from defaults import DEFAULT_AGENTS, DEFAULT_SETTINGS, PROVIDER_PRESETS _lock = threading.RLock() @@ -817,6 +818,38 @@ def clear_pending_ui(conv_id: str) -> None: _pending_ui.pop(conv_id, None) +# --------------------------------------------------------------------------- # +# 「建议整理记忆」的待处理队列 +# --------------------------------------------------------------------------- # +# +# AI 用 memory_suggest_summary 提的建议 —— **只提示不执行**(需求 3.2)。 +# 界面读到之后给用户一个「整理记忆」按钮,用户点了才真的跑总结。 +# +# ★ 为什么放内存而不是落库:它是一次性的提示,用户处理完就该消失。 +# 落库的话重启一次 App 会看到三天前那条建议,莫名其妙。 +# ★ 按智能体存(不是按会话):建议是"你的记忆该整理了",跟哪个会话无关。 +_pending_summary: dict = {} + + +def add_pending_summary_suggestion(agent_id: str, reason: str) -> None: + """同一个人后来的建议**覆盖**前面的 —— 说两遍没有意义""" + if not agent_id: + return + with _lock: + _pending_summary[agent_id] = (reason or '').strip() + + +def peek_summary_suggestion(agent_id: str) -> str: + with _lock: + return _pending_summary.get(agent_id or '', '') + + +def take_summary_suggestion(agent_id: str) -> str: + """取走(取完就没了)""" + with _lock: + return _pending_summary.pop(agent_id or '', '') + + def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict: item = { 'id': _rid_conv(), @@ -899,18 +932,74 @@ def store_file_path() -> str: # 提成常量是为了 create / update 两边不会漂移: # 之前这两个函数各写一份硬编码白名单,加字段时漏改一处, # 表现就是"界面上填了、保存后再打开又变空了"。 -AGENT_FIELDS = ( +# +# ★ v1.1 新增(《智能体系统需求文档》),字段按类型分开,见下面的 _apply_agent_patch: +# description 选择界面上展示的介绍文案(2.1) +# image 外观四件套 front / back / border-main / border-info(2.5) +# modelId 引用全局模型列表里的一个(3.3 多模型) +# worldviewId 绑定的世界观(3.6) +# emotionEnabled 情绪感知开关(3.5) +# tokenLimit Token 限额,0 = 无限制(3.1) +# skillIds 绑定的自定义 Skill(3.7;真正的绑定关系在 agent.db) +AGENT_TEXT_FIELDS = ( + 'name', 'avatar', 'tagline', 'description', 'systemPrompt', 'provider', # 走哪家(留空 = 全局) 'model', # 用哪个模型 'baseUrl', # 自定义网关地址 'ttsEngine', # 朗读引擎:system / volcv3 / volc / openai 'ttsVoice', # 音色 —— 多人会议里靠它区分谁在说话 + 'modelId', # ← 全局模型列表里的 id + 'worldviewId', # ← 绑定的世界观 id +) +AGENT_NUM_FIELDS = ( 'ttsSpeed', # 语速 + 'tokenLimit', # 0 = 无限制(不是"限额为 0") +) +AGENT_BOOL_FIELDS = ('emotionEnabled',) +AGENT_LIST_FIELDS = ('skillIds',) +AGENT_DICT_FIELDS = ('image',) + +#: 能被 patch 改的全部字段(界面上"这个智能体有哪些可配"就看它) +AGENT_FIELDS = ( + AGENT_TEXT_FIELDS + AGENT_NUM_FIELDS + AGENT_BOOL_FIELDS + + AGENT_LIST_FIELDS + AGENT_DICT_FIELDS ) -def _rid_agent() -> str: - return f'a_{_ts36()}_{_rand36(4)}' +def _apply_agent_patch(agent: dict, patch: dict) -> dict: + """ + 把 patch 里的字段规整进 agent。 + + ★ **create 和 update 共用这一份** —— 它们以前各写一份白名单, + 加字段漏改一处就是"界面上填了、保存后再打开又变空了"这种查半天的 bug。 + ★ 类型规整也在这里:从 HTTP 来的东西可能是字符串(`"true"`、`"3"`), + 直接存进去会让界面读到时类型不对(勾选框永远是空的)。 + """ + patch = patch or {} + for key in AGENT_TEXT_FIELDS: + if patch.get(key) is not None: + agent[key] = _as_text(patch[key]) + for key in AGENT_NUM_FIELDS: + if patch.get(key) is not None: + try: + agent[key] = float(patch[key]) + except (TypeError, ValueError): + pass + for key in AGENT_BOOL_FIELDS: + if patch.get(key) is not None: + agent[key] = bool(patch[key]) + for key in AGENT_LIST_FIELDS: + if patch.get(key) is not None: + raw = patch[key] + agent[key] = [str(x) for x in raw] if isinstance(raw, list) else [] + for key in AGENT_DICT_FIELDS: + if patch.get(key) is not None: + raw = patch[key] + agent[key] = ( + {str(k): _as_text(v) for k, v in raw.items()} + if isinstance(raw, dict) else {} + ) + return agent def list_agents() -> list: @@ -938,19 +1027,19 @@ def get_agent(agent_id: str | None): def create_agent(payload: dict) -> dict: payload = payload or {} state = {'agents': list_agents()} + # ★ id 一律 UUID(需求附录 A):`name` 只是显示名,允许重复、允许随便改, + # 所有关联(记忆作者、Token 统计、Skill 绑定)都挂在这个 id 上。 + # 老数据里的 `a_doubao` 这种短 id **保留不动** —— 会话语料引用着它们。 agent = { - 'id': _rid_agent(), + 'id': agentdb.new_id(), 'name': _as_text(payload.get('name') or '新智能体')[:24], - 'avatar': payload.get('avatar') or 'custom', + 'avatar': _as_text(payload.get('avatar') or 'custom'), 'tagline': _as_text(payload.get('tagline'))[:40], 'systemPrompt': _as_text(payload.get('systemPrompt')), 'builtin': False, 'createdAt': now_iso(), } - # 智能体自己的模型/语音(留空 = 继承全局) - for key in AGENT_FIELDS: - if payload.get(key) is not None: - agent[key] = _as_text(payload.get(key)) + _apply_agent_patch(agent, payload) state['agents'].append(agent) _write_json(paths.get().agents_file, state) return agent @@ -961,10 +1050,7 @@ def update_agent(agent_id: str, patch: dict): agent = next((a for a in state['agents'] if a.get('id') == agent_id), None) if not agent: return None - patch = patch or {} - for key in ('name', 'avatar', 'tagline', 'systemPrompt', *AGENT_FIELDS): - if patch.get(key) is not None: - agent[key] = patch[key] + _apply_agent_patch(agent, patch) _write_json(paths.get().agents_file, state) return agent @@ -976,6 +1062,141 @@ def delete_agent(agent_id: str) -> bool: return False state['agents'].pop(index) _write_json(paths.get().agents_file, state) + # 清掉它在数据库里的绑定关系和情绪;**记忆不删** —— 那是用户的数据, + # 删智能体顺手把他攒了几个月的记忆抹掉,他会心疼(而且没法恢复) + try: + agentdb.unbind_agent(agent_id) + except Exception as exc: # noqa: BLE001 - 清理失败不该让删除失败 + print(f'[store] 清理 {agent_id} 的绑定关系失败:{exc}', file=sys.stderr) + return True + + +# --------------------------------------------------------------------------- # +# 通用资源表:世界观 / 全局模型 / Skill +# --------------------------------------------------------------------------- # +# +# ★ 三者的 CRUD 完全一样(列表 + 增 + 改 + 删 + UUID 主键),所以**只写一份** —— +# 区别只是"有哪些字段",那部分在 RESOURCES 里声明。 +# +# ★ 为什么不放 agent.db(SQLite):它们的量级和 agents.json 一样是"几个到几十个" +# (用户自己会去数),而且要人肉可读。分界线见 agentdb.py 的文件头。 + +RESOURCES = { + # 世界观(需求 3.6):名字 + 设定文本 + 外观四件套 + 'worldviews': { + 'file': lambda: paths.get().worldviews_file, + 'key': 'worldviews', + 'text': ('name', 'setting'), + 'dict': ('image',), + 'label': '世界观', + }, + # 全局模型列表(需求 3.3):名称 + API 端点 + Key + 模型标识 + 单价 + 'models': { + 'file': lambda: paths.get().models_file, + 'key': 'models', + 'text': ('name', 'apiBase', 'apiKey', 'model', 'provider'), + 'num': ('pricePerK',), # 元/千 Token,0 = 不显示费用估算 + 'label': '模型', + }, + # Skill(需求 3.7):纯文本的"工具使用手册" + 'skills': { + 'file': lambda: paths.get().skills_file, + 'key': 'skills', + 'text': ('name', 'content'), + 'bool': ('builtin',), + 'label': 'Skill', + }, +} + + +def _res(name: str) -> dict: + cfg = RESOURCES.get(name) + if not cfg: + raise KeyError(f'没有这种资源:{name}') + return cfg + + +def list_resource(name: str) -> list: + cfg = _res(name) + file_path = cfg['file']() + data = _read_json(file_path) + if not isinstance(data, dict) or not isinstance(data.get(cfg['key']), list): + return [] + return data[cfg['key']] + + +def _write_resource(name: str, items: list) -> None: + cfg = _res(name) + _write_json(cfg['file'](), {cfg['key']: items}) + + +def get_resource(name: str, rid: str): + if not rid: + return None + for item in list_resource(name): + if item.get('id') == rid: + return item + return None + + +def _apply_resource_patch(name: str, item: dict, patch: dict) -> dict: + cfg = _res(name) + patch = patch or {} + for key in cfg.get('text', ()): + if patch.get(key) is not None: + item[key] = _as_text(patch[key]) + for key in cfg.get('num', ()): + if patch.get(key) is not None: + try: + item[key] = float(patch[key]) + except (TypeError, ValueError): + pass + for key in cfg.get('bool', ()): + if patch.get(key) is not None: + item[key] = bool(patch[key]) + for key in cfg.get('dict', ()): + if patch.get(key) is not None: + raw = patch[key] + item[key] = ( + {str(k): _as_text(v) for k, v in raw.items()} + if isinstance(raw, dict) else {} + ) + return item + + +def create_resource(name: str, payload: dict) -> dict: + cfg = _res(name) + items = list_resource(name) + item = { + 'id': agentdb.new_id(), # ★ UUID(需求附录 A) + 'name': _as_text((payload or {}).get('name'))[:40], + 'builtin': False, + 'createdAt': now_iso(), + } + _apply_resource_patch(name, item, payload) + # 重名不拦(需求 2.5:重名由用户自己区分),但界面要能看出来, + # 所以这里不做任何"自动改名" —— 显示时加序号是界面的事 + items.append(item) + _write_resource(name, items) + return item + + +def update_resource(name: str, rid: str, patch: dict): + items = list_resource(name) + item = next((x for x in items if x.get('id') == rid), None) + if not item: + return None + _apply_resource_patch(name, item, patch) + _write_resource(name, items) + return item + + +def delete_resource(name: str, rid: str) -> bool: + items = list_resource(name) + left = [x for x in items if x.get('id') != rid] + if len(left) == len(items): + return False + _write_resource(name, left) return True diff --git a/scripts/probe-agent-system.py b/scripts/probe-agent-system.py new file mode 100644 index 0000000..ffcc6b3 --- /dev/null +++ b/scripts/probe-agent-system.py @@ -0,0 +1,319 @@ +"""智能体系统(需求 v1.1)的端到端探针 —— 不装机就能验整条链路。 + +## 怎么做到的 + +内核的存储层是**无状态**的(路径全靠 `paths.get()` 从数据目录推), +所以只要把 `DOUBAO_DATA` 指到一个临时目录,就能在一个进程里把 +"建智能体 → 记东西 → 检索 → 拼提示词 → 导包 → 再导入"整条链路跑一遍。 + +比装机验证快得多,而且**能断言具体字段**(装机只能截图看个大概)。 + +## 覆盖 + + 1. 建智能体拿到的是 UUID(需求附录 A) + 2. 记忆增删改查 + 检索 + 3. pinned 保护(AI 改不动) + 4. 情绪读写 + 5. Token 统计(按模型分桶、输入输出分开) + 6. 世界观 + **共享记忆**(两个智能体共用一个空间) + 7. 写入限权(只能删自己写的) + 8. system prompt 注入(附录 C 的五段都在、空段被删掉) + 9. 智能体包导出 → 导入(导入两次 = 两个独立实体) + 10. 记忆导出/导入(合并按标题去重) + 11. 资源 CRUD(世界观 / 模型列表 / Skill) + +用法: + python scripts/probe-agent-system.py +""" +import io +import json +import os +import shutil +import sys +import tempfile + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +HERE = os.path.dirname(os.path.abspath(__file__)) +REPO = os.path.abspath(os.path.join(HERE, "..")) +KERNEL = os.path.join(REPO, "android", "kernel") + +# ★ 必须在 import 内核之前设好:paths.get() 是**懒加载 + 缓存**的 +DATA = tempfile.mkdtemp(prefix="doubao-agent-probe-") +os.environ["DOUBAO_DATA"] = DATA +sys.path.insert(0, KERNEL) + +fails = [] + + +def check(label, cond, detail=""): + if cond: + print(f" ✓ {label}") + else: + fails.append(label) + print(f" ✗ {label} {detail}") + + +def section(title): + print(f"\n=== {title} ===") + + +import agent_context # noqa: E402 +import agent_tools # noqa: E402 +import agentdb # noqa: E402 +import store # noqa: E402 + + +class FakeHandler: + """冒充 app.py 的 Handler:只要 send_json / read_json_body 两个方法""" + + def __init__(self): + self.status = 200 + self.payload = None + + def send_json(self, code, payload): + self.status = code + self.payload = payload + + def read_json_body(self, *a, **k): + return self._body + + def call(self, pathname, method, body=None): + body = body or {} + self._body = body + import agent_api + + self.status, self.payload = 200, None + agent_api.handle(self, pathname, method) + return self.payload or {} + + +def main(): + print(f"临时数据目录:{DATA}") + h = FakeHandler() + + # ---------------------------------------------------------------- 1 + section("1. 智能体:UUID 主键 + 扩展字段") + a1 = store.create_agent({"name": "玄辰", "description": "仙门大师兄", "systemPrompt": "你是玄辰。"}) + check("新建的 id 是 UUID", len(a1["id"]) == 36 and a1["id"].count("-") == 4, a1["id"]) + check("description 存下来了", a1.get("description") == "仙门大师兄") + a1 = store.update_agent(a1["id"], {"tokenLimit": 5000, "emotionEnabled": True, "skillIds": []}) or a1 + check("tokenLimit 存成数字", a1.get("tokenLimit") == 5000, repr(a1.get("tokenLimit"))) + check("emotionEnabled 是布尔", a1.get("emotionEnabled") is True) + a2 = store.create_agent({"name": "仙辰"}) + check("两个智能体 id 不同", a1["id"] != a2["id"]) + # 内置的还在、短 id 没被动过 + check("内置智能体保留了短 id", any(x["id"] == "a_doubao" for x in store.list_agents())) + + # ---------------------------------------------------------------- 2 + section("2. 记忆:增删改查 + 检索") + scope = agentdb.scope_of(a1["id"]) + m1 = agentdb.memory_add(scope, "用户的名字", "他叫小林", author_agent=a1["id"]) + m2 = agentdb.memory_add(scope, "喝咖啡", "每天早上喝一杯美式", author_agent=a1["id"]) + check("加了两条", len(agentdb.memory_list(scope)) == 2) + check("检索命中正文", len(agentdb.memory_search(scope, "美式")) == 1) + check("检索命中标题", len(agentdb.memory_search(scope, "名字")) == 1) + check("检索无关词不命中", len(agentdb.memory_search(scope, "量子力学")) == 0) + agentdb.memory_update(m1["id"], content="他叫小林,做前端的") + check("改正文生效", "前端" in agentdb.memory_get(m1["id"])["content"]) + agentdb.memory_forget(m2["id"]) + check("删掉一条", len(agentdb.memory_list(scope)) == 1) + + # ---------------------------------------------------------------- 3 + section("3. pinned 保护(AI 改不动)") + agentdb.memory_set_pinned(m1["id"], True) + import tools_runtime + + tools_runtime.push_context(agentId=a1["id"], conversationId="c_test") + try: + agent_tools.memory_forget({"id": m1["id"]}) + check("pinned 的删不掉", False, "居然删成功了") + except ValueError as exc: + check("pinned 的删不掉", "必须保留" in str(exc), str(exc)) + try: + agent_tools.memory_update({"id": m1["id"], "content": "改了"}) + check("pinned 的改不动", False, "居然改成功了") + except ValueError: + check("pinned 的改不动", True) + check("pinned 的还在", agentdb.memory_get(m1["id"]) is not None) + agentdb.memory_set_pinned(m1["id"], False) + + # ---------------------------------------------------------------- 4 + section("4. 工具:memory_add / emotion_set / get_token_usage") + r = agent_tools.memory_add({"title": "喜欢猫", "content": "他家有两只猫"}) + check("memory_add 返回 id", bool(r.get("id"))) + r = agent_tools.memory_search({"keyword": "猫"}) + check("memory_search 找到刚记的", r["count"] >= 1, str(r["count"])) + agent_tools.emotion_set({"emotion": "刚被夸了,有点得意"}) + check("情绪写进去了", "得意" in agentdb.emotion_get(a1["id"])) + agentdb.token_add(a1["id"], "doubao-pro", 1200, 800) + agentdb.token_add(a1["id"], "doubao-pro", 300, 100) + agentdb.token_add(a1["id"], "deepseek-r1", 500, 200) + u = agent_tools.get_token_usage({}) + check("总量 = 输入+输出", u["used"] == 1200 + 800 + 300 + 100 + 500 + 200, str(u["used"])) + check("输入输出分开", u["input"] == 2000 and u["output"] == 1100, f'{u["input"]}/{u["output"]}') + check("按模型分桶", len(u["byModel"]) == 2, str([m["model"] for m in u["byModel"]])) + check("剩余额度按限额算", u["remaining"] == 5000 - u["used"], str(u["remaining"])) + + # ---------------------------------------------------------------- 5 + section("5. 世界观 + 共享记忆") + wv = store.create_resource("worldviews", {"name": "九霄", "setting": "一个仙侠世界,灵气复苏。"}) + check("世界观有 UUID", len(wv["id"]) == 36) + store.update_agent(a1["id"], {"worldviewId": wv["id"]}) + store.update_agent(a2["id"], {"worldviewId": wv["id"]}) + a1 = store.get_agent(a1["id"]) + a2 = store.get_agent(a2["id"]) + check("绑定后 scope 变成世界观的", agentdb.scope_of(a1["id"], a1["worldviewId"]).startswith("world:")) + wscope = agentdb.scope_of(a1["id"], a1["worldviewId"]) + agentdb.memory_add(wscope, "共同约定", "两人都怕师父", author_agent=a1["id"]) + check("共享空间两人都看得到", len(agentdb.memory_list(agentdb.scope_of(a2["id"], a2["worldviewId"]))) == 1) + + # ---------------------------------------------------------------- 6 + section("6. 写入限权:只能删自己写的") + tools_runtime.push_context(agentId=a2["id"], conversationId="c_test") + shared_item = agentdb.memory_list(wscope)[0] + try: + agent_tools.memory_forget({"id": shared_item["id"]}) + check("删不了别人写的", False, "居然删成功了") + except ValueError as exc: + check("删不了别人写的", "其他智能体" in str(exc), str(exc)) + # 自己写的能删 + mine = agent_tools.memory_add({"title": "仙辰的事", "content": "他喜欢御剑"}) + agent_tools.memory_forget({"id": mine["id"]}) + check("自己的能删", agentdb.memory_get(mine["id"]) is None) + + # ---------------------------------------------------------------- 7 + section("7. system prompt 注入(附录 C)") + tools_runtime.push_context(agentId=a1["id"], conversationId="c_test") + agentdb.emotion_set(a2["id"], "有点烦") + store.update_agent(a2["id"], {"emotionEnabled": True}) + # ★ a1 在这一节之前已经绑了世界观 → 它的记忆空间是**共享**的那个, + # 所以验证"记忆进提示词"要往当前 scope 里写(这正是绑定世界观的正确行为) + agentdb.memory_add(agentdb.scope_of(a1["id"], a1["worldviewId"]), + "用户的名字", "他叫小林,做前端的", author_agent=a1["id"]) + # 感知开关先关掉,验证"没开就没有同伴情绪段" + store.update_agent(a1["id"], {"emotionEnabled": False}) + a1 = store.get_agent(a1["id"]) + sk = store.create_resource("skills", {"name": "写作", "content": "写东西要先列大纲。"}) + agentdb.bind_skills(a1["id"], [sk["id"]]) + prompt = agent_context.build_system_prompt(store.read_settings(), a1) + for tag in ("", "", "", ""): + check(f"{tag} 段在", tag in prompt) + check("人设在最前面", prompt.startswith("你是玄辰。"), prompt[:20]) + check("世界观设定进去了", "灵气复苏" in prompt) + check("记忆进去了(标题+正文)", "【用户的名字】" in prompt and "前端" in prompt) + check("自定义 Skill 进去了", "写东西要先列大纲" in prompt) + check("顺序:skills 在 worldview 前", prompt.index("") < prompt.index("")) + check("顺序:worldview 在 emotion 前", prompt.index("") < prompt.index("")) + check("顺序:emotion 在 memory 前", prompt.index("") < prompt.index("")) + # 没开感知 → 不该有同伴情绪段 + check("没开感知时没有同伴情绪段", "" not in prompt) + store.update_agent(a1["id"], {"emotionEnabled": True}) + prompt2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a1["id"])) + check("开了感知后有同伴情绪", "" in prompt2 and "仙辰-有点烦" in prompt2, prompt2[-200:]) + # 空段要整段删掉 + a3 = store.create_agent({"name": "空白的"}) + p3 = agent_context.build_system_prompt(store.read_settings(), a3) + check("没记忆时 整段没了", "" not in p3, p3[-120:]) + check("但 还在(内置手册)", "" in p3) + + # ---------------------------------------------------------------- 8 + section("8. HTTP 接口") + r = h.call("/api/agents", "GET") + check("GET /api/agents", r.get("ok") and len(r["agents"]) >= 4) + r = h.call("/api/agents", "POST", {"name": "接口建的"}) + new_id = (r.get("agent") or {}).get("id") + check("POST /api/agents", bool(new_id)) + r = h.call(f"/api/agents/{new_id}", "PATCH", {"description": "改过的"}) + check("PATCH 生效", (r.get("agent") or {}).get("description") == "改过的") + r = h.call("/api/agents/a_doubao", "DELETE") + check("内置的删不掉", r.get("ok") is False, str(r.get("error"))) + check("内置的还在", store.get_agent("a_doubao") is not None) + r = h.call(f"/api/agents/{a1['id']}/memories", "GET") + check("GET 记忆列表", r.get("ok") and r.get("shared") is True) + r = h.call(f"/api/agents/{a1['id']}/usage", "GET") + check("GET 用量", r.get("ok") and r.get("total", 0) > 0) + r = h.call(f"/api/agents/{a1['id']}/emotion", "PUT", {"emotion": "挺开心的"}) + check("PUT 情绪", r.get("emotion") == "挺开心的") + r = h.call("/api/worldviews", "GET") + check("GET 世界观列表", r.get("ok") and len(r["items"]) == 1) + r = h.call("/api/model-entries", "POST", {"name": "豆包 Pro", "model": "doubao-pro", "pricePerK": 0.8}) + check("POST 模型列表", r.get("ok") and (r.get("item") or {}).get("id")) + r = h.call("/api/skills", "GET") + check("GET Skill 列表", r.get("ok") and len(r["items"]) == 1) + + # ---------------------------------------------------------------- 9 + section("9. 智能体包导出 / 导入") + r = h.call(f"/api/agents/{a1['id']}/package", "GET") + check("导出拿到 base64 zip", bool(r.get("data")), str(r.get("error"))) + blob = r.get("data") + r = h.call("/api/agents/import", "POST", {"data": blob}) + imported = r.get("agent") or {} + check("导入成功", bool(imported.get("id")), str(r.get("error"))) + check("导入的是**新** UUID(不是原来那个)", imported.get("id") not in (None, a1["id"])) + check("名字带过来了", imported.get("name") == "玄辰") + check("提示词带过来了", imported.get("systemPrompt") == "你是玄辰。") + check("描述带过来了", imported.get("description") == "仙门大师兄") + check("**模型引用没带过来**(需求 2.5 的边界)", not imported.get("modelId")) + check("**世界观绑定没带过来**", not imported.get("worldviewId")) + check("**限额没带过来**", not imported.get("tokenLimit")) + r2 = h.call("/api/agents/import", "POST", {"data": blob}) + check("同一个包导入两次 = 两个独立实体", + (r2.get("agent") or {}).get("id") not in (None, imported.get("id"), a1["id"])) + r = h.call("/api/agents/import", "POST", {"data": "bm90IGEgemlw"}) + check("坏包报错而不是崩", r.get("ok") is False, str(r.get("error"))) + + # ---------------------------------------------------------------- 10 + section("10. 记忆导出 / 导入(合并按标题去重)") + r = h.call(f"/api/agents/{a1['id']}/memories/export", "GET") + check("导出 type 正确", r.get("type") == "world-memory", str(r.get("type"))) + check("导出带 version", r.get("version") == 1) + check("导出带 Emotion", "Emotion" in r) + check("导出**不含** author_agent", + all("author_agent" not in m for m in r.get("smartMemory") or [])) + exported = dict(r) + exported["smartMemory"] = [ + {"title": "新的一条", "content": "这是导入进来的", "pinned": False}, + ] + list(exported["smartMemory"]) + r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST", {"data": exported, "mode": "merge"}) + check("合并模式:新增了 1 条", r.get("added") == 1, str(r)) + check("合并模式:同名的跳过了", r.get("skipped", 0) >= 1, str(r)) + check("合并模式:保留当前情绪", agentdb.emotion_get(a1["id"]) == "挺开心的") + r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST", + {"data": {"type": "agent-memory", "version": 1, "smartMemory": [], "Emotion": "换掉了"}, + "mode": "replace"}) + check("覆盖模式:情绪也换了", agentdb.emotion_get(a1["id"]) == "换掉了", agentdb.emotion_get(a1["id"])) + + # ---------------------------------------------------------------- 11 + section("11. 资源 CRUD + Skill 导入导出") + r = h.call("/api/skills", "POST", {"name": "另一个", "content": "内容"}) + sid = (r.get("item") or {}).get("id") + r = h.call(f"/api/skills/{sid}", "PATCH", {"content": "改过的内容"}) + check("PATCH skill", (r.get("item") or {}).get("content") == "改过的内容") + r = h.call(f"/api/skills/{sid}/export", "GET") + check("导出 skill 是单 JSON", r.get("json") and json.loads(r["json"])["type"] == "agent-skill") + r = h.call("/api/skills/import", "POST", {"data": json.loads(r["json"])}) + check("导入 skill", (r.get("item") or {}).get("id") not in (None, sid)) + r = h.call(f"/api/skills/{sid}", "DELETE") + check("删 skill", r.get("deleted") is True) + + # ---------------------------------------------------------------- 汇总 + print() + if fails: + print(f"❌ {len(fails)} 项不合格:") + for f in fails: + print(" -", f) + return 1 + print("✅ 全部通过") + return 0 + + +if __name__ == "__main__": + try: + code = main() + finally: + shutil.rmtree(DATA, ignore_errors=True) + sys.exit(code)