From 52680b9eb740336ebdd12e200cac06910cf9fa1c Mon Sep 17 00:00:00 2001 From: doubao Date: Wed, 14 Oct 2026 15:36:52 +0800 Subject: [PATCH] =?UTF-8?q?AI=20=E7=95=8C=E9=9D=A2=E8=83=BD=E5=8A=9B?= =?UTF-8?q?=EF=BC=9A=E4=B8=BB=E5=8A=A8=E5=BC=B9=E7=95=8C=E9=9D=A2=20/=20?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=20/=20=E6=B0=B8=E4=B9=85=E7=BB=93=E6=9D=9F?= =?UTF-8?q?=E5=AF=B9=E8=AF=9D=20(v2.0.35)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 三个工具,**默认关**(「技能」页可开)。都是 AI 主动驱动界面, 属于"打扰性"能力 —— 装好就默认打开是产品事故。 ## show_ui —— AI 自己写 HTML 弹一个全屏界面 有些东西用文字说不清:一张算出来的图表、排版好的报告卡片、宽对比表。 以前模型只能吐 markdown,表格一宽就乱。现在它能直接写 HTML。 · html 写**片段**即可,自动套一层带样式的骨架(暗色主题、表格、代码块), 模型不用每次重复写 viewport/字体/边距;想完全控制传 full_html=true · **不阻塞**:弹出来就返回,用户看完自己关(展示语义,不该卡住对话) · 界面里可以放 `` 重写成 + * `文字`。 + * + * ★ 用正则做单遍替换,**不引 HTML 解析器** —— 这点转换不值得多一个依赖, + * 而且 AI 的输出是受控的(我们自己提示词里教的写法)。 + * `button` 和 `a` 两种都收,模型有时会写成链接。 + */ +private fun rewriteResultLinks(html: String): String { + val pattern = Regex( + """<(button|a)\b([^>]*?)data-doubao-result\s*=\s*["']([^"']*)["']([^>]*?)>(.*?)""", + setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL), + ) + return pattern.replace(html) { m -> + val value = android.net.Uri.encode(m.groupValues[3]) + val inner = m.groupValues[5] + """$inner""" + } +} + +/** + * 给"片段式" HTML 套一层骨架。 + * + * 为什么要套:模型每次都要重复写 ``、暗色主题背景、字体、 + * 边距 —— 既啰嗦又容易和 App 的主题打架。套一层之后它只管写内容。 + */ +private fun wrapSkeleton(fragment: String): String = """ + + + + + +$fragment + +""" + +/* ==================================================================== */ +/* 二、AI 的选择弹窗(ask_user) */ +/* ==================================================================== */ + +@Composable +fun AiDialogOverlay(dialog: AiSurface.Dialog?, onAnswer: (List, Boolean) -> Unit) { + var last by remember { mutableStateOf(null) } + LaunchedEffect(dialog) { if (dialog != null) last = dialog } + val shown = dialog ?: last + + // 多选时先把已勾的攒起来,点「确定」才回传 + val picked = remember(dialog?.id) { mutableStateListOf() } + + Box(Modifier.fillMaxSize()) { + AnimatedVisibility( + visible = dialog != null, + enter = fadeIn(tween(180)), + exit = fadeOut(tween(150)), + ) { + Box( + Modifier + .fillMaxSize() + .background(Color(0xB3000000)) + .clickable(enabled = shown?.allowCancel == true) { onAnswer(emptyList(), true) }, + ) + } + + AnimatedVisibility( + visible = dialog != null, + modifier = Modifier.align(Alignment.Center), + enter = slideInVertically(tween(280, easing = androidx.compose.animation.core.FastOutSlowInEasing)) { it / 3 } + + fadeIn(tween(200)) + scaleIn(tween(280), initialScale = 0.94f), + exit = slideOutVertically(tween(200)) { it / 4 } + fadeOut(tween(150)) + + scaleOut(tween(200), targetScale = 0.96f), + ) { + if (shown == null) return@AnimatedVisibility + Column( + Modifier + .padding(horizontal = 24.dp) + .fillMaxWidth() + .clip(RoundedCornerShape(22.dp)) + .background(doubaoSurface()) + .padding(20.dp), + ) { + Text("AI 想问你", fontSize = 12.sp, color = doubaoTextDim()) + Spacer(Modifier.height(6.dp)) + Text( + shown.question, + fontSize = 17.sp, + fontWeight = FontWeight.Medium, + lineHeight = 24.sp, + color = doubaoText(), + ) + if (shown.multiple) { + Spacer(Modifier.height(4.dp)) + Text("可多选", fontSize = 12.sp, color = doubaoTextDim()) + } + Spacer(Modifier.height(14.dp)) + + // 选项多时中间区域自己滚,按钮不跟着滚出去 + Column( + Modifier.heightIn(max = 360.dp).verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + shown.options.forEach { opt -> + val on = opt.value in picked + OptionRow( + label = opt.label, + description = opt.description, + selected = on, + multiple = shown.multiple, + onClick = { + if (shown.multiple) { + if (on) picked.remove(opt.value) else picked.add(opt.value) + } else { + onAnswer(listOf(opt.value), false) + } + }, + ) + } + } + + if (shown.multiple) { + Spacer(Modifier.height(16.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + if (shown.allowCancel) { + OutlinedButton( + onClick = { onAnswer(emptyList(), true) }, + modifier = Modifier.weight(1f), + ) { Text("取消") } + } + Button( + onClick = { onAnswer(picked.toList(), false) }, + enabled = picked.isNotEmpty(), + modifier = Modifier.weight(1f), + ) { Text("确定") } + } + } else if (shown.allowCancel) { + Spacer(Modifier.height(10.dp)) + TextButton( + onClick = { onAnswer(emptyList(), true) }, + modifier = Modifier.align(Alignment.End), + ) { Text("取消") } + } + } + } + } +} + +@Composable +private fun OptionRow( + label: String, + description: String, + selected: Boolean, + multiple: Boolean, + onClick: () -> Unit, +) { + // 选中时轻微放大 —— 比单纯变色更能让人感到"点到了" + val scale by animateFloatAsState( + targetValue = if (selected) 1.02f else 1f, + animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy), + label = "optScale", + ) + Row( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(14.dp)) + .background(if (selected) doubaoAccentSoft() else doubaoSurfaceAlt()) + .clickable { onClick() } + .padding(horizontal = 14.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text( + label, + fontSize = 15.sp, + color = if (selected) doubaoAccent() else doubaoText(), + fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal, + ) + if (description.isNotBlank()) { + Spacer(Modifier.height(2.dp)) + Text(description, fontSize = 12.sp, color = doubaoTextDim(), lineHeight = 17.sp) + } + } + if (multiple && selected) { + Spacer(Modifier.width(8.dp)) + Text("✓", fontSize = 16.sp, color = doubaoAccent()) + } + } +} + +/* ==================================================================== */ +/* 三、对话被 AI 结束 —— 屏幕中间的横幅 */ +/* ==================================================================== */ + +/** + * ★ 用户明确要求的样子:**屏幕中间一个横幅,写着 AI 关闭的原因**。 + * + * 几个细节: + * · **停在屏幕正中间**(不是顶部也不是底部)—— 这是"这次对话到此为止" + * 这种终局状态,摆在视线中心最合适 + * · **不自动消失**。它不是提示条,是状态;消失了用户就不知道 + * 为什么发不出消息了 + * · 动画:从下方滑上来 + 淡入 + 轻微放大,像"落定" + * · 只显示在与它相关的那次对话里(调用方按 conversationId 判断) + */ +@Composable +fun EndedBanner(reason: String, onNewConversation: () -> Unit) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + AnimatedVisibility( + visible = true, + enter = slideInVertically( + tween(420, easing = androidx.compose.animation.core.FastOutSlowInEasing), + ) { it } + fadeIn(tween(280)) + scaleIn(tween(420), initialScale = 0.9f), + exit = fadeOut(tween(150)), + ) { + Column( + Modifier + .padding(horizontal = 28.dp) + .fillMaxWidth() + .clip(RoundedCornerShape(20.dp)) + .background(doubaoSurface()) + .padding(horizontal = 20.dp, vertical = 18.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + Icons.Filled.PowerSettingsNew, + null, + tint = doubaoTextDim(), + modifier = Modifier.size(18.dp), + ) + Spacer(Modifier.width(8.dp)) + Text("这次对话已结束", fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText()) + } + Spacer(Modifier.height(10.dp)) + Text( + reason.ifBlank { "AI 结束了这次对话" }, + fontSize = 14.sp, + lineHeight = 21.sp, + color = doubaoTextDim(), + ) + Spacer(Modifier.height(18.dp)) + Button( + onClick = onNewConversation, + colors = ButtonDefaults.buttonColors(containerColor = doubaoAccent()), + modifier = Modifier.fillMaxWidth(), + ) { Text("开始新对话", color = Color.White) } + } + } + } +} 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 5b068f7..18a0eaf 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 @@ -112,6 +112,25 @@ fun AppRoot( Text(vm.hint, color = Color.White, fontSize = 13.sp) } } + + /* ---------------- AI 主动弹出来的东西 ---------------- + * + * ★ 放在**导航之上**(这个 Box 的最后):AI 在任何页面都可能弹东西, + * 挂在 ChatScreen 里的话,用户在会议/设置页时弹不出来 —— + * 而模型那边以为已经弹给用户看了,只能干等(ask_user 会一直等到超时)。 + * + * 顺序(后写的盖在上面):选择弹窗 > HTML 界面。 + * `ask_user` 是阻塞的,用户必须先回答它,所以它压在最上面。 + */ + AiHtmlScreenOverlay( + screen = vm.aiScreen, + onClose = { vm.closeAiScreen() }, + onResult = { vm.onAiScreenResult(it) }, + ) + AiDialogOverlay( + dialog = vm.aiDialog, + onAnswer = { values, cancelled -> vm.answerAiDialog(values, cancelled) }, + ) } } 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 c9fb77d..f3bb236 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 @@ -16,6 +16,7 @@ import com.doubao.lynxclone.data.MeetingEvent import com.doubao.lynxclone.data.MeetingMeta import com.doubao.lynxclone.data.StreamEvent import com.doubao.lynxclone.data.ToolTrace +import com.doubao.lynxclone.termux.AiSurface import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.CancellationException @@ -53,8 +54,86 @@ class AppViewModel(val client: KernelClient) : ViewModel() { /** 模型 / 思考强度面板(底部升起) */ var modelPickerOpen by mutableStateOf(false) + /* -------------------- AI 主动弹出来的东西 -------------------- */ + + /** + * AI 弹的全屏 HTML 界面(`show_ui` 工具);null 表示没有。 + * + * 数据源是 [AiSurface](内核线程往里写),这里通过监听器同步过来 —— + * 内核永远不直接碰 Compose。 + */ + var aiScreen by mutableStateOf(null) + private set + + /** AI 弹的选择弹窗(`ask_user` 工具);null 表示没有 */ + var aiDialog by mutableStateOf(null) + private set + + /** + * 当前对话被 AI 永久结束了 —— 界面据此把输入框换成结束横幅。 + * + * ★ 这是从内核读回来的**落盘状态**(Conversation.ended),不是本地开关。 + */ + var conversationEnded by mutableStateOf(false) + private set + + /** AI 给出的结束原因(屏幕中间那个横幅上写的就是它) */ + var endedReason by mutableStateOf("") + private set + private var chatJob: AtomicBoolean? = null + init { + // 内核线程弹界面 → 这里切主线程更新 Compose 状态 + AiSurface.subscribe { kind -> + viewModelScope.launch { + when (kind) { + "screen" -> aiScreen = AiSurface.screen + "dialog" -> aiDialog = AiSurface.dialog + "ended" -> { + conversationEnded = true + refreshEndedReason() + } + } + } + } + } + + /** 用户关掉 AI 的界面 */ + fun closeAiScreen() { + AiSurface.closeScreen() + aiScreen = null + } + + /** 用户在 AI 的界面里点了带 data-doubao-result 的按钮 */ + fun onAiScreenResult(value: String) { + AiSurface.screenResult(value) + showHint("已选择:$value") + } + + /** 用户在 AI 的选择弹窗里点了 */ + fun answerAiDialog(values: List, cancelled: Boolean = false) { + AiSurface.answerDialog(values, cancelled) + aiDialog = null + } + + /** + * 把当前对话的"已结束"状态读回来。 + * + * ★ 切换对话、刷新之后都要重新读一次 —— 上面那个监听器只在 AI **当场** + * 结束对话时触发;用户重启 App 打开一个早就结束的对话,走的是这条路。 + */ + private fun refreshEndedReason() { + val id = activeConversationId.ifBlank { return } + viewModelScope.launch { + val meta = runCatching { + withContext(Dispatchers.IO) { client.conversationMeta(id) } + }.getOrNull() + conversationEnded = meta?.ended == true + endedReason = meta?.endedReason.orEmpty() + } + } + val settings get() = state.settings val agents: List get() = state.agents val activeAgent: Agent? get() = state.activeAgent @@ -104,6 +183,13 @@ class AppViewModel(val client: KernelClient) : ViewModel() { val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList()) messages.clear() messages.addAll(list) + // ★ 顺手读一下这次对话是不是被 AI 结束过 —— 只读 messages 是看不出来的 + // (ended 在会话对象上,不在消息里)。 + val meta = runCatching { + withContext(Dispatchers.IO) { client.conversationMeta(id) } + }.getOrNull() + conversationEnded = meta?.ended == true + endedReason = meta?.endedReason.orEmpty() } } @@ -111,9 +197,16 @@ class AppViewModel(val client: KernelClient) : ViewModel() { viewModelScope.launch { val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull() refresh() - if (conv != null) openConversation(conv.id) else { + if (conv != null) { + // 新对话一定是没结束的 —— 不复位的话上一个对话的结束横幅会跟过来 + conversationEnded = false + endedReason = "" + openConversation(conv.id) + } else { messages.clear() activeConversationId = "" + conversationEnded = false + endedReason = "" } } } @@ -132,6 +225,12 @@ class AppViewModel(val client: KernelClient) : ViewModel() { val text = draft.trim() if (text.isEmpty() && attachments.isEmpty()) return if (streaming) return + // ★ 对话被 AI 结束后就挡住 —— 界面上的输入框已经换成了横幅, + // 但发送按钮/回车/历史入口都可能绕过界面判断,所以在**这里**再拦一道。 + if (conversationEnded) { + showHint("这次对话已结束,请开一个新对话") + return + } val files = attachments.toList() draft = "" @@ -464,6 +563,19 @@ class AppViewModel(val client: KernelClient) : ViewModel() { val json = JSONObject().put("mode", mode).put("allow", JSONArray(allow)) saveSettings(mapOf("security" to json)) } + + /** + * AI 界面能力(show_ui / ask_user / end_conversation)开关。 + * + * ★ 必须写成**嵌套对象** `{"enabled": true}`,不能写成布尔 —— + * 内核 `ui_tools_enabled()` 认的就是 dict 里的 enabled。 + * 而 `patchToJson` 会把 Map 递归转成 JSONObject(见那个函数的注释: + * 不转的话会变成字符串 `"{enabled=true}"`,内核每次读配置都抛 TypeError)。 + * 所以这里传 Map 进去,让它走那条已经修好的转换路径。 + */ + fun saveUiTools(enabled: Boolean) { + saveSettings(mapOf("uiTools" to mapOf("enabled" to enabled))) + } } /** 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 4a7fe1b..e840964 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 @@ -309,7 +309,27 @@ fun ChatScreen(vm: AppViewModel) { if (vm.attachments.isNotEmpty()) AttachmentStrip(vm) - InputBar(vm, onPickFile, onMic, speech) + if (vm.conversationEnded) { + /** + * ★★ 对话被 AI 结束了 —— **屏幕中间一个横幅,写着关闭原因**。 + * + * `Modifier.weight(1f)` 让它占掉原本给消息列表之外的全部剩余空间, + * 横幅在**这块区域的中心**(也就是视觉上的屏幕中下部)。 + * 要的是"正中间",但顶部还有标题栏、下面还有输入法安全区, + * 放在这块剩余区域的中心在观感上才是居中的。 + * + * 输入框在此处**整个不渲染** —— 用户看到的就是"这儿没得输了", + * 而不是一个点了没反应的框。 + */ + Box(Modifier.weight(1f).fillMaxWidth()) { + EndedBanner( + reason = vm.endedReason, + onNewConversation = { vm.newTopic() }, + ) + } + } else { + InputBar(vm, onPickFile, onMic, speech) + } } val thinkingVisible = vm.thinkingIndex in vm.messages.indices diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt index 6ee1d87..398bde0 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt @@ -77,6 +77,22 @@ fun doubaoCard() = if (isDark()) Color(0xFF1F232A) else Doubao.CardBg @Composable fun doubaoHeroRing() = if (isDark()) Doubao.DarkHeroRing else Doubao.HeroRing +/** 主色(AI 界面/弹窗里强调"选中"用) */ +@Composable +fun doubaoAccent() = if (isDark()) Color(0xFF6EA8FF) else Doubao.Blue + +/** 主色的浅底(选中项的背景) */ +@Composable +fun doubaoAccentSoft() = if (isDark()) Color(0xFF1B2A44) else Color(0xFFEAF1FF) + +/** 比 surface 稍亮/稍暗一档的容器底色(弹窗里的选项行) */ +@Composable +fun doubaoSurfaceAlt() = if (isDark()) Color(0xFF232830) else Doubao.CardBg + +/** 三级文字色(比 secondary 更淡,用于说明小字) */ +@Composable +fun doubaoTextDim() = if (isDark()) Color(0xFF8C939D) else Doubao.TextTertiary + /* ------------------------------ 动画 ------------------------------ */ /** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */ diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/SkillsScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/SkillsScreen.kt index 4b133ed..7af27cf 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/SkillsScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/SkillsScreen.kt @@ -27,6 +27,7 @@ import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface +import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -72,6 +73,12 @@ fun SkillsScreen(vm: AppViewModel) { var mode by remember(saved.mode, saved.allow) { mutableStateOf(saved.mode) } var allow by remember(saved.mode, saved.allow) { mutableStateOf(saved.allow.toSet()) } + // AI 界面能力的开关。改一下立刻存 —— 这个开关不需要"应用"按钮, + // 用户拨完就想生效(跟下面的权限白名单不一样,那个要挑一堆再一起提交)。 + var uiToolsOn by remember(vm.settings.uiToolsEnabled) { + mutableStateOf(vm.settings.uiToolsEnabled) + } + var runTarget by remember { mutableStateOf(null) } val toolArgs = remember { mutableStateOf>(emptyMap()) } val toolResults = remember { mutableStateOf>(emptyMap()) } @@ -105,6 +112,50 @@ fun SkillsScreen(vm: AppViewModel) { ) { Spacer(Modifier.height(2.dp)) + /* ============ ⓪ AI 界面能力(show_ui / ask_user / end_conversation)============ + * + * 为什么单独一个卡片、而且默认关:这三个工具会让 AI **主动往用户脸上 + * 弹东西**(HTML 界面、选择弹窗),甚至**把对话封掉** —— + * 属于"打扰性"能力,不该装好就默认打开。 + */ + SettingsCard("AI 界面能力") { + Row(verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text("允许 AI 弹出界面和弹窗", fontSize = 15.sp, color = doubaoText()) + Spacer(Modifier.height(3.dp)) + Text( + "打开后 AI 才能用这三个工具。关掉时它们对模型完全隐藏。", + fontSize = 12.sp, + color = doubaoTextSecondary(), + lineHeight = 17.sp, + ) + } + Switch( + checked = uiToolsOn, + onCheckedChange = { + uiToolsOn = it + vm.saveUiTools(it) + }, + ) + } + + Spacer(Modifier.height(10.dp)) + FormHint( + "· show_ui —— AI 自己写 HTML 弹一个全屏界面(图表、卡片、对比表)\n" + + "· ask_user —— 弹一个选择框,等用户选完再继续(最多 120 秒)\n" + + "· end_conversation —— AI 永久结束这次对话。屏幕中间会出现一条" + + "写着原因的横幅,之后要开新对话才能继续", + ) + if (!uiToolsOn) { + Spacer(Modifier.height(6.dp)) + Text( + "当前:关闭(模型看不到这三个工具)", + fontSize = 12.sp, + color = doubaoTextDim(), + ) + } + } + /* ==================== ① 工具权限 ==================== */ SettingsCard("工具权限") { SegmentedOptions( diff --git a/android/kernel/agent_loop.py b/android/kernel/agent_loop.py index ed9e398..0731bd6 100644 --- a/android/kernel/agent_loop.py +++ b/android/kernel/agent_loop.py @@ -42,8 +42,29 @@ def _max_rounds(settings: dict) -> int: return max(1, min(12, value)) +# 界面能力的用法说明。**只在开关打开时**追加到系统提示词(见 run_agent)。 +# +# ★ 为什么需要这段:`show_ui` / `ask_user` 这类工具的 description 里已经写了 +# 怎么用,但模型**不会主动想到去用** —— 它默认走"用文字回答"这条路。 +# 加一段"什么时候该用",它才会在合适的时候弹界面/弹窗,而不是把一张宽表 +# 硬塞进 markdown。 +# +# ★ 也不能写得太热情:这三个工具会打断用户,滥用比不用更烦。 +# 所以措辞是"确实用文字说不清时才用"。 +UI_TOOLS_HINT = '\n'.join([ + '界面能力(用户已打开):', + '8. 有些东西用文字说不清,这时可以主动弹界面 —— 用 show_ui 写一段 HTML:', + ' 图表、排版好的卡片、宽对比表、可点的菜单。确实比文字清楚时才用,别滥用。', + '9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。', + ' 它会**等你选完**再继续,所以你不用在正文里再问一遍。', + '10. 事情真的办完、且用户说了不用继续时,可以 end_conversation 结束这次对话。', + ' **调用前必须先在正文里跟用户说明**,别默默封笔。拿不准就别用。', +]) + + def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None], - should_stop: Optional[Callable[[], bool]] = None) -> dict: + should_stop: Optional[Callable[[], bool]] = None, + conversation_id: str = '') -> dict: """ 跑一轮完整对话。 @@ -52,6 +73,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic agent 当前智能体(systemPrompt 覆盖全局的) emit 事件回调,直接往 SSE 里写 should_stop 客户端是否已断开(断了就别再往上游要字了) + conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它 """ # ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的, # 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。 @@ -61,6 +83,16 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic 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 '' + # ★★ 界面能力的用法**只在开关打开时才追加**。 + # + # 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**, + # 会存进用户的 settings.json;而开关可能是关的 —— 关着的时候提示词里 + # 还在教模型"你可以用 show_ui",它就会去调,然后收到"工具已关闭"。 + # 按开关动态追加,两边永远一致。 + # + # ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。 + if tools_runtime.ui_tools_enabled(settings): + system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip() thinking_level = settings.get('thinkingLevel') or 'auto' emit({ @@ -148,10 +180,20 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic for tc in tool_calls: tool_call_count += 1 emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')}) + # ★ 界面工具(show_ui / ask_user / end_conversation)要拿到"当前是哪次对话", + # 而工具签名只有 run(args)。所以在这里把上下文放进 thread-local, + # 执行完立刻清掉 —— HTTP 是每请求一线程,thread-local 天然隔离。 + tools_runtime.push_context( + conversationId=conversation_id, + agentId=(agent or {}).get('id') or '', + toolName=tc.get('name') or '', + ) try: result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings) except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型 result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'} + finally: + tools_runtime.clear_context() if result.get('ok'): raw = result.get('result') payload = truncate('(无输出)' if raw is None else raw) diff --git a/android/kernel/app.py b/android/kernel/app.py index 0b64db5..c823214 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -935,9 +935,24 @@ class KernelHandler(BaseHTTPRequestHandler): self.send_json(400, {'error': '缺少 name'}) return True try: - # 手动试运行不受安全模式限制(是用户自己点的),但仍要能报错 - result = tools_runtime.execute_tool(name, body.get('args') or {}, - {'security': {'mode': 'open'}}) + # ★ 手动试运行**不受安全模式限制**(是用户自己在「技能」页点的), + # 但仍要能报错。所以 mode 强制 open。 + # + # ★★ 但**不能**只传一个空壳 settings(以前就是 {'security':...}): + # 界面工具(show_ui/ask_user/end_conversation)的开关也在 settings 里, + # 空壳会让它们**永远被第二道拦截挡住** —— 用户在技能页点"试运行", + # 明明开关是开的,却收到"已关闭"。这个错会让人以为是开关没生效。 + # 所以拿真实设置、只覆盖 security。 + live = store.read_settings() or {} + settings = {**live, 'security': {'mode': 'open', 'allow': []}} + tools_runtime.push_context( + conversationId=str(body.get('conversationId') or ''), + toolName=name, + ) + try: + result = tools_runtime.execute_tool(name, body.get('args') or {}, settings) + finally: + tools_runtime.clear_context() self.send_json(200, result) except Exception as exc: # noqa: BLE001 self.send_json(500, {'ok': False, 'error': str(exc)}) @@ -1402,6 +1417,9 @@ class KernelHandler(BaseHTTPRequestHandler): messages=[*history, {'role': 'user', 'content': user_content}], emit=emit, should_stop=cancelled, + # ★ 界面工具要靠它知道"结束哪次对话"。不传的话 + # end_conversation 会明确报错(而不是假装成功)。 + conversation_id=conversation_id, ) store.append_messages(conversation_id, [{ diff --git a/android/kernel/defaults.py b/android/kernel/defaults.py index 3d3e4a8..f58cbfa 100644 --- a/android/kernel/defaults.py +++ b/android/kernel/defaults.py @@ -180,6 +180,12 @@ DEFAULT_SETTINGS = { 'toolsDir': '', 'systemPrompt': DEFAULT_SYSTEM_PROMPT, 'tools': {'python': True, 'mcp': True}, + # 界面工具:让 AI 主动弹 HTML 界面 / 弹选择框 / 永久结束对话 + # (show_ui / ask_user / end_conversation)。 + # + # ★ 默认**关**。这三个是"打扰性"能力 —— AI 会主动往用户脸上弹东西、 + # 甚至把对话封掉,不该装好就默认打开。想用就在「技能」页打开。 + 'uiTools': {'enabled': False}, # 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key; # 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。 'speech': { diff --git a/android/kernel/doubao_entry.py b/android/kernel/doubao_entry.py index 4e6472a..20ee802 100644 --- a/android/kernel/doubao_entry.py +++ b/android/kernel/doubao_entry.py @@ -20,6 +20,8 @@ import threading # 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录) BUNDLED_TOOL_FILES = [ '_protocol.py', + # 界面工具三件套共用的安卓桥 + 上下文读取(被下面三个 import,必须先播种) + '_ui_bridge.py', 'calc.py', 'now.py', 'weather.py', @@ -27,6 +29,10 @@ BUNDLED_TOOL_FILES = [ 'web_fetch.py', 'shell.py', 'python_run.py', + # AI 主动弹界面 / 弹选择框 / 永久结束对话(默认关,见 settings.uiTools) + 'show_ui.py', + 'ask_user.py', + 'end_conversation.py', '_mcp_python_example.py', ] diff --git a/android/kernel/tools_runtime.py b/android/kernel/tools_runtime.py index 9f9a446..09a2af1 100644 --- a/android/kernel/tools_runtime.py +++ b/android/kernel/tools_runtime.py @@ -35,6 +35,68 @@ _loaded_modules: dict = {} TOOL_TIMEOUT_S = 60 BUILTIN_FILE_LABEL = '<内置>' +# --------------------------------------------------------------------------- # +# 界面工具的开关 +# --------------------------------------------------------------------------- # + +# 这三个工具由 AI 主动驱动界面,属于"会打扰用户"的能力,所以**默认关**, +# 用户要在「技能」页显式打开。名字要和 tools/ 下的文件名一致。 +UI_TOOLS = ('show_ui', 'ask_user', 'end_conversation') + +# 开关在 settings 里的位置。用嵌套 dict 而不是散落的顶层键, +# 以后加界面工具不必再动 settings 的形状。 +UI_TOOL_SETTINGS_KEY = 'uiTools' + +# --------------------------------------------------------------------------- # +# 当前调用上下文(线程局部) +# --------------------------------------------------------------------------- # +# +# ★ 为什么需要它:工具要拿到"当前是哪次对话"才能结束对话,但工具签名是 +# run(args) —— 只有模型给的参数,没有对话信息。 +# +# 已有先例是往 settings 里塞 `nodeTools`(会议节点工具),但那是**工具定义**, +# 不是**运行时上下文**;上下文每轮都在变,塞进 settings 会和"设置"的语义混在一起。 +# +# 所以单独开一个 thread-local:agent_loop 在执行工具前 push, +# 执行完 pop。HTTP 是每请求一线程,thread-local 天然隔离,不会串。 +_ctx = threading.local() + + +def push_context(**kw) -> None: + """进入一次工具调用(agent_loop 在 execute_tool 前调用)""" + _ctx.value = dict(kw) + + +def clear_context() -> None: + _ctx.value = None + + +def current_context() -> dict: + """当前工具调用的上下文;不在调用中时返回空 dict""" + return dict(getattr(_ctx, 'value', None) or {}) + + +def ui_tools_enabled(settings: dict) -> bool: + """ + 界面工具开了没有。 + + ★ 默认 **False**:这三个工具会让 AI 主动弹界面/弹窗、甚至结束对话, + 对用户是"打扰性"能力,不该装好就默认打开。 + """ + box = (settings or {}).get(UI_TOOL_SETTINGS_KEY) + if isinstance(box, dict): + return box.get('enabled') is True + if isinstance(box, bool): + return box + return False + + +def filter_ui_tools(specs: list, settings: dict) -> list: + """开关关着时,把界面工具从工具表里摘掉(模型根本看不到,也就不会调)。""" + if ui_tools_enabled(settings): + return specs + return [s for s in specs if s.get('name') not in UI_TOOLS] + # --------------------------------------------------------------------------- # # 目录与文件 @@ -235,9 +297,27 @@ def run_python_tool(name: str, args: dict) -> dict: runner = getattr(module, 'run') payload = args if isinstance(args, dict) else {} + # ★★★ **先抓住当前线程的上下文**,因为 run_with_timeout 会在**另一个线程**里 + # 跑工具,而 threading.local() 是**不跨线程继承**的 —— 不搬过去的话, + # 工作线程里 current_context() 永远是空的。 + # + # 这个坑的表现特别隐蔽:工具照常执行(参数都对),只有"当前是哪次对话" + # 拿不到,于是 end_conversation 报"拿不到当前对话 id"。我一开始以为是 + # app.py 没传 conversationId,查了一圈才发现是线程的问题。 + ctx = current_context() + + def _invoke(): + if ctx: + _ctx.value = dict(ctx) + try: + return runner(payload) + finally: + if ctx: + _ctx.value = None + try: # 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死 - outcome = run_with_timeout(lambda: runner(payload), TOOL_TIMEOUT_S) + outcome = run_with_timeout(_invoke, TOOL_TIMEOUT_S) except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500 # 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"}, # 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。 @@ -381,6 +461,8 @@ def build_tool_defs(settings: dict) -> list: defs = [to_openai_tool(t) for t in all_tools['python']] + list(all_tools['mcp']) # 会议里的 Python 节点工具并进来(受限模式也走同一个白名单) defs = defs + node_tool_defs(settings) + # 界面工具(AI 弹界面 / 弹窗 / 结束对话)开关关着时对模型隐藏 + defs = filter_ui_tools(defs, settings) return apply_security(defs, settings) @@ -393,6 +475,15 @@ def execute_tool(name: str, args: dict, settings: dict) -> dict: allow = ((settings or {}).get('security') or {}).get('allow') or [] if name not in allow: return {'ok': False, 'error': f'限制模式:工具 {name} 未授权'} + # ★ 界面工具的第二道拦截:开关关着时,即使模型硬编名字也不执行。 + # (第一道是 build_tool_defs 里根本不把它给模型看。) + # 两道都要有 —— 只藏不给看的话,用户把工具关掉之后模型仍可能 + # 从历史消息里学会这个名字再调一次。 + if name in UI_TOOLS and not ui_tools_enabled(settings): + return { + 'ok': False, + 'error': f'界面工具「{name}」已关闭。请在「技能」页打开"AI 界面能力"后再用。', + } # 会议节点工具优先(它是这次会议里用户刚写的东西,不会有重名歧义) if name in node_tool_names(settings): return run_node_tool(name, args, settings) diff --git a/scripts/adb-accept-final.sh b/scripts/adb-accept-final.sh deleted file mode 100644 index 5893bcf..0000000 --- a/scripts/adb-accept-final.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/system/bin/sh -# 最终验收:模拟 App 给子进程的环境(childEnvMap 的效果) -PKG=com.doubao.lynxclone -P=/data/data/$PKG/files/usr -export PREFIX=$P HOME=/data/data/$PKG/files/home TMPDIR=$P/tmp -export PATH=$P/bin:$P/bin/applets:/system/bin -export LD_LIBRARY_PATH=$P/lib LD_PRELOAD=$P/lib/libtermux-exec.so - -echo "===== 1. python + pip(问题 1、3)=====" -$P/bin/python3 -V 2>&1 | head -1 -$P/bin/python3 -c 'import encodings,json,sqlite3,ssl; print(" import 正常")' 2>&1 | head -2 -$P/bin/pip3 --version 2>&1 | head -1 -$P/bin/python3 -c 'import six; print(" six", six.__version__)' 2>&1 | head -2 - -echo -echo "===== 2. 临时目录(问题 2)=====" -$P/bin/python3 -c 'import tempfile; print(" tempfile =", tempfile.gettempdir())' 2>&1 | head -2 -$P/bin/mktemp 2>&1 | head -1 - -echo -echo "===== 3. 环境健康 =====" -echo " 未配置 = $($P/bin/dpkg -l 2>/dev/null | grep -c '^i[^i]')" -echo " 半装 = $($P/bin/dpkg -l 2>/dev/null | grep -c '^i[UFH]')" -echo " 架构 = $($P/bin/dpkg --print-architecture)" -echo " dpkg = $($P/bin/dpkg --version 2>&1 | head -1 | cut -d' ' -f6)" -echo " 源 = $(grep -m1 '^deb' $P/etc/apt/sources.list | cut -d/ -f3)" - -echo -echo "===== 4. 真 Termux 仍共存 =====" -ls -ld /data/data/com.termux 2>&1 | awk '{print " " $1, $3}' diff --git a/scripts/probe-ai-surfaces.py b/scripts/probe-ai-surfaces.py new file mode 100644 index 0000000..5fa7cbb --- /dev/null +++ b/scripts/probe-ai-surfaces.py @@ -0,0 +1,82 @@ +"""端到端测 AI 界面三件套:宿主机 → 内核 /api/tools/run → 安卓桥。 + +★ 为什么从宿主机打而不是在设备上敲:PowerShell/adb 的多层引号会把 JSON + 搅烂(这一路上已经踩过好几次)。adb forward 之后在宿主机上用 Python 打, + 引号只有一层,看得清。 + +★ ask_user 是**阻塞**的:脚本会挂在那儿等用户在手机上点。 + 所以它放在最后,并且单独一个命令跑(另一个终端截图看界面)。 +""" +import json +import sys +import threading +import time +import urllib.request + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +URL = "http://127.0.0.1:15199" +CONV = "c_main" + + +def call(path, payload=None, method="POST", timeout=180): + data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None + req = urllib.request.Request( + URL + path, data=data, method=method, + headers={"Content-Type": "application/json; charset=utf-8"}, + ) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode("utf-8")) + + +def run_tool(name, args, timeout=150): + print(f"\n--- {name} ---", flush=True) + print(" 参数:", json.dumps(args, ensure_ascii=False)[:160], flush=True) + t0 = time.time() + res = call("/api/tools/run", {"name": name, "args": args, "conversationId": CONV}, + timeout=timeout) + print(f" 耗时 {time.time() - t0:.1f}s -> {json.dumps(res, ensure_ascii=False)[:300]}", + flush=True) + return res + + +which = sys.argv[1] if len(sys.argv) > 1 else "all" + +if which in ("all", "state"): + st = call("/api/state", method="GET") + print("uiTools =", json.dumps((st.get("settings") or {}).get("uiTools"), ensure_ascii=False)) + +if which in ("all", "screen"): + run_tool("show_ui", { + "title": "测试界面", + "html": "

