@auto-mas/auto-mas-plugin-adapter-src 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,207 @@
1
+ import { open, readdir, realpath, stat } from 'node:fs/promises';
2
+ import { basename, dirname, isAbsolute, join } from 'node:path';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { execFile, spawn } from 'node:child_process';
5
+ import { runProcess } from '../execution.js';
6
+ export const executableField = (label) => ({ key: 'command', label, kind: 'hostpath', required: true });
7
+ export const directoryField = (key, label) => ({ key, label, kind: 'hostpath', directory: true, required: true });
8
+ export const windowsOnly = () => process.platform === 'win32' ? undefined : '此执行器需要 Windows 桌面会话';
9
+ export function optionalText(input, key) {
10
+ const value = input[key];
11
+ if (value === undefined || value === null)
12
+ return '';
13
+ if (typeof value !== 'string' || /[\u0000-\u001f]/u.test(value))
14
+ throw new Error(`${key} 必须是单行文本`);
15
+ return value.trim();
16
+ }
17
+ export function requiredText(input, key, label) {
18
+ const value = optionalText(input, key);
19
+ if (!value)
20
+ throw new Error(`请填写${label}`);
21
+ return value;
22
+ }
23
+ export function configName(value, label) {
24
+ if (!value || value.startsWith('-') || value.endsWith('.') || /[/\\:*?"<>|]/u.test(value)) {
25
+ throw new Error(`${label}必须是配置名称`);
26
+ }
27
+ return value;
28
+ }
29
+ export async function existingPath(path, label, directory = false) {
30
+ if (!isAbsolute(path))
31
+ throw new Error(`${label}必须是绝对路径`);
32
+ const resolved = await realpath(path).catch(error => {
33
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
34
+ throw new Error(`${label}不存在`);
35
+ throw error;
36
+ });
37
+ const info = await stat(resolved);
38
+ if (directory ? !info.isDirectory() : !info.isFile())
39
+ throw new Error(`${label}类型有误`);
40
+ return resolved;
41
+ }
42
+ export async function prepareExecutable(input, label, names) {
43
+ const command = await existingPath(requiredText(input, 'command', label), label);
44
+ if (!names.includes(basename(command).toLowerCase()))
45
+ throw new Error(`请选择 ${names.join(' 或 ')} 文件`);
46
+ return { command, installRoot: dirname(command) };
47
+ }
48
+ export async function assertWindowsProgramIdle(command, signal) {
49
+ signal.throwIfAborted();
50
+ const pidList = await new Promise((resolve, reject) => execFile('powershell.exe', [
51
+ '-NoProfile', '-NonInteractive', '-Command', [
52
+ '$ErrorActionPreference = "Stop"',
53
+ '$name = [System.IO.Path]::GetFileNameWithoutExtension($env:MAS_NATIVE_PROGRAM)',
54
+ 'Get-Process | Where-Object { $_.ProcessName -eq $name -and (!$_.Path -or $_.Path -eq $env:MAS_NATIVE_PROGRAM) } | Select-Object -ExpandProperty Id',
55
+ ].join('\n'),
56
+ ], { env: { ...process.env, MAS_NATIVE_PROGRAM: command }, windowsHide: true, signal, timeout: 8000 }, (error, stdout) => {
57
+ if (error)
58
+ reject(new Error(`无法检查 ${basename(command)} 是否已打开`, { cause: error }));
59
+ else
60
+ resolve(stdout);
61
+ }));
62
+ if (pidList.trim())
63
+ throw new Error(`请先关闭正在运行的 ${basename(command)}`);
64
+ }
65
+ export async function openNativeEditor(command, cwd, close) {
66
+ const unavailable = windowsOnly();
67
+ if (unavailable)
68
+ throw new Error(unavailable);
69
+ await assertWindowsProgramIdle(command, AbortSignal.timeout(10_000));
70
+ const process = spawn(command, [], { cwd, detached: true, stdio: 'ignore', shell: false });
71
+ if (close)
72
+ process.once('close', close);
73
+ await new Promise((resolve, reject) => {
74
+ process.once('spawn', resolve);
75
+ process.once('error', reject);
76
+ });
77
+ process.unref();
78
+ }
79
+ async function followLogs(spec, consume) {
80
+ const cursors = new Map();
81
+ async function scan(baseline) {
82
+ const entries = await readdir(spec.directory, { withFileTypes: true }).catch(error => {
83
+ if (error.code === 'ENOENT')
84
+ return [];
85
+ throw error;
86
+ });
87
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
88
+ if (!entry.isFile() || !spec.filenames.test(entry.name))
89
+ continue;
90
+ const handle = await open(join(spec.directory, entry.name), 'r').catch(error => {
91
+ if (error.code === 'ENOENT')
92
+ return undefined;
93
+ throw error;
94
+ });
95
+ if (!handle)
96
+ continue;
97
+ try {
98
+ const { dev, ino, size } = await handle.stat();
99
+ const id = `${dev}:${ino}`;
100
+ const previous = cursors.get(entry.name);
101
+ const cursor = previous?.id === id && previous.offset <= size ? previous : {
102
+ id, offset: baseline ? size : 0, decoder: new StringDecoder('utf8'), partial: '',
103
+ };
104
+ cursors.set(entry.name, cursor);
105
+ const buffer = Buffer.allocUnsafe(64 * 1024);
106
+ while (cursor.offset < size) {
107
+ const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, size - cursor.offset), cursor.offset);
108
+ if (!bytesRead)
109
+ break;
110
+ cursor.offset += bytesRead;
111
+ const lines = (cursor.partial + cursor.decoder.write(buffer.subarray(0, bytesRead))).split('\n');
112
+ cursor.partial = (lines.pop() ?? '').slice(-16000);
113
+ for (const line of lines)
114
+ consume(line.replace(/\r$/u, ''));
115
+ }
116
+ }
117
+ finally {
118
+ await handle.close();
119
+ }
120
+ }
121
+ }
122
+ await scan(true);
123
+ return async (final = false) => {
124
+ await scan(false);
125
+ if (final)
126
+ for (const cursor of cursors.values()) {
127
+ const remainder = cursor.partial + cursor.decoder.end();
128
+ if (remainder)
129
+ consume(remainder.replace(/\r$/u, ''));
130
+ }
131
+ };
132
+ }
133
+ export async function runObservedProcess(script, options, files, observation, closeOnCompletion = false) {
134
+ let completedAt;
135
+ const completion = new AbortController();
136
+ const signal = closeOnCompletion ? AbortSignal.any([options.signal, completion.signal]) : options.signal;
137
+ const consume = (line, source) => {
138
+ options.log(line);
139
+ observation.consume(line, source);
140
+ if (observation.complete)
141
+ completedAt ??= Date.now();
142
+ };
143
+ const scan = await followLogs(files, line => consume(line, 'file'));
144
+ let pending;
145
+ let logError;
146
+ const interval = setInterval(() => {
147
+ if (pending || logError)
148
+ return;
149
+ pending = scan().then(() => {
150
+ if (closeOnCompletion && completedAt !== undefined && Date.now() - completedAt >= 1500) {
151
+ completion.abort(new Error('上游任务已结束'));
152
+ }
153
+ }).catch(error => { logError = error; }).finally(() => { pending = undefined; });
154
+ }, 500);
155
+ let processError;
156
+ try {
157
+ await runProcess(script, { ...options, signal, log: line => consume(line, 'process') });
158
+ }
159
+ catch (error) {
160
+ processError = error;
161
+ }
162
+ finally {
163
+ clearInterval(interval);
164
+ await pending;
165
+ }
166
+ options.signal.throwIfAborted();
167
+ if (logError)
168
+ throw logError;
169
+ await scan(true);
170
+ observation.finish(processError === completion.signal.reason ? undefined : processError);
171
+ }
172
+ export function nativeAdapter(builder) {
173
+ return async (script, options) => {
174
+ options.signal.throwIfAborted();
175
+ const launch = await builder(script.adapterConfig ?? {}, script.accountConfig ?? {});
176
+ const { logs, ...command } = launch;
177
+ const processScript = { ...script, ...command, env: { ...script.env, ...command.env } };
178
+ if (!logs)
179
+ return runProcess(processScript, options);
180
+ let success = false;
181
+ let terminal = !logs.terminal;
182
+ let failure;
183
+ return runObservedProcess(processScript, options, logs, {
184
+ consume(line, source) {
185
+ if (source !== 'file')
186
+ return;
187
+ if (logs.success.test(line)) {
188
+ success = true;
189
+ if (logs.successClearsFailure)
190
+ failure = undefined;
191
+ }
192
+ terminal ||= Boolean(logs.terminal?.test(line));
193
+ if (logs.failure?.test(line))
194
+ failure = line.slice(0, 400);
195
+ },
196
+ get complete() { return success && terminal; },
197
+ finish(processError) {
198
+ if (failure)
199
+ throw new Error(failure);
200
+ if (processError)
201
+ throw processError;
202
+ if (!success || !terminal)
203
+ throw new Error('上游日志未报告完成,请查看上游配置与本次运行日志');
204
+ },
205
+ }, logs.closeOnCompletion);
206
+ };
207
+ }
@@ -0,0 +1,115 @@
1
+ import { join } from 'node:path';
2
+ import { parse } from 'yaml';
3
+ import { assertWindowsProgramIdle, executableField, prepareExecutable, runObservedProcess, windowsOnly } from './native.js';
4
+ import { nativeConfigurationComponents, readNativeConfigurationFile } from './native-config.js';
5
+ export const srcProgram = (input) => prepareExecutable(input, 'SRC Windows 发行版', ['src.exe']);
6
+ export async function srcNativeConfiguration(input) {
7
+ const { command, installRoot: root } = await srcProgram(input);
8
+ return { root, directory: join(root, 'config'), files: ['src.json', 'deploy.yaml'], command, open: false };
9
+ }
10
+ function object(value) {
11
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
12
+ }
13
+ function startupLists(value, depth = 0) {
14
+ if (depth > 4)
15
+ return [];
16
+ const entries = Object.entries(object(value));
17
+ return entries.flatMap(([name, child]) => name === 'Run' ? [child] : startupLists(child, depth + 1));
18
+ }
19
+ export async function srcSettings(root) {
20
+ let native;
21
+ let startup;
22
+ try {
23
+ const directory = join(root, 'config');
24
+ const [profile, deployment] = await Promise.all([
25
+ readNativeConfigurationFile({ root, directory, file: 'src.json' }),
26
+ readNativeConfigurationFile({ root, directory, file: 'deploy.yaml' }),
27
+ ]);
28
+ native = object(JSON.parse(profile.replace(/^\uFEFF/u, '')));
29
+ startup = startupLists(parse(deployment, { maxAliasCount: 25 }));
30
+ }
31
+ catch (error) {
32
+ throw new Error('无法读取 SRC 原生配置。请先初始化 SRC 并保存配置。', { cause: error });
33
+ }
34
+ if (startup.length !== 1 || !Array.isArray(startup[0]) || startup[0].length !== 1 || startup[0][0] !== 'src') {
35
+ throw new Error('请在 SRC 中将启动时自动运行的配置设为 src,且只自动启动这一个配置');
36
+ }
37
+ const alas = object(native.Alas);
38
+ if (object(alas.Optimization).WhenTaskQueueEmpty !== 'close_game') {
39
+ throw new Error('请在 SRC 的优化设置中将任务队列为空时的操作设为关闭游戏');
40
+ }
41
+ const serial = object(alas.Emulator).Serial;
42
+ if (typeof serial !== 'string' || !serial.trim() || /^auto$/iu.test(serial))
43
+ throw new Error('请在 SRC 中设置明确的 ADB 设备地址');
44
+ return { serial: serial.trim() };
45
+ }
46
+ export async function srcNativePreview(input) {
47
+ const { installRoot } = await srcProgram(input);
48
+ const { serial } = await srcSettings(installRoot);
49
+ return [
50
+ { label: '原生配置', value: 'src' },
51
+ { label: 'ADB 设备', value: /^[a-z0-9_.:\[\]%-]{1,160}$/iu.test(serial) ? serial : '请在 SRC 中核对设备' },
52
+ { label: '程序启动', value: '自动运行 src' },
53
+ { label: '任务队列为空', value: '关闭游戏' },
54
+ ];
55
+ }
56
+ export function srcObservation(log) {
57
+ let waiting = false;
58
+ let started = false;
59
+ let failure;
60
+ return {
61
+ consume(line, source) {
62
+ if (source !== 'file' || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{1,6} /u.test(line))
63
+ return;
64
+ if (/Request human takeover/iu.test(line))
65
+ failure ??= 'SRC 需要用户接管';
66
+ else if (/\bCRITICAL\b|Please switch to a supported page before starting SRC|\[src\] exited/iu.test(line))
67
+ failure ??= line.slice(0, 400);
68
+ if (/Scheduler:\s*Start task\s/iu.test(line))
69
+ started = true;
70
+ if (/\bClose game during wait\s*$/iu.test(line))
71
+ waiting = true;
72
+ },
73
+ get complete() { return waiting || failure !== undefined; },
74
+ finish(processError) {
75
+ if (failure)
76
+ throw new Error(failure);
77
+ if (processError)
78
+ throw processError;
79
+ if (!waiting)
80
+ throw new Error('SRC 退出前未报告本轮队列进入等待');
81
+ log(started ? 'SRC 本轮已到达原生队列等待' : 'SRC 本轮无到期任务');
82
+ },
83
+ };
84
+ }
85
+ async function srcLaunch(config, target) {
86
+ const program = await srcProgram(config);
87
+ const settings = await srcSettings(program.installRoot);
88
+ if (typeof target === 'string' && target && target.toLowerCase() !== settings.serial.toLowerCase()) {
89
+ throw new Error('托管关联的 ADB 地址和 SRC 原生配置不同,请选择同一个设备');
90
+ }
91
+ return { ...program, ...settings };
92
+ }
93
+ export const src = {
94
+ id: 'src', title: '崩坏:星穹铁道 · StarRailCopilot', group: '游戏专项', supports: windowsOnly,
95
+ description: '运行 SRC 的原生 src 配置,在其队列进入等待后结束本轮。任务、游戏和账号在 SRC 原生界面配置。',
96
+ scriptFields: [executableField('Windows 安装目录中的 src.exe')],
97
+ detailComponents: script => [{
98
+ type: 'metrics', title: 'SRC 原生运行配置', query: 'src.native.preview', queryInput: { scriptId: script.id },
99
+ }, ...nativeConfigurationComponents('src', script, { open: false })],
100
+ prepare: async (input) => {
101
+ const program = await srcLaunch(input);
102
+ return { command: program.command, installRoot: program.installRoot, address: program.serial };
103
+ },
104
+ async validateRun(script) {
105
+ const config = script.adapterConfig;
106
+ await srcLaunch(config, script.address ?? config?.address);
107
+ },
108
+ async run(script, options) {
109
+ const config = script.adapterConfig;
110
+ const { command, installRoot: cwd } = await srcLaunch(config, script.address ?? config?.address);
111
+ await assertWindowsProgramIdle(command, options.signal);
112
+ const files = { directory: join(cwd, 'log'), filenames: /^\d{4}-\d{2}-\d{2}_src\.txt$/u };
113
+ await runObservedProcess({ ...script, command, cwd, args: [] }, options, files, srcObservation(options.log), true);
114
+ },
115
+ };
@@ -0,0 +1,66 @@
1
+ export function generalResultRules(input) {
2
+ const read = (key) => {
3
+ const value = typeof input[key] === 'string' ? input[key].trim() : '';
4
+ if (value.length > 300 || /[\r\n]/u.test(value))
5
+ throw new Error('日志匹配内容必须是 300 字符以内的单行文本');
6
+ return value || undefined;
7
+ };
8
+ const startupText = read('startupText');
9
+ const successText = read('successText');
10
+ const failureText = read('failureText');
11
+ const startupTimeout = startupText ? Number(input.startupTimeout ?? 30) : undefined;
12
+ if (startupTimeout !== undefined && (!Number.isInteger(startupTimeout) || startupTimeout < 1 || startupTimeout > 300)) {
13
+ throw new Error('启动检查时限必须介于 1 至 300 秒');
14
+ }
15
+ return { startupText, startupTimeout, successText, failureText };
16
+ }
17
+ export async function withGeneralResult(script, options, dispatch) {
18
+ const source = script.adapterConfig && typeof script.adapterConfig === 'object'
19
+ ? script.adapterConfig : script;
20
+ const { startupText, startupTimeout, successText, failureText } = generalResultRules(source);
21
+ if (!startupText && !successText && !failureText)
22
+ return dispatch(script, options);
23
+ const monitor = new AbortController();
24
+ let ready = false;
25
+ let success = false;
26
+ let deadline;
27
+ const markReady = () => {
28
+ if (ready || monitor.signal.aborted)
29
+ return;
30
+ ready = true;
31
+ clearTimeout(deadline);
32
+ options.started?.();
33
+ };
34
+ try {
35
+ await dispatch(script, {
36
+ ...options,
37
+ signal: AbortSignal.any([options.signal, monitor.signal]),
38
+ started: () => {
39
+ if (!startupText)
40
+ return markReady();
41
+ if (ready || deadline)
42
+ return;
43
+ deadline = setTimeout(() => monitor.abort(new Error('启动检查超时:未检测到配置的日志文本')), startupTimeout * 1000);
44
+ deadline.unref();
45
+ },
46
+ log(line) {
47
+ options.log(line);
48
+ if (failureText && line.includes(failureText))
49
+ monitor.abort(new Error('匹配到配置的失败日志'));
50
+ if (successText && line.includes(successText))
51
+ success = true;
52
+ if (startupText && line.includes(startupText))
53
+ markReady();
54
+ },
55
+ });
56
+ options.signal.throwIfAborted();
57
+ monitor.signal.throwIfAborted();
58
+ if (startupText && !ready)
59
+ throw new Error('脚本已退出,但未检测到配置的启动日志');
60
+ if (successText && !success)
61
+ throw new Error('脚本已退出,但未检测到配置的成功日志');
62
+ }
63
+ finally {
64
+ clearTimeout(deadline);
65
+ }
66
+ }
@@ -0,0 +1,97 @@
1
+ import { fork } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { adbEnvironment } from '../emulator-managers.js';
4
+ import { readLines, terminateTree } from './process.js';
5
+ export { inspectProject } from './project.js';
6
+ const workerPath = fileURLToPath(new URL('./worker.js', import.meta.url));
7
+ export async function runMaa(input, options) {
8
+ const { signal, log, started, launchProcess } = options;
9
+ signal.throwIfAborted();
10
+ const env = { ...adbEnvironment(input.adbServerPort), ...(process.versions.electron ? { ELECTRON_RUN_AS_NODE: '1' } : {}) };
11
+ if (launchProcess) {
12
+ await launchProcess({ command: process.execPath, args: [workerPath, '--mas-stdio'], env,
13
+ stdin: JSON.stringify({ type: 'run', input }) }, options);
14
+ return;
15
+ }
16
+ await new Promise((resolve, reject) => {
17
+ const worker = fork(workerPath, [], {
18
+ detached: process.platform !== 'win32',
19
+ env: { ...process.env, ...env },
20
+ execArgv: [],
21
+ windowsHide: true,
22
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
23
+ });
24
+ const processes = new Set();
25
+ let result;
26
+ let workerError;
27
+ let stopTimer;
28
+ let deadline;
29
+ let settled = false;
30
+ function abort() {
31
+ if (worker.connected)
32
+ worker.send({ type: 'stop' }, () => undefined);
33
+ stopTimer = setTimeout(() => {
34
+ log('MaaFramework stop deadline reached. Terminating the worker and its project processes.');
35
+ if (worker.pid)
36
+ void terminateTree(worker.pid);
37
+ for (const pid of processes)
38
+ void terminateTree(pid);
39
+ deadline = setTimeout(() => {
40
+ if (worker.connected)
41
+ worker.disconnect();
42
+ worker.stdout?.destroy();
43
+ worker.stderr?.destroy();
44
+ worker.unref();
45
+ void finish(null, null);
46
+ }, 2_000);
47
+ }, 5_000);
48
+ }
49
+ async function finish(code, exitSignal) {
50
+ if (settled)
51
+ return;
52
+ settled = true;
53
+ clearTimeout(stopTimer);
54
+ clearTimeout(deadline);
55
+ signal.removeEventListener('abort', abort);
56
+ await Promise.all([...processes].map(terminateTree));
57
+ if (signal.aborted)
58
+ reject(signal.reason);
59
+ else if (result?.error)
60
+ reject(result.error);
61
+ else if (workerError)
62
+ reject(workerError);
63
+ else if (code === 0 && result)
64
+ resolve();
65
+ else
66
+ reject(new Error(`MaaFramework worker exited before completing (${exitSignal ?? code ?? 'unknown status'}).`));
67
+ }
68
+ readLines(worker.stdout, log);
69
+ readLines(worker.stderr, (line) => log(`[MaaFramework stderr] ${line}`));
70
+ worker.on('message', (message) => {
71
+ if (message.type === 'process-started')
72
+ processes.add(message.pid);
73
+ if (message.type === 'process-exited')
74
+ processes.delete(message.pid);
75
+ if (message.type === 'failed')
76
+ result = { error: new Error(message.error) };
77
+ if (message.type === 'done')
78
+ result = {};
79
+ });
80
+ worker.once('error', (error) => { workerError = error; });
81
+ worker.once('spawn', () => {
82
+ try {
83
+ started?.('MaaFramework Worker 已启动');
84
+ }
85
+ catch (error) {
86
+ workerError = error instanceof Error ? error : new Error(String(error));
87
+ abort();
88
+ }
89
+ });
90
+ worker.once('close', (code, exitSignal) => void finish(code, exitSignal));
91
+ worker.send({ type: 'run', input }, (error) => {
92
+ if (error)
93
+ workerError = error;
94
+ });
95
+ signal.addEventListener('abort', abort, { once: true });
96
+ });
97
+ }
@@ -0,0 +1,34 @@
1
+ import { readFile, realpath } from 'node:fs/promises';
2
+ import { isAbsolute, join, relative, sep } from 'node:path';
3
+ export const managedProjectManifest = '.automasc-maafw.json';
4
+ export const projectIdPattern = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/u;
5
+ export function withinProject(root, path) {
6
+ const displacement = relative(root, path);
7
+ return !isAbsolute(displacement) && displacement !== '..' && !displacement.startsWith(`..${sep}`);
8
+ }
9
+ export async function readManagedProject(root) {
10
+ const source = await readFile(join(root, managedProjectManifest), 'utf8').catch(error => {
11
+ if (error.code === 'ENOENT')
12
+ return undefined;
13
+ throw error;
14
+ });
15
+ if (source === undefined)
16
+ return undefined;
17
+ const record = JSON.parse(source);
18
+ if (record?.schema !== 1 || typeof record.id !== 'string' || !projectIdPattern.test(record.id) ||
19
+ typeof record.name !== 'string' || typeof record.label !== 'string' || typeof record.source !== 'string' || !isAbsolute(record.source) ||
20
+ typeof record.current !== 'string' || !Array.isArray(record.revisions) || !record.revisions.some(item => item?.id === record.current) ||
21
+ record.revisions.some(item => !item || typeof item.id !== 'string' || !projectIdPattern.test(item.id) || typeof item.created !== 'string')) {
22
+ throw new Error('MaaFramework 项目记录有误,请检查副本目录');
23
+ }
24
+ return record;
25
+ }
26
+ export async function managedRevisionPath(root, revision) {
27
+ if (!projectIdPattern.test(revision))
28
+ throw new Error('MaaFramework 项目版本标识无效');
29
+ const canonicalRoot = await realpath(root);
30
+ const selected = await realpath(join(root, 'revisions', revision));
31
+ if (!withinProject(canonicalRoot, selected) || selected === canonicalRoot)
32
+ throw new Error('MaaFramework 项目版本目录超出项目范围');
33
+ return selected;
34
+ }
@@ -0,0 +1,80 @@
1
+ import { mkdtemp, realpath, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { isAbsolute, join } from 'node:path';
4
+ import { runProcess } from '../execution.js';
5
+ import { adbEnvironment } from '../emulator-managers.js';
6
+ import { runMaa } from './index.js';
7
+ import { nativeWorkerSource } from './native-worker-source.js';
8
+ import { bindNodeAgent, readNodeAgentEnvironment } from './node-agent-path.js';
9
+ import { loadProject, planRun } from './project.js';
10
+ const framework = process.platform === 'win32' ? 'MaaFramework.dll' : process.platform === 'darwin' ? 'libMaaFramework.dylib' : 'libMaaFramework.so';
11
+ export async function nativeRuntimePaths(python, libraries) {
12
+ if (!python && !libraries)
13
+ return undefined;
14
+ if (!python || !libraries)
15
+ throw new Error('请一并选择匹配的 Python 解释器与 MaaFramework 原生库目录');
16
+ if (!isAbsolute(python) || !await stat(python).then(item => item.isFile(), () => false))
17
+ throw new Error('请选择有效的原生运行器 Python 可执行文件');
18
+ if (!isAbsolute(libraries))
19
+ throw new Error('请选择 MaaFramework 原生库的绝对目录');
20
+ const path = await realpath(libraries).catch(() => { throw new Error('MaaFramework 原生库目录不存在'); });
21
+ if (!await stat(join(path, framework)).then(item => item.isFile(), () => false))
22
+ throw new Error(`MaaFramework 原生库目录缺少 ${framework}`);
23
+ return { nativePython: python, nativeLibraries: path };
24
+ }
25
+ async function invoke(paths, job, options, adbServerPort) {
26
+ const request = JSON.stringify({ nativeLibraries: paths.nativeLibraries, job });
27
+ let version;
28
+ let failure;
29
+ const args = ['-u', '-X', 'utf8', '-c', nativeWorkerSource];
30
+ const proc = { command: paths.nativePython, args, cwd: job?.directory, env: adbEnvironment(adbServerPort) };
31
+ const execution = { ...options, log(line) {
32
+ if (line.startsWith('MAS_MAA_NATIVE_DONE '))
33
+ version = line.slice('MAS_MAA_NATIVE_DONE '.length);
34
+ else if (line.startsWith('MAS_MAA_NATIVE_ERROR '))
35
+ failure = line.slice('MAS_MAA_NATIVE_ERROR '.length);
36
+ else
37
+ options.log(line);
38
+ } };
39
+ try {
40
+ if (options.launchProcess) {
41
+ await options.launchProcess({ ...proc, stdin: request }, execution);
42
+ }
43
+ else {
44
+ const temp = await mkdtemp(join(tmpdir(), 'masc-maafw-native-'));
45
+ try {
46
+ const path = join(temp, 'request.json');
47
+ await writeFile(path, request, { flag: 'wx', mode: 0o600 });
48
+ await runProcess({ id: 'maafw-native', adapter: 'maafw', name: 'MaaFramework 原生运行器', ...proc, args: [...args, path] }, execution);
49
+ }
50
+ finally {
51
+ await rm(temp, { recursive: true, force: true });
52
+ }
53
+ }
54
+ }
55
+ catch (error) {
56
+ options.signal.throwIfAborted();
57
+ throw new Error(failure || 'MaaFramework 原生运行器异常退出,请检查已安装的 maafw Python 绑定与原生库', { cause: error });
58
+ }
59
+ if (!version)
60
+ throw new Error(failure || 'MaaFramework 原生运行器未返回成功结果');
61
+ return version;
62
+ }
63
+ export async function probeNativeMaa(python, libraries) {
64
+ const paths = (await nativeRuntimePaths(python, libraries));
65
+ const version = await invoke(paths, undefined, { signal: AbortSignal.timeout(15_000), log: () => { } });
66
+ return { version, ...paths };
67
+ }
68
+ export async function runMaaSelected(input, options) {
69
+ const native = await nativeRuntimePaths(input.nativePython, input.nativeLibraries);
70
+ if (!native)
71
+ return runMaa(input, options);
72
+ const project = await loadProject(input.projectPath);
73
+ const plan = planRun(project, input);
74
+ const nodeAgent = input.agentNodeRoot && await readNodeAgentEnvironment(input.agentNodeRoot, project.directory) || undefined;
75
+ const { adbPath, address, windowHandle, agentPython } = input;
76
+ await invoke(native, { ...plan, directory: project.directory, input: { adbPath, address, windowHandle, agentPython },
77
+ agents: plan.agents.map(item => bindNodeAgent(item, project.directory, nodeAgent)),
78
+ pretasks: plan.pretasks.map(item => bindNodeAgent(item, project.directory, nodeAgent)),
79
+ }, options, input.adbServerPort);
80
+ }