用户要求"全部超时做成可调"。改造前 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。
252 lines
7.6 KiB
JavaScript
252 lines
7.6 KiB
JavaScript
/**
|
||
* Python 工具运行时。
|
||
*
|
||
* 工具即 tools/*.py,每个文件用 `_protocol.serve(TOOL, run)` 暴露能力:
|
||
* TOOL = {"name":..., "description":..., "parameters": {JSON Schema}}
|
||
* def run(args: dict) -> dict
|
||
*
|
||
* 发现:python tool.py --spec → 打印 TOOL 的 JSON
|
||
* 执行:python tool.py --input <json文件> → stdout 打印 {"ok":true,"result":...}
|
||
*
|
||
* 注意:这里**刻意用文件重定向**而不是管道(stdio: ['ignore', fd, fd]),
|
||
* 这样在受限沙箱里也能用(某些沙箱禁止子进程使用命名管道)。
|
||
*/
|
||
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 }
|
||
|
||
let cachedPython = null;
|
||
|
||
function candidates() {
|
||
const settings = readSettings();
|
||
const list = [];
|
||
if (settings.pythonBin) list.push({ bin: settings.pythonBin, prefix: [] });
|
||
if (process.env.PYTHON) list.push({ bin: process.env.PYTHON, prefix: [] });
|
||
list.push({ bin: 'python', prefix: [] });
|
||
list.push({ bin: 'python3', prefix: [] });
|
||
list.push({ bin: 'py', prefix: ['-3'] });
|
||
return list;
|
||
}
|
||
|
||
async function runFile({ bin, args, input, timeoutMs = 60000, cwd }) {
|
||
const id = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
||
const inPath = path.join(TMP_DIR, `${id}.in.json`);
|
||
const outPath = path.join(TMP_DIR, `${id}.out.txt`);
|
||
const errPath = path.join(TMP_DIR, `${id}.err.txt`);
|
||
fs.writeFileSync(inPath, input ?? '', 'utf8');
|
||
const outFd = fs.openSync(outPath, 'w');
|
||
const errFd = fs.openSync(errPath, 'w');
|
||
|
||
let child;
|
||
try {
|
||
child = spawn(bin, args, {
|
||
stdio: ['ignore', outFd, errFd],
|
||
cwd,
|
||
windowsHide: true,
|
||
env: { ...process.env, PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' },
|
||
});
|
||
} catch (err) {
|
||
fs.closeSync(outFd);
|
||
fs.closeSync(errFd);
|
||
throw err;
|
||
}
|
||
fs.closeSync(outFd);
|
||
fs.closeSync(errFd);
|
||
|
||
const started = Date.now();
|
||
const result = await new Promise((resolve) => {
|
||
let settled = false;
|
||
const finish = (value) => {
|
||
if (settled) return;
|
||
settled = true;
|
||
resolve(value);
|
||
};
|
||
const timer = setTimeout(() => {
|
||
try {
|
||
child.kill();
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
finish({ code: null, timedOut: true, ms: Date.now() - started });
|
||
}, timeoutMs);
|
||
child.on('error', (err) => {
|
||
clearTimeout(timer);
|
||
finish({ code: null, error: err, ms: Date.now() - started });
|
||
});
|
||
child.on('close', (code) => {
|
||
clearTimeout(timer);
|
||
finish({ code, timedOut: false, ms: Date.now() - started });
|
||
});
|
||
});
|
||
|
||
const read = (p) => {
|
||
try {
|
||
return fs.readFileSync(p, 'utf8');
|
||
} catch {
|
||
return '';
|
||
}
|
||
};
|
||
const stdout = read(outPath);
|
||
const stderr = read(errPath);
|
||
for (const p of [inPath, outPath, errPath]) {
|
||
try {
|
||
fs.unlinkSync(p);
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
}
|
||
return { ...result, stdout, stderr };
|
||
}
|
||
|
||
function parseSpec(stdout) {
|
||
const lines = stdout.split(/\r?\n/).filter((l) => l.trim());
|
||
for (let i = lines.length - 1; i >= 0; i -= 1) {
|
||
try {
|
||
const json = JSON.parse(lines[i]);
|
||
if (json && json.name) return json;
|
||
} catch {
|
||
/* try previous line */
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
async function resolvePython() {
|
||
if (cachedPython) return cachedPython;
|
||
for (const { bin, prefix } of candidates()) {
|
||
const probe = await runFile({
|
||
bin,
|
||
args: [...prefix, '-c', 'print("ok")'],
|
||
input: '',
|
||
timeoutMs: 15000,
|
||
}).catch((err) => ({ error: err }));
|
||
if (!probe.error && probe.code === 0 && String(probe.stdout).includes('ok')) {
|
||
cachedPython = { bin, prefix };
|
||
return cachedPython;
|
||
}
|
||
}
|
||
cachedPython = null;
|
||
throw new Error('找不到可用的 python 解释器,请在设置里指定 pythonBin');
|
||
}
|
||
|
||
/** 工具目录:设置里可以指到别处(安卓端指到手机上的目录) */
|
||
export function toolsDir() {
|
||
const custom = readSettings().toolsDir;
|
||
if (custom && fs.existsSync(custom)) return custom;
|
||
return TOOLS_DIR;
|
||
}
|
||
|
||
export function pythonFiles() {
|
||
const dir = toolsDir();
|
||
if (!fs.existsSync(dir)) return [];
|
||
return fs
|
||
.readdirSync(dir)
|
||
.filter((f) => f.endsWith('.py') && !f.startsWith('_'))
|
||
.map((f) => path.join(dir, f));
|
||
}
|
||
|
||
/** 扫描全部 Python 工具(带 mtime 缓存) */
|
||
export async function discoverPythonTools({ force = false } = {}) {
|
||
const files = pythonFiles();
|
||
const tools = [];
|
||
const errors = [];
|
||
let py = null;
|
||
try {
|
||
py = await resolvePython();
|
||
} catch (err) {
|
||
return { tools: [], errors: [{ file: '*', error: err.message }], python: null };
|
||
}
|
||
|
||
for (const file of files) {
|
||
const stat = fs.statSync(file);
|
||
const cached = specCache.get(file);
|
||
if (!force && cached && cached.mtimeMs === stat.mtimeMs) {
|
||
if (cached.spec) tools.push({ ...cached.spec, __file: file, __python: py });
|
||
else if (cached.error) errors.push({ file: path.basename(file), error: cached.error });
|
||
continue;
|
||
}
|
||
const res = await runFile({
|
||
bin: py.bin,
|
||
args: [...py.prefix, file, '--spec'],
|
||
input: '',
|
||
timeoutMs: 20000,
|
||
cwd: toolsDir(),
|
||
});
|
||
const spec = parseSpec(res.stdout);
|
||
if (spec) {
|
||
specCache.set(file, { mtimeMs: stat.mtimeMs, spec });
|
||
tools.push({ ...spec, __file: file, __python: py });
|
||
} else {
|
||
const error = (res.stderr || res.stdout || `退出码 ${res.code}`).slice(0, 400);
|
||
specCache.set(file, { mtimeMs: stat.mtimeMs, error });
|
||
errors.push({ file: path.basename(file), error });
|
||
}
|
||
}
|
||
return { tools, errors, python: py };
|
||
}
|
||
|
||
/** 执行一个 Python 工具 */
|
||
export async function runPythonTool(name, args) {
|
||
const { tools } = await discoverPythonTools();
|
||
const tool = tools.find((t) => t.name === name);
|
||
if (!tool) throw new Error(`没有名为 ${name} 的 Python 工具`);
|
||
const py = tool.__python || (await resolvePython());
|
||
return runPythonToolWithFile(tool, py, args);
|
||
}
|
||
|
||
async function runPythonToolWithFile(tool, py, args) {
|
||
const id = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
||
const inPath = path.join(TMP_DIR, `${id}.args.json`);
|
||
fs.writeFileSync(inPath, JSON.stringify(args ?? {}), 'utf8');
|
||
const res = await runFile({
|
||
bin: py.bin,
|
||
args: [...py.prefix, tool.__file, '--input', inPath],
|
||
input: '',
|
||
timeoutMs: timeoutOf(readSettings(), 'tool') * 1000,
|
||
cwd: toolsDir(),
|
||
});
|
||
try {
|
||
fs.unlinkSync(inPath);
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
const lines = res.stdout.split(/\r?\n/).filter((l) => l.trim());
|
||
let parsed = null;
|
||
for (let i = lines.length - 1; i >= 0; i -= 1) {
|
||
try {
|
||
parsed = JSON.parse(lines[i]);
|
||
break;
|
||
} catch {
|
||
/* keep looking */
|
||
}
|
||
}
|
||
if (res.error) {
|
||
return { ok: false, error: `无法启动 python:${res.error.message}` };
|
||
}
|
||
if (parsed) {
|
||
return { ok: Boolean(parsed.ok), result: parsed.result, error: parsed.error, stderr: res.stderr || undefined };
|
||
}
|
||
return {
|
||
ok: res.code === 0,
|
||
error: res.timedOut ? `工具执行超时(${Math.round(timeoutOf(readSettings(), 'tool'))}s,可在设置里调)` : `未解析到 JSON 输出(退出码 ${res.code})`,
|
||
stdout: res.stdout.slice(0, 2000),
|
||
stderr: res.stderr.slice(0, 2000),
|
||
};
|
||
}
|
||
|
||
/** 转成 OpenAI tools 定义 */
|
||
export function toOpenAITool(spec) {
|
||
return {
|
||
type: 'function',
|
||
function: {
|
||
name: spec.name,
|
||
description: spec.description || spec.name,
|
||
parameters: spec.parameters || { type: 'object', properties: {} },
|
||
},
|
||
};
|
||
}
|