@auto-mas/auto-mas-plugin-adapter-whimbox 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,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'];
@@ -0,0 +1,76 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ export class Store {
5
+ db;
6
+ lease;
7
+ constructor(directory) {
8
+ mkdirSync(directory, { recursive: true });
9
+ this.lease = new DatabaseSync(join(directory, 'session.db'));
10
+ try {
11
+ this.lease.exec('PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE');
12
+ }
13
+ catch (error) {
14
+ this.lease.close();
15
+ if (error.errcode === 5)
16
+ throw new Error('该数据目录已有 MAS 后端在运行');
17
+ throw error;
18
+ }
19
+ try {
20
+ this.db = new DatabaseSync(join(directory, 'mas.db'));
21
+ this.db.exec(`PRAGMA journal_mode = WAL;
22
+ CREATE TABLE IF NOT EXISTS entries (
23
+ collection TEXT NOT NULL, id TEXT NOT NULL, value TEXT NOT NULL,
24
+ PRIMARY KEY (collection, id)
25
+ );
26
+ CREATE INDEX IF NOT EXISTS run_start ON entries (
27
+ unixepoch(json_extract(value, '$.started'), 'subsec') DESC
28
+ ) WHERE collection = 'runs'`);
29
+ }
30
+ catch (error) {
31
+ this.lease.close();
32
+ throw error;
33
+ }
34
+ }
35
+ recentRuns() {
36
+ return this.db.prepare(`SELECT value FROM entries WHERE collection = 'runs'
37
+ ORDER BY unixepoch(json_extract(value, '$.started'), 'subsec') DESC, rowid DESC LIMIT 200`)
38
+ .all().map(row => JSON.parse(String(row.value)));
39
+ }
40
+ list(collection) {
41
+ const rows = this.db.prepare('SELECT value FROM entries WHERE collection = ? ORDER BY rowid').all(collection);
42
+ return rows.map(row => JSON.parse(String(row.value)));
43
+ }
44
+ get(collection, id) {
45
+ const row = this.db.prepare('SELECT value FROM entries WHERE collection = ? AND id = ?').get(collection, id);
46
+ return row && JSON.parse(String(row.value));
47
+ }
48
+ put(collection, entry) {
49
+ this.db.prepare('INSERT INTO entries VALUES (?, ?, ?) ON CONFLICT(collection, id) DO UPDATE SET value = excluded.value')
50
+ .run(collection, entry.id, JSON.stringify(entry));
51
+ return entry;
52
+ }
53
+ remove(collection, id) {
54
+ this.db.prepare('DELETE FROM entries WHERE collection = ? AND id = ?').run(collection, id);
55
+ }
56
+ transaction(callback) {
57
+ this.db.exec('BEGIN IMMEDIATE');
58
+ try {
59
+ const result = callback();
60
+ this.db.exec('COMMIT');
61
+ return result;
62
+ }
63
+ catch (error) {
64
+ this.db.exec('ROLLBACK');
65
+ throw error;
66
+ }
67
+ }
68
+ close() {
69
+ try {
70
+ this.db.close();
71
+ }
72
+ finally {
73
+ this.lease.close();
74
+ }
75
+ }
76
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
- {
2
- "name": "@auto-mas/auto-mas-plugin-adapter-whimbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@auto-mas/auto-mas-plugin-adapter-whimbox",
3
+ "version": "0.2.0",
4
+ "license": "AGPL-3.0-only",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "exports": "./dist/index.js",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "engines": {
12
+ "node": ">=24"
13
+ },
14
+ "keywords": [
15
+ "auto-mas-plugin"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "description": "AUTO-MAS whimbox Cordis component",
21
+ "autoMas": {
22
+ "id": "whimbox",
23
+ "abi": 1,
24
+ "hostDependencies": {
25
+ "cordis": "4.0.0-rc.13",
26
+ "jsonc-parser": "3.3.1",
27
+ "schemastery": "3.18.0"
28
+ }
29
+ }
30
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.