@auto-mas/auto-mas-plugin-maa-updates 0.0.0-stage → 0.1.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,364 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { realpathSync } from 'node:fs';
4
+ import { resolve, sep } from 'node:path';
5
+ import { createInterface } from 'node:readline';
6
+ import { Store } from './storage.js';
7
+ import { runPhases } from './run-lifecycle.js';
8
+ export function forAccount(store, script, account) {
9
+ if (account.scriptId !== script.id || account.enabled === false)
10
+ throw new Error('账号已停用或不属于此托管');
11
+ const plan = account.planId ? store.get('plans', account.planId) : undefined;
12
+ return { ...script, name: `${script.name} · ${account.name}`, accountId: account.id, accountConfig: account.accountConfig, loginAccount: account.loginAccount,
13
+ args: [...script.args ?? [], ...account.args ?? []], tasks: plan?.tasks ?? script.tasks,
14
+ ...(account.emulatorId ? { emulatorId: account.emulatorId, emulatorInstance: account.emulatorInstance } : {}) };
15
+ }
16
+ export function targetsFor(store, script) {
17
+ const accounts = store.list('accounts').filter(account => account.scriptId === script.id);
18
+ if (!accounts.length)
19
+ return [script];
20
+ return accounts.filter(account => account.enabled !== false).map(account => forAccount(store, script, account));
21
+ }
22
+ export function stopProcess(child) {
23
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null)
24
+ return;
25
+ if (process.platform === 'win32') {
26
+ const killer = spawn('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
27
+ killer.on('error', () => child.kill());
28
+ killer.on('exit', code => { if (code)
29
+ child.kill(); });
30
+ return;
31
+ }
32
+ const pid = child.pid;
33
+ try {
34
+ process.kill(-pid, 'SIGTERM');
35
+ }
36
+ catch {
37
+ child.kill('SIGTERM');
38
+ }
39
+ const deadline = setTimeout(() => {
40
+ try {
41
+ process.kill(-pid, 'SIGKILL');
42
+ }
43
+ catch { /* process group is gone */ }
44
+ }, 4000);
45
+ deadline.unref();
46
+ }
47
+ export const runProcess = async (script, options) => {
48
+ const { signal, log, started, launchProcess } = options;
49
+ if (!script.command)
50
+ throw new Error('请配置可执行文件');
51
+ signal.throwIfAborted();
52
+ if (launchProcess)
53
+ return launchProcess({ command: script.command, args: script.args, cwd: script.cwd, env: script.env }, options);
54
+ const child = spawn(script.command, script.args ?? [], {
55
+ cwd: script.cwd || undefined,
56
+ env: { ...process.env, ...script.env },
57
+ detached: process.platform !== 'win32',
58
+ windowsHide: true,
59
+ shell: false,
60
+ stdio: ['ignore', 'pipe', 'pipe'],
61
+ });
62
+ const stop = () => stopProcess(child);
63
+ signal.addEventListener('abort', stop, { once: true });
64
+ if (signal.aborted)
65
+ stop();
66
+ for (const stream of [child.stdout, child.stderr])
67
+ createInterface({ input: stream }).on('line', log);
68
+ try {
69
+ await new Promise((resolve, reject) => {
70
+ child.once('spawn', () => {
71
+ try {
72
+ started?.();
73
+ }
74
+ catch (error) {
75
+ stop();
76
+ reject(error);
77
+ }
78
+ });
79
+ child.once('error', reject);
80
+ child.once('close', (code, interruptedBy) => {
81
+ if (signal.aborted)
82
+ reject(signal.reason);
83
+ else if (code === 0)
84
+ resolve();
85
+ else
86
+ reject(new Error(`进程结束 (${code ?? interruptedBy})`));
87
+ });
88
+ });
89
+ }
90
+ finally {
91
+ signal.removeEventListener('abort', stop);
92
+ }
93
+ };
94
+ function canonicalPath(path) {
95
+ let result;
96
+ try {
97
+ result = realpathSync.native(path);
98
+ }
99
+ catch {
100
+ result = resolve(path);
101
+ }
102
+ return process.platform === 'win32' ? result.toLowerCase() : result;
103
+ }
104
+ export class Runner {
105
+ active = new Map();
106
+ claimed = new Set();
107
+ accepting = true;
108
+ startPauses = new Set();
109
+ owners = new Map();
110
+ store;
111
+ changed;
112
+ finished;
113
+ options;
114
+ lifecycle;
115
+ constructor(store, changed, finished = () => { }, options = {}, lifecycle = {}) {
116
+ this.store = store;
117
+ this.changed = changed;
118
+ this.finished = finished;
119
+ this.options = options;
120
+ this.lifecycle = lifecycle;
121
+ for (const run of this.store.list('runs').filter(run => run.status === 'running')) {
122
+ const finished = new Date().toISOString();
123
+ const stages = [...(run.stages ?? [])];
124
+ const adapter = stages[0]?.adapter ?? this.store.get('scripts', run.scriptId)?.adapter ?? 'unknown';
125
+ for (const stage of runPhases) {
126
+ const last = stages.findLast(event => event.stage === stage);
127
+ if (last && last.status !== 'started')
128
+ continue;
129
+ const status = last || stage === 'finish-task' ? 'failed' : 'skipped';
130
+ stages.push({ runId: run.id, scriptId: run.scriptId, adapter, sequence: stages.length + 1, stage, status, at: finished,
131
+ message: stage === 'finish-task' ? '上次运行中断,未能确认清理' : '上次运行中断' });
132
+ }
133
+ this.store.put('runs', { ...run, stages, status: 'error', error: '上次运行中断', finished });
134
+ }
135
+ }
136
+ register(id, execute) {
137
+ if (this.owners.has(id))
138
+ throw new Error(`执行器已注册: ${id}`);
139
+ const owner = Symbol(id);
140
+ this.owners.set(id, { execute, owner });
141
+ return () => { if (this.owners.get(id)?.owner === owner)
142
+ this.owners.delete(id); };
143
+ }
144
+ adapters() { return [...this.owners.keys()]; }
145
+ defaultTimeout() { return this.options.defaultTimeoutSeconds ?? 3600; }
146
+ conflict(key) {
147
+ if (this.claimed.has(key))
148
+ return true;
149
+ if (!key.startsWith('path:'))
150
+ return false;
151
+ const withSeparator = (path) => path.endsWith(sep) ? path : path + sep;
152
+ return [...this.claimed].some(held => held.startsWith('path:') && (held.startsWith(withSeparator(key)) || key.startsWith(withSeparator(held))));
153
+ }
154
+ claimInstallation(path) {
155
+ if (!this.accepting || this.startsPaused)
156
+ throw new Error('任务执行服务当前无法接纳维护操作');
157
+ const key = 'path:' + canonicalPath(path);
158
+ if (this.conflict(key))
159
+ throw new Error('安装目录已被其他操作占用');
160
+ this.claimed.add(key);
161
+ let held = true;
162
+ return () => {
163
+ if (held)
164
+ this.claimed.delete(key);
165
+ held = false;
166
+ };
167
+ }
168
+ start(input) {
169
+ if (!this.accepting)
170
+ throw new Error('执行服务正在退出');
171
+ if (this.startsPaused)
172
+ throw new Error('插件正在热重载,请稍后启动任务');
173
+ const script = this.lifecycle.snapshot?.(input) ?? structuredClone(input);
174
+ if (script.enabled === false)
175
+ throw new Error('该托管已停用');
176
+ const adapter = this.owners.get(script.adapter)?.execute;
177
+ if (!adapter)
178
+ throw new Error(`执行器不可用: ${script.adapter}`);
179
+ const config = script.adapterConfig;
180
+ const directory = script.projectPath || script.cwd || config?.installRoot;
181
+ const keys = [`script:${script.id}`];
182
+ if (typeof directory === 'string' && directory)
183
+ keys.push(`path:${canonicalPath(directory)}`);
184
+ if (typeof script.device === 'string' && script.device)
185
+ keys.push(`device:${script.device}`);
186
+ const address = config?.address || script.address;
187
+ if (typeof address === 'string' && address)
188
+ keys.push(`adb:${address.trim().toLowerCase()}`);
189
+ const handle = config?.windowHandle || script.windowHandle;
190
+ if (typeof handle === 'number' && handle > 0)
191
+ keys.push(`win32:${handle}`);
192
+ keys.push(...(this.lifecycle.resourceKeys?.(script) ?? []));
193
+ if (keys.some(key => this.conflict(key)))
194
+ throw new Error('脚本、工作目录或设备已被占用');
195
+ const run = { id: randomUUID(), name: script.name, scriptId: script.id, status: 'running', started: new Date().toISOString(), logs: [], stages: [],
196
+ workflow: script.workflow && Object.freeze(script.workflow), executionTarget: script.executionTarget };
197
+ this.store.put('runs', run);
198
+ keys.forEach(key => this.claimed.add(key));
199
+ const claimAdb = (address, serverPort) => {
200
+ const key = serverPort && serverPort !== 5037 ? `adb:${serverPort}:${address.trim().toLowerCase()}` : `adb:${address.trim().toLowerCase()}`;
201
+ if (keys.includes(key))
202
+ return;
203
+ if (this.claimed.has(key))
204
+ throw new Error(`ADB 设备 ${address} 已被其他任务占用`);
205
+ keys.push(key);
206
+ this.claimed.add(key);
207
+ };
208
+ const controller = new AbortController();
209
+ const done = Promise.resolve().then(async () => {
210
+ const timeout = setTimeout(() => controller.abort(new Error('运行超时')), (script.timeoutSeconds ?? this.defaultTimeout()) * 1000);
211
+ try {
212
+ await this.execute(run, script, adapter, controller.signal, claimAdb);
213
+ }
214
+ finally {
215
+ clearTimeout(timeout);
216
+ keys.forEach(key => this.claimed.delete(key));
217
+ this.active.delete(run.id);
218
+ run.finished = new Date().toISOString();
219
+ this.store.put('runs', run);
220
+ this.changed();
221
+ try {
222
+ this.finished(run);
223
+ }
224
+ catch (error) {
225
+ console.error('运行结束事件处理失败', error);
226
+ }
227
+ }
228
+ return run;
229
+ });
230
+ this.active.set(run.id, { controller, done, snapshot: run });
231
+ this.changed();
232
+ return { run, done };
233
+ }
234
+ async execute(run, original, adapter, signal, claimAdb) {
235
+ const stages = run.stages;
236
+ const log = line => {
237
+ run.logs.push(line.slice(0, 16000));
238
+ if (run.logs.length > (this.options.logLineLimit ?? 4000))
239
+ run.logs.shift();
240
+ this.changed();
241
+ };
242
+ const report = (stage, status, message) => {
243
+ const event = Object.freeze({ runId: run.id, scriptId: run.scriptId, adapter: original.adapter,
244
+ sequence: stages.length + 1, stage, status, at: new Date().toISOString(), ...(message ? { message: message.slice(0, 2000) } : {}),
245
+ ...(run.workflow ? { workflow: run.workflow } : {}) });
246
+ stages.push(event);
247
+ this.store.put('runs', run);
248
+ this.changed();
249
+ try {
250
+ this.lifecycle.stage?.(event);
251
+ }
252
+ catch (error) {
253
+ log(`运行事件处理失败: ${String(error)}`);
254
+ }
255
+ };
256
+ const options = { signal, log, report };
257
+ let targets;
258
+ const progress = { phase: 'prepare-game' };
259
+ let invoked = false;
260
+ let acceptsStart = true;
261
+ let outcome = 'success';
262
+ const started = (message) => {
263
+ if (!acceptsStart || progress.phase !== 'start-script')
264
+ return;
265
+ report('start-script', 'completed', message);
266
+ progress.phase = 'complete-script';
267
+ report('complete-script', 'started');
268
+ };
269
+ try {
270
+ report(progress.phase, 'started');
271
+ signal.throwIfAborted();
272
+ targets = await this.lifecycle.prepare?.(original, { ...options, claimAdb });
273
+ signal.throwIfAborted();
274
+ report(progress.phase, this.lifecycle.prepare ? 'completed' : 'skipped');
275
+ const script = targets?.script ?? original;
276
+ progress.phase = 'start-script';
277
+ report(progress.phase, 'started');
278
+ await this.lifecycle.before?.(script, options);
279
+ signal.throwIfAborted();
280
+ invoked = true;
281
+ const adapterOptions = { ...options, started, output: value => {
282
+ const encoded = JSON.stringify(value);
283
+ if (encoded === undefined || Buffer.byteLength(encoded) > 64 * 1024)
284
+ throw new Error('运行结果必须是 64 KiB 以内的 JSON');
285
+ run.output = JSON.parse(encoded);
286
+ } };
287
+ if (this.lifecycle.execute)
288
+ await this.lifecycle.execute(script, adapterOptions, adapter);
289
+ else if (script.executionTarget)
290
+ throw new Error('任务执行位置不可用');
291
+ else
292
+ await adapter(script, adapterOptions);
293
+ signal.throwIfAborted();
294
+ started('执行器已返回结果');
295
+ report('complete-script', 'completed');
296
+ }
297
+ catch (error) {
298
+ run.error = error instanceof Error ? error.message : String(error);
299
+ outcome = signal.aborted && signal.reason?.message === '用户停止任务' ? 'cancelled' : 'error';
300
+ report(progress.phase, outcome === 'cancelled' ? 'cancelled' : 'failed', run.error);
301
+ if (progress.phase === 'prepare-game')
302
+ report('start-script', 'skipped');
303
+ if (progress.phase !== 'complete-script')
304
+ report('complete-script', 'skipped');
305
+ }
306
+ finally {
307
+ acceptsStart = false;
308
+ const failures = [];
309
+ try {
310
+ report('finish-task', 'started');
311
+ if (invoked)
312
+ await this.lifecycle.after?.(targets?.script ?? original, options, outcome);
313
+ }
314
+ catch (error) {
315
+ failures.push(error instanceof Error ? error.message : String(error));
316
+ }
317
+ try {
318
+ await targets?.close();
319
+ }
320
+ catch (error) {
321
+ failures.push(error instanceof Error ? error.message : String(error));
322
+ }
323
+ if (failures.length) {
324
+ const message = failures.join('。');
325
+ log(`运行收尾失败: ${message}`);
326
+ report('finish-task', 'failed', message);
327
+ if (outcome === 'success') {
328
+ outcome = 'error';
329
+ run.error = message;
330
+ }
331
+ }
332
+ else
333
+ report('finish-task', 'completed');
334
+ run.status = outcome;
335
+ }
336
+ }
337
+ get(id) { return this.active.get(id)?.snapshot ?? this.store.get('runs', id); }
338
+ list() {
339
+ return this.store.recentRuns().map(run => this.active.get(run.id)?.snapshot ?? run);
340
+ }
341
+ summary() {
342
+ return this.list().map(({ logs, stages, output, ...summary }) => summary);
343
+ }
344
+ stop(id) {
345
+ const task = this.active.get(id);
346
+ if (!task)
347
+ throw new Error('任务当前未在运行');
348
+ task.controller.abort(new Error('用户停止任务'));
349
+ }
350
+ busy() { return this.active.size > 0 || this.claimed.size > 0; }
351
+ get startsPaused() { return this.startPauses.size > 0 || this.lifecycle.startsPaused?.() === true; }
352
+ pauseStarts() {
353
+ const pause = Symbol();
354
+ this.startPauses.add(pause);
355
+ return () => { this.startPauses.delete(pause); };
356
+ }
357
+ async close() {
358
+ this.accepting = false;
359
+ const active = [...this.active.values()];
360
+ for (const task of active)
361
+ task.controller.abort(new Error('用户停止任务'));
362
+ await Promise.allSettled(active.map(task => task.done));
363
+ }
364
+ }
@@ -0,0 +1,233 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { constants } from 'node:fs';
3
+ import { access, mkdtemp, readFile, rm, rmdir, stat, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { basename, delimiter, dirname, extname, isAbsolute, join } from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { parse as parseYaml } from 'yaml';
8
+ import { runProcess } from '../execution.js';
9
+ import { configName, existingPath, optionalText } from './native.js';
10
+ import { profileOption, profilesIn } from './profile-options.js';
11
+ const fileExtensions = ['.json', '.toml', '.yaml', '.yml'];
12
+ const executableNames = ['maa', 'maa.exe', 'maa-cli', 'maa-cli.exe'];
13
+ const coreLibrary = process.platform === 'win32' ? 'MaaCore.dll' : process.platform === 'darwin' ? 'libMaaCore.dylib' : 'libMaaCore.so';
14
+ const exec = promisify(execFile);
15
+ export function maaLaunch(config, account) {
16
+ const command = optionalText(config, 'command') || 'maa';
17
+ const task = configName(optionalText(account, 'task') || optionalText(config, 'task'), '任务');
18
+ const profile = optionalText(account, 'profile') || optionalText(config, 'profile');
19
+ const args = ['run', task, '--batch'];
20
+ if (profile)
21
+ args.push('--profile', configName(profile, '设备配置'));
22
+ const address = optionalText(config, 'address');
23
+ if (address) {
24
+ if (!/^[\w.:[\]-]{1,256}$/u.test(address) || address.startsWith('-'))
25
+ throw new Error('MAA 的 ADB 设备地址或序列号无效');
26
+ args.push('--addr', address);
27
+ }
28
+ const configRoot = optionalText(config, 'configRoot');
29
+ const dataRoot = optionalText(config, 'dataRoot');
30
+ const env = {
31
+ ...(configRoot ? { MAA_CONFIG_DIR: configRoot } : {}),
32
+ ...(dataRoot ? { MAA_DATA_DIR: dataRoot, MAA_STATE_DIR: join(dataRoot, 'state'), MAA_CACHE_DIR: join(dataRoot, 'cache') } : {}),
33
+ };
34
+ return { command, args, env: configRoot || dataRoot ? env : undefined };
35
+ }
36
+ async function isFile(path) {
37
+ return (await stat(path).catch(error => {
38
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
39
+ return undefined;
40
+ throw error;
41
+ }))?.isFile() === true;
42
+ }
43
+ async function commandPath(value) {
44
+ if (!isAbsolute(value) && !executableNames.includes(value.toLowerCase()))
45
+ throw new Error('请选择 maa-cli 的可执行文件');
46
+ const names = value === 'maa' ? ['maa', 'maa-cli'] : [value];
47
+ const paths = isAbsolute(value) ? [value] : (process.env.PATH ?? '').split(delimiter).flatMap(directory => {
48
+ if (!isAbsolute(directory))
49
+ return [];
50
+ return names.map(name => join(directory, process.platform === 'win32' && !extname(name) ? `${name}.exe` : name));
51
+ });
52
+ let gui = false;
53
+ for (const candidate of paths) {
54
+ if (!await isFile(candidate))
55
+ continue;
56
+ if (basename(candidate).toLowerCase() === 'maa.exe' && await isFile(join(dirname(candidate), 'MAA.deps.json')) && await isFile(join(dirname(candidate), 'MAA.dll'))) {
57
+ gui = true;
58
+ continue;
59
+ }
60
+ if (await access(candidate, constants.X_OK).then(() => true, () => false))
61
+ return candidate;
62
+ }
63
+ if (gui)
64
+ throw new Error('当前路径是 Windows 图形版 MAA.exe,请选择独立的 maa-cli 可执行文件');
65
+ throw new Error('找不到 maa-cli 可执行文件,请设置路径或将 maa/maa-cli 加入 PATH');
66
+ }
67
+ export async function maaProfiles(input, type) {
68
+ const configured = optionalText(input, 'configRoot');
69
+ const command = configured ? '' : await commandPath(optionalText(input, 'command') || 'maa');
70
+ const base = configured || (await exec(command, ['dir', 'config'], { windowsHide: true, timeout: 8000 })).stdout.trim();
71
+ return profilesIn(join(await existingPath(base, 'maa-cli 配置目录', true), type), fileExtensions);
72
+ }
73
+ async function findConfig(directory, name, label, required = true) {
74
+ const files = await Promise.all(fileExtensions.map(async (ext) => {
75
+ const path = join(directory, `${name}${ext}`);
76
+ return await isFile(path) ? path : undefined;
77
+ }));
78
+ const matches = files.filter(path => path !== undefined);
79
+ if (required && !matches.length)
80
+ throw new Error(`${label}不存在,请检查名称和 maa-cli 配置目录`);
81
+ if (matches.length > 1)
82
+ throw new Error(`${label}有多个同名文件,请为各配置使用不同名称`);
83
+ return matches[0];
84
+ }
85
+ function record(value) {
86
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
87
+ }
88
+ function withLoginSelector(task, loginAccount) {
89
+ const tasks = Array.isArray(task.tasks) ? task.tasks : [];
90
+ const first = record(tasks[0]);
91
+ const params = record(first?.params);
92
+ const conditional = first?.variants !== undefined && (!Array.isArray(first.variants) || first.variants.length > 0);
93
+ const disabled = params?.enable !== undefined && params.enable !== true;
94
+ if (first?.type !== 'StartUp' || conditional || disabled) {
95
+ throw new Error('已指定登录账号,请使用以启用且无条件的 StartUp 开头的 maa-cli 任务文件');
96
+ }
97
+ const patchParams = (entry) => {
98
+ const params = record(entry.params);
99
+ if (entry.params !== undefined && !params)
100
+ throw new Error('MAA StartUp 的 params 必须是对象');
101
+ return { ...entry, params: { ...params, account_name: loginAccount } };
102
+ };
103
+ // Every later StartUp must use the same selector, including its variants.
104
+ return { ...task, tasks: tasks.map(value => {
105
+ const item = record(value);
106
+ if (item?.type !== 'StartUp')
107
+ return value;
108
+ const result = patchParams(item);
109
+ if (item.variants !== undefined) {
110
+ if (!Array.isArray(item.variants) || item.variants.some(variant => !record(variant)))
111
+ throw new Error('MAA StartUp 的 variants 必须是对象列表');
112
+ return { ...result, variants: item.variants.map(patchParams) };
113
+ }
114
+ return result;
115
+ }) };
116
+ }
117
+ async function resolveMaaRun(script, signal) {
118
+ signal?.throwIfAborted();
119
+ const config = record(script.adapterConfig) ?? {};
120
+ const account = record(script.accountConfig) ?? {};
121
+ const launch = maaLaunch({ ...config, address: config.address || script.address }, account);
122
+ const command = await commandPath(launch.command);
123
+ const cwd = script.cwd ? await existingPath(script.cwd, 'MAA 工作目录', true) : undefined;
124
+ const env = launch.env;
125
+ if (env?.MAA_DATA_DIR) {
126
+ const data = await existingPath(env.MAA_DATA_DIR, 'MaaCore 数据目录', true);
127
+ if (!await isFile(join(data, 'lib', coreLibrary)))
128
+ throw new Error(`MaaCore 数据目录缺少 lib/${coreLibrary}`);
129
+ await existingPath(join(data, 'resource'), 'MaaCore 资源目录', true);
130
+ }
131
+ const query = async (args, label) => {
132
+ try {
133
+ const { stdout } = await exec(command, args, { cwd, env: { ...process.env, ...script.env, ...env }, signal, windowsHide: true, timeout: 8000, maxBuffer: 4 * 1024 * 1024 });
134
+ return stdout.trim();
135
+ }
136
+ catch {
137
+ signal?.throwIfAborted();
138
+ throw new Error(label);
139
+ }
140
+ };
141
+ const root = await existingPath(env?.MAA_CONFIG_DIR || await query(['dir', 'config'], '无法查询 maa-cli 配置目录,请检查所选 CLI 或指定目录'), 'maa-cli 配置目录', true);
142
+ const readConfig = async (path, label) => {
143
+ try {
144
+ const ext = extname(path);
145
+ const content = ext === '.toml' ? await query(['convert', path, '-f', 'json'], `maa-cli 无法转换${label}`) : await readFile(path, { encoding: 'utf8', signal });
146
+ const input = content.replace(/^\uFEFF/u, '');
147
+ const value = record(ext === '.json' || ext === '.toml' ? JSON.parse(input) : parseYaml(input, { maxAliasCount: 25 }));
148
+ if (!value)
149
+ throw new Error('Invalid configuration object');
150
+ return value;
151
+ }
152
+ catch {
153
+ signal?.throwIfAborted();
154
+ throw new Error(`${label}内容无效,请检查文件格式`);
155
+ }
156
+ };
157
+ const task = await readConfig(await findConfig(join(root, 'tasks'), launch.args[1], 'MAA 任务文件'), 'MAA 任务文件');
158
+ if (!Array.isArray(task.tasks))
159
+ throw new Error('MAA 任务文件缺少 tasks 列表');
160
+ const profile = optionalText(account, 'profile') || optionalText(config, 'profile');
161
+ const profilePath = await findConfig(join(root, 'profiles'), profile || 'default', 'MAA 设备配置文件', !!profile)
162
+ ?? await findConfig(root, 'asst', 'MAA 设备配置文件', false);
163
+ if (profilePath) {
164
+ const settings = await readConfig(profilePath, 'MAA 设备配置文件');
165
+ if (settings.connection !== undefined && !record(settings.connection))
166
+ throw new Error('MAA 设备配置中的 connection 必须是对象');
167
+ const path = optionalText(record(settings.connection) ?? {}, 'adb_path');
168
+ if (path && isAbsolute(path) && !await isFile(path))
169
+ throw new Error('MAA 设备配置里的 ADB 程序不存在');
170
+ }
171
+ const loginAccount = optionalText(script, 'loginAccount');
172
+ return { command, args: launch.args, cwd, env, loginAccount, task: loginAccount ? withLoginSelector(task, loginAccount) : undefined };
173
+ }
174
+ export async function validateMaaRun(script, signal) {
175
+ await resolveMaaRun(script, signal);
176
+ }
177
+ async function runMaa(script, options) {
178
+ const { loginAccount, task, ...run } = await resolveMaaRun(script, options.signal);
179
+ // maa-cli emits task progress at Info, above its default Warn filter.
180
+ const launch = { ...script, ...run, env: { ...script.env, ...run.env, MAA_LOG: 'info' } };
181
+ if (!task)
182
+ return runProcess(launch, options);
183
+ const directory = await mkdtemp(join(tmpdir(), 'masc-maa-task-'));
184
+ const path = join(directory, 'task.json');
185
+ try {
186
+ await writeFile(path, JSON.stringify(task), { mode: 0o600, signal: options.signal });
187
+ const args = [...run.args];
188
+ args[1] = path;
189
+ await runProcess({ ...launch, args }, {
190
+ ...options, log: line => options.log(line.replaceAll(loginAccount, '[已隐藏账号]')),
191
+ });
192
+ }
193
+ finally {
194
+ await rm(path, { force: true });
195
+ await rmdir(directory);
196
+ }
197
+ }
198
+ export const maa = {
199
+ id: 'maa', title: '明日方舟 · maa-cli', group: '游戏专项',
200
+ description: '使用 maa-cli 和 MaaCore 运行上游任务文件或账号指定的设备配置。',
201
+ scriptFields: [
202
+ { key: 'command', label: 'maa-cli 可执行文件(可留空使用 PATH)', kind: 'hostpath' },
203
+ { key: 'configRoot', label: 'maa-cli 配置目录(可选)', kind: 'hostpath', directory: true },
204
+ { key: 'dataRoot', label: 'MaaCore 数据目录(可选)', kind: 'hostpath', directory: true, hint: '使用包含 lib 和 resource 的目录,独立保存运行状态和缓存。' },
205
+ { key: 'task', label: '任务文件名(无扩展名)', required: true },
206
+ { key: 'profile', label: '设备配置名(可选)' },
207
+ ],
208
+ accountFields: [
209
+ { key: 'loginAccount', label: '登录账号', hint: '填写已登录账号的唯一识别值或尾号。调度时会为任务文件中的 StartUp 生成临时切号设置。' },
210
+ { ...profileOption('task', '任务文件名覆盖(可选)', 'maa.tasks', 'scriptId'), hint: '需要切号时可为此账号选择对应的任务文件。' },
211
+ profileOption('profile', '设备配置名覆盖(可选)', 'maa.profiles', 'scriptId'),
212
+ ],
213
+ prepare: async (input) => {
214
+ const rawCommand = optionalText(input, 'command');
215
+ const command = rawCommand ? await existingPath(rawCommand, 'maa-cli 可执行文件') : '';
216
+ if (command) {
217
+ if (!executableNames.includes(basename(command).toLowerCase()))
218
+ throw new Error('请选择 maa-cli 的可执行文件');
219
+ await commandPath(command);
220
+ }
221
+ const rawConfigRoot = optionalText(input, 'configRoot');
222
+ const configRoot = rawConfigRoot ? await existingPath(rawConfigRoot, 'maa-cli 配置目录', true) : '';
223
+ const rawDataRoot = optionalText(input, 'dataRoot');
224
+ const dataRoot = rawDataRoot ? await existingPath(rawDataRoot, 'MaaCore 数据目录', true) : '';
225
+ const task = configName(optionalText(input, 'task'), '任务');
226
+ const profile = optionalText(input, 'profile');
227
+ if (profile)
228
+ configName(profile, '设备配置');
229
+ return { command, configRoot, dataRoot, task, profile, installRoot: dataRoot || configRoot || (isAbsolute(command) ? dirname(command) : undefined) };
230
+ },
231
+ validateRun: validateMaaRun,
232
+ run: runMaa,
233
+ };