index.ts
3.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { spawnSync } from 'node:child_process';
import { LaunchTool } from '../../../tools/launch-tool';
import { logger } from '../../../utils/logger';
const BUILD_MAX_RETRIES = 2;
const CMD_TIMEOUT_MS = 180_000;
const DEV_SERVER_TIMEOUT_MS = 60_000;
export interface LaunchConfig {
/**
* Skip dependency installation (pnpm i).
* Set to true for iterations 2+ where dependencies haven't changed.
*/
skipDependencyInstall?: boolean;
}
export interface LaunchResult {
success: boolean;
message?: string;
error?: string;
// Server metadata from LaunchTool
serverKey?: string;
url?: string;
port?: number;
}
function runCmd(command: string, cwd: string, timeoutMs: number = CMD_TIMEOUT_MS): { ok: boolean; output: string } {
const r = spawnSync(command, { cwd, timeout: timeoutMs, encoding: 'utf8', shell: true });
const output = [r.stdout, r.stderr].filter(Boolean).join('\n');
return { ok: r.status === 0, output };
}
export const launch = async (appPath: string, config?: LaunchConfig): Promise<LaunchResult> => {
if (!appPath) {
return { success: false, error: 'appPath is required' };
}
try {
// 1. 安装依赖(首轮;迭代 2+ 由 skipDependencyInstall 跳过)
if (!config?.skipDependencyInstall) {
logger.printInfoLog('正在安装依赖(pnpm i)…');
const install = runCmd('pnpm i', appPath);
if (!install.ok) {
return { success: false, error: `依赖安装失败:\n${install.output.slice(-1000)}` };
}
logger.printSuccessLog('依赖安装完成');
}
// 2. 构建(有限次重试,不调用模型)
let buildOk = false;
let buildOutput = '';
for (let attempt = 1; attempt <= BUILD_MAX_RETRIES; attempt++) {
logger.printInfoLog(`正在构建项目(npm run build,第 ${attempt}/${BUILD_MAX_RETRIES} 次)…`);
const build = runCmd('npm run build', appPath);
buildOutput = build.output;
if (build.ok) {
buildOk = true;
break;
}
logger.printWarnLog(`构建失败(第 ${attempt}/${BUILD_MAX_RETRIES} 次):\n${buildOutput.slice(-500)}`);
}
if (!buildOk) {
return { success: false, error: `构建失败,已重试 ${BUILD_MAX_RETRIES} 次:\n${buildOutput.slice(-1000)}` };
}
logger.printSuccessLog('构建完成');
// 3. 启动开发服务器(确定性调用 LaunchTool,不走 LLM)
logger.printInfoLog('正在启动开发服务器(npm run dev)…');
const launchTool = new LaunchTool();
const raw = await launchTool.startDevServer(appPath, 'npm run dev', DEV_SERVER_TIMEOUT_MS);
const res = JSON.parse(raw) as {
success: boolean;
serverKey?: string;
url?: string;
port?: number;
error?: string;
};
if (!res.success || !res.serverKey) {
return { success: false, error: res.error ?? '开发服务器启动失败' };
}
return {
success: true,
message: '开发服务器已启动',
serverKey: res.serverKey,
url: res.url,
port: res.port,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
};
}
};