一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、 不需要另外装 Termux。 安卓端 - 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的 - 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹 - 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端; pty 不可用的 ROM 上自动降级成命令控制台 - APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上 - 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板 - 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎 AI 能力 - 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义 - 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发), 认不出来的一律不发,避免给不支持的厂商发字段直接 400 - MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式 跨端 - 安卓走原生 Compose,Web / Windows 走 Lynx - Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本 自检脚本(都不需要真 Key) - verify-phone.mjs 设备端 24 项验收 - verify-speech.mjs 语音链路 31 项,两份内核各跑一遍 - parity-thinking.mjs 思考强度映射对拍 - probe-settings-wipe.mjs 设置防清空攻击测试 - mock-llm.mjs 假的 OpenAI + 火山语音服务 许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron) 的授权见 LICENSE。
251 lines
7.4 KiB
JavaScript
251 lines
7.4 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';
|
||
|
||
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: 60000,
|
||
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 ? '工具执行超时(60s)' : `未解析到 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: {} },
|
||
},
|
||
};
|
||
}
|