Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c7fed95650 | |||
| d82c3d3176 | |||
| 4850ea12af | |||
| 2c259d4270 |
60
README.md
60
README.md
@@ -322,7 +322,61 @@ mock 会顺便把收到的请求形状打出来,专门核对那个分号鉴权
|
||||
4. **通话界面**:大头像 + 声波 + 计时 + 挂断,全屏、常亮(`FLAG_KEEP_SCREEN_ON`)、
|
||||
息屏后要有前台服务,否则一锁屏就断
|
||||
|
||||
### 3.12 会议模式的节点(独立库 `:nodekit`)
|
||||
|
||||
会议编辑器是「节点 + 连线」编排多个智能体。**节点是什么形式** —— 有哪些节点、
|
||||
每个节点什么引脚、什么颜色、什么形状、卡片多高、连线从哪儿出去 ——
|
||||
这些定义全在**独立模块 [`android/nodekit/`](android/nodekit/)** 里,只有一份。
|
||||
|
||||
界面上最能看出差别的是**形状**(形状即语法,和积木编辑器同一套思路):
|
||||
|
||||
| 形状 | 含义 |
|
||||
|---|---|
|
||||
| 帽形 | 起点(开始事件) |
|
||||
| 菱形 | 一进两出(判断 / 分支) |
|
||||
| 六边形 | 会绕回来(while 循环) |
|
||||
| 胶囊 | 不执行,只提供值(读变量 / 值 / 运算 / 转换) |
|
||||
| 上边切角 | 到这里结束(最终输出) |
|
||||
| 圆角矩形 | 普通动作 |
|
||||
|
||||
「加节点」面板里每个类型前面有形状缩略图,节点卡片标题栏左边也有一个小徽标。
|
||||
|
||||
定义是**跨语言**的(界面 Kotlin、执行 Python),靠
|
||||
`python scripts/verify-nodekit.py` 逐项对拍守着 —— 节点类型、引脚类型、
|
||||
23 个算子、判断条件、转换类型、引脚方向。
|
||||
|
||||
完整说明看 **[docs/节点库.md](docs/节点库.md)**(含"怎么加一种节点"的清单)。
|
||||
|
||||
### 3.13 超时(全部可调)
|
||||
|
||||
设置页最下面那张卡片 →「超时」,**18 项全都能调**:
|
||||
|
||||
| 分组 | 有哪些 |
|
||||
|---|---|
|
||||
| 对话 | 等模型回复、连接空闲上限、心跳间隔、本地接口请求 |
|
||||
| 工具 | 工具执行、shell 命令、跑 Python 代码、Termux 命令、会议节点、自定义节点 |
|
||||
| 界面 | AI 提问等多久、AI 界面等多久、选文件等多久 |
|
||||
| 语音 | 语音合成、语音识别 |
|
||||
| MCP | 单次请求、连接、调用工具 |
|
||||
|
||||
以前这 15 个超时**散在 10 个文件里当模块级常量**,谁也不知道一共有几个 ——
|
||||
"哪些能调、哪些不能调"这个问题根本回答不了。现在收在
|
||||
[`android/kernel/timeouts.py`](android/kernel/timeouts.py) 一份里:
|
||||
|
||||
- 界面上有哪几项、叫什么、默认多少、能填多大、说明写什么 —— **全是内核给的**
|
||||
(`GET /api/timeouts`),加一项只改那个文件,界面自动多出一行
|
||||
- 改完**立刻生效**,不用重启(各处都是现读)
|
||||
- 取值一律夹在每项的 `[min, max]` 里,填 "60秒"、空串、负数、999999 都不会出问题
|
||||
- 「改回默认」= 从配置里**删掉**这一项(不是存一个相同的值),
|
||||
这样以后调默认值时没动过的用户会跟着新默认走
|
||||
- Node 端(Web / exe)有一份对称的 [`server/src/timeouts.mjs`](server/src/timeouts.mjs),
|
||||
`python scripts/verify-timeouts.py` 会把两边**逐项对拍**
|
||||
|
||||
三个"等用户"的项(AI 提问 / AI 界面 / 工具执行)默认是 **0 = 不限时** ——
|
||||
它们的时长取决于你什么时候点,给上限等于"你想久了 AI 就自己编"。
|
||||
|
||||
> 想让 AI 别等太久?把「AI 提问等多久」填个有限值就行。但**不建议**:
|
||||
> 你去忙一会儿回来,AI 已经按自己猜的答案往下写了,而它并不知道自己在猜。
|
||||
|
||||
---
|
||||
|
||||
@@ -593,6 +647,12 @@ node scripts/device-state.mjs <serial> # 看设备内核当前设
|
||||
node scripts/device-tool.mjs <serial> <tool> @args.json # 在设备上跑任意工具
|
||||
node scripts/verify-mcp-stdio.mjs # MCP stdio 传输
|
||||
node scripts/verify-pykernel.mjs # Python 内核与 Node 内核对拍
|
||||
python scripts/verify-nodekit.py # 节点库与 Python 引擎逐项对拍
|
||||
python scripts/verify-timeouts.py # 超时清单:边界 + 没有硬编码 + Node 端对拍
|
||||
python scripts/verify-seed-tools.py # 内置工具的播种/覆盖规则
|
||||
python scripts/verify-ui-tools.py # interface 工具的参数与提示词
|
||||
python scripts/verify-extract-urls.py # 「打开网页」的链接抽取
|
||||
python scripts/verify-ai-webview.py # AI 界面里的 JS 桥
|
||||
node scripts/screenshot.mjs <url> <out.png> # 无头浏览器截图
|
||||
|
||||
# mock(不消耗额度)
|
||||
|
||||
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 244
|
||||
versionName = "2.0.44"
|
||||
versionCode = 246
|
||||
versionName = "2.0.46"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -20,6 +20,7 @@ import android.provider.OpenableColumns
|
||||
import com.chaquo.python.Python
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import com.doubao.lynxclone.data.AppTimeouts
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
import com.doubao.lynxclone.termux.TermuxShell
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
@@ -419,7 +420,7 @@ class NativeBridge(private val activity: Activity) {
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(LOCAL_READ_S, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
@@ -442,7 +443,7 @@ class NativeBridge(private val activity: Activity) {
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(LOCAL_READ_S, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
@@ -837,7 +838,10 @@ class NativeBridge(private val activity: Activity) {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
latch.await(PICK_TIMEOUT_S, TimeUnit.SECONDS)
|
||||
latch.await(
|
||||
AppTimeouts.seconds("filePicker", PICK_TIMEOUT_S.toDouble()).toLong(),
|
||||
TimeUnit.SECONDS,
|
||||
)
|
||||
pickLatch = null
|
||||
return pickedUris.mapNotNull { copyIntoCache(it) }.toTypedArray()
|
||||
}
|
||||
@@ -880,8 +884,25 @@ class NativeBridge(private val activity: Activity) {
|
||||
|
||||
companion object {
|
||||
const val REQ_PICK = 0x4D31
|
||||
|
||||
/**
|
||||
* AI 让你挑文件时等多久的**兜底值**。
|
||||
*
|
||||
* ★ 真实值从设置读(设置 → 超时 → 选文件等多久)——
|
||||
* 去相册里翻一张老照片可能不止两分钟。这里是拿不到设置时的兜底。
|
||||
*/
|
||||
private const val PICK_TIMEOUT_S = 120L
|
||||
|
||||
/**
|
||||
* 打本机内核端口([kernelPost] / [kernelPatch])的读超时。
|
||||
*
|
||||
* ★ 也做成可调的(设置 → 超时 → 本地接口请求):这些请求里有几个
|
||||
* 体积不小(读一条很长的会话、传附件),老设备上 10 秒不一定够。
|
||||
* 每次现读而不是建 client 时读一次 —— 改完立刻生效。
|
||||
*/
|
||||
private val LOCAL_READ_S: Long
|
||||
get() = AppTimeouts.seconds("kernelLocal", 10.0).toLong().coerceAtLeast(3L)
|
||||
|
||||
/** 内核起来后把 bridge 注册给 Python */
|
||||
fun register(bridge: NativeBridge) {
|
||||
val entry = Python.getInstance().getModule("doubao_entry")
|
||||
|
||||
@@ -188,6 +188,21 @@ fun AppRoot(
|
||||
)
|
||||
}
|
||||
|
||||
// 「超时」—— 所有超时都能调(入口在设置页)
|
||||
AnimatedVisibility(
|
||||
visible = vm.timeoutsOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
TimeoutsScreen(
|
||||
state = vm.timeouts,
|
||||
saving = vm.timeoutsSaving,
|
||||
onSave = { vm.saveTimeouts(it) },
|
||||
onReset = { vm.resetTimeouts() },
|
||||
onBack = { vm.closeTimeouts() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「AI 界面」列表(用户要求"AI 写的界面可以再点开")。
|
||||
// 排在 HTML 界面之下:点一个就从列表进到界面。
|
||||
AnimatedVisibility(
|
||||
|
||||
@@ -138,6 +138,82 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------- 超时(全部可调)-------------------- */
|
||||
|
||||
/**
|
||||
* 超时清单 + 当前值。
|
||||
*
|
||||
* ★ 权威在内核(`GET /api/timeouts` ← `android/kernel/timeouts.py`)。
|
||||
* App 启动时会拉一次塞进 [com.doubao.lynxclone.data.AppTimeouts] ——
|
||||
* 客户端有两处(OkHttp 的 readTimeout、文件选择)没法在用的那一刻去问内核。
|
||||
*/
|
||||
var timeouts by mutableStateOf(com.doubao.lynxclone.data.TimeoutsState())
|
||||
private set
|
||||
|
||||
var timeoutsOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
var timeoutsSaving by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
fun openTimeouts() {
|
||||
timeoutsOpen = true
|
||||
refreshTimeouts()
|
||||
}
|
||||
|
||||
fun closeTimeouts() {
|
||||
timeoutsOpen = false
|
||||
}
|
||||
|
||||
fun refreshTimeouts() {
|
||||
viewModelScope.launch {
|
||||
val next = runCatching {
|
||||
withContext(Dispatchers.IO) { client.timeouts() }
|
||||
}.getOrElse { err ->
|
||||
// 拉不到也要把界面立起来(显示错误),别让用户对着空白页
|
||||
com.doubao.lynxclone.data.TimeoutsState(
|
||||
error = "读不到超时设置:${err.message ?: err.javaClass.simpleName}",
|
||||
)
|
||||
}
|
||||
timeouts = next
|
||||
com.doubao.lynxclone.data.AppTimeouts.update(next)
|
||||
// ★ 读完立刻让连接池用上新值 —— readTimeout 必须跟着
|
||||
// "连接空闲上限"走,否则用户调了不生效
|
||||
runCatching { client.applyTimeouts() }
|
||||
}
|
||||
}
|
||||
|
||||
/** 只传改过的那一项;内核会并到当前值上 */
|
||||
fun saveTimeouts(patch: Map<String, Double>) {
|
||||
timeoutsSaving = true
|
||||
viewModelScope.launch {
|
||||
val next = runCatching {
|
||||
withContext(Dispatchers.IO) { client.saveTimeouts(patch) }
|
||||
}.getOrNull()
|
||||
if (next != null) {
|
||||
timeouts = next
|
||||
com.doubao.lynxclone.data.AppTimeouts.update(next)
|
||||
runCatching { client.applyTimeouts() }
|
||||
}
|
||||
timeoutsSaving = false
|
||||
}
|
||||
}
|
||||
|
||||
fun resetTimeouts() {
|
||||
timeoutsSaving = true
|
||||
viewModelScope.launch {
|
||||
val next = runCatching {
|
||||
withContext(Dispatchers.IO) { client.resetTimeouts() }
|
||||
}.getOrNull()
|
||||
if (next != null) {
|
||||
timeouts = next
|
||||
com.doubao.lynxclone.data.AppTimeouts.update(next)
|
||||
runCatching { client.applyTimeouts() }
|
||||
}
|
||||
timeoutsSaving = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 点开一条:列表接口不带正文,这里再去读全文 */
|
||||
fun openNote(item: com.doubao.lynxclone.data.NoteItem) {
|
||||
viewModelScope.launch {
|
||||
@@ -343,6 +419,13 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// ★ 启动时先拉一次超时设置(不等用户进设置页)。
|
||||
// 为什么必须现在就拉:OkHttp 的 readTimeout 要在**建连接时**就定下来,
|
||||
// 而"等用户回答"那种场景会安静好几分钟 —— 值不对的话连接会先被自己掐掉,
|
||||
// 用户在弹窗上点完,答案根本送不回去。
|
||||
// 内核可能还没起来,所以失败是正常的:AppTimeouts 会回落默认值,
|
||||
// 用户一进设置页(或下一轮对话)就会补上。
|
||||
refreshTimeouts()
|
||||
}
|
||||
|
||||
/** 用户关掉 AI 的界面 */
|
||||
|
||||
@@ -495,6 +495,22 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
FormHint("当前发现 Python 工具 ${vm.state.tools.size} 个 · MCP 工具 ${vm.state.mcp.sumOf { it.toolCount }} 个(在「技能·连接器」里看明细)")
|
||||
}
|
||||
|
||||
/* ---------------- 超时 ---------------- */
|
||||
// ★ 这一页**不在这个「保存设置」里** —— 超时有自己的接口
|
||||
// (/api/timeouts)和自己的全屏界面,改一项立刻生效。
|
||||
// 混进"本地草稿 + 一次性保存"反而会让用户以为要按保存。
|
||||
SettingsCard("超时") {
|
||||
NavRow(
|
||||
label = "超时设置",
|
||||
value = if (vm.timeouts.items.isEmpty()) "" else "${vm.timeouts.items.size} 项",
|
||||
onClick = { vm.openTimeouts() },
|
||||
)
|
||||
FormHint(
|
||||
"模型回复、工具执行、命令、MCP、语音、等用户回答……所有超时都能在这里调。" +
|
||||
"「等用户回答」默认是不限时。",
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------------- 个人资料 ---------------- */
|
||||
SettingsCard("个人资料") {
|
||||
FormLabel("昵称")
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
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.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.TimeoutItem
|
||||
import com.doubao.lynxclone.data.TimeoutsState
|
||||
|
||||
/*
|
||||
* 「设置 → 超时」:所有超时都能在这儿调。
|
||||
*
|
||||
* ## 为什么做成全屏界面而不是弹窗
|
||||
*
|
||||
* 见 AGENTS.md「少用弹窗,能开界面就开界面」—— 这里有 17 项、每项还带两三行说明,
|
||||
* 弹窗装不下(用户得在一个半屏高的框里滚十几屏)。
|
||||
*
|
||||
* ## ★★ 这一页**没有硬编码任何一项**
|
||||
*
|
||||
* 有哪些超时、叫什么、默认多少、能填多大、说明写什么 —— 全部来自内核
|
||||
* (`GET /api/timeouts` ← `android/kernel/timeouts.py` 的 SPECS)。
|
||||
*
|
||||
* 这么做的理由不是"架构好看",而是这个东西以前正是**反面教材**:
|
||||
* 15 个超时散在 10 个文件里当模块级常量,加一个超时要改好几处,
|
||||
* 而"到底有几个超时"这个问题谁都答不上来。现在加一项只改内核那一个文件,
|
||||
* 这一页自动多出一行。
|
||||
*
|
||||
* ## 怎么算保存
|
||||
*
|
||||
* 不做"保存按钮":点 +/- 立刻存,输入框失焦时存。
|
||||
* 每个改动都只发**改的那一项**(内核会并到当前值上),所以两项之间不会互相覆盖。
|
||||
*/
|
||||
|
||||
@Composable
|
||||
fun TimeoutsScreen(
|
||||
state: TimeoutsState,
|
||||
saving: Boolean,
|
||||
/** 只传改过的那一项 */
|
||||
onSave: (Map<String, Double>) -> Unit,
|
||||
onReset: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
FullScreen(
|
||||
title = "超时",
|
||||
subtitle = if (saving) "保存中…" else "改完立刻生效,不用重启",
|
||||
onBack = onBack,
|
||||
actions = { TopTextAction("恢复默认", onClick = onReset) },
|
||||
) {
|
||||
if (state.items.isEmpty()) {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
if (state.error.isBlank()) "正在从内核读取…" else state.error,
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
return@FullScreen
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
for ((group, items) in state.groups) {
|
||||
SectionLabel(group)
|
||||
for (item in items) {
|
||||
TimeoutRow(item = item, onSave = onSave)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"说明:这些值的边界由内核把关(填超了会自动夹回去)。" +
|
||||
"「不限时」表示会一直等,不会自己放弃。",
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
modifier = Modifier.padding(14.dp),
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TimeoutRow(item: TimeoutItem, onSave: (Map<String, Double>) -> Unit) {
|
||||
// 输入框里的**草稿**(用户可能正在打字,这时候不能立刻拿它去保存,
|
||||
// 否则打到一半的 "18" 会被当成 18 存进去)
|
||||
var draft by remember(item.key) { mutableStateOf(fmt(item.value)) }
|
||||
var editing by remember(item.key) { mutableStateOf(false) }
|
||||
|
||||
// 值被外部改掉时(保存回来 / 恢复默认)同步草稿,但**别打断正在输入的人**
|
||||
if (!editing && draft != fmt(item.value)) draft = fmt(item.value)
|
||||
|
||||
val step = stepOf(item)
|
||||
|
||||
fun commit(raw: String) {
|
||||
val v = raw.trim().toDoubleOrNull() ?: item.value
|
||||
val clamped = v.coerceIn(item.min, item.max)
|
||||
draft = fmt(clamped)
|
||||
if (kotlin.math.abs(clamped - item.value) > 0.001) {
|
||||
onSave(mapOf(item.key to clamped))
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(item.label, fontSize = 14.sp, color = doubaoText())
|
||||
if (item.isDefault) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("默认", fontSize = 10.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
StepButton("−") {
|
||||
val next = (item.value - step).coerceAtLeast(item.min)
|
||||
draft = fmt(next)
|
||||
onSave(mapOf(item.key to next))
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = draft,
|
||||
onValueChange = { draft = it.filter { c -> c.isDigit() || c == '.' } },
|
||||
singleLine = true,
|
||||
textStyle = androidx.compose.ui.text.TextStyle(
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = Modifier
|
||||
.width(78.dp)
|
||||
.height(48.dp)
|
||||
.onFocusChanged { st ->
|
||||
if (st.isFocused) {
|
||||
editing = true
|
||||
} else if (editing) {
|
||||
editing = false
|
||||
commit(draft)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
StepButton("+") {
|
||||
val next = (item.value + step).coerceAtMost(item.max)
|
||||
draft = fmt(next)
|
||||
onSave(mapOf(item.key to next))
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
// 0 且允许 0 时显示"不限时",比"0 秒"清楚得多
|
||||
if (item.unlimited) "${item.zero} (${item.unit})"
|
||||
else "单位:${item.unit} 范围 ${fmt(item.min)}–${fmt(item.max)}",
|
||||
fontSize = 10.sp,
|
||||
color = if (item.unlimited) Doubao.Blue else doubaoTextSecondary(),
|
||||
fontWeight = if (item.unlimited) FontWeight.Medium else FontWeight.Normal,
|
||||
)
|
||||
}
|
||||
if (item.desc.isNotBlank()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(item.desc, fontSize = 11.sp, lineHeight = 17.sp, color = doubaoTextSecondary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StepButton(label: String, onClick: () -> Unit) {
|
||||
Box(
|
||||
Modifier
|
||||
.padding(horizontal = 4.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(Doubao.Blue.copy(alpha = 0.10f))
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(label, fontSize = 16.sp, fontWeight = FontWeight.Medium, color = Doubao.Blue)
|
||||
}
|
||||
}
|
||||
|
||||
/** 整秒显示,别出现 "180.0" */
|
||||
private fun fmt(v: Double): String =
|
||||
if (kotlin.math.abs(v - v.toInt()) < 0.001) v.toInt().toString() else v.toString()
|
||||
|
||||
/** 步长跟着量级走:5 秒的东西一次加 60 太难用,1800 秒的东西一次加 5 是折磨 */
|
||||
private fun stepOf(item: TimeoutItem): Double = when {
|
||||
item.max <= 60 -> 5.0
|
||||
item.max <= 300 -> 10.0
|
||||
item.max <= 900 -> 30.0
|
||||
else -> 60.0
|
||||
}
|
||||
@@ -38,6 +38,7 @@ import paths
|
||||
import providers
|
||||
import speech
|
||||
import store
|
||||
import timeouts
|
||||
import tools_runtime
|
||||
import uploads
|
||||
from defaults import PROVIDER_PRESETS
|
||||
@@ -245,8 +246,15 @@ class SseChannel:
|
||||
|
||||
def _ping_loop(self) -> None:
|
||||
while not self.closed:
|
||||
# 用 Event.wait 代替 sleep,结束时会立刻退出,不用等满 15 秒
|
||||
if self._stop_event.wait(15):
|
||||
# ★ 心跳间隔可调(设置 → 超时 → 心跳间隔)。
|
||||
# 它必须**明显小于**客户端的读超时(sseRead),否则客户端会先
|
||||
# 判定"连接死了"再断开 —— 等用户回答的那种场景会因此白等。
|
||||
try:
|
||||
gap = float(timeouts.get('heartbeat'))
|
||||
except Exception: # noqa: BLE001
|
||||
gap = 15.0
|
||||
# 用 Event.wait 代替 sleep,结束时会立刻退出,不用等满
|
||||
if self._stop_event.wait(gap):
|
||||
return
|
||||
if self.closed:
|
||||
return
|
||||
@@ -585,6 +593,36 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200, {'ok': True, 'settings': store.mask_settings(nxt)})
|
||||
return True
|
||||
|
||||
# ---------------------------------------------------------------- #
|
||||
# 超时(设置 → 超时)
|
||||
#
|
||||
# ★ 清单由内核给,**界面不硬编码这些项目** —— 加一项超时只改 timeouts.py,
|
||||
# 界面自动多出一行(连说明文字都是这里带过去的)。
|
||||
# ★ 写的时候是**整体替换**而不是深合并:默认值在 timeouts.py 里,
|
||||
# "改回默认"等于"从设置文件里删掉这一项",深合并会让它删不掉。
|
||||
# ---------------------------------------------------------------- #
|
||||
if pathname == '/api/timeouts' and method == 'GET':
|
||||
self.send_json(200, {
|
||||
'ok': True,
|
||||
'items': timeouts.catalog(),
|
||||
'values': timeouts.resolved(),
|
||||
})
|
||||
return True
|
||||
|
||||
if pathname == '/api/timeouts' and method in ('PUT', 'POST'):
|
||||
body = self.read_json_body()
|
||||
if body.get('reset'):
|
||||
next_values = timeouts.reset()
|
||||
else:
|
||||
next_values = timeouts.patch(body.get('values') or body)
|
||||
store.write_settings({'timeouts': next_values})
|
||||
self.send_json(200, {
|
||||
'ok': True,
|
||||
'items': timeouts.catalog(),
|
||||
'values': timeouts.resolved(),
|
||||
})
|
||||
return True
|
||||
|
||||
if pathname == '/api/models' and method == 'GET':
|
||||
settings = store.read_settings()
|
||||
try:
|
||||
|
||||
@@ -26,6 +26,7 @@ import time
|
||||
import traceback
|
||||
|
||||
import paths
|
||||
import timeouts
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 工具定义(与 tools/shell.py、tools/python_run.py 的 TOOL 完全一致,
|
||||
@@ -43,7 +44,10 @@ SHELL_TOOL = {
|
||||
'properties': {
|
||||
'command': {'type': 'string', 'description': '要执行的命令,例如 ls -la 或 python --version'},
|
||||
'cwd': {'type': 'string', 'description': '工作目录,可留空'},
|
||||
'timeout': {'type': 'number', 'description': '超时秒数,默认 30,最大 300'},
|
||||
'timeout': {
|
||||
'type': 'number',
|
||||
'description': '超时秒数。不传就用设置里「超时 → shell 命令」那个值',
|
||||
},
|
||||
},
|
||||
'required': ['command'],
|
||||
},
|
||||
@@ -67,7 +71,10 @@ PYTHON_RUN_TOOL = {
|
||||
'code': {'type': 'string', 'description': '要执行的 Python 代码(action=run 时二选一)'},
|
||||
'file': {'type': 'string', 'description': '要执行的 .py 文件路径(action=run 时二选一)'},
|
||||
'stdin': {'type': 'string', 'description': '传给脚本的标准输入,可留空'},
|
||||
'timeout': {'type': 'number', 'description': '超时秒数,默认 60,最大 600'},
|
||||
'timeout': {
|
||||
'type': 'number',
|
||||
'description': '超时秒数。不传就用设置里「超时 → 跑 Python 代码」那个值',
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -125,7 +132,8 @@ def shell_run(args: dict) -> dict:
|
||||
if bad in lowered:
|
||||
raise ValueError(f'命令命中黑名单({bad}),已拒绝执行。确实需要请设置 DOUBAO_SHELL_UNSAFE=1')
|
||||
|
||||
timeout = max(1, min(300, int(args.get('timeout') or 30)))
|
||||
# 超时:模型传了就用它的,没传就用设置里的(设置 → 超时 → shell 命令)
|
||||
timeout = timeouts.budget(args, 'shell')
|
||||
cwd = args.get('cwd') or None
|
||||
if cwd and not os.path.isdir(cwd):
|
||||
raise ValueError(f'工作目录不存在:{cwd}')
|
||||
@@ -248,6 +256,17 @@ def run_with_timeout(fn, timeout_s: float):
|
||||
而且 CPython 根本杀不掉一个正在跑的线程。超时后我们只能"放弃等待",
|
||||
被放弃的线程会继续在后台跑完(daemon 线程,不阻塞进程退出)。
|
||||
这个取舍必须让用户知道,所以超时消息里写清楚。
|
||||
|
||||
★★ `timeout_s <= 0` = **不限时**(一直等到它跑完)。
|
||||
|
||||
给"停下来等用户"的那类工具用(`ask_user` / `show_ui` 的 wait 模式)——
|
||||
它们的耗时**完全取决于用户什么时候点**,60 秒的上限只会造成:
|
||||
弹窗还开着、用户 5 分钟后才选,而模型早就收到"工具执行超时"、
|
||||
于是按自己猜的答案往下写了。
|
||||
|
||||
为什么默认仍然是 60 秒:这是"工具里写了死循环"的安全网
|
||||
(不让整个内核跟着卡死)。会等用户的工具属于**设计上就该慢**,
|
||||
由工具自己声明 `WAIT_FOR_USER = True` 来豁免,见 tools_runtime。
|
||||
"""
|
||||
box = {}
|
||||
|
||||
@@ -259,9 +278,13 @@ def run_with_timeout(fn, timeout_s: float):
|
||||
|
||||
thread = threading.Thread(target=worker, name='doubao-python-run', daemon=True)
|
||||
thread.start()
|
||||
thread.join(timeout_s)
|
||||
if thread.is_alive():
|
||||
return None
|
||||
if timeout_s and timeout_s > 0:
|
||||
thread.join(timeout_s)
|
||||
if thread.is_alive():
|
||||
return None
|
||||
else:
|
||||
# 不限时:join() 不带参数就是一直等
|
||||
thread.join()
|
||||
if 'error' in box:
|
||||
raise box['error']
|
||||
return box.get('value')
|
||||
@@ -278,7 +301,7 @@ def python_run(args: dict) -> dict:
|
||||
if not code and not file_path:
|
||||
raise ValueError('code 和 file 至少要给一个')
|
||||
|
||||
timeout = max(1, min(600, int(args.get('timeout') or 60)))
|
||||
timeout = timeouts.budget(args, 'pythonRun')
|
||||
stdin_text = args.get('stdin') or ''
|
||||
|
||||
if file_path:
|
||||
|
||||
@@ -67,8 +67,10 @@ import sys
|
||||
import threading
|
||||
import traceback
|
||||
|
||||
# 单个自定义节点最多跑多久(和会议里的 Python 节点同一套兜底)
|
||||
RUN_TIMEOUT = 10
|
||||
import timeouts
|
||||
|
||||
# ★ 单个自定义节点的超时**不在这里** —— 见 timeouts.py 的 'customNode'
|
||||
# (设置 → 超时 → 自定义节点)。和会议里的 Python 节点是同一套兜底。
|
||||
|
||||
# 引脚类型:exec 是执行引脚,其余是数据引脚
|
||||
PIN_KINDS = ('exec', 'str', 'bool', 'num', 'list')
|
||||
@@ -344,9 +346,10 @@ def run_custom(defn: dict, inputs: dict, variables: dict, node: dict,
|
||||
|
||||
th = threading.Thread(target=work, daemon=True)
|
||||
th.start()
|
||||
th.join(RUN_TIMEOUT)
|
||||
budget = timeouts.get('customNode')
|
||||
th.join(budget)
|
||||
if th.is_alive():
|
||||
return {}, f'超过 {RUN_TIMEOUT} 秒还没跑完(可能有死循环)'
|
||||
return {}, f'超过 {budget:g} 秒还没跑完(可能有死循环,可在设置里调)'
|
||||
return result['outs'], result['err']
|
||||
|
||||
|
||||
|
||||
@@ -206,6 +206,13 @@ DEFAULT_SETTINGS = {
|
||||
},
|
||||
# 安全模式:open 全部放行 / restricted 只放 allow 白名单
|
||||
'security': {'mode': 'open', 'allow': []},
|
||||
# 超时。**这里故意是空的** —— 默认值全在 timeouts.py 的 DEFAULT 里,
|
||||
# 只有用户改过的项才会出现在这儿(和默认一样就删掉,见 timeouts.patch)。
|
||||
#
|
||||
# 为什么这么做:以后调整某个默认值时,没动过那一项的用户会跟着新默认走。
|
||||
# 如果把默认值也存进设置文件,老用户会被永久钉在旧的默认上,
|
||||
# 而且"我明明改的是代码里的默认值,怎么没生效"这种问题极难查。
|
||||
'timeouts': {},
|
||||
# Node 版用它指定解释器;Python 内核在进程内执行工具,这个字段只为兼容而保留
|
||||
'pythonBin': '',
|
||||
'nickname': '我',
|
||||
|
||||
@@ -18,6 +18,10 @@ import shutil
|
||||
import sys
|
||||
import threading
|
||||
|
||||
# 超时全部收在 timeouts.py 里(用户可在「设置 → 超时」调)。
|
||||
# 它读不到设置时会回落默认值,所以在启动早期 import 也是安全的。
|
||||
import timeouts
|
||||
|
||||
# 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录)
|
||||
BUNDLED_TOOL_FILES = [
|
||||
'_protocol.py',
|
||||
@@ -148,7 +152,10 @@ SHELL_TOOL_SPEC = {
|
||||
'properties': {
|
||||
'command': {'type': 'string', 'description': '要执行的命令'},
|
||||
'cwd': {'type': 'string', 'description': '工作目录,可留空'},
|
||||
'timeout': {'type': 'number', 'description': '超时秒数,默认 30,最大 300'},
|
||||
'timeout': {
|
||||
'type': 'number',
|
||||
'description': '超时秒数。不传就用设置里「超时 → Termux 命令」那个值',
|
||||
},
|
||||
},
|
||||
'required': ['command'],
|
||||
},
|
||||
@@ -223,7 +230,7 @@ def shell_run(args: dict) -> dict:
|
||||
if not command or _android is None:
|
||||
return fallback_shell(args)
|
||||
|
||||
timeout = max(1, min(300, int(args.get('timeout', 30) or 30)))
|
||||
timeout = timeouts.budget(args, 'termux')
|
||||
hit = _try_termux(command, str(args.get('cwd') or ''), timeout)
|
||||
if hit is not None:
|
||||
return {
|
||||
|
||||
@@ -29,10 +29,37 @@ import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import paths
|
||||
import timeouts
|
||||
|
||||
PROTOCOL_VERSION = '2024-11-05'
|
||||
CLIENT_INFO = {'name': 'doubao-kernel-py', 'version': '0.1.0'}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 超时
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ★ 这三个超时**不写死在这里** —— 它们在 timeouts.py 里,用户可以在
|
||||
# 「设置 → 超时 → MCP」那一组里调。
|
||||
#
|
||||
# ★ 为什么是函数而不是默认参数值:Python 的默认参数**只在函数定义时求值一次**,
|
||||
# 写成 `def request(self, message, timeout=timeouts.get('mcpRequest'))`
|
||||
# 会把第一次读到的值永久钉住 —— 用户在设置里改完发现没生效,
|
||||
# 而且这种 bug 光看代码看不出来(写法看起来很合理)。
|
||||
# 所以默认值一律写 None,真正取值在这里做。
|
||||
|
||||
def _span_timeout(value, key: str, fallback: float) -> float:
|
||||
if value:
|
||||
return float(value)
|
||||
try:
|
||||
return float(timeouts.get(key))
|
||||
except Exception: # noqa: BLE001 - 设置读不出来也不能让 MCP 用不了
|
||||
return fallback
|
||||
|
||||
|
||||
def _req_timeout(value) -> float:
|
||||
"""单次请求的超时"""
|
||||
return _span_timeout(value, 'mcpRequest', 60.0)
|
||||
|
||||
_clients: dict = {} # serverName -> {'spec','client','tools','error'}
|
||||
_lock = threading.RLock()
|
||||
|
||||
@@ -204,7 +231,8 @@ class _HttpTransport:
|
||||
self.session_id = sid
|
||||
return resp
|
||||
|
||||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||
def request(self, message: dict, timeout: float = None) -> dict:
|
||||
timeout = _req_timeout(timeout)
|
||||
resp = self._post(message, timeout)
|
||||
try:
|
||||
status = getattr(resp, 'status', 200)
|
||||
@@ -575,7 +603,8 @@ class _StdioTransport:
|
||||
self._closed = True
|
||||
self._cv.notify_all()
|
||||
|
||||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||
def request(self, message: dict, timeout: float = None) -> dict:
|
||||
timeout = _req_timeout(timeout)
|
||||
with self._cv:
|
||||
if self._closed:
|
||||
raise McpError('MCP 服务进程已退出')
|
||||
@@ -704,7 +733,8 @@ class _InprocTransport:
|
||||
self._closed = True
|
||||
self._cv.notify_all()
|
||||
|
||||
def request(self, message: dict, timeout: float = 60) -> dict:
|
||||
def request(self, message: dict, timeout: float = None) -> dict:
|
||||
timeout = _req_timeout(timeout)
|
||||
req_id = message.get('id')
|
||||
with self._cv:
|
||||
if self._closed:
|
||||
@@ -805,7 +835,8 @@ class McpClient:
|
||||
raise McpError(f'{method} 失败:{detail}')
|
||||
return response.get('result')
|
||||
|
||||
def connect(self, timeout: float = 180) -> 'McpClient':
|
||||
def connect(self, timeout: float = None) -> 'McpClient':
|
||||
timeout = _span_timeout(timeout, 'mcpConnect', 180.0)
|
||||
# initialize 允许失败:inproc 的最小实现可能只认 tools/list、tools/call
|
||||
self._request(
|
||||
'initialize',
|
||||
@@ -818,11 +849,12 @@ class McpClient:
|
||||
tolerate_error=True,
|
||||
)
|
||||
self.transport.notify({'jsonrpc': '2.0', 'method': 'notifications/initialized', 'params': {}})
|
||||
listed = self._request('tools/list', {}, 60) or {}
|
||||
listed = self._request('tools/list', {}, _req_timeout(None)) or {}
|
||||
self.tools = listed.get('tools') or []
|
||||
return self
|
||||
|
||||
def call_tool(self, name: str, arguments: dict, timeout: float = 120) -> dict:
|
||||
def call_tool(self, name: str, arguments: dict, timeout: float = None) -> dict:
|
||||
timeout = _span_timeout(timeout, 'mcpTool', 120.0)
|
||||
result = self._request('tools/call', {'name': name, 'arguments': arguments or {}}, timeout)
|
||||
return result or {}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
import timeouts
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
@@ -74,7 +75,8 @@ NODE_TYPES = ('start', 'agent', 'judge', 'end', 'var', 'readvar', 'while', 'valu
|
||||
# 但**必须**做两件事:超时(死循环不能把 App 卡死)和异常兜底
|
||||
# (报错要显示在哪一步,而不是整场会议崩掉)。
|
||||
|
||||
PY_TIMEOUT = 10 # 单个 Python 节点最多跑多少秒
|
||||
# ★ 单个 Python 节点的超时**不在这里** —— 见 timeouts.py 的 'meetingNode'
|
||||
# (设置 → 超时 → 会议节点)。以前写死 10 秒,跑个稍重的计算就会被判死循环。
|
||||
PY_MAX_OUTPUT = 20000 # 输出最多留多少字符
|
||||
|
||||
|
||||
@@ -131,9 +133,10 @@ def run_py_node(code: str, input_text: str, variables: dict,
|
||||
|
||||
th = threading.Thread(target=work, daemon=True)
|
||||
th.start()
|
||||
th.join(PY_TIMEOUT)
|
||||
budget = timeouts.get('meetingNode')
|
||||
th.join(budget)
|
||||
if th.is_alive():
|
||||
return (result['out'] or '')[:PY_MAX_OUTPUT], f'超过 {PY_TIMEOUT} 秒还没跑完(可能有死循环)'
|
||||
return (result['out'] or '')[:PY_MAX_OUTPUT], f'超过 {budget:g} 秒还没跑完(可能有死循环,可在设置里调)'
|
||||
|
||||
for k, v in writes.items():
|
||||
variables[k] = v
|
||||
|
||||
@@ -20,11 +20,20 @@ import urllib.request
|
||||
from typing import Callable, Iterator, Optional
|
||||
|
||||
from defaults import PROVIDER_PRESETS
|
||||
import timeouts
|
||||
|
||||
# 推理模型(o 系列 / gpt-5 系)不接受 temperature 等采样参数
|
||||
REASONING_MODEL_RE = re.compile(r'^(o1|o3|o4|gpt-5|gpt-6)', re.IGNORECASE)
|
||||
|
||||
DEFAULT_TIMEOUT_MS = 180000
|
||||
# ★ 模型请求的超时**不在这里** —— 它和别的超时一起收在 timeouts.py 里
|
||||
# (设置 → 超时 → 等模型回复)。以前这里是 `DEFAULT_TIMEOUT_MS = 180000`,
|
||||
# 用户改不了;现在每次请求现读,改了立刻生效、不用重启。
|
||||
def model_timeout_s() -> float:
|
||||
"""等模型返回的秒数(读设置,出错时回落 180 秒)"""
|
||||
try:
|
||||
return float(timeouts.get('model'))
|
||||
except Exception: # noqa: BLE001 - 设置读不出来也不能让请求发不出去
|
||||
return 180.0
|
||||
|
||||
|
||||
def join_url(base_url: str, suffix: str) -> str:
|
||||
@@ -109,7 +118,7 @@ def _request(url: str, api_key: str, body: dict | None = None, method: str = 'PO
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
# 不用 urlopen 的 with:流式响应要留给调用方边读边消费
|
||||
return urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_MS / 1000)
|
||||
return urllib.request.urlopen(req, timeout=model_timeout_s())
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
try:
|
||||
@@ -263,7 +272,7 @@ def list_models(*, base_url: str, api_key: str) -> list:
|
||||
url = join_url(base_url, '/models')
|
||||
req = urllib.request.Request(url, headers={'Authorization': f'Bearer {api_key}'}, method='GET')
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_MS / 1000)
|
||||
resp = urllib.request.urlopen(req, timeout=model_timeout_s())
|
||||
except urllib.error.HTTPError as exc:
|
||||
raise UpstreamError(f'上游 {exc.code}') from exc
|
||||
except urllib.error.URLError as exc:
|
||||
|
||||
@@ -28,8 +28,28 @@ import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
DEFAULT_TIMEOUT_TTS = 60
|
||||
DEFAULT_TIMEOUT_STT = 120
|
||||
import timeouts
|
||||
|
||||
# ★ 语音的超时也收在 timeouts.py 里(设置 → 超时 → 语音合成 / 语音识别)。
|
||||
# 以前这里是 `DEFAULT_TIMEOUT_TTS = 60` / `DEFAULT_TIMEOUT_STT = 120` 两个常量,
|
||||
# 网络慢或者回复长的时候用户只能忍着。现在是函数 —— 每次现读,改完立刻生效。
|
||||
|
||||
|
||||
def tts_timeout() -> float:
|
||||
"""语音合成等多久(出错回落 60 秒)"""
|
||||
try:
|
||||
return float(timeouts.get('tts'))
|
||||
except Exception: # noqa: BLE001
|
||||
return 60.0
|
||||
|
||||
|
||||
def stt_timeout() -> float:
|
||||
"""语音识别等多久(出错回落 120 秒)"""
|
||||
try:
|
||||
return float(timeouts.get('stt'))
|
||||
except Exception: # noqa: BLE001
|
||||
return 120.0
|
||||
|
||||
|
||||
# 允许用环境变量覆盖:自测时把火山接口指到本地 mock,就能验证"我们到底发了什么"
|
||||
# (鉴权头那个分号、body 的层级,光看代码容易自我说服,实测才算数)
|
||||
@@ -267,7 +287,7 @@ def _synthesize_volc_v3(text: str, speech: dict, speed: float) -> dict:
|
||||
req.add_header('X-Control-Require-Usage-Tokens-Return', '*')
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp:
|
||||
with urllib.request.urlopen(req, timeout=tts_timeout()) as resp:
|
||||
raw = resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
@@ -342,7 +362,7 @@ def _synthesize_volc(text: str, speech: dict, speed: float) -> dict:
|
||||
'operation': 'query',
|
||||
},
|
||||
}
|
||||
result = _post_json(VOLC_TTS_URL, body, {'Authorization': f'Bearer;{token}'}, DEFAULT_TIMEOUT_TTS)
|
||||
result = _post_json(VOLC_TTS_URL, body, {'Authorization': f'Bearer;{token}'}, tts_timeout())
|
||||
|
||||
code = result.get('code')
|
||||
if code != 3000:
|
||||
@@ -374,7 +394,7 @@ def _synthesize_openai(text: str, settings: dict, speech: dict, speed: float) ->
|
||||
req.add_header('Authorization', f'Bearer {api_key}')
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp:
|
||||
with urllib.request.urlopen(req, timeout=tts_timeout()) as resp:
|
||||
raw = resp.read()
|
||||
ctype = resp.headers.get('Content-Type') or 'audio/mpeg'
|
||||
except urllib.error.HTTPError as exc:
|
||||
@@ -429,7 +449,7 @@ def transcribe(audio: bytes, filename: str, content_type: str, settings: dict) -
|
||||
req.add_header('Authorization', f'Bearer {api_key}')
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_STT) as resp:
|
||||
with urllib.request.urlopen(req, timeout=stt_timeout()) as resp:
|
||||
raw = resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
@@ -564,7 +584,7 @@ def _stream_volc_v3(text: str, speech: dict, speed: float):
|
||||
|
||||
mime = VOLC_MIME.get(fmt, 'audio/L16')
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS)
|
||||
resp = urllib.request.urlopen(req, timeout=tts_timeout())
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
try:
|
||||
|
||||
@@ -135,6 +135,11 @@ def read_settings() -> dict:
|
||||
# ({"speech":"{autoRead=true}"}),存进去之后**每一次**读配置都会抛
|
||||
# TypeError,/api/state 从此一直 500 —— 一个坏字段把整个 App 弄成空白。
|
||||
# 所以:读的时候发现不是字典就回落默认值(自愈),写的时候也不让非字典覆盖。
|
||||
#
|
||||
# ★ timeouts **刻意不在这个列表里**:它的默认值是空 dict(真正的默认值在
|
||||
# timeouts.py 里),深合并会让"改回默认 = 删掉这一项"永远删不掉 ——
|
||||
# 旧值残留在设置文件里,用户会看到"我明明恢复默认了怎么还是 30 秒"。
|
||||
# 所以它走**整体替换**:写进来的就是全部,没写到的等于用默认值。
|
||||
for key in ('tools', 'security', 'speech'):
|
||||
defaults = DEFAULT_SETTINGS.get(key) or {}
|
||||
raw = stored.get(key)
|
||||
@@ -202,6 +207,16 @@ def write_settings(patch: dict) -> dict:
|
||||
else:
|
||||
nxt[key] = current.get(key) or {}
|
||||
print(f'[config] 补丁里的 {key} 不是对象({type(patch[key]).__name__}),已忽略', file=sys.stderr, flush=True)
|
||||
# ★ timeouts 是**整体替换**,不深合并 —— 默认值在 timeouts.py 里,
|
||||
# 深合并会让"改回默认 = 从设置里删掉这一项"永远删不掉。
|
||||
# 调用方(/api/timeouts)传进来的就是**完整的非默认集合**。
|
||||
if 'timeouts' in patch:
|
||||
raw_t = patch['timeouts']
|
||||
if isinstance(raw_t, dict):
|
||||
nxt['timeouts'] = raw_t
|
||||
else:
|
||||
nxt['timeouts'] = current.get('timeouts') or {}
|
||||
print(f'[config] 补丁里的 timeouts 不是对象({type(raw_t).__name__}),已忽略', file=sys.stderr, flush=True)
|
||||
if patch.get('apiKey') == '••••••••':
|
||||
nxt['apiKey'] = current.get('apiKey', '')
|
||||
# ★ 掩码回写保护:界面读到的是 '••••••••',用户不改语音设置直接保存时,
|
||||
|
||||
315
android/kernel/timeouts.py
Normal file
315
android/kernel/timeouts.py
Normal file
@@ -0,0 +1,315 @@
|
||||
"""**所有超时的唯一一份定义**,以及读取它们的入口。
|
||||
|
||||
## 为什么要收成一份
|
||||
|
||||
改造前,15 个超时散在 10 个文件里,全是模块级常量,谁也说不清一共有几个:
|
||||
|
||||
tools_runtime.py TOOL_TIMEOUT_S = 60 工具执行
|
||||
builtin_tools.py shell 工具 30 / python 60 命令执行(还各自夹了上限)
|
||||
doubao_entry.py termux 命令 30
|
||||
providers.py DEFAULT_TIMEOUT_MS = 180000 模型请求
|
||||
speech.py TTS 60 / STT 120
|
||||
mcp_client.py 请求 60 / 连接 180 / 工具 120
|
||||
meeting.py PY_TIMEOUT = 10 会议里的 Python 节点
|
||||
custom_nodes.py RUN_TIMEOUT = 10
|
||||
tools/ask_user.py TIMEOUT_S = 0 / MAX 3600
|
||||
tools/show_ui.py MIN 5 / MAX 3600
|
||||
KernelClient.kt connect 5s / read 120s
|
||||
|
||||
后果和"节点定义写 6 遍"是同一类:**想调一个超时要先找到它在哪**,
|
||||
而且改了一处不知道还有没有别处也在卡同一个东西。
|
||||
|
||||
## 用户要"全部可调",所以这里同时是**界面数据的来源**
|
||||
|
||||
界面不硬编码这些项目 —— 它读 `GET /api/timeouts`,那个接口返回的就是 [SPECS]。
|
||||
所以**加一项超时只改这个文件**(加 [DEFAULT] 一条 + [SPECS] 一条),
|
||||
内核各处 `timeouts.get('名字')`,界面自动多出一行。
|
||||
|
||||
## 边界
|
||||
|
||||
每项都带 `min` / `max`,取值时**一律夹进去**([get] 里做的)。
|
||||
不是"相信用户不会填错":填 0 会让 curl 永远不超时、填 999999 会让内核线程
|
||||
挂到天荒地老。夹取是这一层唯一该做的"业务判断",所以放在这里而不是各调用点。
|
||||
|
||||
`min = 0` 表示这一项**允许"不限时"**(只有"等用户"这类才该允许)。
|
||||
"""
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 默认值
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 这里只放**数字**。每一项都必须能在 SPECS 里找到同名条目 ——
|
||||
# `scripts/verify-timeouts.py` 会检查两边对得上(少一条就报错)。
|
||||
|
||||
DEFAULT = {
|
||||
# ---- 对话 ----
|
||||
'model': 180, # 等模型返回
|
||||
'sseRead': 120, # 客户端读 SSE 的间隔上限(内核只负责告诉客户端)
|
||||
'heartbeat': 15, # SSE 心跳间隔
|
||||
'kernelLocal': 10, # 客户端调内核本地接口(安卓侧用)
|
||||
|
||||
# ---- 工具 ----
|
||||
'tool': 60, # 任意 Python 工具执行
|
||||
'shell': 30, # 安卓 shell 命令(builtin)
|
||||
'pythonRun': 60, # 跑一段 Python 代码(builtin)
|
||||
'termux': 30, # 内置 Termux 里跑命令
|
||||
'meetingNode': 10, # 会议里的 Python / 自定义节点
|
||||
'customNode': 10, # 自定义节点(nodes/ 里的)
|
||||
|
||||
# ---- 界面(等用户)----
|
||||
'askUser': 0, # ask_user 等用户选,0 = 不限时
|
||||
'waitUi': 0, # show_ui 的 wait 模式等用户,0 = 不限时
|
||||
'filePicker': 120, # AI 让你选文件时等你多久
|
||||
|
||||
# ---- 语音 ----
|
||||
'tts': 60,
|
||||
'stt': 120,
|
||||
|
||||
# ---- MCP ----
|
||||
'mcpRequest': 60,
|
||||
'mcpConnect': 180,
|
||||
'mcpTool': 120,
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 每一项的说明(界面直接用这些文字)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# group 决定界面上分到哪一组;unit 目前全是"秒"(毫秒的东西一律在调用点换算)。
|
||||
|
||||
SPECS = [
|
||||
# ---------------- 对话 ----------------
|
||||
{
|
||||
'key': 'model', 'group': '对话', 'label': '等模型回复',
|
||||
'default': 180, 'min': 10, 'max': 1800, 'unit': '秒',
|
||||
'desc': '发出去到开始收到第一个字的最长等待。深度思考的模型(R1 这类)'
|
||||
'经常要想一分钟以上,调小了会频繁断在半路;本地小模型可以调大。',
|
||||
},
|
||||
{
|
||||
'key': 'sseRead', 'group': '对话', 'label': '连接空闲上限',
|
||||
'default': 120, 'min': 20, 'max': 3600, 'unit': '秒',
|
||||
'desc': '手机上"多久没收到任何数据就断开"。内核每【心跳间隔】秒发一次心跳,'
|
||||
'所以这个值必须比心跳间隔大不少 —— 内核发的就是心跳间隔那项。'
|
||||
'弱网/代理会悄悄掐长连接,可以把两个都调小一点,断得早反而好重连。',
|
||||
},
|
||||
{
|
||||
'key': 'heartbeat', 'group': '对话', 'label': '心跳间隔',
|
||||
'default': 15, 'min': 5, 'max': 300, 'unit': '秒',
|
||||
'desc': '对话过程中内核每隔这么久发一个空包,证明连接还活着。'
|
||||
'调大了在弱网下容易被中间设备当成死连接掐掉;调小了费电。',
|
||||
},
|
||||
{
|
||||
'key': 'kernelLocal', 'group': '对话', 'label': '本地接口请求',
|
||||
'default': 10, 'min': 3, 'max': 300, 'unit': '秒',
|
||||
'desc': '界面调内核的普通接口(读会话、存设置、拉笔记)等多久。'
|
||||
'只有老设备 + 会话特别长时才会顶到这个值。',
|
||||
},
|
||||
|
||||
# ---------------- 工具 ----------------
|
||||
{
|
||||
'key': 'tool', 'group': '工具', 'label': '工具执行',
|
||||
'default': 60, 'min': 0, 'max': 3600, 'unit': '秒', 'zero': '不限时',
|
||||
'desc': '任意一个 Python 工具最多跑多久。这是"工具里写了死循环"的安全网。\n'
|
||||
'填 0 = 不限时。注意:会停下来等你的工具(AI 提问、AI 界面等待)'
|
||||
'本来就不受这一项限制 —— 它们的时长取决于你什么时候点。',
|
||||
},
|
||||
{
|
||||
'key': 'shell', 'group': '工具', 'label': 'shell 命令',
|
||||
'default': 30, 'min': 1, 'max': 3600, 'unit': '秒',
|
||||
'desc': 'AI 调用内置 shell 工具跑一条命令的最长时间。'
|
||||
'装包(pkg install / pip install)这类会超过 30 秒,那时可以让 AI 自己传更长的值。',
|
||||
},
|
||||
{
|
||||
'key': 'pythonRun', 'group': '工具', 'label': '跑 Python 代码',
|
||||
'default': 60, 'min': 1, 'max': 3600, 'unit': '秒',
|
||||
'desc': 'AI 写一段 Python 交给内核执行的最长时间。算得久(循环、大文件)就调大。',
|
||||
},
|
||||
{
|
||||
'key': 'termux', 'group': '工具', 'label': 'Termux 命令',
|
||||
'default': 30, 'min': 1, 'max': 3600, 'unit': '秒',
|
||||
'desc': '在内置 Termux 环境里跑命令的最长时间。',
|
||||
},
|
||||
{
|
||||
'key': 'meetingNode', 'group': '工具', 'label': '会议节点',
|
||||
'default': 10, 'min': 1, 'max': 600, 'unit': '秒',
|
||||
'desc': '会议里一个 Python 节点 / 自定义节点最多跑多久。'
|
||||
'这是防死循环的 —— 调太大会让整个会议卡住,建议别超过 60。',
|
||||
},
|
||||
{
|
||||
'key': 'customNode', 'group': '工具', 'label': '自定义节点',
|
||||
'default': 10, 'min': 1, 'max': 600, 'unit': '秒',
|
||||
'desc': 'nodes/ 目录里自己写的节点,执行一次的最长时间。',
|
||||
},
|
||||
|
||||
# ---------------- 界面 ----------------
|
||||
{
|
||||
'key': 'askUser', 'group': '界面', 'label': 'AI 提问等多久',
|
||||
'default': 0, 'min': 0, 'max': 3600, 'unit': '秒', 'zero': '不限时',
|
||||
'desc': 'AI 弹选择框问你时,等多久算"你没空"。**默认 0 = 一直等**。\n'
|
||||
'不建议改:设成有限值后,你去忙一会儿回来,AI 已经按它自己猜的答案'
|
||||
'往下写了,而它并不知道自己在猜。',
|
||||
},
|
||||
{
|
||||
'key': 'waitUi', 'group': '界面', 'label': 'AI 界面等多久',
|
||||
'default': 0, 'min': 0, 'max': 3600, 'unit': '秒', 'zero': '不限时',
|
||||
'desc': 'AI 弹的界面在 wait 模式下等你点按钮的时长。**默认 0 = 一直等**。',
|
||||
},
|
||||
{
|
||||
'key': 'filePicker', 'group': '界面', 'label': '选文件等多久',
|
||||
'default': 120, 'min': 10, 'max': 3600, 'unit': '秒',
|
||||
'desc': 'AI 让你挑一个文件时,等你挑完的时长。'
|
||||
'去相册里翻一张老照片可能不止两分钟,可以调大。',
|
||||
},
|
||||
|
||||
# ---------------- 语音 ----------------
|
||||
{
|
||||
'key': 'tts', 'group': '语音', 'label': '语音合成',
|
||||
'default': 60, 'min': 5, 'max': 600, 'unit': '秒',
|
||||
'desc': '把回复转成语音的最长等待。长回复、网络慢时要更久。',
|
||||
},
|
||||
{
|
||||
'key': 'stt', 'group': '语音', 'label': '语音识别',
|
||||
'default': 120, 'min': 5, 'max': 600, 'unit': '秒',
|
||||
'desc': '把录音转成文字的最长等待。录音越长越久。',
|
||||
},
|
||||
|
||||
# ---------------- MCP ----------------
|
||||
{
|
||||
'key': 'mcpRequest', 'group': 'MCP', 'label': '单次请求',
|
||||
'default': 60, 'min': 5, 'max': 600, 'unit': '秒',
|
||||
'desc': '和 MCP 服务说话时,单次请求等多久。',
|
||||
},
|
||||
{
|
||||
'key': 'mcpConnect', 'group': 'MCP', 'label': '连接',
|
||||
'default': 180, 'min': 5, 'max': 900, 'unit': '秒',
|
||||
'desc': '启动 MCP 服务(npx / uvx 第一次要下载)的最长等待。'
|
||||
'第一次装包经常要几分钟,这也是默认给到 180 秒的原因。',
|
||||
},
|
||||
{
|
||||
'key': 'mcpTool', 'group': 'MCP', 'label': '调用工具',
|
||||
'default': 120, 'min': 5, 'max': 900, 'unit': '秒',
|
||||
'desc': '调用 MCP 服务里某个工具的最长等待。',
|
||||
},
|
||||
]
|
||||
|
||||
BY_KEY = {s['key']: s for s in SPECS}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 读取
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _stored() -> dict:
|
||||
"""用户改过的那部分(没改过就是空的)"""
|
||||
try:
|
||||
import store # 局部导入:store 依赖 paths,放顶部会把导入顺序弄难读
|
||||
raw = (store.read_settings() or {}).get('timeouts')
|
||||
except Exception: # noqa: BLE001 - 设置读不出来时一律用默认值,别让业务挂掉
|
||||
return {}
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def coerce(key: str, raw) -> float:
|
||||
"""
|
||||
把用户填的东西变成一个合法的秒数。
|
||||
|
||||
★ 容错是必须的:界面上是输入框,用户可能填 "60秒"、空串、负数、
|
||||
或者一个巨大的数。任何一种都不该让调用它的地方炸掉。
|
||||
"""
|
||||
spec = BY_KEY.get(key)
|
||||
if spec is None:
|
||||
raise KeyError(f'没有这个超时项:{key}')
|
||||
value = spec['default']
|
||||
if raw is not None and raw != '':
|
||||
try:
|
||||
value = float(str(raw).strip().rstrip('秒sS'))
|
||||
except (TypeError, ValueError):
|
||||
value = spec['default']
|
||||
lo, hi = spec['min'], spec['max']
|
||||
if value < lo:
|
||||
value = lo
|
||||
if value > hi:
|
||||
value = hi
|
||||
return value
|
||||
|
||||
|
||||
def get(key: str) -> float:
|
||||
"""读一项当前的超时(秒)。0 = 不限时(只有允许的项才会是 0)。"""
|
||||
return coerce(key, _stored().get(key))
|
||||
|
||||
|
||||
def ms(key: str) -> int:
|
||||
"""要毫秒的地方用这个(别在每个调用点自己写 * 1000)"""
|
||||
return int(get(key) * 1000)
|
||||
|
||||
|
||||
def resolved() -> dict:
|
||||
"""当前生效的全部值(默认 + 用户改的),给界面和诊断用"""
|
||||
stored = _stored()
|
||||
return {s['key']: coerce(s['key'], stored.get(s['key'])) for s in SPECS}
|
||||
|
||||
|
||||
def catalog() -> list:
|
||||
"""
|
||||
给界面的清单:每一项的说明 + 默认值 + 边界 + 现在是多少。
|
||||
|
||||
★ 界面**不硬编码**这些项目,它读这个。加一项超时只改本文件。
|
||||
"""
|
||||
stored = _stored()
|
||||
out = []
|
||||
for s in SPECS:
|
||||
item = dict(s)
|
||||
item['value'] = coerce(s['key'], stored.get(s['key']))
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def patch(values: dict) -> dict:
|
||||
"""
|
||||
算出"要存下来的那部分"(只含和默认值不同的项)。
|
||||
|
||||
★ 只存"和默认值不同的":这样以后改了默认值,没动过的项会跟着新默认走
|
||||
(如果一律存下来,老用户会被永久钉在旧默认上)。
|
||||
和默认一样就**删掉**这个键,不是存一个相同的值。
|
||||
"""
|
||||
current = dict(_stored())
|
||||
if not isinstance(values, dict):
|
||||
return resolved()
|
||||
for key, raw in values.items():
|
||||
if key not in BY_KEY:
|
||||
continue
|
||||
value = coerce(key, raw)
|
||||
if abs(value - float(BY_KEY[key]['default'])) < 1e-9:
|
||||
current.pop(key, None)
|
||||
else:
|
||||
# 存成 int 更好看(都是整秒),带小数的也不丢
|
||||
current[key] = int(value) if float(value).is_integer() else value
|
||||
return current
|
||||
|
||||
|
||||
def reset() -> dict:
|
||||
"""全部恢复默认"""
|
||||
return {}
|
||||
|
||||
|
||||
def budget(args: dict, key: str) -> int:
|
||||
"""
|
||||
算一次工具执行的超时:**工具参数优先,否则用设置里的值**,一律夹在该项边界内。
|
||||
|
||||
给 shell / python_run / termux 这几个"模型自己可以传 timeout"的工具用:
|
||||
|
||||
· 模型传了就用它的(它知道自己要跑多久:装个包当然比 ls 久)
|
||||
· 没传就用设置里的默认值(用户可能在设置里统一调大了)
|
||||
· 不管谁给的都夹在 [min, max] 里 —— 模型传 999999 也不能真的等那么久
|
||||
"""
|
||||
spec = BY_KEY.get(key)
|
||||
if spec is None:
|
||||
raise KeyError(f'没有这个超时项:{key}')
|
||||
raw = (args or {}).get('timeout')
|
||||
if raw in (None, ''):
|
||||
return int(get(key))
|
||||
try:
|
||||
value = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
return int(get(key))
|
||||
return int(max(spec['min'], min(spec['max'], value)))
|
||||
@@ -24,6 +24,7 @@ import threading
|
||||
|
||||
import mcp_client
|
||||
import paths
|
||||
import timeouts
|
||||
from builtin_tools import BUILTIN_TOOLS, run_with_timeout
|
||||
|
||||
# 文件工具的缓存:path -> {'mtime':..., 'spec':..., 'error':...}
|
||||
@@ -32,9 +33,73 @@ _cache_lock = threading.Lock()
|
||||
# 已经 import 过的模块名(重载时要先从 sys.modules 里摘掉)
|
||||
_loaded_modules: dict = {}
|
||||
|
||||
TOOL_TIMEOUT_S = 60
|
||||
# ★ 工具的默认执行超时**不在这里** —— 它和别的 15 个超时一起收在
|
||||
# `timeouts.py` 里,用户可以在「设置 → 超时」里调。这里以前写死 `TOOL_TIMEOUT_S = 60`,
|
||||
# 现在一律 `timeouts.get('tool')`。
|
||||
BUILTIN_FILE_LABEL = '<内置>'
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 会"停下来等用户"的工具:执行超时对它们不适用
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★★ 这个坑很隐蔽,记下来:
|
||||
#
|
||||
# 用户要求"AI 询问界面不要限时",我把弹窗那侧改成了无限等(`AiSurface.ask`),
|
||||
# 实测弹窗确实 135 秒还在 —— **但工具调用在 60 秒时就被内核判超时了**,
|
||||
# 模型收到的是"工具执行超时(60s)",用户五分钟后点的那个选项**根本回不到
|
||||
# 模型手里**。表现就是"弹窗还在、但 AI 已经自己往下写了"。
|
||||
#
|
||||
# 所以"不限时"必须**三处一起改**才算数:
|
||||
# ① 界面侧等多久(AiSurface)
|
||||
# ② 内核侧给工具多少时间(这里)
|
||||
# ③ 工具自己声明的 timeout(tools/ask_user.py、tools/show_ui.py)
|
||||
#
|
||||
# 判定方式:工具模块里声明 `WAIT_FOR_USER = True`。
|
||||
# 放在工具文件里而不是在这个列表里硬编码 —— 加新工具时不会漏(写工具的人
|
||||
# 自己知道它会不会等用户)。
|
||||
def _waits_for_user(name: str, spec: dict, module) -> bool:
|
||||
"""这个工具会不会停下来等用户交互"""
|
||||
if spec.get('_builtin'):
|
||||
return bool((BUILTIN_TOOLS.get(name) or {}).get('WAIT_FOR_USER'))
|
||||
return bool(getattr(module, 'WAIT_FOR_USER', False))
|
||||
|
||||
|
||||
def _with_default_timeouts(name: str, spec: dict, module, payload: dict) -> dict:
|
||||
"""
|
||||
把设置里的默认超时**注入**给声明了要的工具。
|
||||
|
||||
## 工具是这么声明的
|
||||
|
||||
# tools/ask_user.py
|
||||
TIMEOUT_KEYS = {'timeout': 'askUser'}
|
||||
|
||||
意思是:"我这个 `timeout` 参数如果模型没给,就用设置里 `askUser` 那一项的值。"
|
||||
|
||||
## 为什么要走这条路,而不是让工具自己 import timeouts
|
||||
|
||||
因为工具**不一定跑在内核进程里**:安卓端是进程内 import(能读),
|
||||
电脑端是 `python tool.py` 起子进程(读不到内核的模块)。而工具是要跨端复用的,
|
||||
所以不能让它们依赖内核的模块。
|
||||
|
||||
内核在**调用前**把值塞进参数里,工具照常从自己的参数读 —— 两端行为一致,
|
||||
工具本身也不用知道"设置"这回事(单独跑、自测时用自己文件里的兜底默认值)。
|
||||
"""
|
||||
keys = getattr(module, 'TIMEOUT_KEYS', None)
|
||||
if not isinstance(keys, dict) or not keys:
|
||||
return payload
|
||||
out = dict(payload)
|
||||
for arg_name, key in keys.items():
|
||||
# 模型给了就不覆盖(模型知道自己要等多久);给 0 也当"没给",
|
||||
# 因为 0 是"不限时"的合法值,但默认参数里它和"没填"是同一个意思
|
||||
if out.get(arg_name) in (None, '', 0, '0'):
|
||||
try:
|
||||
out[arg_name] = timeouts.get(key)
|
||||
except Exception: # noqa: BLE001 - 设置读不出来就用工具自己的兜底
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 界面工具的开关
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -301,6 +366,8 @@ def run_python_tool(name: str, args: dict) -> dict:
|
||||
runner = getattr(module, 'run')
|
||||
|
||||
payload = args if isinstance(args, dict) else {}
|
||||
# ★ 设置里的默认超时注入给声明了 TIMEOUT_KEYS 的工具(ask_user / show_ui)
|
||||
payload = _with_default_timeouts(name, spec, module, payload)
|
||||
# ★★★ **先抓住当前线程的上下文**,因为 run_with_timeout 会在**另一个线程**里
|
||||
# 跑工具,而 threading.local() 是**不跨线程继承**的 —— 不搬过去的话,
|
||||
# 工作线程里 current_context() 永远是空的。
|
||||
@@ -320,14 +387,22 @@ def run_python_tool(name: str, args: dict) -> dict:
|
||||
_ctx.value = None
|
||||
|
||||
try:
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
|
||||
outcome = run_with_timeout(_invoke, TOOL_TIMEOUT_S)
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死。
|
||||
# ★ 会等用户的工具(ask_user / show_ui 的 wait 模式)**不限时** ——
|
||||
# 它们的耗时取决于用户什么时候点,给上限等于"用户想久了 AI 就自己编"。
|
||||
# 见 _waits_for_user 的注释。
|
||||
# ★ 预算是**设置里可调**的(设置 → 超时 → 工具执行),不是写死的 60。
|
||||
if _waits_for_user(name, spec, module):
|
||||
budget = 0
|
||||
else:
|
||||
budget = timeouts.get('tool')
|
||||
outcome = run_with_timeout(_invoke, budget)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500
|
||||
# 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"},
|
||||
# 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。
|
||||
return {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||
if outcome is None:
|
||||
return {'ok': False, 'error': f'工具执行超时({TOOL_TIMEOUT_S}s)'}
|
||||
return {'ok': False, 'error': f'工具执行超时({budget:g}s,可在设置里调)'}
|
||||
result = outcome
|
||||
# 工具可以像 _protocol 那样返回 {"ok":..,"result":..},也可以直接返回业务结果
|
||||
if isinstance(result, dict) and 'ok' in result:
|
||||
|
||||
@@ -25,11 +25,49 @@
|
||||
| 工具 | 阻不阻塞 | 为什么 |
|
||||
|---|---|---|
|
||||
| `show_ui` | **不阻塞** | 展示语义。用户可能盯着看很久,把内核线程占住没意义 |
|
||||
| `ask_user` | **阻塞**(最多 120s) | 问询语义。拿不到答案就没法继续 |
|
||||
| `ask_user` | **阻塞**(默认**不限时**,见下) | 问询语义。拿不到答案就没法继续 |
|
||||
| `end_conversation` | 立刻返回 | 它只改状态(落盘 + 界面收输入框) |
|
||||
|
||||
超时是**必须**的:用户可能锁屏就走了。不设的话内核的工作线程永远挂着,
|
||||
而 HTTP 是每请求一线程,挂一个少一个。
|
||||
### ★★ 不限时(v2.0.45 起):要三处一起改才算数
|
||||
|
||||
原来是 120 秒上限,用户明确要求去掉:"AI 询问界面不要限时"。理由很实在:
|
||||
|
||||
> 用户看到选项、去翻了下手机算个数、回来弹窗没了;模型收到 `timeout=true`,
|
||||
> 理解成"用户不想理我",于是**按自己猜的答案往下写** —— 这一轮整个废掉。
|
||||
|
||||
现在的默认是**一直等**,放行出口是:点任意选项 / 点「取消」/ 关掉 App。
|
||||
模型真想限时得自己传 `timeout`(`ask_user` 1~3600 秒,`show_ui` 5~3600 秒)。
|
||||
|
||||
**这个值现在也是可调的**:设置 → 超时 → 「AI 提问等多久」/「AI 界面等多久」
|
||||
(默认 0 = 不限时)。内核在调用工具前把它注入到 `timeout` 参数里,
|
||||
见 `tools_runtime._with_default_timeouts`。
|
||||
|
||||
**这个改动必须同时改三处**,只改一两处的表现是"看起来改了其实没生效":
|
||||
|
||||
| # | 改哪儿 | 不改的后果 |
|
||||
|---|---|---|
|
||||
| ① | `AiSurface.ask` / `showScreen`(界面侧等多久) | 弹窗到点自己消失 |
|
||||
| ② | `timeouts.py` 的 `tool` 那一项(内核给工具多少时间) | 弹窗还开着,但内核 60 秒就把这次调用判超时、把结果丢了 |
|
||||
| ③ | 工具自己声明的 `timeout`(现在由设置注入) | 工具主动提前放弃 |
|
||||
|
||||
②最隐蔽:`TOOL_TIMEOUT_S = 60` 是"工具里写了死循环"的安全网,
|
||||
而等用户的工具**设计上就该慢**。所以它们在自己的文件里声明
|
||||
`WAIT_FOR_USER = True`,内核据此把超时预算设成 0(不限时)。
|
||||
|
||||
> 实测记录:只改 ①③ 时,弹窗 135 秒确实还在,但工具在 **60.0 秒**返回了
|
||||
> `{"ok":false,"error":"工具执行超时(60s)"}` —— 用户后来点的选项根本回不到
|
||||
> 模型手里。补上 ② 之后同一个探针在 **66.2 秒**返回
|
||||
> `{"choice":"B","timeout":false}`。
|
||||
> 探针:`scripts/probe-ask-user-forever.py`;守门:`scripts/verify-ui-tools.py`。
|
||||
|
||||
### 客户端那条长连接为什么不会断
|
||||
|
||||
对话是 SSE 长连接,等待期间可能几分钟没有正常数据。两端都不会断:
|
||||
|
||||
- 内核每 **15 秒**发一个 `: ping` 心跳(`app.py` 的 `_ping_loop`)
|
||||
- 客户端 `readTimeout` 是 **120 秒**(`KernelClient`)—— 它管的是"两次数据之间的最大间隔",不是总时长
|
||||
|
||||
所以心跳只要 < 120 秒就安全。
|
||||
|
||||
---
|
||||
|
||||
@@ -38,7 +76,7 @@
|
||||
| 用法 | 行为 | 适合 |
|
||||
|---|---|---|
|
||||
| `wait` 不传(默认) | 弹出就返回,不等 | 图表、报告这类"给用户看"的 |
|
||||
| `wait=true` | **等用户点回传按钮或关掉界面**,最多 `timeout` 秒(默认 120,上限 600) | "弹几个选项让用户挑,然后我接着干" |
|
||||
| `wait=true` | **等用户点回传按钮或关掉界面**(默认**不限时**;显式传 `timeout` 则 5~3600 秒) | "弹几个选项让用户挑,然后我接着干" |
|
||||
| 不调用 | 纯文字回答 | —— |
|
||||
|
||||
等待模式下用户点的值**立刻**作为工具返回值给模型,**同一个回合里**就能接着处理:
|
||||
@@ -48,7 +86,7 @@ wait=true → 阻塞 9.3s → {"waited":true,"timeout":false,"value":"方案丙
|
||||
```
|
||||
|
||||
- 用户直接关掉界面(没点任何按钮)→ `value=""` + `closed=true`
|
||||
- 超时 → `timeout=true`,提示词里明确要求**别反复重弹**
|
||||
- 只有显式设了 `timeout` 才可能 `timeout=true`,提示词里要求**别反复重弹**
|
||||
|
||||
### ★ 实现上的一个竞态
|
||||
|
||||
|
||||
BIN
docs/screenshots/markdown-table.png
Normal file
BIN
docs/screenshots/markdown-table.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 123 KiB |
BIN
docs/screenshots/nodekit-node-shapes.png
Normal file
BIN
docs/screenshots/nodekit-node-shapes.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 98 KiB |
@@ -207,6 +207,10 @@ App 侧的 `ui/MeetNodeKit.kt` 是**唯一一层胶水**:把 `MeetingNode` 转
|
||||
| `Terminal` 上边切角 | 到这里结束 | `end` |
|
||||
| `Rect` 圆角矩形 | 普通动作 | `agent` `var` `py` `custom` |
|
||||
|
||||
「加节点」面板里就是这样(从上到下:帽形 / 矩形 / 菱形 / 终点 / 矩形 / 胶囊):
|
||||
|
||||

|
||||
|
||||
**形状是"圆角矩形 + 局部变形",不是纯菱形/纯六边形** —— 因为卡片里要装东西
|
||||
(标题栏 24 + 引脚行 21×N + 内容 34),画成尖菱形四个角全是空的,而引脚必须紧贴
|
||||
左右边缘(那是连线的出发点,不能为了形状把线挪走)。
|
||||
|
||||
72
scripts/probe-ask-user-forever.py
Normal file
72
scripts/probe-ask-user-forever.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""验证:`ask_user` 弹窗**不限时**(用户要求"AI 询问界面不要限时")。
|
||||
|
||||
## 怎么验
|
||||
|
||||
以前是 120 秒到点自己消失。所以要证明"改了",必须**跨过 120 秒那条线**:
|
||||
调一次 ask_user,然后在 5 秒 / 130 秒两个时刻截图:
|
||||
|
||||
· 5 秒:弹窗在(说明调通了)
|
||||
· 130 秒:**弹窗还在**(说明真的不限时了。旧版这时候已经没了)
|
||||
· 再点一下选项:请求返回,`timeout` 是 false、`choice` 是点的那个
|
||||
|
||||
★ 这个脚本会**阻塞到用户点为止**(那正是它要测的东西),所以必须后台跑。
|
||||
|
||||
用法:
|
||||
adb forward tcp:15199 tcp:5199
|
||||
python scripts/probe-ask-user-forever.py
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=900):
|
||||
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 main():
|
||||
print("调 ask_user —— 这个请求会一直挂着,直到有人在弹窗上点一下", flush=True)
|
||||
t0 = time.time()
|
||||
try:
|
||||
r = call("/api/tools/run", {
|
||||
"name": "ask_user",
|
||||
"args": {
|
||||
"question": "不限时测试:随便点一个(我不催你)",
|
||||
"options": [
|
||||
{"label": "选项 A", "value": "A"},
|
||||
{"label": "选项 B", "value": "B"},
|
||||
{"label": "选项 C", "value": "C"},
|
||||
],
|
||||
},
|
||||
}, timeout=900)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"!! 请求失败({time.time() - t0:.1f} 秒后):{exc}", flush=True)
|
||||
return 1
|
||||
|
||||
dt = time.time() - t0
|
||||
print(f"\n等了 {dt:.1f} 秒才返回(旧版 120 秒就会 timeout)", flush=True)
|
||||
print(json.dumps(r, ensure_ascii=False)[:500], flush=True)
|
||||
|
||||
if dt > 125 and not (r.get("result") or {}).get("timeout"):
|
||||
print("\n✅ 不限时生效:超过 120 秒仍然等到了用户的选择", flush=True)
|
||||
return 0
|
||||
print("\n? 结果需要人工看一眼(可能点得太快,或 timeout 语义不对)", flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -21,6 +21,15 @@ import sys
|
||||
import urllib.error
|
||||
import urllib.request as u
|
||||
|
||||
# ★★ 不加重定向的话,Windows 控制台默认 GBK,脚本里那些 `✓` 会直接
|
||||
# UnicodeEncodeError 崩掉 —— 而且**崩在创建 release 之后、传附件之前**:
|
||||
# 结果是"release 建好了、说明也写上了,就是没有 APK"。
|
||||
# 这个坑真踩过(v2.0.44 发版时),所以所有会打 ✓ 的脚本都要这一行。
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
API = 'http://192.168.100.103:8080/api/v1/repos/l/doubao-clone'
|
||||
# ★ 凭据不从仓库读(仓库是公开的)。要发版就先把这两个环境变量设上:
|
||||
|
||||
266
scripts/verify-timeouts.py
Normal file
266
scripts/verify-timeouts.py
Normal file
@@ -0,0 +1,266 @@
|
||||
"""守门:**所有超时都是可调的**(用户要求"全部超时做成可调")。
|
||||
|
||||
## 为什么需要这个脚本
|
||||
|
||||
超时这件事以前散在 10 个文件里当模块级常量,谁也不知道一共有几个 ——
|
||||
所以"哪些能调、哪些不能调"根本回答不了。收进 `timeouts.py` 之后,
|
||||
这个脚本负责钉住两件事:
|
||||
|
||||
A. **清单是完整的**:每一项都有默认值 + 边界 + 说明,界面拿得到
|
||||
B. **没有漏网的硬编码**:内核里不该再出现写死的超时数字
|
||||
(这是最容易回退的地方 —— 下次谁顺手写个 `timeout=30` 就又多一个调不了的)
|
||||
|
||||
B 是重点。"查硬编码"必然会有误报(`join(timeout=2)` 这种内部清理、
|
||||
`proc.wait(timeout=3)`),所以用一个**白名单**显式列出允许的例外,
|
||||
并且要求每条例外都在代码里带注释说明为什么不用可调 —— 而不是靠正则蒙。
|
||||
|
||||
用法:
|
||||
python scripts/verify-timeouts.py
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
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")
|
||||
TOOLS = os.path.join(REPO, "tools")
|
||||
sys.path.insert(0, KERNEL)
|
||||
|
||||
fails = []
|
||||
warns = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
def warn(m):
|
||||
warns.append(m)
|
||||
print(f" ! {m}")
|
||||
|
||||
|
||||
import timeouts as TO # noqa: E402
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# A. 清单本身
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("=== A. 超时清单 ===")
|
||||
|
||||
if set(TO.DEFAULT) == set(TO.BY_KEY):
|
||||
ok(f"{len(TO.DEFAULT)} 项:默认值和说明一一对应")
|
||||
else:
|
||||
only_default = sorted(set(TO.DEFAULT) - set(TO.BY_KEY))
|
||||
only_spec = sorted(set(TO.BY_KEY) - set(TO.DEFAULT))
|
||||
if only_default:
|
||||
fail(f"这些有默认值但没有说明(界面会少一行):{only_default}")
|
||||
if only_spec:
|
||||
fail(f"这些有说明但没有默认值:{only_spec}")
|
||||
|
||||
for spec in TO.SPECS:
|
||||
for field in ("key", "label", "group", "desc", "default", "min", "max", "unit"):
|
||||
if field not in spec:
|
||||
fail(f"{spec.get('key')} 少了字段 {field}")
|
||||
if spec["min"] > spec["default"] or spec["default"] > spec["max"]:
|
||||
fail(f"{spec['key']} 的默认值 {spec['default']} 不在 [{spec['min']}, {spec['max']}] 里")
|
||||
|
||||
groups = sorted({s["group"] for s in TO.SPECS})
|
||||
ok(f"分组:{' / '.join(groups)}")
|
||||
|
||||
# 边界的实际效果:填什么都不该炸
|
||||
print("\n=== 边界(用户输入的容错)===")
|
||||
cases = [
|
||||
("tool", "abc", "文字"),
|
||||
("tool", "", "空串"),
|
||||
("tool", -5, "负数"),
|
||||
("tool", 999999, "超大值"),
|
||||
("tool", "60秒", "带单位"),
|
||||
("tool", None, "None"),
|
||||
("model", 0, "0"),
|
||||
]
|
||||
for key, raw, label in cases:
|
||||
try:
|
||||
got = TO.coerce(key, raw)
|
||||
spec = TO.BY_KEY[key]
|
||||
if spec["min"] <= got <= spec["max"]:
|
||||
ok(f"{label:>8} → {got:g}(夹在 [{spec['min']}, {spec['max']}] 内)")
|
||||
else:
|
||||
fail(f"{label} 算出来 {got},越界了")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
fail(f"{label} 把 coerce 弄炸了:{exc}")
|
||||
|
||||
# 「不限时」只给该给的项
|
||||
zero_ok = sorted(k for k, s in TO.BY_KEY.items() if s["min"] == 0)
|
||||
if zero_ok == ["askUser", "tool", "waitUi"]:
|
||||
ok(f"允许「不限时」的只有:{zero_ok}")
|
||||
else:
|
||||
fail(f"允许 min=0 的项不对:{zero_ok}(应该只有等用户的那两项 + 工具执行)")
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# B. 没有漏网的硬编码
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("\n=== B. 内核里的硬编码超时 ===")
|
||||
|
||||
# 允许的例外:内部清理用的短超时 / 探测。
|
||||
# 每一条都必须能在源码里找到一句说明"为什么它不用可调"。
|
||||
ALLOWED = {
|
||||
"mcp_client.py": [
|
||||
# 进程退出时等它自己收尾,跟用户可感知的"等多久"无关
|
||||
(r"proc\.wait\(timeout=3\)", "关进程时的收尾等待"),
|
||||
(r"_thread\.join\(timeout=2\)", "收线程时的收尾等待"),
|
||||
(r"_thread\.join\(timeout=", "收线程时的收尾等待"),
|
||||
],
|
||||
"providers.py": [
|
||||
(r"return 180\.0", "读设置失败时的兜底值"),
|
||||
],
|
||||
"speech.py": [
|
||||
(r"return 60\.0", "读设置失败时的兜底值"),
|
||||
(r"return 120\.0", "读设置失败时的兜底值"),
|
||||
],
|
||||
"timeouts.py": [
|
||||
(r".*", "它就是定义超时的那个文件"),
|
||||
],
|
||||
"doubao_entry.py": [
|
||||
(r"_TERMUX_FIRST_PROBE_S", "第一次探测 Termux 可用性的短超时"),
|
||||
],
|
||||
"main.py": [
|
||||
# 主线程每秒醒一次看"要不要停机" —— 这是**轮询间隔**不是超时,
|
||||
# 调它没有任何用户可感知的意义
|
||||
(r"stop\.wait\(1\)", "停机轮询间隔"),
|
||||
],
|
||||
}
|
||||
|
||||
# 形如 timeout=30 / timeout: float = 60 / join(10) / wait(15) 的写法
|
||||
PAT = re.compile(
|
||||
r"(?:timeout\s*[:=]\s*|\.join\(\s*|\.wait\(\s*|\.wait\(timeout\s*=\s*)"
|
||||
r"(\d+(?:\.\d+)?)\b"
|
||||
)
|
||||
# 本来就该带数字的地方(这些不是"超时")
|
||||
SKIP_LINE = re.compile(r"TIMEOUT_KEYS|'timeout'|\"timeout\"|#|timeouts\.get|budget|api/v1|version")
|
||||
|
||||
checked = 0
|
||||
for name in sorted(os.listdir(KERNEL)):
|
||||
if not name.endswith(".py"):
|
||||
continue
|
||||
if name in ("builtin_tools.py",):
|
||||
# 这里的 join(timeout_s) 是**实现超时机制本身**,不是某个超时值
|
||||
continue
|
||||
path = os.path.join(KERNEL, name)
|
||||
with io.open(path, encoding="utf-8") as fh:
|
||||
for lineno, line in enumerate(fh, 1):
|
||||
if SKIP_LINE.search(line):
|
||||
continue
|
||||
for m in PAT.finditer(line):
|
||||
checked += 1
|
||||
allowed = any(re.search(pat, line) for pat, _ in ALLOWED.get(name, []))
|
||||
if allowed:
|
||||
continue
|
||||
fail(f"{name}:{lineno} 写死了超时 {m.group(0).strip()}:{line.strip()[:70]}")
|
||||
|
||||
if checked and not fails:
|
||||
ok(f"扫了 {len(os.listdir(KERNEL))} 个内核文件,没有调不了的硬编码超时")
|
||||
elif not checked:
|
||||
warn("一条 timeout=数字 都没扫到 —— 正则可能失效了,检查一下")
|
||||
|
||||
# tools/ 下的工具:它们的默认值必须是**兜底**,真值由内核注入
|
||||
print("\n=== C. 工具侧的默认值只是兜底 ===")
|
||||
for tool, key in (("ask_user.py", "askUser"), ("show_ui.py", "waitUi")):
|
||||
with io.open(os.path.join(TOOLS, tool), encoding="utf-8") as fh:
|
||||
src = fh.read()
|
||||
if "TIMEOUT_KEYS" in src and key in src:
|
||||
ok(f"{tool} 声明了 TIMEOUT_KEYS(内核会把设置里的值注入进去)")
|
||||
else:
|
||||
fail(f"{tool} 没声明 TIMEOUT_KEYS —— 设置里那一项对它无效")
|
||||
|
||||
import tools_runtime as TR # noqa: E402
|
||||
|
||||
if "TIMEOUT_KEYS" in __import__("inspect").getsource(TR._with_default_timeouts):
|
||||
ok("tools_runtime 会按 TIMEOUT_KEYS 注入默认值")
|
||||
else:
|
||||
fail("tools_runtime 的注入逻辑不见了")
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# D. Node 端那份必须和 Python 这份逐项一致
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("\n=== D. Node 端(server/src/timeouts.mjs)对拍 ===")
|
||||
|
||||
import json # noqa: E402
|
||||
import subprocess # noqa: E402
|
||||
|
||||
NODE_PROBE = (
|
||||
"import('./server/src/timeouts.mjs').then(m => "
|
||||
"console.log(JSON.stringify({d: m.DEFAULT_TIMEOUTS, s: m.TIMEOUT_SPECS})))"
|
||||
)
|
||||
proc = None
|
||||
try:
|
||||
# ★ encoding 必须显式给 utf-8:node 输出的是 UTF-8,而这台机器的
|
||||
# locale 是 GBK —— 用 text=True 的默认编码去解会把中文解崩
|
||||
# (表现是 stdout 读不出来,还看不出是编码问题)。
|
||||
proc = subprocess.run(
|
||||
["node", "--input-type=module", "-e", NODE_PROBE],
|
||||
cwd=REPO, capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace", timeout=60,
|
||||
)
|
||||
raw = (proc.stdout or "").strip().splitlines()
|
||||
data = json.loads(raw[-1]) if raw else None
|
||||
except Exception as exc: # noqa: BLE001
|
||||
data = None
|
||||
warn(f"跑不了 node 对拍({exc})—— 跳过这一节")
|
||||
|
||||
if data is None:
|
||||
detail = ""
|
||||
if proc is not None:
|
||||
detail = (f"(退出码 {proc.returncode},stdout={(proc.stdout or '')[:120]!r},"
|
||||
f"stderr={(proc.stderr or '')[:200]!r})")
|
||||
warn(f"node 探测没拿到结果{detail} —— 跳过这一节")
|
||||
else:
|
||||
js_default = data["d"]
|
||||
js_specs = {s["key"]: s for s in data["s"]}
|
||||
|
||||
if set(js_default) == set(TO.DEFAULT):
|
||||
ok(f"默认值的键两边一致(各 {len(js_default)} 项)")
|
||||
else:
|
||||
only_py = sorted(set(TO.DEFAULT) - set(js_default))
|
||||
only_js = sorted(set(js_default) - set(TO.DEFAULT))
|
||||
if only_py:
|
||||
fail(f"Python 有、Node 没有的项:{only_py}")
|
||||
if only_js:
|
||||
fail(f"Node 有、Python 没有的项:{only_js}")
|
||||
|
||||
if set(js_specs) == set(TO.BY_KEY):
|
||||
ok("说明表的键两边一致")
|
||||
else:
|
||||
fail(f"说明表对不上:Node 独有 {sorted(set(js_specs) - set(TO.BY_KEY))},"
|
||||
f"Python 独有 {sorted(set(TO.BY_KEY) - set(js_specs))}")
|
||||
|
||||
diff = 0
|
||||
for key, spec in TO.BY_KEY.items():
|
||||
js = js_specs.get(key)
|
||||
if not js:
|
||||
continue
|
||||
for field in ("label", "group", "default", "min", "max"):
|
||||
if spec.get(field) != js.get(field):
|
||||
diff += 1
|
||||
fail(f"{key}.{field} 不一致:Python {spec.get(field)!r} vs Node {js.get(field)!r}")
|
||||
if not diff:
|
||||
ok("每一项的 名字 / 分组 / 默认值 / 上下界 都一致")
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print(f"✅ 全部通过(警告 {len(warns)} 条)")
|
||||
@@ -295,6 +295,85 @@ else:
|
||||
else:
|
||||
fail("run_agent 没按开关追加提示词")
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ★★ 会等用户的工具必须**豁免工具超时**
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 用户要求"AI 询问界面不要限时"。这个需求**要三处一起改才算数**:
|
||||
# ① 界面侧等多久(AiSurface.ask / showScreen)
|
||||
# ② 内核侧给工具多少时间(timeouts.tool,设置里可调)
|
||||
# ③ 工具自己声明的 timeout
|
||||
# 只改 ①③ 的后果实测过:弹窗 135 秒还开着,**但工具调用 60 秒就被内核判超时**,
|
||||
# 模型收到"工具执行超时(60s)",用户五分钟后点的选项根本回不到模型手里 ——
|
||||
# 表现是"弹窗还在、AI 已经自己往下写了"。这种"看起来改了其实没生效"最坑,
|
||||
# 所以在这里钉住。
|
||||
print("\n=== 等用户的工具不被工具超时掐掉 ===")
|
||||
|
||||
import inspect # noqa: E402 - 上面那个分支里才 import,这里保证一定有
|
||||
|
||||
import tools_runtime as TR
|
||||
|
||||
for tool_name in ("ask_user", "show_ui"):
|
||||
path = os.path.join(TOOLS, f"{tool_name}.py")
|
||||
src = open(path, encoding="utf-8").read()
|
||||
if "WAIT_FOR_USER = True" in src:
|
||||
ok(f"{tool_name}.py 声明了 WAIT_FOR_USER = True")
|
||||
else:
|
||||
fail(f"{tool_name}.py 没声明 WAIT_FOR_USER —— 内核会在 60 秒时把这次调用判超时")
|
||||
|
||||
if hasattr(TR, "_waits_for_user"):
|
||||
ok("tools_runtime 里有 _waits_for_user")
|
||||
else:
|
||||
fail("tools_runtime 没有 _waits_for_user,豁免逻辑不见了")
|
||||
|
||||
_src = inspect.getsource(TR.run_python_tool)
|
||||
if "_waits_for_user" in _src and "budget" in _src:
|
||||
ok("run_python_tool 是按它决定超时预算的")
|
||||
else:
|
||||
fail("run_python_tool 没用 _waits_for_user 决定预算")
|
||||
|
||||
# 引擎侧:0 必须真的等于"不限时"
|
||||
import builtin_tools as BT
|
||||
|
||||
if "thread.join()" in inspect.getsource(BT.run_with_timeout):
|
||||
ok("run_with_timeout 支持 timeout<=0 = 不限时")
|
||||
else:
|
||||
fail("run_with_timeout 不支持不限时(join 那支不见了)")
|
||||
|
||||
# 仿真一遍:给一个"永远不返回"的任务配 0 预算,它必须**不返回**
|
||||
# (真跑起来要等到天荒地老,所以这里用一个 20ms 后自己结束的任务代替,
|
||||
# 验证的是"0 走的是无限等待那支"而不是"0 立刻超时")
|
||||
import threading as _th
|
||||
|
||||
_done = _th.Event()
|
||||
|
||||
|
||||
def _slow():
|
||||
_done.wait(0.05)
|
||||
return "ok"
|
||||
|
||||
|
||||
_r = BT.run_with_timeout(_slow, 0)
|
||||
if _r == "ok":
|
||||
ok("预算 0 时会一直等到任务真的跑完(不是立刻超时)")
|
||||
else:
|
||||
fail(f"预算 0 的行为不对,拿到 {_r!r}")
|
||||
|
||||
# 反面:非豁免工具的预算仍然来自设置(死循环的安全网还在,别为了这个把超时全关了)
|
||||
# ★ 这里查的是"预算从 timeouts 读",不是"等于 60" —— 60 现在是**默认值**,
|
||||
# 用户可以在「设置 → 超时 → 工具执行」里改。
|
||||
if "timeouts.get('tool')" in _src:
|
||||
ok("普通工具的预算来自设置项 timeouts.tool(默认 60 秒,死循环的安全网没丢)")
|
||||
else:
|
||||
fail("run_python_tool 没从 timeouts 读工具预算")
|
||||
|
||||
import timeouts as TO
|
||||
|
||||
if TO.get("tool") == 60 and TO.BY_KEY["tool"]["min"] == 0:
|
||||
ok("工具执行超时的默认值 60 秒、且允许 0(不限时)")
|
||||
else:
|
||||
fail(f"timeouts.tool 的默认值/边界不对:默认 {TO.get('tool')},min {TO.BY_KEY['tool']['min']}")
|
||||
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
|
||||
@@ -311,6 +311,10 @@ export const DEFAULT_SETTINGS = {
|
||||
openaiBaseUrl: '', // 留空则复用主对话的 Base URL
|
||||
ttsModel: 'tts-1',
|
||||
},
|
||||
// 超时。**这里故意是空的** —— 默认值全在 timeouts.mjs 的 DEFAULT_TIMEOUTS 里,
|
||||
// 只有用户改过的项才会出现在这儿(和默认一样就删掉,见 patchTimeouts)。
|
||||
// 和 Python 端 config 的 'timeouts': {} 一致。
|
||||
timeouts: {},
|
||||
pythonBin: '',
|
||||
nickname: '我',
|
||||
doubaoId: '378269252',
|
||||
@@ -354,6 +358,12 @@ export function readSettings() {
|
||||
};
|
||||
}
|
||||
if (!Array.isArray(settings.security.allow)) settings.security.allow = [];
|
||||
// ★ timeouts 走**整体替换**(和 Python 端 store.py 一致):
|
||||
// 默认值在 timeouts.mjs 里,深合并会让"改回默认 = 删掉这一项"永远删不掉,
|
||||
// 旧值残留在配置里,用户会看到"我明明恢复默认了怎么还是 30 秒"。
|
||||
if (typeof settings.timeouts !== 'object' || settings.timeouts === null || Array.isArray(settings.timeouts)) {
|
||||
settings.timeouts = {};
|
||||
}
|
||||
|
||||
// 环境变量兜底:没填 key 时用 .env 里的
|
||||
const preset = PROVIDER_PRESETS[settings.provider];
|
||||
@@ -406,6 +416,16 @@ export function writeSettings(patch) {
|
||||
console.error(`[config] 补丁里的 ${key} 不是对象(${typeof v}),已忽略`);
|
||||
}
|
||||
}
|
||||
// ★ timeouts 是**整体替换**,不深合并 —— 和 Python 端同一套语义。
|
||||
// 调用方(/api/timeouts)传进来的就是"完整的非默认集合"。
|
||||
if ('timeouts' in clean) {
|
||||
const t = clean.timeouts;
|
||||
if (t && typeof t === 'object' && !Array.isArray(t)) next.timeouts = t;
|
||||
else {
|
||||
next.timeouts = current.timeouts || {};
|
||||
console.error(`[config] 补丁里的 timeouts 不是对象(${typeof t}),已忽略`);
|
||||
}
|
||||
}
|
||||
// 掩码值表示"不修改"
|
||||
if (clean.apiKey === '••••••••') next.apiKey = current.apiKey;
|
||||
// ★ 语音里的密钥同理:界面读到的是掩码,用户不改语音设置直接保存时掩码会跟着回来,
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
readSettings,
|
||||
writeSettings,
|
||||
} from './config.mjs';
|
||||
import { patchTimeouts, resolvedTimeouts, timeoutsCatalog } from './timeouts.mjs';
|
||||
import * as store from './store.mjs';
|
||||
import { listAllTools, runAgent, executeTool, suggestAllowlist } from './agent.mjs';
|
||||
import {
|
||||
@@ -589,6 +590,34 @@ async function handleApi(req, res, url) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- 超时(设置 → 超时)----
|
||||
// ★ 和 Python 内核的 /api/timeouts 行为一致:清单由服务端给(界面不硬编码
|
||||
// 有哪些超时),写的时候是**整体替换**(默认值在 timeouts.mjs 里,
|
||||
// "改回默认" = 从配置里删掉这一项)。
|
||||
if (pathname === '/api/timeouts' && method === 'GET') {
|
||||
const settings = readSettings();
|
||||
sendJson(res, 200, {
|
||||
ok: true,
|
||||
items: timeoutsCatalog(settings),
|
||||
values: resolvedTimeouts(settings),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname === '/api/timeouts' && (method === 'PUT' || method === 'POST')) {
|
||||
const body = await readBody(req);
|
||||
const current = readSettings();
|
||||
const nextValues = body.reset ? {} : patchTimeouts(current, body.values || body);
|
||||
writeSettings({ timeouts: nextValues });
|
||||
const after = readSettings();
|
||||
sendJson(res, 200, {
|
||||
ok: true,
|
||||
items: timeoutsCatalog(after),
|
||||
values: resolvedTimeouts(after),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pathname === '/api/models' && method === 'GET') {
|
||||
const settings = readSettings();
|
||||
try {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* MCP(Model Context Protocol)客户端管理。
|
||||
*
|
||||
* tools/mcp.servers.json 描述要连接的服务:
|
||||
@@ -9,7 +9,8 @@
|
||||
* 对外暴露的工具名统一为 mcp__<server>__<tool>,避免和 Python 工具重名。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import { MCP_FILE } from './config.mjs';
|
||||
import { MCP_FILE, readSettings } from './config.mjs';
|
||||
import { timeoutOf } from './timeouts.mjs';
|
||||
|
||||
const clients = new Map(); // serverName -> { client, transport, tools, error, spec }
|
||||
|
||||
@@ -149,8 +150,9 @@ export async function connect(serverName, { force = false } = {}) {
|
||||
}
|
||||
const client = new sdk.Client({ name: 'doubao-kernel', version: '0.1.0' }, { capabilities: {} });
|
||||
// 首次用 npx 拉起服务器时要下载包,可能远超 SDK 默认的 60s 超时
|
||||
await client.connect(transport, { timeout: 180000 });
|
||||
const listed = await client.listTools(undefined, { timeout: 60000 });
|
||||
// ★ 超时可调(设置 → 超时 → MCP 连接)。npx/uvx 第一次要下载,默认给到 180 秒
|
||||
await client.connect(transport, { timeout: timeoutOf(readSettings(), 'mcpConnect') * 1000 });
|
||||
const listed = await client.listTools(undefined, { timeout: timeoutOf(readSettings(), 'mcpRequest') * 1000 });
|
||||
record.client = client;
|
||||
record.transport = transport;
|
||||
record.tools = listed.tools || [];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* 提供商调用层:火山方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter …
|
||||
* 全都是 OpenAI 兼容协议,所以这里只有一份实现。
|
||||
* 统一暴露:
|
||||
@@ -7,7 +7,8 @@
|
||||
* listModels() - 拉取模型列表(可选能力,失败不致命)
|
||||
*/
|
||||
|
||||
import { PROVIDER_PRESETS } from './config.mjs';
|
||||
import { PROVIDER_PRESETS, readSettings } from './config.mjs';
|
||||
import { timeoutOf } from './timeouts.mjs';
|
||||
|
||||
function joinUrl(baseUrl, suffix) {
|
||||
return `${String(baseUrl || '').replace(/\/+$/, '')}${suffix}`;
|
||||
@@ -86,7 +87,10 @@ function buildBody({ provider, model, messages, tools, temperature, stream, thin
|
||||
return normalizeBody({ provider, model, thinkingLevel, body });
|
||||
}
|
||||
|
||||
async function post({ baseUrl, apiKey, body, signal, timeoutMs = 180000 }) {
|
||||
async function post({ baseUrl, apiKey, body, signal, timeoutMs = null }) {
|
||||
// ★ 超时可调(设置 → 超时 → 等模型回复)。JS 的默认参数是**每次调用**求值的,
|
||||
// 所以这里现读就能立刻生效(不用重启)。
|
||||
if (!timeoutMs) timeoutMs = timeoutOf(readSettings(), 'model') * 1000;
|
||||
if (!apiKey) {
|
||||
throw new Error('缺少 API Key:请在「设置 → AI 内核」里填写,或在 server/.env 里配置');
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* Python 工具运行时。
|
||||
*
|
||||
* 工具即 tools/*.py,每个文件用 `_protocol.serve(TOOL, run)` 暴露能力:
|
||||
@@ -15,6 +15,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { TMP_DIR, TOOLS_DIR, readSettings } from './config.mjs';
|
||||
import { timeoutOf } from './timeouts.mjs';
|
||||
|
||||
const specCache = new Map(); // file -> { mtimeMs, spec, error }
|
||||
|
||||
@@ -205,7 +206,7 @@ async function runPythonToolWithFile(tool, py, args) {
|
||||
bin: py.bin,
|
||||
args: [...py.prefix, tool.__file, '--input', inPath],
|
||||
input: '',
|
||||
timeoutMs: 60000,
|
||||
timeoutMs: timeoutOf(readSettings(), 'tool') * 1000,
|
||||
cwd: toolsDir(),
|
||||
});
|
||||
try {
|
||||
@@ -231,7 +232,7 @@ async function runPythonToolWithFile(tool, py, args) {
|
||||
}
|
||||
return {
|
||||
ok: res.code === 0,
|
||||
error: res.timedOut ? '工具执行超时(60s)' : `未解析到 JSON 输出(退出码 ${res.code})`,
|
||||
error: res.timedOut ? `工具执行超时(${Math.round(timeoutOf(readSettings(), 'tool'))}s,可在设置里调)` : `未解析到 JSON 输出(退出码 ${res.code})`,
|
||||
stdout: res.stdout.slice(0, 2000),
|
||||
stderr: res.stderr.slice(0, 2000),
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* 语音:朗读(TTS)和语音识别(STT)。
|
||||
*
|
||||
* 对应 Python 版 android/kernel/speech.py —— 两份实现的请求体、返回字段、错误文案
|
||||
@@ -17,6 +17,8 @@
|
||||
|
||||
// 全量音色表(抓官方文档生成)。常用精选在下面,界面上是"常用 + 全部可搜索"两段式。
|
||||
import { VOLC_VOICES_ALL, VOLC_V3_SPEAKERS_ALL } from './voices_doubao.mjs';
|
||||
import { readSettings } from './config.mjs';
|
||||
import { timeoutOf } from './timeouts.mjs';
|
||||
|
||||
/** V1 合成接口(appid + access_token,Bearer 后面是分号)。自测时可指到 mock */
|
||||
export const VOLC_TTS_URL = process.env.DOUBAO_VOLC_TTS_URL || 'https://openspeech.bytedance.com/api/v1/tts';
|
||||
@@ -57,8 +59,11 @@ export const VOLC_V3_TTS_URL = process.env.DOUBAO_VOLC_V3_TTS_URL
|
||||
|| 'https://openspeech.bytedance.com/api/v3/tts/unidirectional';
|
||||
export const VOLC_V3_RESOURCE_ID = 'seed-tts-2.0';
|
||||
|
||||
const TIMEOUT_TTS = 60000;
|
||||
const TIMEOUT_STT = 120000;
|
||||
// ★ ★ 超时可调(设置 → 超时 → 语音合成 / 语音识别)。**现读**,改完立刻生效,
|
||||
// 不用重启。默认值在 timeouts.mjs 里,和 Python 内核那份逐字对应。
|
||||
// 以前这里是两个模块级常量(60000 / 120000),网络慢或回复长的时候用户只能忍着。
|
||||
const ttsTimeoutMs = () => timeoutOf(readSettings(), 'tts') * 1000;
|
||||
const sttTimeoutMs = () => timeoutOf(readSettings(), 'stt') * 1000;
|
||||
|
||||
const VOLC_MIME = {
|
||||
mp3: 'audio/mpeg',
|
||||
@@ -360,7 +365,7 @@ async function synthesizeVolcV3(text, speech, speed) {
|
||||
'X-Control-Require-Usage-Tokens-Return': '*',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
}, TIMEOUT_TTS);
|
||||
}, ttsTimeoutMs());
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上火山 V3:${err.message}`);
|
||||
}
|
||||
@@ -438,7 +443,7 @@ async function synthesizeVolc(text, speech, speed) {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer;${token}` },
|
||||
body: JSON.stringify(body),
|
||||
}, TIMEOUT_TTS);
|
||||
}, ttsTimeoutMs());
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上:${err.message}`);
|
||||
}
|
||||
@@ -472,7 +477,7 @@ async function synthesizeOpenai(text, settings, speech, speed) {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
|
||||
body: JSON.stringify({ model, input: text, voice, response_format: format, speed }),
|
||||
}, TIMEOUT_TTS);
|
||||
}, ttsTimeoutMs());
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上:${err.message}`);
|
||||
}
|
||||
@@ -511,7 +516,7 @@ export async function transcribe(audio, filename, contentType, settings) {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
body: form,
|
||||
}, TIMEOUT_STT);
|
||||
}, sttTimeoutMs());
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上:${err.message}`);
|
||||
}
|
||||
|
||||
210
server/src/timeouts.mjs
Normal file
210
server/src/timeouts.mjs
Normal file
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* 所有超时的定义 —— **和 Python 内核的 `android/kernel/timeouts.py` 逐字对应**。
|
||||
*
|
||||
* ## 为什么两端各写一份,而不是共享
|
||||
*
|
||||
* 因为一个是 Python、一个是 JS,没法共享代码。这是这个仓库里跨语言一致性的
|
||||
* 标准做法:**两边都写 + 一个脚本盯着**(`scripts/verify-timeouts.py` 会把
|
||||
* 这份和 Python 那份逐项对拍:key / label / 分组 / 默认值 / 上下界)。
|
||||
*
|
||||
* 对拍的不是"默认值"那么简单 —— 默认值不一致的表现最难查:
|
||||
* Web 端说 60 秒、安卓端说 30 秒,同一句"命令超时"在两个端上根本不是一回事。
|
||||
*
|
||||
* ## 用户要"全部超时做成可调"
|
||||
*
|
||||
* 所以这份同时是**界面数据的来源**(`GET /api/timeouts` 返回的就是它)。
|
||||
* 加一项超时:这里加一条 + Python 那份加一条,跑一次对拍脚本。
|
||||
*/
|
||||
|
||||
/** 默认值 —— 和 Python 的 `DEFAULT` 一一对应 */
|
||||
export const DEFAULT_TIMEOUTS = {
|
||||
// ---- 对话 ----
|
||||
model: 180,
|
||||
sseRead: 120,
|
||||
heartbeat: 15,
|
||||
kernelLocal: 10,
|
||||
// ---- 工具 ----
|
||||
tool: 60,
|
||||
shell: 30,
|
||||
pythonRun: 60,
|
||||
termux: 30,
|
||||
meetingNode: 10,
|
||||
customNode: 10,
|
||||
// ---- 界面(等用户)----
|
||||
askUser: 0,
|
||||
waitUi: 0,
|
||||
filePicker: 120,
|
||||
// ---- 语音 ----
|
||||
tts: 60,
|
||||
stt: 120,
|
||||
// ---- MCP ----
|
||||
mcpRequest: 60,
|
||||
mcpConnect: 180,
|
||||
mcpTool: 120,
|
||||
};
|
||||
|
||||
/** 每一项的说明(界面直接用) */
|
||||
export const TIMEOUT_SPECS = [
|
||||
{
|
||||
key: 'model', group: '对话', label: '等模型回复',
|
||||
default: 180, min: 10, max: 1800, unit: '秒',
|
||||
desc: '发出去到开始收到第一个字的最长等待。深度思考的模型(R1 这类)'
|
||||
+ '经常要想一分钟以上,调小了会频繁断在半路;本地小模型可以调大。',
|
||||
},
|
||||
{
|
||||
key: 'sseRead', group: '对话', label: '连接空闲上限',
|
||||
default: 120, min: 20, max: 3600, unit: '秒',
|
||||
desc: '手机上"多久没收到任何数据就断开"。内核每【心跳间隔】秒发一次心跳,'
|
||||
+ '所以这个值必须比心跳间隔大不少 —— 内核发的就是心跳间隔那项。'
|
||||
+ '弱网/代理会悄悄掐长连接,可以把两个都调小一点,断得早反而好重连。',
|
||||
},
|
||||
{
|
||||
key: 'heartbeat', group: '对话', label: '心跳间隔',
|
||||
default: 15, min: 5, max: 300, unit: '秒',
|
||||
desc: '对话过程中内核每隔这么久发一个空包,证明连接还活着。'
|
||||
+ '调大了在弱网下容易被中间设备当成死连接掐掉;调小了费电。',
|
||||
},
|
||||
{
|
||||
key: 'kernelLocal', group: '对话', label: '本地接口请求',
|
||||
default: 10, min: 3, max: 300, unit: '秒',
|
||||
desc: '界面调内核的普通接口(读会话、存设置、拉笔记)等多久。'
|
||||
+ '只有老设备 + 会话特别长时才会顶到这个值。',
|
||||
},
|
||||
{
|
||||
key: 'tool', group: '工具', label: '工具执行',
|
||||
default: 60, min: 0, max: 3600, unit: '秒', zero: '不限时',
|
||||
desc: '任意一个 Python 工具最多跑多久。这是"工具里写了死循环"的安全网。\n'
|
||||
+ '填 0 = 不限时。注意:会停下来等你的工具(AI 提问、AI 界面等待)'
|
||||
+ '本来就不受这一项限制 —— 它们的时长取决于你什么时候点。',
|
||||
},
|
||||
{
|
||||
key: 'shell', group: '工具', label: 'shell 命令',
|
||||
default: 30, min: 1, max: 3600, unit: '秒',
|
||||
desc: 'AI 调用内置 shell 工具跑一条命令的最长时间。'
|
||||
+ '装包(pkg install / pip install)这类会超过 30 秒,那时可以让 AI 自己传更长的值。',
|
||||
},
|
||||
{
|
||||
key: 'pythonRun', group: '工具', label: '跑 Python 代码',
|
||||
default: 60, min: 1, max: 3600, unit: '秒',
|
||||
desc: 'AI 写一段 Python 交给内核执行的最长时间。算得久(循环、大文件)就调大。',
|
||||
},
|
||||
{
|
||||
key: 'termux', group: '工具', label: 'Termux 命令',
|
||||
default: 30, min: 1, max: 3600, unit: '秒',
|
||||
desc: '在内置 Termux 环境里跑命令的最长时间。',
|
||||
},
|
||||
{
|
||||
key: 'meetingNode', group: '工具', label: '会议节点',
|
||||
default: 10, min: 1, max: 600, unit: '秒',
|
||||
desc: '会议里一个 Python 节点 / 自定义节点最多跑多久。'
|
||||
+ '这是防死循环的 —— 调太大会让整个会议卡住,建议别超过 60。',
|
||||
},
|
||||
{
|
||||
key: 'customNode', group: '工具', label: '自定义节点',
|
||||
default: 10, min: 1, max: 600, unit: '秒',
|
||||
desc: 'nodes/ 目录里自己写的节点,执行一次的最长时间。',
|
||||
},
|
||||
{
|
||||
key: 'askUser', group: '界面', label: 'AI 提问等多久',
|
||||
default: 0, min: 0, max: 3600, unit: '秒', zero: '不限时',
|
||||
desc: 'AI 弹选择框问你时,等多久算"你没空"。**默认 0 = 一直等**。\n'
|
||||
+ '不建议改:设成有限值后,你去忙一会儿回来,AI 已经按它自己猜的答案'
|
||||
+ '往下写了,而它并不知道自己在猜。',
|
||||
},
|
||||
{
|
||||
key: 'waitUi', group: '界面', label: 'AI 界面等多久',
|
||||
default: 0, min: 0, max: 3600, unit: '秒', zero: '不限时',
|
||||
desc: 'AI 弹的界面在 wait 模式下等你点按钮的时长。**默认 0 = 一直等**。',
|
||||
},
|
||||
{
|
||||
key: 'filePicker', group: '界面', label: '选文件等多久',
|
||||
default: 120, min: 10, max: 3600, unit: '秒',
|
||||
desc: 'AI 让你挑一个文件时,等你挑完的时长。'
|
||||
+ '去相册里翻一张老照片可能不止两分钟,可以调大。',
|
||||
},
|
||||
{
|
||||
key: 'tts', group: '语音', label: '语音合成',
|
||||
default: 60, min: 5, max: 600, unit: '秒',
|
||||
desc: '把回复转成语音的最长等待。长回复、网络慢时要更久。',
|
||||
},
|
||||
{
|
||||
key: 'stt', group: '语音', label: '语音识别',
|
||||
default: 120, min: 5, max: 600, unit: '秒',
|
||||
desc: '把录音转成文字的最长等待。录音越长越久。',
|
||||
},
|
||||
{
|
||||
key: 'mcpRequest', group: 'MCP', label: '单次请求',
|
||||
default: 60, min: 5, max: 600, unit: '秒',
|
||||
desc: '和 MCP 服务说话时,单次请求等多久。',
|
||||
},
|
||||
{
|
||||
key: 'mcpConnect', group: 'MCP', label: '连接',
|
||||
default: 180, min: 5, max: 900, unit: '秒',
|
||||
desc: '启动 MCP 服务(npx / uvx 第一次要下载)的最长等待。'
|
||||
+ '第一次装包经常要几分钟,这也是默认给到 180 秒的原因。',
|
||||
},
|
||||
{
|
||||
key: 'mcpTool', group: 'MCP', label: '调用工具',
|
||||
default: 120, min: 5, max: 900, unit: '秒',
|
||||
desc: '调用 MCP 服务里某个工具的最长等待。',
|
||||
},
|
||||
];
|
||||
|
||||
const BY_KEY = new Map(TIMEOUT_SPECS.map((s) => [s.key, s]));
|
||||
|
||||
/**
|
||||
* 把用户填的东西变成合法的秒数。
|
||||
* ★ 容错是必须的:界面上是输入框,可能填 "60秒"、空串、负数、巨大的数。
|
||||
*/
|
||||
export function coerceTimeout(key, raw) {
|
||||
const spec = BY_KEY.get(key);
|
||||
if (!spec) throw new Error(`没有这个超时项:${key}`);
|
||||
let value = spec.default;
|
||||
if (raw !== null && raw !== undefined && raw !== '') {
|
||||
const n = parseFloat(String(raw).trim().replace(/[秒sS]$/, ''));
|
||||
value = Number.isFinite(n) ? n : spec.default;
|
||||
}
|
||||
return Math.min(spec.max, Math.max(spec.min, value));
|
||||
}
|
||||
|
||||
/** 读一项(秒)。0 = 不限时 */
|
||||
export function timeoutOf(settings, key) {
|
||||
const stored = (settings && typeof settings.timeouts === 'object' && settings.timeouts) || {};
|
||||
return coerceTimeout(key, stored[key]);
|
||||
}
|
||||
|
||||
/** 当前生效的全部值 */
|
||||
export function resolvedTimeouts(settings) {
|
||||
const stored = (settings && typeof settings.timeouts === 'object' && settings.timeouts) || {};
|
||||
const out = {};
|
||||
for (const s of TIMEOUT_SPECS) out[s.key] = coerceTimeout(s.key, stored[s.key]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 给界面的清单(说明 + 默认值 + 边界 + 现在是多少) */
|
||||
export function timeoutsCatalog(settings) {
|
||||
const stored = (settings && typeof settings.timeouts === 'object' && settings.timeouts) || {};
|
||||
return TIMEOUT_SPECS.map((s) => ({
|
||||
...s,
|
||||
value: coerceTimeout(s.key, stored[s.key]),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 算出"要存下来的那部分":只含和默认值不同的项。
|
||||
*
|
||||
* ★ 和 Python 的 `patch()` 同一套语义:改回默认 = 从设置里**删掉**这一项,
|
||||
* 这样以后调整默认值时,没动过的用户会跟着新默认走。
|
||||
*/
|
||||
export function patchTimeouts(settings, values) {
|
||||
const stored = (settings && typeof settings.timeouts === 'object' && settings.timeouts) || {};
|
||||
const out = { ...stored };
|
||||
if (!values || typeof values !== 'object') return out;
|
||||
for (const [key, raw] of Object.entries(values)) {
|
||||
if (!BY_KEY.has(key)) continue;
|
||||
const value = coerceTimeout(key, raw);
|
||||
if (Math.abs(value - BY_KEY.get(key).default) < 1e-9) delete out[key];
|
||||
else out[key] = Number.isInteger(value) ? value : value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -10,7 +10,9 @@
|
||||
],
|
||||
"ask_user.py": [
|
||||
"94a9734c8c934db2",
|
||||
"c4728d5dfd765a99"
|
||||
"c4728d5dfd765a99",
|
||||
"3adcd9b3c634cc22",
|
||||
"161cc07b197fdd8b"
|
||||
],
|
||||
"calc.py": [
|
||||
"4d9e5a51ad8f71eb"
|
||||
@@ -37,7 +39,9 @@
|
||||
"ecea108ef1118386",
|
||||
"f80e4da69db41722",
|
||||
"5f11cf92d2a78ce1",
|
||||
"fc8c411abd1addeb"
|
||||
"fc8c411abd1addeb",
|
||||
"a6f1bdaa5de71fcc",
|
||||
"c017a7e950030ca3"
|
||||
],
|
||||
"weather.py": [
|
||||
"bff69719c190d3d9"
|
||||
|
||||
@@ -39,13 +39,28 @@ 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
|
||||
|
||||
# 等用户的秒数。**0 = 不限时**(默认)。
|
||||
# 等用户的秒数。**0 = 不限时**(默认,也是设置里的默认值)。
|
||||
#
|
||||
# ★ 这只是"工具单独跑"时的兜底 —— 真正生效的值来自设置
|
||||
# (设置 → 超时 → AI 提问等多久)。内核调用前会把它注入到 args['timeout'] 里,
|
||||
# 见 tools_runtime._with_default_timeouts 和下面的 TIMEOUT_KEYS。
|
||||
TIMEOUT_S = 0
|
||||
|
||||
# 模型显式传 timeout 时的上限:1 小时。再长没有意义 ——
|
||||
# 用户多半是走了,而内核那条 HTTP 工作线程会一直占着。
|
||||
MAX_TIMEOUT_S = 3600
|
||||
|
||||
# ★★ 告诉内核:这个工具**会停下来等用户**,别拿工具执行超时卡它。
|
||||
#
|
||||
# 不声明的话后果很隐蔽:弹窗还开着(界面侧是不限时的),
|
||||
# 但内核 60 秒就把这次调用判成"工具执行超时"、把结果丢掉了 ——
|
||||
# 用户五分钟后点的那个选项**根本回不到模型手里**,模型已经开始自己编了。
|
||||
# 见 android/kernel/tools_runtime.py 的 _waits_for_user。
|
||||
WAIT_FOR_USER = True
|
||||
|
||||
# "我这个 timeout 参数如果模型没给,就用设置里 askUser 那一项的值"
|
||||
TIMEOUT_KEYS = {'timeout': 'askUser'}
|
||||
|
||||
TOOL = {
|
||||
"name": "ask_user",
|
||||
"description": (
|
||||
|
||||
@@ -29,10 +29,20 @@ 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
|
||||
|
||||
# wait=true 时的等待秒数上限 / 下限。0 = 不限时(默认,见 run)。
|
||||
# wait=true 时的等待秒数上限 / 下限。默认 0 = 不限时(见 run)。
|
||||
MIN_TIMEOUT_S = 5.0
|
||||
MAX_TIMEOUT_S = 3600.0
|
||||
|
||||
# ★★ 告诉内核:这个工具在 wait=true 时**会停下来等用户**,别拿工具执行超时卡它
|
||||
# (wait=false 时它立刻就返回,不受影响)。
|
||||
# 不声明的后果和 ask_user 那边一样:界面还开着,模型却已经收到"工具超时"。
|
||||
# 见 android/kernel/tools_runtime.py 的 _waits_for_user。
|
||||
WAIT_FOR_USER = True
|
||||
|
||||
# "我这个 timeout 参数如果模型没给,就用设置里 waitUi 那一项的值"
|
||||
# (内核调用前注入,见 tools_runtime._with_default_timeouts)
|
||||
TIMEOUT_KEYS = {'timeout': 'waitUi'}
|
||||
|
||||
TOOL = {
|
||||
"name": "show_ui",
|
||||
"description": (
|
||||
|
||||
Reference in New Issue
Block a user