feat: 所有超时收成一份、全部可调(设置 → 超时,18 项)

用户要求"全部超时做成可调"。改造前 15 个超时散在 10 个文件里当模块级常量,
说不清一共有几个,也答不了"哪些能调"。

内核
- 新增 android/kernel/timeouts.py:**超时的唯一一份定义**(DEFAULT + SPECS),
  带每项的 名字/分组/说明/默认值/上下界;get() 一律夹取,用户填什么都不炸
- 新增 GET/POST /api/timeouts(清单 + 当前值 + 保存 + 恢复默认)
- 各处改现读:tools_runtime(tool)、builtin_tools(shell/pythonRun)、
  doubao_entry(termux)、providers(model)、speech(tts/stt)、
  mcp_client(请求/连接/调用)、meeting(meetingNode)、custom_nodes(customNode)、
  app.py 的 SSE 心跳
- ask_user / show_ui 用 TIMEOUT_KEYS 声明"哪个参数该用设置里的值",
  内核调用前注入(工具的默认值退化成单独跑时的兜底)
- store.py:timeouts 走**整体替换**而不是深合并 —— 深合并会让"改回默认"删不掉

安卓
- data/AppTimeouts.kt:客户端缓存(OkHttp 的 readTimeout、文件选择没法现问内核)
- KernelClient:readTimeout 跟着 sseRead 走,改完重建连接池;新增 timeouts 接口
- ui/TimeoutsScreen.kt:全屏界面,按分组列出、-/+ 与输入框、恢复默认
- 设置页加「超时」卡片入口;NativeBridge 的本地接口请求 / 选文件等待接上
- Settings 模型加 TimeoutItem / TimeoutsState(字段全部来自内核)

Node 端(Web/exe)
- 新增 server/src/timeouts.mjs(和 Python 那份逐字对应)
- config.mjs 加 timeouts(同样整体替换);speech / python-tools / mcp / providers
  各处改读;index.mjs 加 /api/timeouts

验证
- 新增 scripts/verify-timeouts.py:清单完整性、边界容错(文字/空串/负数/超大值/
  带单位/None)、**扫内核有没有漏网的硬编码超时**(带白名单)、
  工具侧声明、以及和 Node 端逐项对拍
- 实测真机:界面显示 18 项来自内核 → 点 + 保存 → 内核 heartbeat 15→25 →
  恢复默认 → 回 15;askUser 显示"不限时"

文档:README §3.13;docs/AI界面能力.md 的"不限时要三处一起改"补上可调入口。
版本 2.0.46。
This commit is contained in:
l
2026-10-16 10:29:46 +08:00
parent d82c3d3176
commit c7fed95650
32 changed files with 1523 additions and 70 deletions

View File

@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。
*/
versionCode = 245
versionName = "2.0.45"
versionCode = 246
versionName = "2.0.46"
ndk {
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份

View File

@@ -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")

View File

@@ -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(

View File

@@ -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 的界面 */

View File

@@ -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("昵称")

View File

@@ -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
}

View File

@@ -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:

View File

@@ -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}')
@@ -293,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:

View File

@@ -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']

View File

@@ -206,6 +206,13 @@ DEFAULT_SETTINGS = {
},
# 安全模式:open 全部放行 / restricted 只放 allow 白名单
'security': {'mode': 'open', 'allow': []},
# 超时。**这里故意是空的** —— 默认值全在 timeouts.py 的 DEFAULT 里,
# 只有用户改过的项才会出现在这儿(和默认一样就删掉,见 timeouts.patch)。
#
# 为什么这么做:以后调整某个默认值时,没动过那一项的用户会跟着新默认走。
# 如果把默认值也存进设置文件,老用户会被永久钉在旧的默认上,
# 而且"我明明改的是代码里的默认值,怎么没生效"这种问题极难查。
'timeouts': {},
# Node 版用它指定解释器;Python 内核在进程内执行工具,这个字段只为兼容而保留
'pythonBin': '',
'nickname': '我',

View File

@@ -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 {

View File

@@ -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 {}

View File

@@ -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

View File

@@ -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:

View File

@@ -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:

View File

@@ -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
View 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)))

View File

@@ -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,7 +33,9 @@ _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 = '<内置>'
# --------------------------------------------------------------------------- #
@@ -61,6 +64,41 @@ def _waits_for_user(name: str, spec: dict, module) -> bool:
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
# --------------------------------------------------------------------------- #
# 界面工具的开关
@@ -328,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() 永远是空的。
@@ -351,14 +391,18 @@ def run_python_tool(name: str, args: dict) -> dict:
# ★ 会等用户的工具(ask_user / show_ui 的 wait 模式)**不限时** ——
# 它们的耗时取决于用户什么时候点,给上限等于"用户想久了 AI 就自己编"。
# 见 _waits_for_user 的注释。
budget = 0 if _waits_for_user(name, spec, module) else TOOL_TIMEOUT_S
# ★ 预算是**设置里可调**的(设置 → 超时 → 工具执行),不是写死的 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: