@auto-mas/auto-mas-plugin-adapter-hsr 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.
- package/dist/LICENSE +661 -0
- package/dist/index.js +1 -0
- package/dist/server/adapters.js +147 -0
- package/dist/server/builtin-plugins/adapter-hsr.js +30 -0
- package/dist/server/builtin-plugins/icons/hsr.png +0 -0
- package/dist/server/emulator-managers.js +219 -0
- package/dist/server/execution.js +364 -0
- package/dist/server/game-plugins/hsr.js +268 -0
- package/dist/server/game-plugins/native.js +207 -0
- package/dist/server/game-plugins/profile-options.js +38 -0
- package/dist/server/game-plugins/sra.js +74 -0
- package/dist/server/general-result.js +66 -0
- package/dist/server/maa/index.js +97 -0
- package/dist/server/maa/managed-project-path.js +34 -0
- package/dist/server/maa/native-runtime.js +80 -0
- package/dist/server/maa/native-worker-source.js +198 -0
- package/dist/server/maa/node-agent-path.js +55 -0
- package/dist/server/maa/process.js +34 -0
- package/dist/server/maa/project.js +502 -0
- package/dist/server/maa/worker.js +361 -0
- package/dist/server/run-lifecycle.js +1 -0
- package/dist/server/storage.js +76 -0
- package/package.json +30 -6
- package/README.md +0 -3
|
@@ -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,268 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { isAbsolute, join } from 'node:path';
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import { textList } from '../adapters.js';
|
|
7
|
+
import { stopProcess } from '../execution.js';
|
|
8
|
+
import { executableField, optionalText, prepareExecutable, requiredText, windowsOnly } from './native.js';
|
|
9
|
+
import { profileOption } from './profile-options.js';
|
|
10
|
+
import { runSra, sraLaunch } from './sra.js';
|
|
11
|
+
const tasks = [
|
|
12
|
+
{ value: 'daily', label: '每日实训与奖励' }, { value: 'main', label: '完整运行' },
|
|
13
|
+
{ value: 'power', label: '清体力' }, { value: 'routine', label: '日常' },
|
|
14
|
+
{ value: 'divergent', label: '差分宇宙' }, { value: 'currencywars', label: '货币战争' },
|
|
15
|
+
{ value: 'universe', label: '模拟宇宙' },
|
|
16
|
+
];
|
|
17
|
+
const m7aModules = tasks.map(item => ({ value: `m7a:${item.value}`, label: `三月七 · ${item.label}` }));
|
|
18
|
+
const sraModules = [
|
|
19
|
+
{ value: 'sra:start', label: 'SRA · 启动游戏与原生切号' },
|
|
20
|
+
{ value: 'sra:power', label: 'SRA · 清体力' },
|
|
21
|
+
{ value: 'sra:reward', label: 'SRA · 领取奖励' },
|
|
22
|
+
{ value: 'sra:full', label: 'SRA · 完整运行所选档案' },
|
|
23
|
+
];
|
|
24
|
+
const modules = [...m7aModules, ...sraModules];
|
|
25
|
+
const runIdPattern = /^\d{8}-\d{6}-[0-9a-f]{4}$/u;
|
|
26
|
+
const exitMessages = {
|
|
27
|
+
1: '任务失败', 2: '启动参数无效', 3: '需先在三月七图形界面确认首次使用',
|
|
28
|
+
4: '已有三月七任务运行', 5: '三月七未获得运行权限', 6: '任务已停止',
|
|
29
|
+
};
|
|
30
|
+
function jsonRecord(text) {
|
|
31
|
+
try {
|
|
32
|
+
const value = JSON.parse(text);
|
|
33
|
+
if (value && typeof value === 'object' && !Array.isArray(value))
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
catch { /* A task can write plain-text progress before the final JSON line. */ }
|
|
37
|
+
}
|
|
38
|
+
function commandAt(command, cwd) {
|
|
39
|
+
return async (args, signal, log, started) => {
|
|
40
|
+
signal.throwIfAborted();
|
|
41
|
+
const child = spawn(command, args, { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
42
|
+
const abort = () => stopProcess(child);
|
|
43
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
44
|
+
if (signal.aborted)
|
|
45
|
+
abort();
|
|
46
|
+
let output = '';
|
|
47
|
+
let data;
|
|
48
|
+
let announcedRunId;
|
|
49
|
+
createInterface({ input: child.stdout }).on('line', line => {
|
|
50
|
+
output = (output + line + '\n').slice(-1_048_576);
|
|
51
|
+
const candidate = jsonRecord(line);
|
|
52
|
+
if (candidate)
|
|
53
|
+
data = candidate;
|
|
54
|
+
else
|
|
55
|
+
log?.(line);
|
|
56
|
+
if (args.includes('--detach'))
|
|
57
|
+
announcedRunId ??= /运行编号 (\d{8}-\d{6}-[0-9a-f]{4})/u.exec(line)?.[1];
|
|
58
|
+
});
|
|
59
|
+
createInterface({ input: child.stderr }).on('line', line => log?.(line));
|
|
60
|
+
try {
|
|
61
|
+
const code = await new Promise((resolve, reject) => {
|
|
62
|
+
child.once('spawn', () => {
|
|
63
|
+
try {
|
|
64
|
+
started?.();
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
abort();
|
|
68
|
+
reject(error);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
child.once('error', reject);
|
|
72
|
+
child.once('close', resolve);
|
|
73
|
+
});
|
|
74
|
+
if (signal.aborted && (!args.includes('--detach') || !announcedRunId))
|
|
75
|
+
signal.throwIfAborted();
|
|
76
|
+
return { code, data: args[0] === '--status' ? jsonRecord(output) : data, announcedRunId };
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
signal.removeEventListener('abort', abort);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function resultId(result) {
|
|
84
|
+
return typeof result?.run_id === 'string' && runIdPattern.test(result.run_id) ? result.run_id : undefined;
|
|
85
|
+
}
|
|
86
|
+
function isTerminal(result, expectedId) {
|
|
87
|
+
const id = resultId(result.data);
|
|
88
|
+
const status = result.data?.effective_status ?? result.data?.status;
|
|
89
|
+
return Boolean(id && (!expectedId || id === expectedId) && typeof status === 'string' && status !== 'running' && status !== 'unknown');
|
|
90
|
+
}
|
|
91
|
+
function requireSuccess(result, expectedId) {
|
|
92
|
+
const status = result.data?.effective_status ?? result.data?.status;
|
|
93
|
+
if (result.code === 0 && status === 'success' && isTerminal(result, expectedId))
|
|
94
|
+
return;
|
|
95
|
+
const details = [result.data?.reason, result.data?.error].filter(value => typeof value === 'string' && value).join(' · ');
|
|
96
|
+
const label = result.code && exitMessages[result.code] || '三月七未确认本次任务完成';
|
|
97
|
+
throw new Error(details ? `${label}(${details.slice(0, 400)})` : label);
|
|
98
|
+
}
|
|
99
|
+
async function waitRecord(id, directory, signal) {
|
|
100
|
+
const path = join(directory, `${id}.json`);
|
|
101
|
+
while (true) {
|
|
102
|
+
signal.throwIfAborted();
|
|
103
|
+
const contents = await readFile(path, 'utf8').catch(error => {
|
|
104
|
+
if (error.code === 'ENOENT')
|
|
105
|
+
return '';
|
|
106
|
+
throw error;
|
|
107
|
+
});
|
|
108
|
+
if (resultId(jsonRecord(contents)) === id)
|
|
109
|
+
return;
|
|
110
|
+
await delay(200, undefined, { signal });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async function stopDetached(invoke, waitForRecord, id, directory, log) {
|
|
114
|
+
const timeLimit = AbortSignal.timeout(45_000);
|
|
115
|
+
try {
|
|
116
|
+
await waitForRecord(id, directory, timeLimit);
|
|
117
|
+
await invoke(['--control', id, 'stop', '--json'], timeLimit, log);
|
|
118
|
+
const stopped = await invoke(['--follow', id, '--json'], timeLimit, log);
|
|
119
|
+
if (!isTerminal(stopped, id))
|
|
120
|
+
throw new Error('三月七未返回结束状态');
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
throw new Error(`无法确认三月七已停止运行 ${id},请在三月七中检查该任务`, { cause: error });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
export async function runM7a(invoke, waitForRecord, input, signal, log, started) {
|
|
127
|
+
if (!tasks.some(task => task.value === input.task))
|
|
128
|
+
throw new Error('请选择三月七支持的任务');
|
|
129
|
+
const { code, data: status } = await invoke(['--status'], AbortSignal.any([signal, AbortSignal.timeout(15_000)]));
|
|
130
|
+
if (code !== 0 || !status || typeof status.first_run_completed !== 'boolean')
|
|
131
|
+
throw new Error('无法读取三月七状态,请使用支持 --status 的 m7a.exe');
|
|
132
|
+
if (!status.first_run_completed)
|
|
133
|
+
throw new Error('请先在三月七图形界面完成首次使用确认');
|
|
134
|
+
if (!status.game_path_exists && !status.cloud_game_enable)
|
|
135
|
+
throw new Error('请先在三月七中配置游戏路径或云游戏平台');
|
|
136
|
+
if (status.active_run)
|
|
137
|
+
throw new Error('已有三月七任务运行');
|
|
138
|
+
if (status.elevation !== 'admin' && status.elevation !== 'task')
|
|
139
|
+
throw new Error('三月七当前需要交互式 UAC,无法无人值守运行');
|
|
140
|
+
const args = [input.task, '--after-finish', 'None', '--non-interactive', '--json'];
|
|
141
|
+
if (input.uid) {
|
|
142
|
+
const accounts = status.accounts;
|
|
143
|
+
if (!/^\d+$/u.test(input.uid) || accounts?.effective !== true || !Array.isArray(accounts.list) ||
|
|
144
|
+
!accounts.list.some(account => account?.uid === input.uid))
|
|
145
|
+
throw new Error('当前三月七未启用此 UID 的原生账号配置');
|
|
146
|
+
args.push('--account', input.uid);
|
|
147
|
+
}
|
|
148
|
+
signal.throwIfAborted();
|
|
149
|
+
if (status.elevation === 'admin') {
|
|
150
|
+
requireSuccess(await invoke(args, signal, log, () => started?.('三月七进程已启动')));
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const directory = typeof status.runs_dir === 'string' && isAbsolute(status.runs_dir) ? status.runs_dir : undefined;
|
|
154
|
+
if (!directory)
|
|
155
|
+
throw new Error('三月七状态缺少运行记录目录');
|
|
156
|
+
// The non-administrator CLI starts an independent worker. Keep the short
|
|
157
|
+
// launch handshake alive so cancellation can use the worker's exact ID.
|
|
158
|
+
const launched = await invoke([...args, '--detach'], AbortSignal.timeout(30_000), log);
|
|
159
|
+
if (isTerminal(launched) || !resultId(launched.data) && !launched.announcedRunId) {
|
|
160
|
+
signal.throwIfAborted();
|
|
161
|
+
requireSuccess(launched);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const id = resultId(launched.data) ?? launched.announcedRunId;
|
|
165
|
+
let finished;
|
|
166
|
+
try {
|
|
167
|
+
if (launched.code !== 0)
|
|
168
|
+
throw new Error(`三月七未确认启动运行 ${id}`);
|
|
169
|
+
await waitForRecord(id, directory, AbortSignal.any([signal, AbortSignal.timeout(30_000)]));
|
|
170
|
+
started?.('三月七已确认运行编号');
|
|
171
|
+
signal.throwIfAborted();
|
|
172
|
+
finished = await invoke(['--follow', id, '--json'], signal, log);
|
|
173
|
+
if (!isTerminal(finished, id))
|
|
174
|
+
throw new Error(`三月七未确认运行 ${id} 已结束`);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
await stopDetached(invoke, waitForRecord, id, directory, log);
|
|
178
|
+
signal.throwIfAborted();
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
signal.throwIfAborted();
|
|
182
|
+
requireSuccess(finished, id);
|
|
183
|
+
}
|
|
184
|
+
export function hsrCombinedSteps(value) {
|
|
185
|
+
const steps = textList(value);
|
|
186
|
+
if (!steps.every(key => modules.some(task => task.value === key)) || steps.length !== new Set(steps).size) {
|
|
187
|
+
throw new Error('请选择有效且不重复的星穹铁道任务');
|
|
188
|
+
}
|
|
189
|
+
if (!steps.some(step => step.startsWith('m7a:')) || !steps.some(step => step.startsWith('sra:'))) {
|
|
190
|
+
throw new Error('双引擎流程须分别选择两个引擎的任务');
|
|
191
|
+
}
|
|
192
|
+
return steps;
|
|
193
|
+
}
|
|
194
|
+
function sraConfig(config) {
|
|
195
|
+
return config.engine === 'combined' ? { ...config, command: config.sraCommand } : config;
|
|
196
|
+
}
|
|
197
|
+
async function runMarch(script, task, options) {
|
|
198
|
+
const config = script.adapterConfig ?? {};
|
|
199
|
+
const account = script.accountConfig ?? {};
|
|
200
|
+
const command = requiredText(config, 'command', '三月七公开 CLI');
|
|
201
|
+
const cwd = requiredText(config, 'installRoot', '三月七安装目录');
|
|
202
|
+
await runM7a(commandAt(command, cwd), waitRecord, { task, uid: optionalText(account, 'uid') }, options.signal, options.log, options.started);
|
|
203
|
+
}
|
|
204
|
+
async function runCombined(script, config, options) {
|
|
205
|
+
const steps = hsrCombinedSteps(config.steps);
|
|
206
|
+
const linkedSra = { ...script, adapterConfig: sraConfig(config) };
|
|
207
|
+
let started = false;
|
|
208
|
+
const moduleOptions = { ...options, started(message) {
|
|
209
|
+
if (started)
|
|
210
|
+
return;
|
|
211
|
+
started = true;
|
|
212
|
+
options.started?.(message);
|
|
213
|
+
} };
|
|
214
|
+
for (const step of steps) {
|
|
215
|
+
options.signal.throwIfAborted();
|
|
216
|
+
options.log(modules.find(item => item.value === step).label);
|
|
217
|
+
const [engine, module] = step.split(':');
|
|
218
|
+
if (engine === 'sra')
|
|
219
|
+
await runSra(linkedSra, moduleOptions, module);
|
|
220
|
+
else
|
|
221
|
+
await runMarch(script, module, moduleOptions);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
export const hsr = {
|
|
225
|
+
id: 'hsr', title: '崩坏:星穹铁道 · 三月七与 SRA', group: '游戏专项', supports: windowsOnly,
|
|
226
|
+
description: '运行三月七、SRA 或按指定顺序组合两个引擎的任务。请先完成原生游戏和账号设置。',
|
|
227
|
+
scriptFields: [{ key: 'engine', label: '运行引擎', kind: 'select', default: 'm7a', options: [
|
|
228
|
+
{ value: 'm7a', label: '三月七' }, { value: 'sra', label: 'SRA' }, { value: 'combined', label: '三月七与 SRA 按序执行' },
|
|
229
|
+
] }, executableField('主程序(双引擎时请选择 m7a.exe)'), { key: 'task', label: '三月七任务', kind: 'select', options: tasks, default: 'daily', required: true,
|
|
230
|
+
visibleWhen: { key: 'engine', equals: 'm7a' } },
|
|
231
|
+
{ key: 'sraCommand', label: 'SRA-cli.exe', kind: 'hostpath', visibleWhen: { key: 'engine', equals: 'combined' } },
|
|
232
|
+
{ key: 'sraProfile', label: 'SRA 原生配置', kind: 'select', source: 'hsr.sra-profiles', sourceBy: 'engine', sourceInputs: ['command', 'sraCommand'] },
|
|
233
|
+
{ key: 'steps', label: '双引擎任务顺序', kind: 'multiselect', options: modules, visibleWhen: { key: 'engine', equals: 'combined' } }],
|
|
234
|
+
accountFields: [{ key: 'uid', label: '三月七原生账号 UID(可选)', hint: '使用三月七引擎时生效。留空使用当前登录身份。' },
|
|
235
|
+
profileOption('sraProfile', 'SRA 原生配置覆盖(可选)', 'hsr.sra-profiles', 'scriptId')],
|
|
236
|
+
prepare: async (input) => {
|
|
237
|
+
const engine = optionalText(input, 'engine') || 'm7a';
|
|
238
|
+
if (engine === 'sra') {
|
|
239
|
+
const launch = await sraLaunch(input, {});
|
|
240
|
+
return { command: launch.command, installRoot: launch.cwd, engine, sraProfile: launch.sraProfile };
|
|
241
|
+
}
|
|
242
|
+
if (engine !== 'm7a' && engine !== 'combined')
|
|
243
|
+
throw new Error('请选择支持的星穹铁道执行引擎');
|
|
244
|
+
const paths = await prepareExecutable(input, '三月七公开 CLI', ['m7a.exe']);
|
|
245
|
+
if (engine === 'combined') {
|
|
246
|
+
const steps = hsrCombinedSteps(input.steps);
|
|
247
|
+
const second = await sraLaunch(sraConfig({ ...input, engine }), {});
|
|
248
|
+
return { ...paths, engine, steps, sraCommand: second.command, sraInstallRoot: second.cwd, sraProfile: second.sraProfile };
|
|
249
|
+
}
|
|
250
|
+
const task = optionalText(input, 'task') || 'daily';
|
|
251
|
+
if (!tasks.some(item => item.value === task))
|
|
252
|
+
throw new Error('请选择三月七支持的任务');
|
|
253
|
+
return { ...paths, engine, task };
|
|
254
|
+
},
|
|
255
|
+
async validateRun(script) {
|
|
256
|
+
const config = script.adapterConfig ?? {};
|
|
257
|
+
if (config.engine === 'sra' || config.engine === 'combined')
|
|
258
|
+
await sraLaunch(sraConfig(config), script.accountConfig ?? {});
|
|
259
|
+
},
|
|
260
|
+
run: async (script, options) => {
|
|
261
|
+
const config = script.adapterConfig ?? {};
|
|
262
|
+
if (config.engine === 'sra')
|
|
263
|
+
return runSra(script, options);
|
|
264
|
+
if (config.engine === 'combined')
|
|
265
|
+
return runCombined(script, config, options);
|
|
266
|
+
await runMarch(script, requiredText(config, 'task', '三月七任务'), options);
|
|
267
|
+
},
|
|
268
|
+
};
|