@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.
- package/dist/LICENSE +661 -0
- package/dist/index.js +1 -0
- package/dist/server/builtin-plugins/maafw-projects.js +60 -0
- package/dist/server/download.js +15 -0
- package/dist/server/emulator-managers.js +219 -0
- package/dist/server/execution.js +364 -0
- package/dist/server/features.js +31 -0
- package/dist/server/maa/agent-environment.js +130 -0
- package/dist/server/maa/index.js +97 -0
- package/dist/server/maa/managed-project-path.js +34 -0
- package/dist/server/maa/managed-projects.js +133 -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-environment.js +133 -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/release-projects.js +213 -0
- package/dist/server/maa/worker.js +361 -0
- package/dist/server/run-lifecycle.js +1 -0
- package/dist/server/schema.js +353 -0
- package/dist/server/storage.js +76 -0
- package/dist/server/ui.js +171 -0
- package/dist/server/updates.js +183 -0
- package/package.json +36 -6
- package/README.md +0 -3
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export const ui = (ctx) => ctx.get('mas.ui');
|
|
2
|
+
export const store = (ctx) => ctx.get('mas.store');
|
|
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', '结果详情']);
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
4
|
+
import { runProcess } from '../execution.js';
|
|
5
|
+
import { projectIdPattern, withinProject } from './managed-project-path.js';
|
|
6
|
+
import { isPythonCommand } from './process.js';
|
|
7
|
+
import { loadProject, projectPath } from './project.js';
|
|
8
|
+
export function venvPython(directory) {
|
|
9
|
+
return process.platform === 'win32' ? join(directory, 'Scripts', 'python.exe') : join(directory, 'bin', 'python');
|
|
10
|
+
}
|
|
11
|
+
async function optionalFile(path, limit) {
|
|
12
|
+
const file = await stat(path).catch(error => {
|
|
13
|
+
if (error.code === 'ENOENT')
|
|
14
|
+
return undefined;
|
|
15
|
+
throw error;
|
|
16
|
+
});
|
|
17
|
+
if (!file)
|
|
18
|
+
return undefined;
|
|
19
|
+
if (!file.isFile() || file.size > limit)
|
|
20
|
+
throw new Error('Agent 的项目描述或锁文件无法读取');
|
|
21
|
+
return readFile(path);
|
|
22
|
+
}
|
|
23
|
+
async function uvProject(path) {
|
|
24
|
+
const project = await loadProject(path);
|
|
25
|
+
const root = await realpath(project.directory);
|
|
26
|
+
const python = [...project.agents, ...project.pretasks].filter(command => isPythonCommand(command.executable));
|
|
27
|
+
if (!python.length)
|
|
28
|
+
throw new Error('项目未声明由 Python 启动的 Agent 或前置任务');
|
|
29
|
+
const directories = new Set([root]);
|
|
30
|
+
for (const command of python) {
|
|
31
|
+
for (const argument of command.args) {
|
|
32
|
+
if (!argument.endsWith('.py') || argument.startsWith('-'))
|
|
33
|
+
continue;
|
|
34
|
+
const directory = dirname(projectPath(root, argument));
|
|
35
|
+
if (withinProject(root, directory))
|
|
36
|
+
directories.add(directory);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const locked = await Promise.all([...directories].map(async (directory) => {
|
|
40
|
+
const [definition, lock, pythonVersion] = await Promise.all([
|
|
41
|
+
optionalFile(join(directory, 'pyproject.toml'), 1024 ** 2),
|
|
42
|
+
optionalFile(join(directory, 'uv.lock'), 16 * 1024 ** 2),
|
|
43
|
+
optionalFile(join(directory, '.python-version'), 4096),
|
|
44
|
+
]);
|
|
45
|
+
return definition && lock ? { definition, lock, pythonVersion, directory } : undefined;
|
|
46
|
+
}));
|
|
47
|
+
const candidates = locked.filter(item => item !== undefined);
|
|
48
|
+
if (candidates.length === 0)
|
|
49
|
+
throw new Error('项目 Agent 目录必须包含 pyproject.toml 和 uv.lock 才能准备独立环境');
|
|
50
|
+
if (candidates.length !== 1)
|
|
51
|
+
throw new Error('项目包含多个 Python 环境,请直接指定 Agent 所用的 Python 程序');
|
|
52
|
+
return candidates[0];
|
|
53
|
+
}
|
|
54
|
+
async function syncUv(command, args, options) {
|
|
55
|
+
await runProcess({ id: 'maafw-agent-env', name: 'MaaFramework Agent', adapter: 'general', command, args, ...options }, {
|
|
56
|
+
signal: AbortSignal.timeout(10 * 60_000),
|
|
57
|
+
log: () => { },
|
|
58
|
+
}).catch(error => { throw new Error('项目 Python 环境准备失败,请检查 uv、网络和项目锁文件', { cause: error }); });
|
|
59
|
+
}
|
|
60
|
+
export class MaaAgentEnvironments {
|
|
61
|
+
dir;
|
|
62
|
+
sync;
|
|
63
|
+
pending = new Map();
|
|
64
|
+
constructor(dataDir, sync = syncUv) {
|
|
65
|
+
this.dir = join(dataDir, 'maafw-agent-env');
|
|
66
|
+
this.sync = sync;
|
|
67
|
+
}
|
|
68
|
+
async prepare(path) {
|
|
69
|
+
if (!isAbsolute(path))
|
|
70
|
+
throw new Error('请选择项目的绝对路径');
|
|
71
|
+
const project = await uvProject(path);
|
|
72
|
+
const key = createHash('sha256').update(`1\0${process.platform}\0${process.arch}\0${project.directory}\0`)
|
|
73
|
+
.update(project.definition).update('\0').update(project.lock).update('\0').update(project.pythonVersion ?? '').digest('hex');
|
|
74
|
+
const active = this.pending.get(key);
|
|
75
|
+
if (active)
|
|
76
|
+
return active;
|
|
77
|
+
const work = this.build(key, project.directory);
|
|
78
|
+
this.pending.set(key, work);
|
|
79
|
+
try {
|
|
80
|
+
return await work;
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
this.pending.delete(key);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async build(key, project) {
|
|
87
|
+
const base = join(this.dir, key);
|
|
88
|
+
const ready = join(base, 'ready.json');
|
|
89
|
+
const previous = await readFile(ready, 'utf8').then(content => JSON.parse(content), error => {
|
|
90
|
+
if (error.code === 'ENOENT')
|
|
91
|
+
return undefined;
|
|
92
|
+
throw error;
|
|
93
|
+
});
|
|
94
|
+
if (previous !== undefined) {
|
|
95
|
+
const generation = previous?.generation;
|
|
96
|
+
if (typeof generation !== 'string' || !projectIdPattern.test(generation) || typeof previous?.prepared !== 'string') {
|
|
97
|
+
throw new Error('Agent 环境记录已损坏');
|
|
98
|
+
}
|
|
99
|
+
const python = venvPython(join(base, generation, 'venv'));
|
|
100
|
+
if (await stat(python).then(item => item.isFile(), () => false))
|
|
101
|
+
return { key, project, python, prepared: previous.prepared };
|
|
102
|
+
}
|
|
103
|
+
const generation = randomUUID();
|
|
104
|
+
const staging = join(base, generation);
|
|
105
|
+
const environment = join(staging, 'venv');
|
|
106
|
+
await mkdir(staging, { recursive: true });
|
|
107
|
+
const python = venvPython(environment);
|
|
108
|
+
const temp = join(base, `.ready-${generation}.json`);
|
|
109
|
+
let published = false;
|
|
110
|
+
try {
|
|
111
|
+
await this.sync(process.platform === 'win32' ? 'uv.exe' : 'uv', ['sync', '--locked', '--no-install-project', '--no-dev'], {
|
|
112
|
+
cwd: project,
|
|
113
|
+
env: { UV_PROJECT_ENVIRONMENT: environment, UV_PYTHON_INSTALL_DIR: join(this.dir, 'interpreters'), UV_CACHE_DIR: join(this.dir, 'cache') },
|
|
114
|
+
});
|
|
115
|
+
if (!await stat(python).then(item => item.isFile(), () => false))
|
|
116
|
+
throw new Error('uv 未生成可用的项目 Python 程序');
|
|
117
|
+
const prepared = new Date().toISOString();
|
|
118
|
+
await writeFile(temp, JSON.stringify({ generation, prepared }), { flag: 'wx', mode: 0o600 });
|
|
119
|
+
await rename(temp, ready);
|
|
120
|
+
published = true;
|
|
121
|
+
return { key, project, python, prepared };
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
if (!published) {
|
|
125
|
+
await rm(temp, { force: true });
|
|
126
|
+
await rm(staging, { recursive: true, force: true });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { fork } from 'node:child_process';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { adbEnvironment } from '../emulator-managers.js';
|
|
4
|
+
import { readLines, terminateTree } from './process.js';
|
|
5
|
+
export { inspectProject } from './project.js';
|
|
6
|
+
const workerPath = fileURLToPath(new URL('./worker.js', import.meta.url));
|
|
7
|
+
export async function runMaa(input, options) {
|
|
8
|
+
const { signal, log, started, launchProcess } = options;
|
|
9
|
+
signal.throwIfAborted();
|
|
10
|
+
const env = { ...adbEnvironment(input.adbServerPort), ...(process.versions.electron ? { ELECTRON_RUN_AS_NODE: '1' } : {}) };
|
|
11
|
+
if (launchProcess) {
|
|
12
|
+
await launchProcess({ command: process.execPath, args: [workerPath, '--mas-stdio'], env,
|
|
13
|
+
stdin: JSON.stringify({ type: 'run', input }) }, options);
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
await new Promise((resolve, reject) => {
|
|
17
|
+
const worker = fork(workerPath, [], {
|
|
18
|
+
detached: process.platform !== 'win32',
|
|
19
|
+
env: { ...process.env, ...env },
|
|
20
|
+
execArgv: [],
|
|
21
|
+
windowsHide: true,
|
|
22
|
+
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
|
|
23
|
+
});
|
|
24
|
+
const processes = new Set();
|
|
25
|
+
let result;
|
|
26
|
+
let workerError;
|
|
27
|
+
let stopTimer;
|
|
28
|
+
let deadline;
|
|
29
|
+
let settled = false;
|
|
30
|
+
function abort() {
|
|
31
|
+
if (worker.connected)
|
|
32
|
+
worker.send({ type: 'stop' }, () => undefined);
|
|
33
|
+
stopTimer = setTimeout(() => {
|
|
34
|
+
log('MaaFramework stop deadline reached. Terminating the worker and its project processes.');
|
|
35
|
+
if (worker.pid)
|
|
36
|
+
void terminateTree(worker.pid);
|
|
37
|
+
for (const pid of processes)
|
|
38
|
+
void terminateTree(pid);
|
|
39
|
+
deadline = setTimeout(() => {
|
|
40
|
+
if (worker.connected)
|
|
41
|
+
worker.disconnect();
|
|
42
|
+
worker.stdout?.destroy();
|
|
43
|
+
worker.stderr?.destroy();
|
|
44
|
+
worker.unref();
|
|
45
|
+
void finish(null, null);
|
|
46
|
+
}, 2_000);
|
|
47
|
+
}, 5_000);
|
|
48
|
+
}
|
|
49
|
+
async function finish(code, exitSignal) {
|
|
50
|
+
if (settled)
|
|
51
|
+
return;
|
|
52
|
+
settled = true;
|
|
53
|
+
clearTimeout(stopTimer);
|
|
54
|
+
clearTimeout(deadline);
|
|
55
|
+
signal.removeEventListener('abort', abort);
|
|
56
|
+
await Promise.all([...processes].map(terminateTree));
|
|
57
|
+
if (signal.aborted)
|
|
58
|
+
reject(signal.reason);
|
|
59
|
+
else if (result?.error)
|
|
60
|
+
reject(result.error);
|
|
61
|
+
else if (workerError)
|
|
62
|
+
reject(workerError);
|
|
63
|
+
else if (code === 0 && result)
|
|
64
|
+
resolve();
|
|
65
|
+
else
|
|
66
|
+
reject(new Error(`MaaFramework worker exited before completing (${exitSignal ?? code ?? 'unknown status'}).`));
|
|
67
|
+
}
|
|
68
|
+
readLines(worker.stdout, log);
|
|
69
|
+
readLines(worker.stderr, (line) => log(`[MaaFramework stderr] ${line}`));
|
|
70
|
+
worker.on('message', (message) => {
|
|
71
|
+
if (message.type === 'process-started')
|
|
72
|
+
processes.add(message.pid);
|
|
73
|
+
if (message.type === 'process-exited')
|
|
74
|
+
processes.delete(message.pid);
|
|
75
|
+
if (message.type === 'failed')
|
|
76
|
+
result = { error: new Error(message.error) };
|
|
77
|
+
if (message.type === 'done')
|
|
78
|
+
result = {};
|
|
79
|
+
});
|
|
80
|
+
worker.once('error', (error) => { workerError = error; });
|
|
81
|
+
worker.once('spawn', () => {
|
|
82
|
+
try {
|
|
83
|
+
started?.('MaaFramework Worker 已启动');
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
workerError = error instanceof Error ? error : new Error(String(error));
|
|
87
|
+
abort();
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
worker.once('close', (code, exitSignal) => void finish(code, exitSignal));
|
|
91
|
+
worker.send({ type: 'run', input }, (error) => {
|
|
92
|
+
if (error)
|
|
93
|
+
workerError = error;
|
|
94
|
+
});
|
|
95
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
96
|
+
});
|
|
97
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readFile, realpath } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute, join, relative, sep } from 'node:path';
|
|
3
|
+
export const managedProjectManifest = '.automasc-maafw.json';
|
|
4
|
+
export const projectIdPattern = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/u;
|
|
5
|
+
export function withinProject(root, path) {
|
|
6
|
+
const displacement = relative(root, path);
|
|
7
|
+
return !isAbsolute(displacement) && displacement !== '..' && !displacement.startsWith(`..${sep}`);
|
|
8
|
+
}
|
|
9
|
+
export async function readManagedProject(root) {
|
|
10
|
+
const source = await readFile(join(root, managedProjectManifest), 'utf8').catch(error => {
|
|
11
|
+
if (error.code === 'ENOENT')
|
|
12
|
+
return undefined;
|
|
13
|
+
throw error;
|
|
14
|
+
});
|
|
15
|
+
if (source === undefined)
|
|
16
|
+
return undefined;
|
|
17
|
+
const record = JSON.parse(source);
|
|
18
|
+
if (record?.schema !== 1 || typeof record.id !== 'string' || !projectIdPattern.test(record.id) ||
|
|
19
|
+
typeof record.name !== 'string' || typeof record.label !== 'string' || typeof record.source !== 'string' || !isAbsolute(record.source) ||
|
|
20
|
+
typeof record.current !== 'string' || !Array.isArray(record.revisions) || !record.revisions.some(item => item?.id === record.current) ||
|
|
21
|
+
record.revisions.some(item => !item || typeof item.id !== 'string' || !projectIdPattern.test(item.id) || typeof item.created !== 'string')) {
|
|
22
|
+
throw new Error('MaaFramework 项目记录有误,请检查副本目录');
|
|
23
|
+
}
|
|
24
|
+
return record;
|
|
25
|
+
}
|
|
26
|
+
export async function managedRevisionPath(root, revision) {
|
|
27
|
+
if (!projectIdPattern.test(revision))
|
|
28
|
+
throw new Error('MaaFramework 项目版本标识无效');
|
|
29
|
+
const canonicalRoot = await realpath(root);
|
|
30
|
+
const selected = await realpath(join(root, 'revisions', revision));
|
|
31
|
+
if (!withinProject(canonicalRoot, selected) || selected === canonicalRoot)
|
|
32
|
+
throw new Error('MaaFramework 项目版本目录超出项目范围');
|
|
33
|
+
return selected;
|
|
34
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { cp, lstat, mkdir, readdir, realpath, rename, rm, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { basename, isAbsolute, join } from 'node:path';
|
|
4
|
+
import { inspectProject } from './project.js';
|
|
5
|
+
import { managedProjectManifest, managedRevisionPath, projectIdPattern, readManagedProject, withinProject } from './managed-project-path.js';
|
|
6
|
+
export class ManagedMaaProjects {
|
|
7
|
+
directory;
|
|
8
|
+
editing = new Set();
|
|
9
|
+
constructor(dataDir) { this.directory = join(dataDir, 'maafw-projects'); }
|
|
10
|
+
path(id) {
|
|
11
|
+
if (!projectIdPattern.test(id))
|
|
12
|
+
throw new Error('请选择有效的 MaaFramework 项目');
|
|
13
|
+
return join(this.directory, id);
|
|
14
|
+
}
|
|
15
|
+
async get(id) {
|
|
16
|
+
const path = this.path(id);
|
|
17
|
+
const record = await readManagedProject(path);
|
|
18
|
+
if (!record || record.id !== id)
|
|
19
|
+
throw new Error('MaaFramework 项目不存在');
|
|
20
|
+
return { ...record, path };
|
|
21
|
+
}
|
|
22
|
+
async list() {
|
|
23
|
+
const entries = await readdir(this.directory, { withFileTypes: true }).catch(error => {
|
|
24
|
+
if (error.code === 'ENOENT')
|
|
25
|
+
return [];
|
|
26
|
+
throw error;
|
|
27
|
+
});
|
|
28
|
+
const projects = await Promise.all(entries.filter(entry => entry.isDirectory() && projectIdPattern.test(entry.name)).map(async (entry) => {
|
|
29
|
+
const path = this.path(entry.name);
|
|
30
|
+
const record = await readManagedProject(path);
|
|
31
|
+
return record ? { ...record, path } : undefined;
|
|
32
|
+
}));
|
|
33
|
+
return projects.filter(project => project !== undefined).sort((a, b) => a.label.localeCompare(b.label));
|
|
34
|
+
}
|
|
35
|
+
async importFrom(path) {
|
|
36
|
+
if (!isAbsolute(path))
|
|
37
|
+
throw new Error('请选择 MaaFramework 项目的绝对路径');
|
|
38
|
+
const source = await realpath(path);
|
|
39
|
+
await mkdir(this.directory, { recursive: true });
|
|
40
|
+
const managedRoot = await realpath(this.directory);
|
|
41
|
+
if (withinProject(source, managedRoot) || withinProject(managedRoot, source))
|
|
42
|
+
throw new Error('请从托管项目目录之外导入');
|
|
43
|
+
if (!(await lstat(source)).isDirectory())
|
|
44
|
+
throw new Error('请选择含 interface.json 的项目目录');
|
|
45
|
+
const preview = await inspectProject(source);
|
|
46
|
+
const id = randomUUID();
|
|
47
|
+
const record = { schema: 1, id, name: preview.name, label: preview.label, source, current: '', revisions: [] };
|
|
48
|
+
return this.copyRevision(record);
|
|
49
|
+
}
|
|
50
|
+
async sync(id) {
|
|
51
|
+
return this.edit(id, async (record) => this.copyRevision(record));
|
|
52
|
+
}
|
|
53
|
+
async install(id, source, expectedCurrent, expectedVersion) {
|
|
54
|
+
return this.edit(id, async (record) => {
|
|
55
|
+
if (record.current !== expectedCurrent)
|
|
56
|
+
throw new Error('项目版本已变化,请重新检查更新');
|
|
57
|
+
return this.copyRevision(record, source, expectedVersion);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
async restore(id, revision) {
|
|
61
|
+
return this.edit(id, async (record) => {
|
|
62
|
+
if (!record.revisions.some(item => item.id === revision))
|
|
63
|
+
throw new Error('MaaFramework 项目历史版本不存在');
|
|
64
|
+
const restored = await inspectProject(await managedRevisionPath(record.path, revision));
|
|
65
|
+
if (restored.name !== record.name)
|
|
66
|
+
throw new Error('历史副本的项目标识已变化');
|
|
67
|
+
const next = { ...record, label: restored.label, current: revision };
|
|
68
|
+
await this.writeManifest(next);
|
|
69
|
+
return next;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
async edit(id, action) {
|
|
73
|
+
if (this.editing.has(id))
|
|
74
|
+
throw new Error('项目正在同步或恢复');
|
|
75
|
+
this.editing.add(id);
|
|
76
|
+
try {
|
|
77
|
+
return await action(await this.get(id));
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
this.editing.delete(id);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async copyRevision(record, sourceDirectory = record.source, expectedVersion) {
|
|
84
|
+
const path = this.path(record.id);
|
|
85
|
+
const revisions = join(path, 'revisions');
|
|
86
|
+
await mkdir(revisions, { recursive: true });
|
|
87
|
+
const revision = { id: randomUUID(), created: new Date().toISOString() };
|
|
88
|
+
const staging = join(revisions, `.pending-${revision.id}`);
|
|
89
|
+
const release = join(revisions, revision.id);
|
|
90
|
+
let transferred = false;
|
|
91
|
+
try {
|
|
92
|
+
await cp(sourceDirectory, staging, { recursive: true, errorOnExist: true, force: false, filter: async (source) => {
|
|
93
|
+
if (source !== sourceDirectory && basename(source) === '.git')
|
|
94
|
+
return false;
|
|
95
|
+
const item = await lstat(source);
|
|
96
|
+
if (!item.isFile() && !item.isDirectory())
|
|
97
|
+
throw new Error('MaaFramework 项目含符号链接或其他特殊文件,无法复制');
|
|
98
|
+
return true;
|
|
99
|
+
} });
|
|
100
|
+
if (await readManagedProject(staging))
|
|
101
|
+
throw new Error('同步来源包含另一个托管项目记录');
|
|
102
|
+
const preview = await inspectProject(staging);
|
|
103
|
+
if (preview.name !== record.name)
|
|
104
|
+
throw new Error('来源目录的项目标识已变化');
|
|
105
|
+
if (expectedVersion && preview.version?.replace(/^v/u, '') !== expectedVersion.replace(/^v/u, '')) {
|
|
106
|
+
throw new Error('MaaFramework 项目包版本与所选发行版本不一致');
|
|
107
|
+
}
|
|
108
|
+
await rename(staging, release);
|
|
109
|
+
transferred = true;
|
|
110
|
+
const next = { ...record, path, label: preview.label, current: revision.id,
|
|
111
|
+
revisions: [...record.revisions, { ...revision, version: preview.version }] };
|
|
112
|
+
await this.writeManifest(next);
|
|
113
|
+
return next;
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
if (!transferred)
|
|
117
|
+
await rm(staging, { recursive: true, force: true });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async writeManifest(record) {
|
|
121
|
+
const { path, ...manifest } = record;
|
|
122
|
+
const target = join(path, managedProjectManifest);
|
|
123
|
+
const temporary = `${target}.${randomUUID()}.tmp`;
|
|
124
|
+
await writeFile(temporary, JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
125
|
+
try {
|
|
126
|
+
await rename(temporary, target);
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
await unlink(temporary).catch(error => { if (error.code !== 'ENOENT')
|
|
130
|
+
throw error; });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { mkdtemp, realpath, rm, stat, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { isAbsolute, join } from 'node:path';
|
|
4
|
+
import { runProcess } from '../execution.js';
|
|
5
|
+
import { adbEnvironment } from '../emulator-managers.js';
|
|
6
|
+
import { runMaa } from './index.js';
|
|
7
|
+
import { nativeWorkerSource } from './native-worker-source.js';
|
|
8
|
+
import { bindNodeAgent, readNodeAgentEnvironment } from './node-agent-path.js';
|
|
9
|
+
import { loadProject, planRun } from './project.js';
|
|
10
|
+
const framework = process.platform === 'win32' ? 'MaaFramework.dll' : process.platform === 'darwin' ? 'libMaaFramework.dylib' : 'libMaaFramework.so';
|
|
11
|
+
export async function nativeRuntimePaths(python, libraries) {
|
|
12
|
+
if (!python && !libraries)
|
|
13
|
+
return undefined;
|
|
14
|
+
if (!python || !libraries)
|
|
15
|
+
throw new Error('请一并选择匹配的 Python 解释器与 MaaFramework 原生库目录');
|
|
16
|
+
if (!isAbsolute(python) || !await stat(python).then(item => item.isFile(), () => false))
|
|
17
|
+
throw new Error('请选择有效的原生运行器 Python 可执行文件');
|
|
18
|
+
if (!isAbsolute(libraries))
|
|
19
|
+
throw new Error('请选择 MaaFramework 原生库的绝对目录');
|
|
20
|
+
const path = await realpath(libraries).catch(() => { throw new Error('MaaFramework 原生库目录不存在'); });
|
|
21
|
+
if (!await stat(join(path, framework)).then(item => item.isFile(), () => false))
|
|
22
|
+
throw new Error(`MaaFramework 原生库目录缺少 ${framework}`);
|
|
23
|
+
return { nativePython: python, nativeLibraries: path };
|
|
24
|
+
}
|
|
25
|
+
async function invoke(paths, job, options, adbServerPort) {
|
|
26
|
+
const request = JSON.stringify({ nativeLibraries: paths.nativeLibraries, job });
|
|
27
|
+
let version;
|
|
28
|
+
let failure;
|
|
29
|
+
const args = ['-u', '-X', 'utf8', '-c', nativeWorkerSource];
|
|
30
|
+
const proc = { command: paths.nativePython, args, cwd: job?.directory, env: adbEnvironment(adbServerPort) };
|
|
31
|
+
const execution = { ...options, log(line) {
|
|
32
|
+
if (line.startsWith('MAS_MAA_NATIVE_DONE '))
|
|
33
|
+
version = line.slice('MAS_MAA_NATIVE_DONE '.length);
|
|
34
|
+
else if (line.startsWith('MAS_MAA_NATIVE_ERROR '))
|
|
35
|
+
failure = line.slice('MAS_MAA_NATIVE_ERROR '.length);
|
|
36
|
+
else
|
|
37
|
+
options.log(line);
|
|
38
|
+
} };
|
|
39
|
+
try {
|
|
40
|
+
if (options.launchProcess) {
|
|
41
|
+
await options.launchProcess({ ...proc, stdin: request }, execution);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
const temp = await mkdtemp(join(tmpdir(), 'masc-maafw-native-'));
|
|
45
|
+
try {
|
|
46
|
+
const path = join(temp, 'request.json');
|
|
47
|
+
await writeFile(path, request, { flag: 'wx', mode: 0o600 });
|
|
48
|
+
await runProcess({ id: 'maafw-native', adapter: 'maafw', name: 'MaaFramework 原生运行器', ...proc, args: [...args, path] }, execution);
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
await rm(temp, { recursive: true, force: true });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
options.signal.throwIfAborted();
|
|
57
|
+
throw new Error(failure || 'MaaFramework 原生运行器异常退出,请检查已安装的 maafw Python 绑定与原生库', { cause: error });
|
|
58
|
+
}
|
|
59
|
+
if (!version)
|
|
60
|
+
throw new Error(failure || 'MaaFramework 原生运行器未返回成功结果');
|
|
61
|
+
return version;
|
|
62
|
+
}
|
|
63
|
+
export async function probeNativeMaa(python, libraries) {
|
|
64
|
+
const paths = (await nativeRuntimePaths(python, libraries));
|
|
65
|
+
const version = await invoke(paths, undefined, { signal: AbortSignal.timeout(15_000), log: () => { } });
|
|
66
|
+
return { version, ...paths };
|
|
67
|
+
}
|
|
68
|
+
export async function runMaaSelected(input, options) {
|
|
69
|
+
const native = await nativeRuntimePaths(input.nativePython, input.nativeLibraries);
|
|
70
|
+
if (!native)
|
|
71
|
+
return runMaa(input, options);
|
|
72
|
+
const project = await loadProject(input.projectPath);
|
|
73
|
+
const plan = planRun(project, input);
|
|
74
|
+
const nodeAgent = input.agentNodeRoot && await readNodeAgentEnvironment(input.agentNodeRoot, project.directory) || undefined;
|
|
75
|
+
const { adbPath, address, windowHandle, agentPython } = input;
|
|
76
|
+
await invoke(native, { ...plan, directory: project.directory, input: { adbPath, address, windowHandle, agentPython },
|
|
77
|
+
agents: plan.agents.map(item => bindNodeAgent(item, project.directory, nodeAgent)),
|
|
78
|
+
pretasks: plan.pretasks.map(item => bindNodeAgent(item, project.directory, nodeAgent)),
|
|
79
|
+
}, options, input.adbServerPort);
|
|
80
|
+
}
|