@auto-mas/auto-mas-plugin-adapter-zenless 0.0.0-stage → 0.2.0

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,108 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { parse } from 'yaml';
5
+ import { executableField, existingPath, nativeAdapter, prepareExecutable, windowsOnly } from './native.js';
6
+ import { profileOption } from './profile-options.js';
7
+ const zenlessProgram = (input) => prepareExecutable(input, 'OneDragon-RuntimeLauncher.exe', ['onedragon-runtimelauncher.exe']);
8
+ function instanceIndex(value) {
9
+ const instance = typeof value === 'string' && /^\d+$/u.test(value) ? Number(value) : value;
10
+ if (typeof instance !== 'number' || !Number.isSafeInteger(instance) || instance < 1)
11
+ throw new Error('一条龙实例编号必须是正整数');
12
+ return instance;
13
+ }
14
+ async function zenlessConfiguration(directory) {
15
+ const path = await existingPath(join(directory, 'config', 'one_dragon.yml'), '绝区零一条龙账号配置');
16
+ let data;
17
+ try {
18
+ const value = parse(await readFile(path, 'utf8'), { maxAliasCount: 25 });
19
+ if (!value || typeof value !== 'object' || Array.isArray(value))
20
+ throw new Error();
21
+ data = value;
22
+ }
23
+ catch {
24
+ throw new Error('绝区零一条龙账号配置无法读取或格式无效');
25
+ }
26
+ if (!Array.isArray(data.instance_list))
27
+ throw new Error('绝区零一条龙账号配置缺少实例列表');
28
+ const instances = data.instance_list.filter((item) => !!item && typeof item === 'object' && Number.isSafeInteger(item.idx) && item.idx >= 1);
29
+ return { instances, onlyActive: 'instance_run' in data && data.instance_run !== '全部实例' };
30
+ }
31
+ export async function zenlessInstances(input) {
32
+ const { instances, onlyActive } = await zenlessConfiguration((await zenlessProgram(input)).installRoot);
33
+ return instances.filter(item => (!onlyActive || item.active === true) && instances.filter(candidate => candidate.idx === item.idx).length === 1)
34
+ .map(item => ({ value: item.idx, label: `${item.idx} · ${typeof item.name === 'string' && item.name.trim() ? item.name : '实例'}` }));
35
+ }
36
+ async function checkInstance(directory, instance) {
37
+ const { instances, onlyActive } = await zenlessConfiguration(directory);
38
+ const matches = instances.filter(item => item.idx === instance);
39
+ if (!matches.length)
40
+ throw new Error(`绝区零一条龙实例 ${instance} 不存在`);
41
+ if (matches.length > 1)
42
+ throw new Error(`绝区零一条龙实例编号 ${instance} 重复`);
43
+ const active = instances.filter(item => item.active === true);
44
+ if (active.length !== 1)
45
+ throw new Error('请在绝区零一条龙中设置一个当前实例');
46
+ if (onlyActive && active[0].idx !== instance) {
47
+ throw new Error('绝区零一条龙设置为「仅运行当前」时,所选实例必须是当前实例');
48
+ }
49
+ }
50
+ async function prepareZenless(input, override) {
51
+ const paths = await zenlessProgram(input);
52
+ const instance = instanceIndex(override ?? input.instance ?? 1);
53
+ await checkInstance(paths.installRoot, instance);
54
+ return { ...paths, instance };
55
+ }
56
+ export async function zenlessLaunch(config, account) {
57
+ const { command, installRoot: cwd, instance } = await prepareZenless(config, account.instance);
58
+ return { command, cwd, args: ['-o', '-c', '-i', String(instance)], logs: {
59
+ directory: join(cwd, '.log'), filenames: /^log\.txt(?:\.\d{4}-\d{2}-\d{2})?$/u,
60
+ success: /\[\s*一条龙\s*\]\s*执行成功\s+返回状态\s+全部结束\s*$/u,
61
+ failure: /\[\s*一条龙\s*\]\s*执行失败\s+返回状态/u,
62
+ } };
63
+ }
64
+ async function windowsElevation(signal) {
65
+ const unsupported = windowsOnly();
66
+ if (unsupported)
67
+ throw new Error(unsupported);
68
+ signal?.throwIfAborted();
69
+ const command = [
70
+ '$ErrorActionPreference = "Stop"',
71
+ '$identity = [Security.Principal.WindowsIdentity]::GetCurrent()',
72
+ '$principal = [Security.Principal.WindowsPrincipal]::new($identity)',
73
+ 'if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { exit 0 }',
74
+ 'exit 1',
75
+ ].join('\n');
76
+ return new Promise((resolve, reject) => execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], { signal, timeout: 8000, windowsHide: true, shell: false }, (error, _stdout, stderr) => {
77
+ if (signal?.aborted)
78
+ reject(signal.reason);
79
+ else if (!error)
80
+ resolve(true);
81
+ else if (error.code === 1 && !stderr.trim())
82
+ resolve(false);
83
+ else
84
+ reject(new Error('无法读取当前后端的 Windows 管理员权限'));
85
+ }));
86
+ }
87
+ async function requireElevation(signal, check = windowsElevation) {
88
+ if (!await check(signal))
89
+ throw new Error('绝区零一条龙启动器需要管理员权限。请用管理员终端启动 MASC 后端,以便调度等待游戏任务完成。');
90
+ }
91
+ export async function validateZenlessRun(script, signal, check) {
92
+ signal?.throwIfAborted();
93
+ await zenlessLaunch(script.adapterConfig ?? {}, script.accountConfig ?? {});
94
+ await requireElevation(signal, check);
95
+ }
96
+ const runZenless = nativeAdapter(zenlessLaunch);
97
+ export const zenless = {
98
+ id: 'zenless', title: '绝区零 · 原生一条龙', group: '游戏专项', supports: windowsOnly,
99
+ description: '使用 OneDragon 集成启动器运行指定实例,结束后由一条龙关闭游戏。',
100
+ scriptFields: [executableField('OneDragon-RuntimeLauncher.exe'), { ...profileOption('instance', '默认一条龙实例', 'zenless.instances', 'command', true), default: 1 }],
101
+ accountFields: [profileOption('instance', '一条龙实例覆盖(可选)', 'zenless.instances', 'scriptId')],
102
+ prepare: prepareZenless,
103
+ validateRun: validateZenlessRun,
104
+ async run(script, options) {
105
+ await requireElevation(options.signal);
106
+ await runZenless(script, options);
107
+ },
108
+ };
@@ -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
+ }
@@ -0,0 +1,198 @@
1
+ // Runs with the project's chosen Python binding and native libraries, in a separate process.
2
+ export const nativeWorkerSource = String.raw `
3
+ import json
4
+ import os
5
+ import re
6
+ import subprocess
7
+ import sys
8
+ from importlib.metadata import version
9
+ from pathlib import Path
10
+
11
+
12
+ def say(message):
13
+ print(message, flush=True)
14
+
15
+
16
+ def require(job, label):
17
+ if not job.wait().succeeded:
18
+ raise RuntimeError(label)
19
+
20
+
21
+ def executable(command, directory, agent_python=None):
22
+ if agent_python and re.fullmatch(r'python3?(?:\.exe)?', command, re.IGNORECASE):
23
+ return agent_python
24
+ expanded = command.replace('{PROJECT_DIR}', directory)
25
+ candidate = Path(directory, expanded)
26
+ if Path(expanded).is_absolute() or '/' in expanded or '\\' in expanded or candidate.is_file():
27
+ return str(candidate)
28
+ if sys.platform == 'win32' and Path(str(candidate) + '.exe').is_file():
29
+ return str(candidate) + '.exe'
30
+ return expanded
31
+
32
+
33
+ def launch(command, args, directory, env, agent_python):
34
+ program = executable(command['executable'], directory, agent_python)
35
+ return subprocess.Popen([program, *args], cwd=directory, env=env, stdin=subprocess.DEVNULL)
36
+
37
+
38
+ def methods(enum, value, default):
39
+ names = value if isinstance(value, list) else value.split('|') if isinstance(value, str) else [default]
40
+ result = 0
41
+ for name in names:
42
+ result |= int(enum[name.strip()])
43
+ return result
44
+
45
+
46
+ def make_controller(job):
47
+ from maa.controller import AdbController, Win32Controller
48
+ from maa.define import MaaWin32ScreencapMethodEnum, MaaWin32InputMethodEnum
49
+ from maa.toolkit import Toolkit
50
+
51
+ definition = job['controller']
52
+ selection = job['input']
53
+ if definition['type'] == 'Adb':
54
+ adb = selection.get('adbPath')
55
+ address = selection.get('address')
56
+ if adb:
57
+ adb = executable(adb, job['directory'])
58
+ devices = [item for item in Toolkit.find_adb_devices(adb) if not address or item.address == address]
59
+ if len(devices) > 1:
60
+ raise RuntimeError('发现多个 ADB 设备,请选择设备地址')
61
+ if devices:
62
+ device = devices[0]
63
+ return AdbController(device.adb_path, device.address, device.screencap_methods, device.input_methods, device.config)
64
+ if adb and address:
65
+ return AdbController(adb, address)
66
+ raise RuntimeError('原生运行器未发现所选 ADB 设备')
67
+
68
+ if definition['type'] != 'Win32' or sys.platform != 'win32':
69
+ raise RuntimeError('原生运行器仅支持 ADB 和 Windows Win32 控制器')
70
+ config = definition.get('win32') or {}
71
+ handle = selection.get('windowHandle')
72
+ if handle is None:
73
+ class_filter = config.get('class_regex')
74
+ window_filter = config.get('window_regex')
75
+ if not class_filter and not window_filter:
76
+ raise RuntimeError('请选择 Win32 窗口或声明窗口过滤条件')
77
+ windows = [item for item in Toolkit.find_desktop_windows()
78
+ if (not class_filter or re.search(class_filter, item.class_name))
79
+ and (not window_filter or re.search(window_filter, item.window_name))]
80
+ if len(windows) != 1:
81
+ raise RuntimeError('Win32 窗口匹配数为 ' + str(len(windows)) + ',请选择唯一窗口')
82
+ handle = windows[0].hwnd
83
+ elif not isinstance(handle, int) or handle <= 0:
84
+ raise RuntimeError('Win32 窗口句柄必须是正整数')
85
+
86
+ return Win32Controller(handle,
87
+ methods(MaaWin32ScreencapMethodEnum, config.get('screencap'), 'Background'),
88
+ methods(MaaWin32InputMethodEnum, config.get('mouse'), 'PostMessage'),
89
+ methods(MaaWin32InputMethodEnum, config.get('keyboard'), 'PostMessage'))
90
+
91
+
92
+ def configure_display(controller, definition):
93
+ if definition.get('display_raw') is True:
94
+ controller.set_screenshot_use_raw_size(True)
95
+ elif isinstance(definition.get('display_expand'), list) and len(definition['display_expand']) == 2:
96
+ controller.set_screenshot_target_expand(*definition['display_expand'])
97
+ elif isinstance(definition.get('display_long_side'), int):
98
+ controller.set_screenshot_target_long_side(definition['display_long_side'])
99
+ else:
100
+ controller.set_screenshot_target_short_side(definition.get('display_short_side') or 720)
101
+
102
+
103
+ def run(job, framework_version):
104
+ from maa.agent_client import AgentClient
105
+ from maa.resource import Resource
106
+ from maa.tasker import Tasker
107
+
108
+ directory = job['directory']
109
+ agent_python = job['input'].get('agentPython')
110
+ env = dict(os.environ, **job['agentEnvironment'], PI_CLIENT_MAAFW_VERSION=framework_version)
111
+ # Agent executables own their libraries. Apply the override only to this worker.
112
+ env.pop('MAAFW_BINARY_PATH', None)
113
+ for index, pretask in enumerate(job['pretasks'], 1):
114
+ say(f'执行前置任务 {index}')
115
+ cwd = pretask.get('directory', directory)
116
+ args = [arg.replace('{PROJECT_DIR}', cwd) for arg in pretask['args']]
117
+ if pretask.get('optionArgument'):
118
+ args.append(pretask['optionArgument'])
119
+ if launch(pretask, args, cwd, env, agent_python).wait() != 0:
120
+ raise RuntimeError(f'前置任务 {index} 执行失败')
121
+
122
+ resource = Resource()
123
+ for path in [*job['resourcePaths'], *job['attachedPaths']]:
124
+ require(resource.post_bundle(path), '原生运行器无法加载资源:' + path)
125
+ controller = make_controller(job)
126
+ configure_display(controller, job['controller'])
127
+ require(controller.post_connection(), '原生运行器无法连接控制目标')
128
+ tasker = Tasker()
129
+ if not tasker.bind(resource, controller):
130
+ raise RuntimeError('原生运行器无法绑定资源及控制器')
131
+ agents = []
132
+ try:
133
+ for index, agent in enumerate(job['agents'], 1):
134
+ say(f'启动 Agent {index}')
135
+ client = AgentClient(agent.get('identifier'))
136
+ if not client.identifier or not client.bind(resource) or not client.register_sink(resource, controller, tasker):
137
+ raise RuntimeError(f'Agent {index} 无法绑定 MaaFramework')
138
+ client.set_timeout(15_000)
139
+ cwd = agent.get('directory', directory)
140
+ args = [arg.replace('{PROJECT_DIR}', cwd) for arg in agent['args']] + [client.identifier]
141
+ process = launch(agent, args, cwd, env, agent_python)
142
+ agents.append((client, process))
143
+ if not client.connect():
144
+ raise RuntimeError(f'Agent {index} 无法连接')
145
+ for task in job['tasks']:
146
+ say('开始任务 ' + task['name'])
147
+ require(tasker.post_task(task['entry'], task['override']), '任务执行失败:' + task['name'])
148
+ if any(process.poll() is not None for _, process in agents):
149
+ raise RuntimeError('Agent 提前退出')
150
+ say('完成任务 ' + task['name'])
151
+ finally:
152
+ for client, process in reversed(agents):
153
+ try:
154
+ if client.connected:
155
+ client.disconnect()
156
+ finally:
157
+ if process.poll() is None:
158
+ process.terminate()
159
+ try:
160
+ process.wait(timeout=2)
161
+ except subprocess.TimeoutExpired:
162
+ process.kill()
163
+ process.wait()
164
+
165
+
166
+ def main():
167
+ if len(sys.argv) > 1:
168
+ request = json.loads(Path(sys.argv[1]).read_text(encoding='utf-8'))
169
+ else:
170
+ request = json.load(sys.stdin)
171
+ path = request['nativeLibraries']
172
+ os.environ['MAAFW_BINARY_PATH'] = path
173
+ dll_directory = os.add_dll_directory(path) if sys.platform == 'win32' else None
174
+ try:
175
+ from maa.library import Library
176
+ binding_version = version('maafw')
177
+ framework_version = Library.version()
178
+ number = lambda value: re.match(r'^v?(\d+\.\d+\.\d+)', value)
179
+ binding_number = number(binding_version)
180
+ library_number = number(framework_version)
181
+ if not binding_number or not library_number or binding_number.group(1) != library_number.group(1):
182
+ raise RuntimeError(f'MaaFramework 原生库 {framework_version} 与 Python 绑定 {binding_version} 不匹配')
183
+ if request.get('job') is not None:
184
+ say('MaaFramework 项目原生运行库 ' + framework_version)
185
+ run(request['job'], framework_version)
186
+ say('MAS_MAA_NATIVE_DONE ' + framework_version)
187
+ finally:
188
+ if dll_directory:
189
+ dll_directory.close()
190
+
191
+
192
+ if __name__ == '__main__':
193
+ try:
194
+ main()
195
+ except Exception as error:
196
+ say('MAS_MAA_NATIVE_ERROR ' + str(error).replace('\n', ' ')[:400])
197
+ sys.exit(1)
198
+ `;
@@ -0,0 +1,55 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstat, readFile, realpath, stat } from 'node:fs/promises';
3
+ import { isAbsolute, join, relative, resolve } from 'node:path';
4
+ import { withinProject } from './managed-project-path.js';
5
+ import { isNodeCommand } from './process.js';
6
+ export const nodeAgentManifest = '.automasc-maafw-node-agent.json';
7
+ export async function nodeAgentLock(path) {
8
+ async function read(file, limit) {
9
+ const name = join(path, file);
10
+ const info = await lstat(name).catch(error => {
11
+ if (error.code === 'ENOENT')
12
+ return undefined;
13
+ throw error;
14
+ });
15
+ if (!info)
16
+ return undefined;
17
+ if (!info.isFile() || info.size > limit)
18
+ throw new Error('Node Agent 的描述文件或 npm 锁文件无法读取');
19
+ return readFile(name);
20
+ }
21
+ const [definition, lock] = await Promise.all([
22
+ read('package.json', 1024 ** 2),
23
+ read('package-lock.json', 16 * 1024 ** 2),
24
+ ]);
25
+ return definition && lock
26
+ ? createHash('sha256').update(definition).update('\0').update(lock).digest('hex')
27
+ : undefined;
28
+ }
29
+ export async function readNodeAgentEnvironment(path, projectDirectory) {
30
+ if (!isAbsolute(path))
31
+ throw new Error('请选择已准备的 Node Agent 环境绝对目录');
32
+ const directory = await realpath(path).catch(() => { throw new Error('Node Agent 环境目录不存在'); });
33
+ const record = await readFile(join(directory, nodeAgentManifest), 'utf8').then(JSON.parse, () => undefined);
34
+ if (record?.schema !== 1 || typeof record.source !== 'string' || typeof record.packageRoot !== 'string' ||
35
+ typeof record.lock !== 'string' || typeof record.node !== 'string' || !isAbsolute(record.node)) {
36
+ throw new Error('请选择在项目管理中准备的 Node Agent 环境');
37
+ }
38
+ const source = await realpath(projectDirectory);
39
+ if (record.source !== source)
40
+ throw new Error('Node Agent 环境属于不同项目或版本,请为当前版本重新准备');
41
+ const packageDir = resolve(source, record.packageRoot);
42
+ if (!withinProject(source, packageDir) || await nodeAgentLock(packageDir) !== record.lock) {
43
+ throw new Error('Node Agent 锁文件已变化,请重新准备环境');
44
+ }
45
+ if (!await stat(record.node).then(info => info.isFile(), () => false))
46
+ throw new Error('Node Agent 的 Node.js 解释器已失效,请重新准备环境');
47
+ return { node: record.node, directory };
48
+ }
49
+ export function bindNodeAgent(command, projectDirectory, env) {
50
+ if (!env || !isNodeCommand(command.executable))
51
+ return { ...command, directory: projectDirectory };
52
+ const args = command.args.map(arg => isAbsolute(arg) && withinProject(projectDirectory, arg)
53
+ ? join(env.directory, relative(projectDirectory, arg)) : arg);
54
+ return { ...command, executable: env.node, args, directory: env.directory };
55
+ }