/** * 在**真机/模拟器上**直接验证内置 Python 内核(不经过电脑)。 * * 为什么要 base64:adb shell 的引号转义会把 JSON 里的双引号搞坏, * 直接 `-d '{"a":1}'` 到手机上必然变成"请求体不是合法 JSON"。 * * 用法: node scripts/verify-phone.mjs [serial] [port] */ import { spawnSync } from 'node:child_process'; import fs from 'node:fs'; const SERIAL = process.argv[2] || 'YOUR_DEVICE_SERIAL'; const PORT = process.argv[3] || '5199'; const ADB = 'C:\\Android\\Sdk\\platform-tools\\adb.exe'; function sh(cmd, timeout = 60000) { const res = spawnSync(ADB, ['-s', SERIAL, 'shell', cmd], { encoding: 'utf8', timeout }); return `${res.stdout || ''}${res.stderr || ''}`.trim(); } /** 把 JSON 塞进设备上的文件,再用 curl -d @file,绕开 shell 引号地狱 */ function post(path, payload) { const b64 = Buffer.from(JSON.stringify(payload ?? {}), 'utf8').toString('base64'); sh(`echo '${b64}' | base64 -d > /data/local/tmp/p.json`); const out = sh(`curl -s --max-time 40 -X POST -H 'Content-Type: application/json' -d @/data/local/tmp/p.json http://127.0.0.1:${PORT}${path}`); try { return JSON.parse(out); } catch { return { __raw: out.slice(0, 300) }; } } function get(path) { const out = sh(`curl -s --max-time 20 http://127.0.0.1:${PORT}${path}`); try { return JSON.parse(out); } catch { return { __raw: out.slice(0, 300) }; } } let pass = 0; let fail = 0; /** detail 一定要能安全字符串化:返回体缺字段时 JSON.stringify(undefined) 会炸 */ const d = (value, max = 260) => { let text; try { text = typeof value === 'string' ? value : JSON.stringify(value); } catch { text = String(value); } return (text ?? 'undefined').slice(0, max); }; const check = (label, ok, detail) => { console.log(`${ok ? '✅' : '❌'} ${label}${detail ? ` → ${d(detail)}` : ''}`); ok ? (pass += 1) : (fail += 1); }; console.log(`设备 ${SERIAL}\n`); console.log('=== 0. 手机信息 ==='); console.log(' ', sh('getprop ro.product.model'), '|', sh('getprop ro.build.version.release'), '|', sh('uname -m')); console.log('\n=== 1. 本机内核在监听吗 ==='); const health = get('/api/health'); check('GET /api/health', health.ok === true, JSON.stringify(health)); console.log('\n=== 2. /api/state ==='); const state = get('/api/state'); check('智能体 4 个', state.agents?.length === 4, state.agents?.map((a) => a.name).join(', ')); const toolNames = state.toolNames || []; check('工具列表(含 device)', toolNames.includes('device'), toolNames.join(', ')); check('默认思考强度可读', typeof state.settings?.thinkingLevel === 'string', state.settings?.thinkingLevel); console.log('\n=== 3. shell 工具(安卓 toybox)==='); const shellRes = post('/api/tools/run', { name: 'shell', args: { command: 'getprop ro.product.model; uname -m; echo ok' } }); check('执行系统命令', shellRes.ok === true, JSON.stringify(shellRes.result || shellRes.error)); console.log('\n=== 4. python_run(进程内 CPython)==='); const pyRes = post('/api/tools/run', { name: 'python_run', args: { code: 'import sys, platform\nprint(sys.version.split()[0], platform.machine(), platform.system())' }, }); check('跑 Python 代码', pyRes.ok === true, JSON.stringify(pyRes.result || pyRes.error)); const libs = post('/api/tools/run', { name: 'python_run', args: { action: 'libs' } }); check('libs(网络库)', libs.ok === true, `可用 ${libs.result?.available?.length ?? 0} 个:${(libs.result?.available || []).join(', ')}`); console.log('\n=== 5. 网络能力 ==='); const net = post('/api/tools/run', { name: 'python_run', args: { code: 'import urllib.request\nprint("HTTP", urllib.request.urlopen("https://example.com", timeout=25).status)' }, }); check('手机上能联网', net.ok === true && String(net.result?.stdout || '').includes('HTTP 200'), JSON.stringify(net.result?.stdout || net.error)); const req = post('/api/tools/run', { name: 'python_run', args: { code: 'import requests\nprint("requests", requests.get("https://example.com", timeout=25).status_code)' }, }); check('requests 库可用', req.ok === true && String(req.result?.stdout || '').includes('200'), d()); console.log('\n=== 6. device 工具(定位/传感器)==='); const info = post('/api/tools/run', { name: 'device', args: { action: 'info' } }); check('设备信息', info.ok === true && info.result?.model, d()); const sensors = post('/api/tools/run', { name: 'device', args: { action: 'sensors' } }); const sensorList = sensors.result?.sensors || []; check('传感器列表', sensors.ok === true && sensorList.length > 0, `共 ${sensors.result?.count ?? 0} 个:${sensorList.slice(0, 6).map((s) => s.key).join(', ')}`); const acc = post('/api/tools/run', { name: 'device', args: { action: 'sensor', sensor: 'accelerometer', duration: 1.5 } }); check('加速度计采样', acc.ok === true && (acc.result?.sample_count ?? 0) > 0, `样本 ${acc.result?.sample_count} 个,last=${JSON.stringify(acc.result?.last)} ${acc.result?.unit || ''}`); const gyro = post('/api/tools/run', { name: 'device', args: { action: 'sensor', sensor: 'gyroscope', duration: 1.2 } }); check('陀螺仪采样', gyro.ok === true && (gyro.result?.sample_count ?? 0) > 0, `样本 ${gyro.result?.sample_count} 个,last=${JSON.stringify(gyro.result?.last)}`); const loc = post('/api/tools/run', { name: 'device', args: { action: 'location' } }); check('定位', loc.ok === true && loc.result?.available === true, loc.result?.available ? `lat=${loc.result.latitude} lon=${loc.result.longitude} ±${loc.result.accuracy_m}m` : loc.result?.hint || loc.error); console.log('\n=== 7. 工具目录 ==='); const dirs = sh(`ls /sdcard/Android/data/com.doubao.lynxclone/files/tools 2>/dev/null`); check('内置工具已播种到可写目录', dirs.includes('_protocol.py'), dirs.replace(/\s+/g, ' ').slice(0, 240)); console.log('\n=== 8. MCP:Python 写的服务(inproc)==='); const mcpConfig = { servers: [ { name: 'py-demo', enabled: true, transport: 'inproc', path: '/sdcard/Android/data/com.doubao.lynxclone/files/tools/_mcp_python_example.py', }, ], }; const saved = post('/api/mcp/config', { text: JSON.stringify(mcpConfig, null, 2) }); check('写入 MCP 配置并连接', saved.ok === true, d()); if (saved.ok) { const wc = post('/api/tools/run', { name: 'mcp__py-demo__word_count', args: { text: 'hello 世界' } }); check('调用 py 写的 MCP 工具', wc.ok === true, d()); const host = post('/api/tools/run', { name: 'mcp__py-demo__host_info', args: {} }); check('MCP 里能拿到手机信息', host.ok === true, d()); } console.log('\n=== 9. 语音接口 ==='); // 这几项不需要任何 Key:验的是"接口在、默认走设备自带引擎"。 // 云端合成要 Key,放在 verify-speech.mjs 里用 mock 单独验。 const speechState = get('/api/speech'); check('语音配置可读', speechState.ok === true && !!speechState.speech, `tts=${speechState.speech?.ttsEngine} stt=${speechState.speech?.sttEngine}`); check('音色列表已下发', Array.isArray(speechState.voices?.volc) && speechState.voices.volc.length > 0, `火山 ${speechState.voices?.volc?.length} 个 / OpenAI ${speechState.voices?.openai?.length} 个`); // 把引擎临时切回 system 再打 /api/tts —— 否则用户配了云端时,跑一次验收就消耗一次额度。 // ★ 一定要还原:验收脚本不该改用户的配置。 const engineBefore = { ttsEngine: speechState.speech?.ttsEngine || 'system', sttEngine: speechState.speech?.sttEngine || 'system', }; post('/api/settings', { speech: { ttsEngine: 'system', sttEngine: 'system' } }); const tts = post('/api/tts', { text: '语音接口自检' }); check('朗读接口在(system 不联网)', tts.ok === true && tts.engine === 'system', `engine=${tts.engine}`); // /api/stt 收的是**原始音频字节**而不是 JSON,所以不能用 post(),单独发 const sttB64 = Buffer.from('RIFF____WAVE').toString('base64'); sh(`echo '${sttB64}' | base64 -d > /data/local/tmp/a.wav`); const sttOut = sh( `curl -s --max-time 30 -X POST -H 'Content-Type: audio/wav' -H 'X-Audio-Filename: a.wav' ` + `--data-binary @/data/local/tmp/a.wav http://127.0.0.1:${PORT}/api/stt`, ); let stt = {}; try { stt = JSON.parse(sttOut); } catch { stt = { __raw: sttOut.slice(0, 200) }; } check('识别接口在(system 不联网)', stt.ok === true && stt.engine === 'system', `engine=${stt.engine}`); const speechSettings = get('/api/state'); check('语音 Token 不明文外泄', speechSettings.settings?.speech?.volcToken !== undefined && (speechSettings.settings.speech.volcToken === '' || speechSettings.settings.speech.volcToken === '••••••••'), JSON.stringify(speechSettings.settings?.speech?.volcToken)); // 把用户原来的引擎设置还回去 post('/api/settings', { speech: engineBefore }); const restored = get('/api/state').settings?.speech; check('验收后原样还原了语音配置', restored?.ttsEngine === engineBefore.ttsEngine && restored?.sttEngine === engineBefore.sttEngine, `tts=${restored?.ttsEngine} stt=${restored?.sttEngine}`); console.log(`\n结果:${pass} 通过 / ${fail} 失败`); fs.writeFileSync('phone-verify-result.json', JSON.stringify({ pass, fail, at: new Date().toISOString() }, null, 2)); process.exit(fail === 0 ? 0 : 1);