@auto-mas/auto-mas-plugin-adapter-bettergi 0.2.1 → 0.2.2

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.
@@ -3,6 +3,7 @@ import { isAbsolute } from 'node:path';
3
3
  import { stat } from 'node:fs/promises';
4
4
  import { Runner, runProcess } from './execution.js';
5
5
  import { generalResultRules, withGeneralResult } from './general-result.js';
6
+ import { applyMaaAccountSettings, maaAccountFields } from './maa/account-settings.js';
6
7
  export function optionalText(value) { return typeof value === 'string' ? value.trim() : ''; }
7
8
  export function textList(value) {
8
9
  if (!value)
@@ -130,18 +131,31 @@ export async function prepareMaa(input) {
130
131
  return { projectPath, controller, resource, preset, tasks, projectOptions, agentPython, agentNodeRoot, nativePython, nativeLibraries, address: optionalText(input.address) || undefined,
131
132
  adbPath: optionalText(input.adbPath) || undefined, windowHandle: input.windowHandle ? Number(input.windowHandle) : undefined };
132
133
  }
134
+ export function maaRunInput(config, plannedTasks) {
135
+ const tasks = textList(plannedTasks ?? config.tasks);
136
+ return {
137
+ projectPath: optionalText(config.projectPath), controller: optionalText(config.controller) || undefined,
138
+ resource: optionalText(config.resource) || undefined, preset: optionalText(config.preset) || undefined, tasks: tasks.length ? tasks : undefined,
139
+ adbPath: optionalText(config.adbPath) || undefined, address: optionalText(config.address) || undefined,
140
+ adbServerPort: typeof config.adbServerPort === 'number' ? config.adbServerPort : undefined, agentPython: optionalText(config.agentPython) || undefined,
141
+ agentNodeRoot: optionalText(config.agentNodeRoot) || undefined,
142
+ nativePython: optionalText(config.nativePython) || undefined, nativeLibraries: optionalText(config.nativeLibraries) || undefined,
143
+ windowHandle: config.windowHandle, options: config.projectOptions,
144
+ };
145
+ }
133
146
  const runMaaProject = async (script, config) => {
134
147
  const { runMaaSelected } = await import('./maa/native-runtime.js');
135
- const tasks = script.tasks;
136
- await runMaaSelected({ projectPath: optionalText(script.projectPath), controller: optionalText(script.controller) || undefined,
137
- resource: optionalText(script.resource) || undefined, preset: optionalText(script.preset) || undefined, tasks: tasks?.length ? tasks : undefined,
138
- adbPath: optionalText(script.adbPath) || undefined, address: optionalText(script.address) || undefined,
139
- adbServerPort: typeof script.adbServerPort === 'number' ? script.adbServerPort : undefined, agentPython: optionalText(script.agentPython) || undefined,
140
- agentNodeRoot: optionalText(script.agentNodeRoot) || undefined,
141
- nativePython: optionalText(script.nativePython) || undefined, nativeLibraries: optionalText(script.nativeLibraries) || undefined,
142
- windowHandle: script.windowHandle, options: script.projectOptions }, config);
148
+ const input = applyMaaAccountSettings(maaRunInput(script), script.accountConfig ?? {});
149
+ await runMaaSelected(input, config);
143
150
  };
144
151
  export const runtimeAdapters = [general, {
145
152
  id: 'maafw', title: 'MaaFramework', description: '通过官方 Node SDK 运行 ProjectInterface V2 项目。', group: '通用',
146
- scriptFields: maaFields, usesPlan: true, prepare: prepareMaa, run: runMaaProject,
153
+ scriptFields: maaFields, accountFields: maaAccountFields('maafw'), usesPlan: true, prepare: prepareMaa, run: runMaaProject,
154
+ async validateAccount(script, account) {
155
+ if (!Object.keys(account).length)
156
+ return;
157
+ const input = applyMaaAccountSettings(maaRunInput(script), account);
158
+ const { loadProject, planRun } = await import('./maa/project.js');
159
+ planRun(await loadProject(input.projectPath), input);
160
+ },
147
161
  }];
@@ -1,8 +1,9 @@
1
1
  import { adapterFeature } from '../adapters.js';
2
- import { bettergi, betterGiProfiles } from '../game-plugins/bettergi.js';
2
+ import { bettergi, betterGiGroups, betterGiProfiles } from '../game-plugins/bettergi.js';
3
3
  import { scopedProfileOptions } from '../game-plugins/profile-options.js';
4
4
  export default function createFeature() {
5
5
  return adapterFeature(bettergi, { icon: new URL('./icons/bettergi.png', import.meta.url), apply(ctx) {
6
6
  scopedProfileOptions(ctx, bettergi.id, 'bettergi.profiles', betterGiProfiles);
7
+ scopedProfileOptions(ctx, bettergi.id, 'bettergi.groups', betterGiGroups);
7
8
  } });
8
9
  }
@@ -0,0 +1,65 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
2
+ import { lstat, readFile, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ export class CredentialVault {
5
+ path;
6
+ namespace;
7
+ pending;
8
+ constructor(dataDir, scope = 'community') {
9
+ this.path = join(dataDir, scope === 'community' ? '.community-key' : '.plugin-config-key');
10
+ this.namespace = scope === 'community' ? 'Cordis MAS community sign-in v1:cloud-genshin' : 'AUTO-MASC plugin configuration v1';
11
+ }
12
+ async load(create) {
13
+ try {
14
+ const info = await lstat(this.path);
15
+ if (!info.isFile() || info.size !== 32 || (process.platform !== 'win32' && (info.mode & 0o077) !== 0)) {
16
+ throw new Error('本机加密密钥文件无效或权限过宽');
17
+ }
18
+ return await readFile(this.path);
19
+ }
20
+ catch (error) {
21
+ if (error.code !== 'ENOENT')
22
+ throw error;
23
+ if (!create)
24
+ throw new Error('找不到本机加密密钥,请重新配置');
25
+ const key = randomBytes(32);
26
+ try {
27
+ await writeFile(this.path, key, { flag: 'wx', mode: 0o600 });
28
+ }
29
+ catch (writeError) {
30
+ if (writeError.code !== 'EEXIST')
31
+ throw writeError;
32
+ return this.load(false);
33
+ }
34
+ return key;
35
+ }
36
+ }
37
+ key(create) {
38
+ this.pending ??= this.load(create).catch(error => { this.pending = undefined; throw error; });
39
+ return this.pending;
40
+ }
41
+ context(id) {
42
+ return Buffer.from(`${this.namespace}:${id}`);
43
+ }
44
+ async seal(id, secret) {
45
+ const nonce = randomBytes(12);
46
+ const cipher = createCipheriv('aes-256-gcm', await this.key(true), nonce);
47
+ cipher.setAAD(this.context(id));
48
+ const data = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
49
+ return { version: 1, nonce: nonce.toString('base64'), cipher: data.toString('base64'), tag: cipher.getAuthTag().toString('base64') };
50
+ }
51
+ async reveal(id, secret) {
52
+ const key = await this.key(false);
53
+ try {
54
+ if (secret.version !== 1)
55
+ throw new Error('Unrecognized credential');
56
+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(secret.nonce, 'base64'), { authTagLength: 16 });
57
+ decipher.setAAD(this.context(id));
58
+ decipher.setAuthTag(Buffer.from(secret.tag, 'base64'));
59
+ return Buffer.concat([decipher.update(Buffer.from(secret.cipher, 'base64')), decipher.final()]).toString('utf8');
60
+ }
61
+ catch {
62
+ throw new Error('无法解密本机配置,请重新配置');
63
+ }
64
+ }
65
+ }
@@ -3,7 +3,6 @@ import { randomUUID } from 'node:crypto';
3
3
  import { realpathSync } from 'node:fs';
4
4
  import { resolve, sep } from 'node:path';
5
5
  import { createInterface } from 'node:readline';
6
- import { Store } from './storage.js';
7
6
  import { runPhases } from './run-lifecycle.js';
8
7
  export function forAccount(store, script, account) {
9
8
  if (account.scriptId !== script.id || account.enabled === false)
@@ -112,26 +111,42 @@ export class Runner {
112
111
  finished;
113
112
  options;
114
113
  lifecycle;
115
- constructor(store, changed, finished = () => { }, options = {}, lifecycle = {}) {
114
+ persistence;
115
+ constructor(store, changed, finished = () => { }, options = {}, lifecycle = {}, persistence) {
116
116
  this.store = store;
117
117
  this.changed = changed;
118
118
  this.finished = finished;
119
119
  this.options = options;
120
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' ? '上次运行中断,未能确认清理' : '上次运行中断' });
121
+ this.persistence = persistence;
122
+ if (!persistence)
123
+ for (const run of this.store.list('runs').filter(run => run.status === 'running')) {
124
+ this.store.put('runs', this.interrupted(run, this.store.get('scripts', run.scriptId)));
132
125
  }
133
- this.store.put('runs', { ...run, stages, status: 'error', error: '上次运行中断', finished });
126
+ }
127
+ interrupted(run, script) {
128
+ const finished = new Date().toISOString();
129
+ const stages = [...(run.stages ?? [])];
130
+ const adapter = stages[0]?.adapter ?? script?.adapter ?? 'unknown';
131
+ for (const stage of runPhases) {
132
+ const last = stages.findLast(event => event.stage === stage);
133
+ if (last && last.status !== 'started')
134
+ continue;
135
+ const status = last || stage === 'finish-task' ? 'failed' : 'skipped';
136
+ stages.push({ runId: run.id, scriptId: run.scriptId, adapter, sequence: stages.length + 1, stage, status, at: finished,
137
+ message: stage === 'finish-task' ? '上次运行中断,未能确认清理' : '上次运行中断' });
134
138
  }
139
+ return { ...run, stages, status: 'error', error: '上次运行中断', finished };
140
+ }
141
+ async recoverInterrupted() {
142
+ if (!this.persistence)
143
+ return;
144
+ const { database } = this.persistence;
145
+ await database.transaction(async (tx) => {
146
+ const runs = await tx.list('runs', { where: { status: 'running' } });
147
+ for (const run of runs)
148
+ await tx.put('runs', this.interrupted(run, await tx.get('scripts', run.scriptId)));
149
+ });
135
150
  }
136
151
  register(id, execute) {
137
152
  if (this.owners.has(id))
@@ -166,6 +181,19 @@ export class Runner {
166
181
  };
167
182
  }
168
183
  start(input) {
184
+ const { run, done } = this.startRun(input);
185
+ return { run, done };
186
+ }
187
+ async startAsync(input, mayStart) {
188
+ if (mayStart && !mayStart())
189
+ throw new Error('运行请求已失效');
190
+ if (!this.persistence)
191
+ return this.start(input);
192
+ const { run, done, ready } = this.startRun(input, this.persistence.database, mayStart);
193
+ await ready;
194
+ return { run, done };
195
+ }
196
+ startRun(input, database, mayStart) {
169
197
  if (!this.accepting)
170
198
  throw new Error('执行服务正在退出');
171
199
  if (this.startsPaused)
@@ -194,7 +222,8 @@ export class Runner {
194
222
  throw new Error('脚本、工作目录或设备已被占用');
195
223
  const run = { id: randomUUID(), name: script.name, scriptId: script.id, status: 'running', started: new Date().toISOString(), logs: [], stages: [],
196
224
  workflow: script.workflow && Object.freeze(script.workflow), executionTarget: script.executionTarget };
197
- this.store.put('runs', run);
225
+ if (!database)
226
+ this.store.put('runs', run);
198
227
  keys.forEach(key => this.claimed.add(key));
199
228
  const claimAdb = (address, serverPort) => {
200
229
  const key = serverPort && serverPort !== 5037 ? `adb:${serverPort}:${address.trim().toLowerCase()}` : `adb:${address.trim().toLowerCase()}`;
@@ -206,17 +235,38 @@ export class Runner {
206
235
  this.claimed.add(key);
207
236
  };
208
237
  const controller = new AbortController();
209
- const done = Promise.resolve().then(async () => {
238
+ let released = false;
239
+ const release = () => {
240
+ if (released)
241
+ return;
242
+ released = true;
243
+ keys.forEach(key => this.claimed.delete(key));
244
+ this.active.delete(run.id);
245
+ };
246
+ const ready = database ? database.put('runs', run).then(async () => {
247
+ try {
248
+ if (mayStart && !mayStart())
249
+ throw new Error('运行请求已失效');
250
+ }
251
+ catch (error) {
252
+ await database.remove('runs', run.id);
253
+ throw error;
254
+ }
255
+ this.changed();
256
+ }) : Promise.resolve();
257
+ const done = ready.then(async () => {
210
258
  const timeout = setTimeout(() => controller.abort(new Error('运行超时')), (script.timeoutSeconds ?? this.defaultTimeout()) * 1000);
211
259
  try {
212
- await this.execute(run, script, adapter, controller.signal, claimAdb);
260
+ await this.execute(run, script, adapter, controller.signal, claimAdb, database);
213
261
  }
214
262
  finally {
215
263
  clearTimeout(timeout);
216
- keys.forEach(key => this.claimed.delete(key));
217
- this.active.delete(run.id);
218
264
  run.finished = new Date().toISOString();
219
- this.store.put('runs', run);
265
+ if (database)
266
+ await database.put('runs', run);
267
+ else
268
+ this.store.put('runs', run);
269
+ release();
220
270
  this.changed();
221
271
  try {
222
272
  this.finished(run);
@@ -226,13 +276,17 @@ export class Runner {
226
276
  }
227
277
  }
228
278
  return run;
229
- });
279
+ }).finally(release);
280
+ if (database)
281
+ void done.catch(error => console.error('运行记录保存失败', error));
230
282
  this.active.set(run.id, { controller, done, snapshot: run });
231
- this.changed();
232
- return { run, done };
283
+ if (!database)
284
+ this.changed();
285
+ return { run, done, ready };
233
286
  }
234
- async execute(run, original, adapter, signal, claimAdb) {
287
+ async execute(run, original, adapter, signal, claimAdb, database) {
235
288
  const stages = run.stages;
289
+ let writing = Promise.resolve();
236
290
  const log = line => {
237
291
  run.logs.push(line.slice(0, 16000));
238
292
  if (run.logs.length > (this.options.logLineLimit ?? 4000))
@@ -244,13 +298,25 @@ export class Runner {
244
298
  sequence: stages.length + 1, stage, status, at: new Date().toISOString(), ...(message ? { message: message.slice(0, 2000) } : {}),
245
299
  ...(run.workflow ? { workflow: run.workflow } : {}) });
246
300
  stages.push(event);
247
- this.store.put('runs', run);
248
- this.changed();
249
- try {
250
- this.lifecycle.stage?.(event);
301
+ const announce = () => {
302
+ this.changed();
303
+ try {
304
+ this.lifecycle.stage?.(event);
305
+ }
306
+ catch (error) {
307
+ log(`运行事件处理失败: ${String(error)}`);
308
+ }
309
+ };
310
+ if (database) {
311
+ const snapshot = structuredClone(run);
312
+ writing = writing.then(async () => {
313
+ await database.put('runs', snapshot);
314
+ announce();
315
+ }).catch(error => console.error('运行阶段保存失败', error));
251
316
  }
252
- catch (error) {
253
- log(`运行事件处理失败: ${String(error)}`);
317
+ else {
318
+ this.store.put('runs', run);
319
+ announce();
254
320
  }
255
321
  };
256
322
  const options = { signal, log, report };
@@ -332,15 +398,30 @@ export class Runner {
332
398
  else
333
399
  report('finish-task', 'completed');
334
400
  run.status = outcome;
401
+ await writing;
335
402
  }
336
403
  }
337
404
  get(id) { return this.active.get(id)?.snapshot ?? this.store.get('runs', id); }
405
+ async getAsync(id) {
406
+ if (!this.persistence)
407
+ return this.get(id);
408
+ return this.active.get(id)?.snapshot ?? this.persistence.database.get('runs', id);
409
+ }
338
410
  list() {
339
411
  return this.store.recentRuns().map(run => this.active.get(run.id)?.snapshot ?? run);
340
412
  }
341
413
  summary() {
342
414
  return this.list().map(({ logs, stages, output, ...summary }) => summary);
343
415
  }
416
+ async listAsync() {
417
+ if (!this.persistence)
418
+ return this.list();
419
+ const runs = await this.persistence.history.recentRuns();
420
+ return runs.map(run => this.active.get(run.id)?.snapshot ?? run);
421
+ }
422
+ async summaryAsync() {
423
+ return (await this.listAsync()).map(({ logs, stages, output, ...summary }) => summary);
424
+ }
344
425
  stop(id) {
345
426
  const task = this.active.get(id);
346
427
  if (!task)
@@ -0,0 +1,31 @@
1
+ export const ui = (ctx) => ctx.get('mas.ui');
2
+ export const store = (ctx) => ctx.get('mas.storage-core');
3
+ export const runner = (ctx) => ctx.get('mas.runner');
4
+ export function text(input, key, label, required = true) {
5
+ const value = input[key];
6
+ if (typeof value === 'string' && value.trim())
7
+ return value.trim();
8
+ if (required)
9
+ throw new Error(`请输入${label}`);
10
+ return '';
11
+ }
12
+ export function strings(value) {
13
+ if (!value)
14
+ return [];
15
+ if (Array.isArray(value) && value.every(item => typeof item === 'string'))
16
+ return value;
17
+ if (typeof value === 'string') {
18
+ if (value.trim().startsWith('[')) {
19
+ const parsed = JSON.parse(value);
20
+ if (Array.isArray(parsed) && parsed.every(item => typeof item === 'string'))
21
+ return parsed;
22
+ throw new Error('JSON 必须是字符串数组');
23
+ }
24
+ return value.split(/[\n,]+/).map(item => item.trim()).filter(Boolean);
25
+ }
26
+ throw new Error('请输入字符串列表');
27
+ }
28
+ export const field = (key, label, extra = {}) => ({ key, label, ...extra });
29
+ export const columns = (...pairs) => pairs.map(([key, label]) => ({ key, label }));
30
+ export const action = (id, label) => ({ id, label });
31
+ export const runColumns = columns(['name', '托管'], ['status', '状态'], ['started', '开始时间'], ['finished', '结束时间'], ['error', '结果详情']);
@@ -1,25 +1,64 @@
1
1
  import { join } from 'node:path';
2
+ import { textList } from '../adapters.js';
2
3
  import { configName, executableField, existingPath, nativeAdapter, optionalText, prepareExecutable, requiredText, windowsOnly } from './native.js';
4
+ import { readNativeConfigurationFile } from './native-config.js';
3
5
  import { profileOption, profilesIn } from './profile-options.js';
4
6
  const betterGiProgram = (input) => prepareExecutable(input, 'BetterGI.exe', ['bettergi.exe']);
5
7
  const profilesDirectory = (path) => join(path, 'User', 'OneDragon');
6
8
  export async function betterGiProfiles(input) { return profilesIn(profilesDirectory((await betterGiProgram(input)).installRoot)); }
9
+ async function groupOptions(root) {
10
+ const directory = join(root, 'User', 'ScriptGroup');
11
+ const files = await profilesIn(directory);
12
+ const groups = new Map();
13
+ for (const { value } of files) {
14
+ try {
15
+ const contents = await readNativeConfigurationFile({ root, directory, file: `${value}.json` });
16
+ const document = JSON.parse(contents.replace(/^\uFEFF/u, ''));
17
+ const name = document?.Name ?? document?.name;
18
+ if (typeof name !== 'string' || name !== name.trim() || /[\u0000-\u001f]/u.test(name))
19
+ continue;
20
+ configName(name, 'BetterGI 配置组');
21
+ groups.set(name, (groups.get(name) ?? 0) + 1);
22
+ }
23
+ catch {
24
+ continue;
25
+ }
26
+ }
27
+ return [...groups].filter(([, count]) => count === 1)
28
+ .map(([value]) => ({ value, label: value })).sort((a, b) => a.label.localeCompare(b.label));
29
+ }
30
+ export async function betterGiGroups(input) {
31
+ return groupOptions((await betterGiProgram(input)).installRoot);
32
+ }
7
33
  export async function betterGiLaunch(config, account) {
8
34
  const command = requiredText(config, 'command', 'BetterGI.exe');
9
35
  const cwd = requiredText(config, 'installRoot', 'BetterGI 安装目录');
36
+ const groups = textList(account.groups);
37
+ const logs = { directory: join(cwd, 'log'), filenames: /^better-genshin-impact\d{8}\.log$/u, closeOnCompletion: true };
38
+ if (groups.length) {
39
+ const available = new Set((await groupOptions(cwd)).map(group => group.value));
40
+ for (const name of groups)
41
+ if (!available.has(name))
42
+ throw new Error(`BetterGI 配置组不存在或同名:${name}`);
43
+ return { command, cwd, args: ['--startGroups', ...groups], logs: { ...logs,
44
+ success: /一条龙和配置组任务结束|→\s*任务结束\s*$/u,
45
+ failure: /传入的配置组名称不存在|需要执行的配置组为空|执行脚本时发生异常|取消执行配置组|任务启动失败/u,
46
+ } };
47
+ }
10
48
  const profile = configName(optionalText(account, 'profile') || optionalText(config, 'profile'), '一条龙配置');
11
49
  // Upstream silently uses its selected profile if a supplied name is missing.
12
50
  await existingPath(join(profilesDirectory(cwd), `${profile}.json`), 'BetterGI 一条龙配置文件');
13
- return { command, cwd, args: ['startOneDragon', profile], logs: {
14
- directory: join(cwd, 'log'), filenames: /^better-genshin-impact\d{8}\.log$/u,
15
- success: /一条龙和配置组任务结束/u, closeOnCompletion: true,
16
- } };
51
+ return { command, cwd, args: ['startOneDragon', profile], logs: { ...logs, success: /一条龙和配置组任务结束/u } };
17
52
  }
18
53
  export const bettergi = {
19
54
  id: 'bettergi', title: '原神 · BetterGI 原生一条龙', group: '游戏专项', supports: windowsOnly,
20
55
  description: '调用 BetterGI 0.45.3 以上的命名一条龙入口。请在 BetterGI 中设置任务及结束后退出。',
21
56
  scriptFields: [executableField('BetterGI.exe'), profileOption('profile', '默认一条龙配置名称', 'bettergi.profiles', 'command', true)],
22
- accountFields: [profileOption('profile', '一条龙配置名称覆盖(可选)', 'bettergi.profiles', 'scriptId')],
57
+ accountFields: [
58
+ profileOption('profile', '一条龙配置名称覆盖(可选)', 'bettergi.profiles', 'scriptId'),
59
+ { key: 'groups', kind: 'multiselect', label: '配置组(可选)', source: 'bettergi.groups', sourceBy: 'scriptId',
60
+ hint: '依照列表顺序交给支持 --startGroups 的 BetterGI。留空时运行一条龙配置。' },
61
+ ],
23
62
  prepare: async (input) => {
24
63
  const paths = await betterGiProgram(input);
25
64
  const config = { ...paths, profile: requiredText(input, 'profile', '一条龙配置名称') };