/** * 在设备上跑任意内核工具(走 /api/tools/run)。 * 用法: node scripts/device-tool.mjs * 例: node scripts/device-tool.mjs 3B1F... python_run "{\"code\":\"print(1+1)\"}" */ import { spawnSync } from 'node:child_process'; import fs from 'node:fs'; const [SERIAL, TOOL, ARGS = '{}'] = process.argv.slice(2); const PORT = process.env.PORT || '5199'; const ADB = 'C:\\Android\\Sdk\\platform-tools\\adb.exe'; if (!SERIAL || !TOOL) { console.error('用法: node scripts/device-tool.mjs '); process.exit(2); } function sh(cmd, timeout = 90000) { const res = spawnSync(ADB, ['-s', SERIAL, 'shell', cmd], { encoding: 'utf8', timeout }); return `${res.stdout || ''}${res.stderr || ''}`.trim(); } // 参数可以用 @文件 传:PowerShell 会把命令行里的 JSON 引号搅坏,写文件最稳 const argsText = ARGS.startsWith('@') ? fs.readFileSync(ARGS.slice(1), 'utf8') : ARGS; const payload = JSON.stringify({ name: TOOL, args: JSON.parse(argsText) }); const b64 = Buffer.from(payload, 'utf8').toString('base64'); sh(`echo '${b64}' | base64 -d > /data/local/tmp/p.json`); const out = sh( `curl -s --max-time 60 -X POST -H 'Content-Type: application/json' -d @/data/local/tmp/p.json http://127.0.0.1:${PORT}/api/tools/run`, ); try { const parsed = JSON.parse(out); console.log(JSON.stringify(parsed, null, 2)); } catch { console.log('原始返回:', out.slice(0, 500)); }