@auto-mas/auto-mas-plugin-maafw-projects 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,213 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import { mkdir, mkdtemp, readdir, rm, stat } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { Transform } from 'node:stream';
5
+ import { pipeline } from 'node:stream/promises';
6
+ import { t as listTar, x as extractTar } from 'tar';
7
+ import { Open } from 'unzipper';
8
+ import { stageAsset } from '../updates.js';
9
+ import { inspectProject } from './project.js';
10
+ const maximumDownload = 1024 ** 3;
11
+ const maximumExpansion = 4 * 1024 ** 3;
12
+ const assetName = /^[a-z0-9][\w .-]{0,100}\.(?:zip|tar\.gz)$/iu;
13
+ const redirectHosts = new Set(['github.com', 'release-assets.githubusercontent.com', 'objects.githubusercontent.com', 'github-releases.githubusercontent.com']);
14
+ function githubRepository(raw) {
15
+ let url;
16
+ try {
17
+ url = new URL(raw);
18
+ }
19
+ catch {
20
+ throw new Error('ProjectInterface 未提供有效的 GitHub 仓库地址');
21
+ }
22
+ const path = /^\/([a-z\d_.-]+)\/([a-z\d_.-]+)\/?$/iu.exec(url.pathname);
23
+ if (!path || url.origin !== 'https://github.com' || url.username || url.password || url.search || url.hash) {
24
+ throw new Error('请选择 ProjectInterface 声明的公开 GitHub 仓库');
25
+ }
26
+ return `${path[1]}/${path[2].replace(/\.git$/iu, '')}`;
27
+ }
28
+ async function boundedJson(response) {
29
+ if (!response.ok || !response.body)
30
+ throw new Error(`GitHub 发行查询失败(HTTP ${response.status})`);
31
+ const reader = response.body.getReader();
32
+ const parts = [];
33
+ let size = 0;
34
+ try {
35
+ while (true) {
36
+ const chunk = await reader.read();
37
+ if (chunk.done)
38
+ break;
39
+ size += chunk.value.byteLength;
40
+ if (size > 1024 * 1024)
41
+ throw new Error('GitHub 发行记录过大');
42
+ parts.push(chunk.value);
43
+ }
44
+ return JSON.parse(Buffer.concat(parts).toString('utf8'));
45
+ }
46
+ finally {
47
+ await reader.cancel();
48
+ }
49
+ }
50
+ export async function githubProjectAssets(repository, load = fetch, signal = AbortSignal.timeout(15_000)) {
51
+ const slug = githubRepository(repository);
52
+ const response = await load(`https://api.github.com/repos/${slug}/releases/latest`, { signal, redirect: 'error',
53
+ headers: { Accept: 'application/vnd.github+json' } });
54
+ const latest = await boundedJson(response);
55
+ if (typeof latest?.tag_name !== 'string' || !latest.tag_name.trim() || !Array.isArray(latest.assets))
56
+ throw new Error('GitHub 未返回可识别的发行数据');
57
+ const tag = latest.tag_name;
58
+ const assets = [];
59
+ let excluded = 0;
60
+ for (const row of latest.assets) {
61
+ if (!row || typeof row.name !== 'string' || !assetName.test(row.name))
62
+ continue;
63
+ const url = `https://github.com/${slug}/releases/download/${encodeURIComponent(tag)}/${encodeURIComponent(row.name)}`;
64
+ const digest = typeof row.digest === 'string' ? /^sha256:([a-f\d]{64})$/iu.exec(row.digest) : undefined;
65
+ if (!digest || row.browser_download_url !== url || !Number.isSafeInteger(row.size) || row.size < 1 || row.size > maximumDownload) {
66
+ excluded++;
67
+ continue;
68
+ }
69
+ assets.push({ name: row.name, size: row.size, sha256: digest[1], url, platform: process.platform, arch: process.arch });
70
+ }
71
+ return { tag, assets, excluded };
72
+ }
73
+ function archiveEntryPath(root, raw) {
74
+ let path = raw.replace(/^\.\//u, '').replace(/\/$/u, '');
75
+ if (!path)
76
+ return root;
77
+ const segments = path.split('/');
78
+ if (segments.some(segment => !segment || segment === '.' || segment === '..' || /[\\:\u0000-\u001f*?"<>|]|[ .]$/u.test(segment) ||
79
+ /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(segment)))
80
+ throw new Error(`项目包含无效路径:${path}`);
81
+ path = join(root, ...segments);
82
+ return path;
83
+ }
84
+ async function tarProject(file, root) {
85
+ let size = 0;
86
+ let fileCount = 0;
87
+ let failure;
88
+ const files = new Set();
89
+ await listTar({ file, strict: true, onReadEntry(entry) {
90
+ if (failure)
91
+ return;
92
+ try {
93
+ const target = archiveEntryPath(root, entry.path).toLowerCase();
94
+ if (entry.type === 'Directory')
95
+ return;
96
+ if (!['File', 'OldFile', 'ContiguousFile'].includes(entry.type))
97
+ throw new Error('项目包含链接或特殊文件');
98
+ if (files.has(target) || target === root.toLowerCase())
99
+ throw new Error('项目包含重复或无效文件路径');
100
+ files.add(target);
101
+ size += entry.size;
102
+ fileCount++;
103
+ if (!Number.isSafeInteger(size) || size > maximumExpansion || fileCount > 50_000)
104
+ throw new Error('项目包解压后体积或文件数超出限制');
105
+ }
106
+ catch (error) {
107
+ failure = error instanceof Error ? error : new Error(String(error));
108
+ }
109
+ } });
110
+ if (failure)
111
+ throw failure;
112
+ await extractTar({ file, cwd: root, strict: true, preservePaths: false, noMtime: true, chmod: false,
113
+ filter(_path, entry) { if (entry.mode !== undefined)
114
+ entry.mode &= 0o755; return true; } });
115
+ }
116
+ async function zipProject(file, root) {
117
+ const { files } = await Open.file(file);
118
+ if (files.length > 50_000)
119
+ throw new Error('项目包文件数超出限制');
120
+ let declaredTotal = 0;
121
+ const seen = new Set();
122
+ const entries = files.map(entry => {
123
+ const target = archiveEntryPath(root, entry.path);
124
+ const { externalFileAttributes = 0, uncompressedSize = 0 } = entry;
125
+ const mode = externalFileAttributes >>> 16;
126
+ const type = mode & 0o170000;
127
+ if (type && type !== (entry.type === 'Directory' ? 0o040000 : 0o100000))
128
+ throw new Error('项目包含链接或特殊文件');
129
+ if (seen.has(target.toLowerCase()) || target === root && entry.type !== 'Directory')
130
+ throw new Error('项目包含重复或无效文件路径');
131
+ seen.add(target.toLowerCase());
132
+ declaredTotal += uncompressedSize;
133
+ if (!Number.isSafeInteger(declaredTotal) || declaredTotal > maximumExpansion)
134
+ throw new Error('项目包解压后体积超出限制');
135
+ return { entry, target, mode, uncompressedSize };
136
+ });
137
+ let size = 0;
138
+ for (const { entry, target, mode, uncompressedSize } of entries) {
139
+ if (entry.type === 'Directory') {
140
+ await mkdir(target, { recursive: true });
141
+ continue;
142
+ }
143
+ await mkdir(dirname(target), { recursive: true });
144
+ let read = 0;
145
+ const limit = new Transform({ transform(chunk, _encoding, callback) {
146
+ read += chunk.length;
147
+ size += chunk.length;
148
+ if (read > uncompressedSize || size > maximumExpansion)
149
+ callback(new Error('项目包实际解压大小与记录不符'));
150
+ else
151
+ callback(null, chunk);
152
+ } });
153
+ await pipeline(entry.stream(), limit, createWriteStream(target, { flags: 'wx', mode: (mode || 0o644) & 0o755 }));
154
+ if (read !== uncompressedSize)
155
+ throw new Error('项目包实际解压大小与记录不符');
156
+ }
157
+ }
158
+ export async function extractProjectArchive(file, directory) {
159
+ if (/\.zip$/iu.test(file))
160
+ await zipProject(file, directory);
161
+ else if (/\.tar\.gz$/iu.test(file))
162
+ await tarProject(file, directory);
163
+ else
164
+ throw new Error('请选择 .zip 或 .tar.gz 项目完整包');
165
+ return projectRoot(directory);
166
+ }
167
+ async function projectRoot(directory) {
168
+ const hasInterface = async (path) => (await stat(join(path, 'interface.json')).catch(error => {
169
+ if (error.code === 'ENOENT')
170
+ return undefined;
171
+ throw error;
172
+ }))?.isFile() === true;
173
+ if (await hasInterface(directory))
174
+ return directory;
175
+ const children = (await readdir(directory, { withFileTypes: true })).filter(item => item.isDirectory());
176
+ const candidates = (await Promise.all(children.map(async (item) => {
177
+ const path = join(directory, item.name);
178
+ return await hasInterface(path) ? path : undefined;
179
+ }))).filter(path => path !== undefined);
180
+ if (candidates.length !== 1)
181
+ throw new Error('项目包须包含唯一的顶层 interface.json');
182
+ return candidates[0];
183
+ }
184
+ export async function inspectProjectRelease(projects, id) {
185
+ const record = await projects.get(id);
186
+ const preview = await inspectProject(record.path);
187
+ const latest = await githubProjectAssets(preview.github ?? '');
188
+ return { current: preview.version, ...latest };
189
+ }
190
+ export async function installProjectRelease(projects, id, sha256) {
191
+ const record = await projects.get(id);
192
+ const { github } = await inspectProject(record.path);
193
+ const latest = await githubProjectAssets(github ?? '');
194
+ const asset = latest.assets.find(item => item.sha256 === sha256);
195
+ if (!asset)
196
+ throw new Error('官方发行包不存在、已变化或缺少 SHA-256');
197
+ const directory = await mkdtemp(join(projects.directory, '.download-'));
198
+ try {
199
+ const file = await stageAsset(directory, asset, (url, init) => {
200
+ const parsed = new URL(String(url));
201
+ if (parsed.protocol !== 'https:' || !redirectHosts.has(parsed.hostname) || parsed.username || parsed.password || parsed.port) {
202
+ throw new Error('GitHub 项目包重定向至未认可的来源');
203
+ }
204
+ return fetch(parsed, init);
205
+ });
206
+ const unpacked = join(directory, 'project');
207
+ await mkdir(unpacked);
208
+ return await projects.install(id, await extractProjectArchive(file, unpacked), record.current, latest.tag);
209
+ }
210
+ finally {
211
+ await rm(directory, { recursive: true, force: true });
212
+ }
213
+ }
@@ -0,0 +1,361 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { isAbsolute, resolve } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { loadProject, planRun, projectPath } from './project.js';
6
+ import { bindNodeAgent, readNodeAgentEnvironment } from './node-agent-path.js';
7
+ import { isPythonCommand, readLines, terminateTree } from './process.js';
8
+ const cancellation = new AbortController();
9
+ const signal = cancellation.signal;
10
+ let activeTasker;
11
+ let nativeStop;
12
+ let running = false;
13
+ function log(line) {
14
+ process.stdout.write(`${line}\n`);
15
+ }
16
+ function deliver(message) {
17
+ if (process.connected)
18
+ process.send?.(message, () => undefined);
19
+ }
20
+ function stop() {
21
+ if (!nativeStop && activeTasker) {
22
+ const tasker = activeTasker;
23
+ try {
24
+ nativeStop = tasker.post_stop().wait().catch((error) => log(`MaaFramework stop request failed: ${String(error)}`));
25
+ }
26
+ catch (error) {
27
+ log(`MaaFramework stop request failed: ${String(error)}`);
28
+ }
29
+ }
30
+ cancellation.abort(new DOMException('MaaFramework run stopped.', 'AbortError'));
31
+ }
32
+ function resolveCommand(directory, command) {
33
+ const expanded = command.replaceAll('{PROJECT_DIR}', directory);
34
+ if (isAbsolute(expanded))
35
+ return expanded;
36
+ const local = resolve(directory, expanded);
37
+ if (/[\\/]/.test(expanded) || existsSync(local))
38
+ return local;
39
+ if (process.platform === 'win32' && existsSync(`${local}.exe`))
40
+ return `${local}.exe`;
41
+ return expanded;
42
+ }
43
+ function startProjectCommand(command, args, directory, environment, label, terminateOnAbort, agentPython) {
44
+ signal.throwIfAborted();
45
+ const executable = agentPython && isPythonCommand(command.executable) ? agentPython : resolveCommand(directory, command.executable);
46
+ const env = { ...process.env, ...environment };
47
+ delete env.ELECTRON_RUN_AS_NODE;
48
+ const child = spawn(executable, args, {
49
+ cwd: directory,
50
+ env,
51
+ stdio: ['ignore', 'pipe', 'pipe'],
52
+ windowsHide: true,
53
+ detached: process.platform !== 'win32',
54
+ });
55
+ const pid = child.pid;
56
+ if (pid)
57
+ deliver({ type: 'process-started', pid });
58
+ async function terminate() {
59
+ if (pid && child.exitCode === null && child.signalCode === null)
60
+ await terminateTree(pid);
61
+ }
62
+ function onAbort() { void terminate(); }
63
+ if (terminateOnAbort)
64
+ signal.addEventListener('abort', onAbort, { once: true });
65
+ let launchError;
66
+ child.once('error', (error) => { launchError = error; });
67
+ const started = new Promise((done) => {
68
+ child.once('spawn', () => done(true));
69
+ child.once('error', () => done(false));
70
+ });
71
+ const outcome = new Promise((done) => child.once('close', (code, exitSignal) => {
72
+ signal.removeEventListener('abort', onAbort);
73
+ if (pid)
74
+ deliver({ type: 'process-exited', pid });
75
+ done({ code, signal: exitSignal, error: launchError });
76
+ }));
77
+ readLines(child.stdout, (line) => log(`[${label}] ${line}`));
78
+ readLines(child.stderr, (line) => log(`[${label} stderr] ${line}`));
79
+ return { outcome, started, terminate };
80
+ }
81
+ function commandFailure(label, outcome) {
82
+ return new Error(outcome.error ? `${label} could not start: ${outcome.error.message}`
83
+ : `${label} exited with ${outcome.signal ?? outcome.code ?? 'unknown status'}.`);
84
+ }
85
+ function expandArgs(args, directory) {
86
+ return args.map((arg) => arg.replaceAll('{PROJECT_DIR}', directory));
87
+ }
88
+ async function loadSDK() {
89
+ try {
90
+ await import('@maaxyz/maa-node');
91
+ }
92
+ catch (error) {
93
+ throw new Error(`MaaFramework Node SDK could not load on ${process.platform}-${process.arch}: ${String(error)}`);
94
+ }
95
+ if (!globalThis.maa?.Global || !globalThis.maa.Tasker || !globalThis.maa.Resource) {
96
+ throw new Error(`MaaFramework Node SDK is unavailable on ${process.platform}-${process.arch}.`);
97
+ }
98
+ return globalThis.maa;
99
+ }
100
+ function winMethod(table, value, fallback, combine = false) {
101
+ const names = typeof value === 'string' ? (combine ? value.split(/[|,]/) : [value]) : [fallback];
102
+ let result = 0n;
103
+ for (const name of names) {
104
+ const key = name.trim();
105
+ if (!Object.hasOwn(table, key))
106
+ throw new Error(`Unknown Win32 controller method "${key}".`);
107
+ result |= BigInt(table[key]);
108
+ }
109
+ return result.toString();
110
+ }
111
+ function setDisplay(controller, config) {
112
+ if (config.display_raw === true)
113
+ controller.screenshot_use_raw_size = true;
114
+ else if (Array.isArray(config.display_expand) && config.display_expand.length === 2 && config.display_expand.every((part) => Number.isInteger(part) && part > 0)) {
115
+ controller.screenshot_target_expand = [config.display_expand[0], config.display_expand[1]];
116
+ }
117
+ else if (typeof config.display_long_side === 'number')
118
+ controller.screenshot_target_long_side = config.display_long_side;
119
+ else
120
+ controller.screenshot_target_short_side = typeof config.display_short_side === 'number' ? config.display_short_side : 720;
121
+ }
122
+ function configOf(value) {
123
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
124
+ }
125
+ async function makeController(sdk, definition, input, directory) {
126
+ if (definition.type === 'Adb') {
127
+ if (!sdk.AdbController || !sdk.AdbScreencapMethod || !sdk.AdbInputMethod)
128
+ throw new Error('This MaaFramework SDK build lacks ADB support.');
129
+ const adb = input.adbPath && resolveCommand(directory, input.adbPath);
130
+ const devices = await sdk.AdbController.find(adb) ?? [];
131
+ const matches = input.address ? devices.filter((item) => item[2] === input.address) : devices;
132
+ if (matches.length > 1)
133
+ throw new Error('Multiple ADB devices match. Set an explicit device address.');
134
+ const device = matches[0];
135
+ if (device) {
136
+ const [, adbPath, address, screencap, inputMethod, config] = device;
137
+ log(`ADB device ${address}`);
138
+ return new sdk.AdbController(adbPath, address, screencap, inputMethod, config);
139
+ }
140
+ if (!input.address || !adb)
141
+ throw new Error('No matching ADB device was discovered. Connect a device or set both its ADB executable and address.');
142
+ log(`ADB device ${input.address}`);
143
+ return new sdk.AdbController(adb, input.address, sdk.AdbScreencapMethod.Default, sdk.AdbInputMethod.Default, '{}');
144
+ }
145
+ if (!sdk.Win32Controller || !sdk.Win32ScreencapMethod || !sdk.Win32InputMethod)
146
+ throw new Error('This MaaFramework SDK build lacks Win32 support.');
147
+ const config = configOf(definition.win32);
148
+ let handle;
149
+ if (input.windowHandle !== undefined) {
150
+ if (!Number.isSafeInteger(input.windowHandle) || input.windowHandle <= 0)
151
+ throw new Error('The Win32 window handle must be a positive safe integer.');
152
+ handle = String(input.windowHandle);
153
+ }
154
+ else {
155
+ const classRegex = typeof config.class_regex === 'string' && config.class_regex ? new RegExp(config.class_regex) : undefined;
156
+ const titleRegex = typeof config.window_regex === 'string' && config.window_regex ? new RegExp(config.window_regex) : undefined;
157
+ if (!classRegex && !titleRegex)
158
+ throw new Error('Set a Win32 window handle or define a window title or class filter in ProjectInterface.');
159
+ const windows = await sdk.Win32Controller.find() ?? [];
160
+ const matches = windows.filter(([, className, title]) => (!classRegex || classRegex.test(className)) && (!titleRegex || titleRegex.test(title)));
161
+ if (matches.length === 0)
162
+ throw new Error('No Win32 window matches the ProjectInterface controller.');
163
+ if (matches.length > 1)
164
+ throw new Error('Multiple Win32 windows match. Set an explicit window handle.');
165
+ handle = matches[0][0];
166
+ }
167
+ log(`Win32 window ${handle}`);
168
+ return new sdk.Win32Controller(handle, winMethod(sdk.Win32ScreencapMethod, config.screencap, 'Background', true), winMethod(sdk.Win32InputMethod, config.mouse, 'PostMessage'), winMethod(sdk.Win32InputMethod, config.keyboard, 'PostMessage'));
169
+ }
170
+ async function requireSuccess(job, failure) {
171
+ const completed = await job.wait();
172
+ signal.throwIfAborted();
173
+ if (!completed.succeeded)
174
+ throw new Error(failure);
175
+ }
176
+ function cleanup(action) {
177
+ try {
178
+ action();
179
+ }
180
+ catch (error) {
181
+ log(`MaaFramework cleanup warning: ${String(error)}`);
182
+ }
183
+ }
184
+ async function execute(input) {
185
+ const project = await loadProject(input.projectPath);
186
+ const plan = planRun(project, input);
187
+ const nodeAgent = input.agentNodeRoot && await readNodeAgentEnvironment(input.agentNodeRoot, project.directory) || undefined;
188
+ signal.throwIfAborted();
189
+ const sdk = await loadSDK();
190
+ sdk.Global.stdout_level = 'Warn';
191
+ const environment = { ...plan.agentEnvironment, PI_CLIENT_MAAFW_VERSION: sdk.Global.version };
192
+ log(`MaaFramework ${sdk.Global.version} · ${project.label} · ${plan.controller.name} · ${plan.resource.name}`);
193
+ for (const warning of plan.warnings)
194
+ log(warning);
195
+ if (plan.controller.permission_required === true)
196
+ log('This controller requires the application to run with administrator privileges.');
197
+ for (const [index, pretask] of plan.pretasks.entries()) {
198
+ const label = `Pretask ${index + 1}`;
199
+ log(`${label} starting`);
200
+ const command = bindNodeAgent(pretask, project.directory, nodeAgent);
201
+ const args = expandArgs(command.args, command.directory);
202
+ if (pretask.optionArgument)
203
+ args.push(pretask.optionArgument);
204
+ const { outcome } = startProjectCommand(command, args, command.directory, environment, label, true, input.agentPython);
205
+ const completed = await outcome;
206
+ signal.throwIfAborted();
207
+ if (completed.code !== 0 || completed.error)
208
+ throw commandFailure(label, completed);
209
+ }
210
+ const resource = new sdk.Resource();
211
+ let controller;
212
+ let tasker;
213
+ const clients = [];
214
+ const agents = [];
215
+ const unexpectedExit = Promise.withResolvers();
216
+ // Observe the rejection even if it occurs between two native jobs.
217
+ void unexpectedExit.promise.catch(() => undefined);
218
+ let taskOperation;
219
+ let agentError;
220
+ let cleaning = false;
221
+ try {
222
+ for (const path of plan.resourcePaths) {
223
+ signal.throwIfAborted();
224
+ log(`Loading resource ${path}`);
225
+ await requireSuccess(resource.post_bundle(path), `MaaFramework could not load resource ${path}.`);
226
+ }
227
+ if (typeof plan.resource.hash === 'string' && resource.hash !== plan.resource.hash)
228
+ log(`Resource hash mismatch for ${plan.resource.name}.`);
229
+ for (const path of plan.attachedPaths) {
230
+ log(`Loading controller resource ${path}`);
231
+ await requireSuccess(resource.post_bundle(path), `MaaFramework could not load resource ${path}.`);
232
+ }
233
+ signal.throwIfAborted();
234
+ controller = await makeController(sdk, plan.controller, input, project.directory);
235
+ signal.throwIfAborted();
236
+ setDisplay(controller, plan.controller);
237
+ await requireSuccess(controller.post_connection(), `MaaFramework could not connect controller ${plan.controller.name}.`);
238
+ tasker = new sdk.Tasker();
239
+ tasker.controller = controller;
240
+ tasker.resource = resource;
241
+ if (!tasker.inited)
242
+ throw new Error('MaaFramework could not initialize the tasker.');
243
+ activeTasker = tasker;
244
+ if (plan.agents.length && !sdk.Client)
245
+ throw new Error('This MaaFramework SDK build lacks Agent Client support.');
246
+ for (const [index, agent] of plan.agents.entries()) {
247
+ signal.throwIfAborted();
248
+ const client = new sdk.Client(agent.identifier);
249
+ clients.push(client);
250
+ client.bind_resource(resource);
251
+ client.register_resource_sink(resource);
252
+ client.register_controller_sink(controller);
253
+ client.register_tasker_sink(tasker);
254
+ const label = `Agent ${index + 1}`;
255
+ log(`${label} starting`);
256
+ const command = bindNodeAgent(agent, project.directory, nodeAgent);
257
+ const args = [...expandArgs(command.args, command.directory), client.identifier];
258
+ const spawned = startProjectCommand(command, args, command.directory, environment, label, false, input.agentPython);
259
+ agents.push(spawned);
260
+ void spawned.outcome.then((outcome) => {
261
+ if (!cleaning && !signal.aborted) {
262
+ agentError = commandFailure(label, outcome);
263
+ unexpectedExit.reject(agentError);
264
+ }
265
+ });
266
+ if (!(await spawned.started))
267
+ throw commandFailure(label, await spawned.outcome);
268
+ client.timeout = '10000';
269
+ // The SDK holds the client handle for the duration of connect().
270
+ await client.connect();
271
+ signal.throwIfAborted();
272
+ if (agentError)
273
+ throw agentError;
274
+ if (!client.connected)
275
+ throw new Error(`${label} did not connect to MaaFramework.`);
276
+ client.timeout = '30000';
277
+ }
278
+ for (const task of plan.tasks) {
279
+ signal.throwIfAborted();
280
+ if (agentError)
281
+ throw agentError;
282
+ log(`Starting ${task.name} (${task.entry})`);
283
+ taskOperation = requireSuccess(tasker.post_task(task.entry, task.override), `MaaFramework task ${task.name} failed.`);
284
+ await Promise.race([taskOperation, unexpectedExit.promise]);
285
+ log(`Completed ${task.name}`);
286
+ }
287
+ }
288
+ catch (error) {
289
+ if (activeTasker?.running)
290
+ stop();
291
+ throw error;
292
+ }
293
+ finally {
294
+ cleaning = true;
295
+ await nativeStop;
296
+ await taskOperation?.catch(() => undefined);
297
+ activeTasker = undefined;
298
+ for (const client of clients.reverse()) {
299
+ cleanup(() => { if (client.connected)
300
+ client.disconnect(); });
301
+ cleanup(() => client.destroy());
302
+ }
303
+ await Promise.all(agents.map((agent) => agent.terminate()));
304
+ if (tasker)
305
+ cleanup(() => tasker?.destroy());
306
+ if (controller)
307
+ cleanup(() => controller?.destroy());
308
+ cleanup(() => resource.destroy());
309
+ }
310
+ }
311
+ async function finish(message, code) {
312
+ // Complete pipe writes and IPC before exiting the isolated native process.
313
+ await new Promise((done) => process.stdout.write('', () => done()));
314
+ if (process.connected)
315
+ process.send?.(message, () => process.exit(code));
316
+ else
317
+ process.exit(code);
318
+ }
319
+ const stdio = !process.connected && process.argv.includes('--mas-stdio');
320
+ function handleRequest(request) {
321
+ if (request.type === 'stop')
322
+ stop();
323
+ if (request.type === 'run' && !running) {
324
+ running = true;
325
+ void execute(request.input).then(() => finish({ type: 'done' }, 0), (error) => {
326
+ const message = error instanceof Error ? error.message : String(error);
327
+ if (stdio)
328
+ log(message);
329
+ return finish({ type: 'failed', error: message }, 1);
330
+ });
331
+ }
332
+ }
333
+ function disconnected() {
334
+ stop();
335
+ setTimeout(() => process.exit(1), 4_000).unref();
336
+ }
337
+ if (stdio) {
338
+ const commands = createInterface({ input: process.stdin });
339
+ commands.on('line', line => {
340
+ try {
341
+ if (Buffer.byteLength(line) > 256 * 1024)
342
+ throw new Error('MaaFramework worker input is too large.');
343
+ const message = JSON.parse(line);
344
+ if (message?.type !== 'run' && message?.type !== 'stop')
345
+ throw new Error('MaaFramework worker input is invalid.');
346
+ handleRequest(message);
347
+ }
348
+ catch (error) {
349
+ log(error instanceof Error ? error.message : String(error));
350
+ if (running)
351
+ disconnected();
352
+ else
353
+ void finish({ type: 'failed' }, 1);
354
+ }
355
+ });
356
+ commands.once('close', disconnected);
357
+ }
358
+ else {
359
+ process.on('message', handleRequest);
360
+ process.once('disconnect', disconnected);
361
+ }
@@ -0,0 +1 @@
1
+ export const runPhases = ['prepare-game', 'start-script', 'complete-script', 'finish-task'];