/** * 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 → 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: {} }, }, }; }