你好

这是 AI 写的 HTML。

" + "
项值
甲1
" + "" + "", + }) + +if which in ("all", "end"): + run_tool("end_conversation", {"reason": "这件事已经办完了,没有后续可聊的。"}) + print("\n=== 确认落盘 ===", flush=True) + full = call(f"/api/conversations/{CONV}", method="GET").get("conversation") or {} + print(" ended =", full.get("ended"), "| endedReason =", full.get("endedReason"), flush=True) + +if which == "ask": + run_tool("ask_user", { + "question": "这个方案你要哪一个?", + "options": [ + {"label": "方案 A", "value": "A", "description": "快但功能少"}, + {"label": "方案 B", "value": "B", "description": "慢一点但完整"}, + {"label": "都不要", "value": "none"}, + ], + }, timeout=240) + +if which == "askmulti": + run_tool("ask_user", { + "question": "想装哪几个?(可多选)", + "multiple": True, + "options": ["python", "git", "nmap", "nodejs"], + }, timeout=240) diff --git a/scripts/verify-ui-tools.py b/scripts/verify-ui-tools.py new file mode 100644 index 0000000..42f25dc --- /dev/null +++ b/scripts/verify-ui-tools.py @@ -0,0 +1,304 @@ +"""守 AI 界面三件套(show_ui / ask_user / end_conversation)的硬性质。 + +这些性质每一条都对应一个"想当然会出错"的地方,光看代码看不出来: + + 1. **开关默认关**。这三个工具会让 AI 主动往用户脸上弹东西、甚至封掉对话, + 默认打开是产品事故。而且必须**默认关**(新装/老设备升上来都是关)。 + 2. **两道拦截都要在**:关掉时① 工具对模型隐藏,② 即使模型硬编名字也拒绝执行。 + 只做①的话,用户关掉之后模型仍可能从历史消息里学会这个名字再调一次。 + 3. **ask_user 的 options 两种写法都要收**(对象数组 / 裸字符串数组)—— + 模型写裸字符串数组非常常见,只认一种就会平白吃一个报错。 + 4. **end_conversation 拿不到对话 id 时必须报错,不能假装成功** —— + 假装成功会变成"界面封了、盘上没封",用户重启后又能发消息。 + 5. **不占用户的消息预算**:这几个工具的规则不能渗进系统提示词的 + "回答要求"编号里(那会让模型把它们当成每轮都要考虑的事)。 + +用法: + python scripts/verify-ui-tools.py +""" + +import json +import os +import sys + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +KERNEL = os.path.join(WS, "android", "kernel") +TOOLS = os.path.join(WS, "tools") +sys.path.insert(0, KERNEL) +sys.path.insert(0, TOOLS) + +fails = [] + + +def fail(m): + fails.append(m) + print(f" ✗ {m}") + + +def ok(m): + print(f" ✓ {m}") + + +# ---------------------------------------------------------------- 1 +print("=== 1. 工具能被发现,spec 合法 ===") +import importlib.util + +for name in ("show_ui", "ask_user", "end_conversation"): + path = os.path.join(TOOLS, name + ".py") + if not os.path.isfile(path): + fail(f"{name}.py 不存在") + continue + spec = importlib.util.spec_from_file_location("t_" + name, path) + mod = importlib.util.module_from_spec(spec) + try: + spec.loader.exec_module(mod) + except Exception as exc: # noqa: BLE001 + fail(f"{name}.py 导入失败:{type(exc).__name__}: {exc}") + continue + tool = getattr(mod, "TOOL", None) + if not isinstance(tool, dict) or not tool.get("name"): + fail(f"{name}.py 没有合法的 TOOL") + continue + if not callable(getattr(mod, "run", None)): + fail(f"{name}.py 没有 run(args)") + continue + if tool["name"] != name: + fail(f"{name}.py 的 TOOL.name 是 {tool['name']},和文件名不一致") + continue + params = tool.get("parameters") or {} + if params.get("type") != "object": + fail(f"{name} 的 parameters.type 不是 object") + continue + ok(f"{name}:spec 合法(必填 {params.get('required') or '无'})") + +# ---------------------------------------------------------------- 2 +print("\n=== 2. 开关默认关 + 两道拦截 ===") +import tools_runtime as TR + +if TR.ui_tools_enabled({}): + fail("空 settings 时 ui_tools_enabled 竟然是 True —— 默认必须关") +else: + ok("空 settings → 关闭") + +if TR.ui_tools_enabled({"uiTools": {"enabled": True}}): + ok("uiTools.enabled=True → 打开") +else: + fail("uiTools.enabled=True 没被认成打开") + +if TR.ui_tools_enabled({"uiTools": True}): + ok("uiTools=True(老写法)→ 也认") +else: + fail("uiTools=True 没被认(兼容写法失效)") + +# ① 关掉时对模型隐藏 +defs_off = TR.filter_ui_tools([{"name": n} for n in TR.UI_TOOLS], {}) +if defs_off: + fail(f"关闭时仍把 {[d['name'] for d in defs_off]} 给了模型") +else: + ok("关闭时三个工具对模型隐藏") + +defs_on = TR.filter_ui_tools([{"name": n} for n in TR.UI_TOOLS], {"uiTools": {"enabled": True}}) +if len(defs_on) == len(TR.UI_TOOLS): + ok("打开时三个工具都给模型") +else: + fail(f"打开时只给了 {len(defs_on)} 个") + +# ② 关掉时即使硬编名字也拒绝 +res = TR.execute_tool("ask_user", {"question": "x", "options": ["a"]}, {}) +if res.get("ok") is False and "关闭" in str(res.get("error")): + ok("关闭时 execute_tool 拒绝执行(第二道拦截在)") +else: + fail(f"关闭时 execute_tool 没拦住:{res}") + +# ---------------------------------------------------------------- 3 +print("\n=== 3. ask_user 的选项规整 ===") +import ask_user as AU + +cases = [ + (["A", "B"], 2, "裸字符串数组"), + ([{"label": "A"}, {"label": "B", "value": "b"}], 2, "对象数组"), + ([{"value": "only"}], 1, "只有 value 没有 label"), + ([{"label": "A", "description": "说明"}], 1, "带 description"), + (["A", {"label": ""}, " ", "B"], 2, "混杂空项(应被丢掉)"), + ([], 0, "空数组"), +] +for raw, want, label in cases: + got = AU._clean_options(raw) + if len(got) == want: + ok(f"{label} → {len(got)} 项") + else: + fail(f"{label}:期望 {want} 项,实际 {len(got)} 项({got})") + +opts = AU._clean_options([{"label": "A"}]) +if opts and opts[0]["value"] == "A": + ok("value 留空时自动用 label") +else: + fail(f"value 没回落到 label:{opts}") + +# 超过 8 个要截断 +many = AU._clean_options([f"opt{i}" for i in range(20)]) +if len(many) == 20: + ok("规整阶段不截断(截断在 run 里做)") +else: + fail(f"规整阶段就把选项截了:{len(many)}") + +# ---------------------------------------------------------------- 4 +print("\n=== 4. 拿不到对话 id 时必须报错 ===") +import _ui_bridge as UB + +# 不在工具调用上下文里 → conversation_id() 应该是空 +UB_ctx = TR.current_context() +if UB_ctx == {}: + ok("不在调用中时 current_context() 是空 dict") +else: + fail(f"current_context() 不是空的:{UB_ctx}") + +# push 之后能读到 +TR.push_context(conversationId="c_test", toolName="end_conversation") +if TR.current_context().get("conversationId") == "c_test": + ok("push_context 之后能读到 conversationId") +else: + fail(f"push_context 没生效:{TR.current_context()}") + +# ★★★ 关键:**上下文必须能跨线程** —— run_with_timeout 是在新线程里跑工具的, +# 而 threading.local() 不跨线程继承。这里直接验"另一个线程里读得到"。 +import threading + +seen = {} + + +def _in_other_thread(): + seen["ctx"] = TR.current_context() + + +worker = threading.Thread(target=_in_other_thread) +worker.start() +worker.join(5) +if seen.get("ctx") == {}: + ok("另一个线程里读不到(符合 thread-local 语义 —— 所以必须显式搬过去)") +else: + fail(f"另一个线程里读到了东西,语义和预期不符:{seen.get('ctx')}") + +TR.clear_context() +if TR.current_context() == {}: + ok("clear_context 之后读不到了") +else: + fail("clear_context 之后还能读到") + +# ---------------------------------------------------------------- 5 +print("\n=== 5. 工具真的执行时,上下文能送到工具手里 ===") +# 造一个假工具:它把读到的上下文写进返回值。 +# +# ★★ 必须走 **run_python_tool** 这条真实路径 —— 它内部会调 run_with_timeout, +# 而那个函数是在**新线程**里跑工具的。第一版验证脚本图省事直接调了 +# run_with_timeout(lambda: mod.run(...)),绕开了被修的那段代码, +# 于是"修好了没有"根本没测到(脚本报红但红得不是地方)。 +# 教训:验证要走**调用方真正走的那条路**。 +probe_src = ''' +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +TOOL = {"name": "probe_ctx", "description": "探针", + "parameters": {"type": "object", "properties": {}}} +def run(args): + import tools_runtime as TR + import _ui_bridge as UB + return {"ctx": TR.current_context(), "conv": UB.conversation_id()} +''' +import tempfile + +tmpdir = tempfile.mkdtemp() +open(os.path.join(tmpdir, "probe_ctx.py"), "w", encoding="utf-8").write(probe_src) + +# 让 tools_runtime 去 tmpdir 里找工具(改的是 `paths.get().tools_dir`, +# 不动用户真正的工具目录) +import paths as P + +_orig_tools_dir = P.get().tools_dir +P.get().tools_dir = tmpdir +TR.discover_python_tools(force=True) +try: + TR.push_context(conversationId="c_from_parent", toolName="probe_ctx") + try: + res = TR.run_python_tool("probe_ctx", {}) + finally: + TR.clear_context() +finally: + P.get().tools_dir = _orig_tools_dir + TR.discover_python_tools(force=True) + +got = (res or {}).get("result") if isinstance(res, dict) else None +if not isinstance(got, dict): + fail(f"探针没返回 dict:{res}") +else: + if got.get("conv") == "c_from_parent": + ok("换线程之后工具仍拿得到 conversationId(修好了)") + else: + fail(f"换线程之后 conversationId 丢了:{got}") + + + +# end_conversation.run 在没有对话 id 时应该抛错(而不是返回 ended:True) +import end_conversation as EC + +try: + # 桥不在(电脑端)会先抛"没有界面能力",两种都算"没假装成功" + out = EC.run({"reason": "测试"}) + if out.get("ended") is True: + fail("没有对话 id 却报 ended=True —— 这是最坏的失败模式(界面封了、盘上没封)") + else: + ok(f"没有对话 id 时没假装成功:{out}") +except Exception as exc: # noqa: BLE001 + ok(f"没有对话 id 时抛错(正确):{type(exc).__name__}") + +# ---------------------------------------------------------------- 6 +print("\n=== 6. 界面能力的提示词只在开关打开时追加 ===") +import defaults as D + +prompt = D.DEFAULT_SYSTEM_PROMPT +if "show_ui" in prompt or "ask_user" in prompt or "end_conversation" in prompt: + fail("默认提示词里点名了界面工具 —— 开关关着时会误导模型去调") +else: + ok("默认提示词里没点名界面工具(开关管得住)") +if "附件" in prompt: + ok("附件说明还在(没被覆盖)") +else: + fail("附件说明不见了") + +# 追加的那段:关着不该出现,开着必须在 +import agent_loop as AL + +if not hasattr(AL, "UI_TOOLS_HINT"): + fail("agent_loop 里没有 UI_TOOLS_HINT") +else: + hint = AL.UI_TOOLS_HINT + if "show_ui" in hint and "ask_user" in hint and "end_conversation" in hint: + ok("UI_TOOLS_HINT 里三个工具都讲到了") + else: + fail("UI_TOOLS_HINT 没覆盖三个工具") + if "必须先在正文里" in hint: + ok("提示了 end_conversation 要先说明(这条很重要)") + else: + fail("UI_TOOLS_HINT 没要求'结束前先说明'") + + # ★ 追加逻辑必须**按开关**走。这里直接验证那段代码的存在性 + + # ui_tools_enabled 的语义(真正的拼接在 run_agent 里,需要起网络,不在这儿跑)。 + import inspect + + src = inspect.getsource(AL.run_agent) + if "ui_tools_enabled" in src and "UI_TOOLS_HINT" in src: + ok("run_agent 里是按开关决定要不要追加") + else: + fail("run_agent 没按开关追加提示词") + +print() +if fails: + print(f"❌ {len(fails)} 项不合格:") + for m in fails: + print(" -", m) + sys.exit(1) +print("✅ 全部通过") diff --git a/tools/_ui_bridge.py b/tools/_ui_bridge.py new file mode 100644 index 0000000..df4daa7 --- /dev/null +++ b/tools/_ui_bridge.py @@ -0,0 +1,85 @@ +""" +界面工具(AI 主动弹界面 / 弹窗 / 结束对话)和安卓原生桥之间的公共部分。 + +## 为什么单独一个模块 + +三个工具干的事不同,但**和安卓那一侧通话的方式完全一样**:都是往 +`NativeBridge.device()` 发一个 JSON、收一个 JSON。把这段收在一处, +以后加第四个界面工具就只要写 TOOL + run,不用再抄一遍桥接代码 —— +这个仓库里"同一个逻辑抄两份,加功能时只改一份"的坑已经踩过好几次了。 + +## 为什么要带 conversationId + +`end_conversation` 要**永久结束当前这次对话**,内核必须知道是哪一次。 +内核在组装工具前会把当前对话 id 塞进 settings 的 `_conversationId` +(下划线开头,不会外泄给模型,也不会出现在 /api/state 里), +这里取出来一起发给安卓侧。 + +## 电脑端会怎样 + +没有 `_android` 桥(桌面版)时,这几个工具都**明确返回不可用**, +而不是假装成功 —— 让模型知道"这个端没有界面能力",它就不会反复重试。 +""" + +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + + +def _bridge(): + """ + 拿到安卓原生桥对象;电脑端返回 None。 + + `doubao_entry` 只在安卓上存在(它是 Chaquopy 的入口模块), + 所以这里用 try/except 而不是判断平台字符串 —— 平台字符串判断错过一次 + (sys.platform 在 Chaquopy 里也是 'linux',跟桌面 Linux 分不开)。 + """ + try: + import doubao_entry # noqa: PLC0415 - 电脑端没有这个模块,只能运行时导入 + + return getattr(doubao_entry, '_android', None) + except Exception: # noqa: BLE001 + return None + + +def call_device(payload: dict) -> dict: + """ + 往安卓侧发一个 device 请求。 + + ★ 参数名要和 Kotlin 侧 `NativeBridge.device()` 的 `req.optString(...)` + 对得上 —— 对不上不会报错,只会**静默拿到空字符串**, + 表现是"界面弹出来但标题是空的"。所以两边都写全。 + + @return 安卓侧回的 JSON;桥不在时返回 {'unavailable': True, ...} + """ + bridge = _bridge() + if bridge is None: + return { + 'unavailable': True, + 'error': '当前环境没有界面能力(电脑端的界面在桌面窗口里,这几个工具只在手机上生效)', + } + raw = bridge.device(json.dumps(payload, ensure_ascii=False)) + try: + return json.loads(str(raw)) + except (ValueError, TypeError): + return {'raw': str(raw)} + + +def conversation_id() -> str: + """ + 当前对话 id。 + + ★ 从内核的"当前调用上下文"里取。`tools_runtime.execute_tool` 在调用工具前 + 会把 settings 里的 `_conversationId` 放到 `_protocol` 能读到的地方 —— + 见 tools_runtime.current_context()。取不到就返回空串(安卓侧会当成 + "没有指定对话",只是不能结束对话,别的功能不受影响)。 + """ + try: + import tools_runtime # noqa: PLC0415 + + ctx = tools_runtime.current_context() or {} + return str(ctx.get('conversationId') or '') + except Exception: # noqa: BLE001 + return '' diff --git a/tools/ask_user.py b/tools/ask_user.py new file mode 100644 index 0000000..e4276de --- /dev/null +++ b/tools/ask_user.py @@ -0,0 +1,152 @@ +"""让 AI 弹一个选择弹窗,并把用户选的那一项拿回去。 + +## 和 show_ui 的分工 + + `show_ui` 展示用 —— **不阻塞**,弹出来就返回,用户看完自己关 + `ask_user` 问询用 —— **阻塞**,等用户选完才返回,模型拿到选择继续干活 + +这两个刻意分开:展示性的东西不该把对话卡住;而"让用户在几个方案里选一个" +必须拿到答案才能继续。 + +## 阻塞是怎么实现的 + +安卓侧 `NativeBridge.device()` 是同步的 —— 它在 UI 线程上弹出界面, +然后用一个 `CountDownLatch` 等用户点,等到(或超时)才把结果回给 Python。 +Python 这边就是一次普通调用,不需要轮询。 + +★ 超时必须有:用户可能把手机锁屏走了,不能让内核线程永远挂着。 + 默认 120 秒,到点返回 `timeout: true`,模型据此知道"用户没理我"。 + +## 电脑端 + +明确返回不可用(桌面版的界面在桌面窗口里)。 +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from _protocol import serve # noqa: E402 +from _ui_bridge import call_device, conversation_id # noqa: E402 + +# 等用户的秒数上限。安卓侧也有自己的上限,两边都不设的话 +# 用户锁屏走了会把内核的工作线程永远占住。 +TIMEOUT_S = 120 + +TOOL = { + "name": "ask_user", + "description": ( + "弹一个选择弹窗问用户,**等用户选完**再继续(最多等 120 秒)。" + "适合:几个方案让人挑一个、要确认一个危险操作、需要用户补充一个选择。" + "options 传选项数组(每项 {label, value, description}):" + "label 是按钮上显示的字,value 是你要拿到的值(留空则用 label)," + "description 是选项下方的小字说明。" + "多选请传 multiple=true。返回里 choice/values 就是用户选的东西;" + "timeout=true 表示用户没在时限内回答。" + ), + "parameters": { + "type": "object", + "properties": { + "question": { + "type": "string", + "description": "要问的问题", + }, + "options": { + "type": "array", + "description": "选项列表", + "items": { + "type": "object", + "properties": { + "label": {"type": "string", "description": "按钮上显示的文字"}, + "value": {"type": "string", "description": "返回给模型的值,留空则用 label"}, + "description": {"type": "string", "description": "选项下方的小字说明"}, + }, + "required": ["label"], + }, + }, + "multiple": { + "type": "boolean", + "description": "是否允许多选,默认 false", + }, + "allow_cancel": { + "type": "boolean", + "description": "是否显示「取消」按钮,默认 true", + }, + }, + "required": ["question", "options"], + }, +} + + +def _clean_options(raw) -> list: + """ + 规整选项。 + + ★ 模型经常把 options 写成裸字符串数组(`["A", "B"]`)而不是对象数组 —— + 这在 tool calling 里非常常见,直接 `.get()` 会 AttributeError。 + 所以两种都收下,别让模型因为格式小错就吃一个报错。 + """ + out = [] + for item in raw or []: + if isinstance(item, dict): + label = str(item.get("label") or item.get("value") or "").strip() + if not label: + continue + out.append( + { + "label": label, + "value": str(item.get("value") or label), + "description": str(item.get("description") or ""), + } + ) + elif isinstance(item, (str, int, float)): + text = str(item).strip() + if text: + out.append({"label": text, "value": text, "description": ""}) + return out + + +def run(args: dict) -> dict: + question = str(args.get("question") or "").strip() + if not question: + raise ValueError("question 不能为空") + options = _clean_options(args.get("options")) + if not options: + raise ValueError("options 至少要给一个选项") + # 选项太多按钮会挤成一屏,截断并告诉模型(而不是静默丢掉) + truncated = False + if len(options) > 8: + options = options[:8] + truncated = True + + res = call_device( + { + "action": "ui_dialog", + "question": question, + "options": options, + "multiple": bool(args.get("multiple")), + "allowCancel": bool(args.get("allow_cancel", True)), + "timeoutMs": TIMEOUT_S * 1000, + "conversationId": conversation_id(), + } + ) + if res.get("unavailable"): + raise RuntimeError(res.get("error") or "当前环境没有界面能力") + if res.get("error"): + raise RuntimeError(str(res["error"])) + + out = { + "question": question, + "multiple": bool(res.get("multiple")), + "timeout": bool(res.get("timeout")), + "cancelled": bool(res.get("cancelled")), + "choice": res.get("choice") or "", + "values": res.get("values") or [], + } + if truncated: + out["note"] = "选项超过 8 个,只显示了前 8 个" + return out + + +if __name__ == "__main__": + serve(TOOL, run) diff --git a/tools/end_conversation.py b/tools/end_conversation.py new file mode 100644 index 0000000..a3e06cd --- /dev/null +++ b/tools/end_conversation.py @@ -0,0 +1,90 @@ +"""让 AI 主动**永久结束**当前这次对话。 + +## "永久"是什么意思 + +不是"这一轮说完了",而是这次对话就此封笔: + + · 会话被标记 `ended`(落盘,重启 App 也还在) + · 界面上输入框变成「这次对话已结束」+ 一个「开始新对话」按钮 + · 再往里发消息会被挡住(用户想继续就开新的) + +## 模型什么时候该用 + + · 用户要的事情已经彻底办完,且没有后续可聊的("帮我查完这趟航班" → 结束) + · 用户自己说"就这样吧 / 不用了 / 结束" + · 任务走进了死胡同,继续聊下去只会兜圈子 + +★ 提示词里明确要求它**先说明再结束** —— 直接封笔会让人莫名其妙。 + 所以这个工具的 description 里写死了"要先在正文里说明已经结束"。 + +## 为什么要落盘而不是只改界面状态 + +界面状态一刷新就没了。用户关掉 App 再进来,会看到一个能继续输入的框, +而模型那边以为自己已经结束了 —— 两边状态不一致是这类功能最容易出的问题。 +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from _protocol import serve # noqa: E402 +from _ui_bridge import call_device, conversation_id # noqa: E402 + +TOOL = { + "name": "end_conversation", + "description": ( + "**永久结束当前这次对话**(落盘,重启 App 也生效):之后再发消息会被挡住," + "用户需要开一个新对话。" + "只在事情真的办完、用户说了不用了、或者继续聊只会兜圈子时才用。" + "★ 调用前必须先在正文里跟用户说明这次对话已经结束,别默默封笔。" + "reason 用一句话说明为什么结束(会给用户看)。" + ), + "parameters": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "为什么结束(一句话,会给用户看)", + }, + "summary": { + "type": "string", + "description": "这次对话做了什么(可选,留作记录)", + }, + }, + "required": ["reason"], + }, +} + + +def run(args: dict) -> dict: + reason = str(args.get("reason") or "").strip() + if not reason: + raise ValueError("reason 不能为空(要告诉用户为什么结束)") + conv = conversation_id() + if not conv: + # 拿不到对话 id 时**不能假装成功** —— 那样界面封了、盘上没封, + # 用户重启后又能发消息,而模型以为自己结束了。 + raise RuntimeError("拿不到当前对话 id,无法结束对话") + + res = call_device( + { + "action": "end_conversation", + "conversationId": conv, + "reason": reason, + "summary": str(args.get("summary") or ""), + } + ) + if res.get("unavailable"): + raise RuntimeError(res.get("error") or "当前环境没有界面能力") + if res.get("error"): + raise RuntimeError(str(res["error"])) + return { + "ended": True, + "conversationId": conv, + "reason": reason, + "note": "这次对话已永久结束。用户需要开新对话才能继续。", + } + + +if __name__ == "__main__": + serve(TOOL, run) diff --git a/tools/show_ui.py b/tools/show_ui.py new file mode 100644 index 0000000..08c2549 --- /dev/null +++ b/tools/show_ui.py @@ -0,0 +1,89 @@ +"""让 AI 主动弹出一个 WebView 界面(自己写 HTML)。 + +## 这个工具存在的意义 + +普通的对话是一来一回的文本。有些东西**用界面表达比用文字好得多**: +一张自己算出来的图表、一个把结果排版好的报告卡片、一个可以点的菜单、 +一段带样式的对比表。以前模型只能吐 markdown,表格一宽就乱。 + +这个工具让模型**直接写 HTML**,App 用一个全屏 WebView 渲染出来。 + +## 用法约定(也是给模型看的) + + · `html` 里写**片段**就行(不用 /),会自动套一层带样式的骨架 —— + 这样模型不用每次重复写 viewport、暗色主题这些 + · 想要完整控制就传 `full_html=true`,那时 html 必须是一份完整文档 + · 界面里可以放按钮:`` + —— 用户点了之后,那个 `data-doubao-result` 的值会回到模型手里 + (走 [ask_user] 那条回传通道,所以不需要模型自己写 JS) + +## 电脑端 + +桌面版的界面在桌面窗口里,这个工具**明确返回不可用**,不假装成功。 +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from _protocol import serve # noqa: E402 +from _ui_bridge import call_device, conversation_id # noqa: E402 + +TOOL = { + "name": "show_ui", + "description": ( + "在用户手机/平板上弹出一个界面,自己写 HTML 渲染(全屏 WebView)。" + "适合:图表、排版好的报告卡片、对比表、可点的菜单、任何用文字说不清的东西。" + "html 里只写片段即可(不用 html/body 标签,会自动套一层带样式的骨架);" + "想完全控制就传 full_html=true。" + "界面里可以放 ," + "用户点了之后那个值会回到你手里。" + "调用后界面立刻显示、本工具立刻返回,用户看到之后再继续对话。" + ), + "parameters": { + "type": "object", + "properties": { + "html": { + "type": "string", + "description": "要渲染的 HTML(片段即可,除非 full_html=true)", + }, + "title": { + "type": "string", + "description": "顶部标题栏文字,可留空", + }, + "full_html": { + "type": "boolean", + "description": "true 表示 html 是一份完整文档,不再套骨架。默认 false", + }, + }, + "required": ["html"], + }, +} + + +def run(args: dict) -> dict: + html = str(args.get("html") or "").strip() + if not html: + raise ValueError("html 不能为空") + res = call_device( + { + "action": "ui_screen", + "html": html, + "title": str(args.get("title") or ""), + "full_html": bool(args.get("full_html")), + "conversationId": conversation_id(), + } + ) + if res.get("unavailable"): + raise RuntimeError(res.get("error") or "当前环境没有界面能力") + if res.get("error"): + raise RuntimeError(str(res["error"])) + return { + "shown": True, + "bytes": len(html), + "note": "界面已弹出,用户看完会自己关掉。你不需要再重复内容。", + } + + +if __name__ == "__main__": + serve(TOOL, run)