ai-direct-server.mjs
17.2 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#!/usr/bin/env node
import { spawn } from "node:child_process";
import fs from "node:fs";
import fsp from "node:fs/promises";
import http from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { requireWorkspaceRoot } from "./workspace-root.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = requireWorkspaceRoot();
const PORT = Number.parseInt(process.env.AI_DIRECT_PORT || "3210", 10);
const PREVIEW_DIR = "apps/web/ai-previews";
const DEFAULT_CONFIG = {
figmaApiKey: "figd_Cs0tDjz-UVojDvRlC2c-_4g5xR-hSwm7xP6kFzwd",
aiBaseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",
aiApiKey: "sk-954dfaed75e040b6a06f9c908b0a8c85",
aiModel: "qwen3.7-max",
visionModel: "qwen3.6-plus",
};
const MODEL_CANDIDATES = [
{ label: "Qwen3.7 Max", value: "qwen3.7-max" },
{ label: "Qwen3.6 Plus", value: "qwen3.6-plus" },
{ label: "Qwen Max", value: "qwen-max" },
{ label: "Qwen Plus", value: "qwen-plus" },
{ label: "Qwen Turbo", value: "qwen-turbo" },
{ label: "DeepSeek V3", value: "deepseek-v3" },
{ label: "DeepSeek R1", value: "deepseek-r1" },
];
const URL_CANDIDATES = [
{ label: "阿里云 DashScope", value: "https://dashscope.aliyuncs.com/compatible-mode/v1" },
{ label: "OpenAI Official", value: "https://api.openai.com/v1" },
{ label: "SiliconFlow", value: "https://api.siliconflow.cn/v1" },
{ label: "自定义", value: "" },
];
const clients = new Set();
let currentProcess = null;
let isRunning = false;
let heartbeatTimer = null;
let previewUrl = null;
function setPreviewUrl(url) {
previewUrl = url;
log(`预览地址: ${url}`);
broadcast("preview", { url });
}
function broadcast(event, data) {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
for (const client of clients) {
try { client.write(payload); } catch {}
}
}
function log(msg) {
console.log(`[ai-direct-server] ${msg}`);
broadcast("log", { message: msg, timestamp: Date.now() });
}
function readJson(filePath) {
try { return JSON.parse(fs.readFileSync(filePath, "utf8")); } catch { return null; }
}
function listPreviewProjects() {
const dir = path.join(repoRoot, PREVIEW_DIR);
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir, { withFileTypes: true })
.filter(e => e.isDirectory())
.map(e => {
const pkg = readJson(path.join(dir, e.name, "package.json"));
return { name: e.name, packageName: pkg?.name || `@venus/${e.name}`, path: path.join(dir, e.name) };
});
}
function listBundlePages() {
const dir = path.join(repoRoot, "apps/web/ai-workspace/.ai-direct");
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir, { withFileTypes: true })
.filter(e => e.isDirectory())
.map(e => {
const files = fs.readdirSync(path.join(dir, e.name));
const bundle = files.find(f => f.endsWith(".ai-direct-context-bundle.json"));
return { slug: e.name, bundleFile: bundle ? path.join(dir, e.name, bundle) : null };
})
.filter(p => p.bundleFile);
}
function listGeneratedFiles(projectRoot) {
if (!projectRoot || !fs.existsSync(projectRoot)) return [];
const viewsDir = path.join(projectRoot, "src", "views");
if (!fs.existsSync(viewsDir)) return [];
const results = [];
function walk(dir, prefix) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) walk(path.join(dir, entry.name), relPath);
else if (/\.(vue|ts|tsx|css|scss)$/.test(entry.name))
results.push({ path: `src/views/${relPath}`, fullPath: path.join(dir, entry.name) });
}
}
walk(viewsDir, "");
return results;
}
function parseBody(req) {
return new Promise((resolve, reject) => {
let body = "";
req.on("data", chunk => body += chunk);
req.on("end", () => { try { resolve(JSON.parse(body)); } catch { reject(new Error("Invalid JSON")); } });
req.on("error", reject);
});
}
function emitConsole(text, stream) {
broadcast("output", { stream: stream || "stdout", text, timestamp: Date.now() });
}
function emitStep(step, label) {
broadcast("status", { running: true, step, label });
emitConsole(`\n⏳ [${new Date().toLocaleTimeString()}] ${label}\n`, "progress");
}
function startHeartbeat() {
stopHeartbeat();
heartbeatTimer = setInterval(() => {
if (isRunning) {
emitConsole(`⏳ [${new Date().toLocaleTimeString()}] 处理中...\n`, "heartbeat");
}
}, 15_000);
}
function stopHeartbeat() {
if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }
}
async function runPipeline(config) {
if (isRunning) {
if (currentProcess) {
log("停止旧任务...");
currentProcess.kill("SIGTERM");
await new Promise(r => setTimeout(r, 1000));
if (currentProcess) {
currentProcess.kill("SIGKILL");
await new Promise(r => setTimeout(r, 500));
}
}
isRunning = false;
stopHeartbeat();
}
isRunning = true;
startHeartbeat();
const env = {
...process.env,
FIGMA_API_KEY: config.figmaApiKey || DEFAULT_CONFIG.figmaApiKey,
AI_DIRECT_OPENAI_BASE_URL: config.aiBaseUrl || DEFAULT_CONFIG.aiBaseUrl,
AI_DIRECT_OPENAI_API_KEY: config.aiApiKey || DEFAULT_CONFIG.aiApiKey,
AI_DIRECT_OPENAI_MODEL: config.aiModel || DEFAULT_CONFIG.aiModel,
AI_DIRECT_VISION_MODEL: config.visionModel || DEFAULT_CONFIG.visionModel,
};
const args = ["scripts/ai-direct-execute.mjs"];
// 清理空字符串参数
const bundleFile = config.bundleFile?.trim() || null;
const figmaUrl = config.figmaUrl?.trim() || null;
if (bundleFile) {
args.push("--bundle-file", bundleFile);
log(`使用已有 bundle: ${bundleFile}`);
} else if (figmaUrl) {
// 新建页面模式:智能选择参考项目
let projectDir = config.projectDir?.trim() || null;
if (!projectDir) {
// 优先使用已有的预览项目作为参考
const previews = listPreviewProjects();
if (previews.length > 0) {
projectDir = previews[0].path;
log(`使用已有预览项目作为参考: ${previews[0].name}`);
} else {
// 没有预览项目,使用仓库根目录
projectDir = ".";
log("使用仓库根目录作为项目参考");
}
}
args.push("--project-dir", projectDir, "--figma-url", figmaUrl);
if (config.pageName?.trim()) args.push("--page-name", config.pageName.trim());
if (config.refreshContext) args.push("--refresh-context");
} else {
broadcast("error", { message: "必须提供 Figma URL 或选择已有的 Context Bundle" });
broadcast("status", { running: false, step: "error" });
isRunning = false;
stopHeartbeat();
return;
}
args.push("--provider", "openai-compatible", "--model", config.aiModel || DEFAULT_CONFIG.aiModel, "--auto-repair", "--without-variables", "--preview-dir", PREVIEW_DIR);
if (config.force !== false) args.push("--force");
if (config.skipPreview) args.push("--skip-preview");
if (config.targetPlatform?.trim()) {
args.push("--target-platform", config.targetPlatform.trim());
log(`目标平台: ${config.targetPlatform.trim()}`);
}
if (config.fallbackUi?.trim()) {
args.push("--fallback-ui", config.fallbackUi.trim());
log(`降级组件库: ${config.fallbackUi.trim()}`);
}
emitConsole(`\n═══════════════════════════════════════\n`, "system");
emitConsole(` Venus AI Direct Pipeline\n`, "system");
emitConsole(` ${new Date().toLocaleString()}\n`, "system");
emitConsole(`═══════════════════════════════════════\n\n`, "system");
emitStep("init", "初始化流程...");
log(`启动命令: node ${args.join(" ")}`);
log(`参数数量: ${args.length}`);
log(`Provider: ${args.find(a => a.includes("provider")) || "not found"}`);
const child = spawn(process.execPath, args, {
cwd: repoRoot,
env,
stdio: ["ignore", "pipe", "pipe"],
});
currentProcess = child;
let lastStep = "init";
child.stdout.on("data", data => {
const text = data.toString();
broadcast("output", { stream: "stdout", text, timestamp: Date.now() });
// 检测 Vite dev server URL
const viteMatch = text.match(/Local:\s+(https?:\/\/localhost:\d+\/?)/);
if (viteMatch) {
setPreviewUrl(viteMatch[1]);
}
const stepMap = [
[/\[ai-direct-execute\].*\[0\/8\] 环境预检/, "precheck", "⏳ [0/8] 环境预检..."],
[/\[ai-direct-execute\].*✓ \[0\/8\] 环境预检完成/, "precheck-done", "✓ [0/8] 环境预检完成"],
[/\[ai-direct-execute\].*\[1\/8\] Context 收集/, "context", "⏳ [1/8] Context 收集..."],
[/\[ai-direct-execute\].*✓ \[1\/8\] Context 收集完成/, "context-done", "✓ [1/8] Context 收集完成"],
[/\[ai-direct-execute\].*\[2\/8\] Messages/, "messages", "⏳ [2/8] Messages 构建..."],
[/\[ai-direct-execute\].*✓ \[2\/8\] Messages 构建完成/, "messages-done", "✓ [2/8] Messages 构建完成"],
[/\[ai-direct-execute\].*\[3\/8\] 项目决策/, "project-decision", "⏳ [3/8] 项目决策..."],
[/\[ai-direct-execute\].*✓ \[3\/8\] 项目决策完成/, "project-decision-done", "✓ [3/8] 项目决策完成"],
[/\[ai-direct-execute\].*\[4\/8\] AI 生成/, "ai-generate", "⏳ [4/8] AI 生成..."],
[/\[ai-direct-execute\].*✓ \[4\/8\] AI 生成完成/, "ai-generate-done", "✓ [4/8] AI 生成完成"],
[/\[ai-direct-execute\].*\[5\/8\] 质量校验/, "quality-check", "⏳ [5/8] 质量校验..."],
[/\[ai-direct-execute\].*Fitness.*通过/, "fitness-item", "Fitness 维度通过"],
[/\[ai-direct-execute\].*✓ \[5\/8\] Fitness 汇总/, "quality-check-done", "✓ [5/8] 质量校验完成"],
[/\[ai-direct-execute\].*\[6\/8\] 健康修复/, "health-fix", "⏳ [6/8] 健康修复..."],
[/\[ai-direct-execute\].*✓ \[6\/8\] 健康修复/, "health-fix-done", "✓ [6/8] 健康修复完成"],
[/\[ai-direct-execute\].*\[7\/8\] 安装启动/, "install-launch", "⏳ [7/8] 安装启动..."],
[/\[ai-direct-execute\].*安装依赖/, "install", "安装依赖..."],
[/\[ai-direct-execute\].*启动预览/, "launch", "启动预览服务..."],
[/\[ai-direct-execute\].*\[8\/8\] 人工确认/, "manual-confirm", "⏳ [8/8] 人工确认..."],
[/\[ai-direct-execute\].*✓ \[8\/8\] 全流程完成/, "complete", "✓ [8/8] 全流程完成"],
[/项目创建成功/, "project-created", "✓ 项目创建成功"],
[/VITE.*ready/, "dev-ready", "✓ Dev Server 已就绪"],
[/\[ai-direct-messages\].*准备/, "messages-legacy", "准备 AI 消息..."],
[/\[ai-direct-messages\].*✓/, "messages-legacy-done", "✓ 消息准备完成"],
[/\[ai-direct-preview-project\].*准备/, "preview-legacy", "创建预览项目..."],
[/\[ai-direct-preview-project\].*✓/, "preview-legacy-done", "✓ 预览项目就绪"],
[/\[ai-direct-apply-output\].*应用/, "apply-legacy", "应用 AI 输出..."],
[/\[ai-direct-apply-output\].*✓/, "apply-legacy-done", "✓ 输出已应用"],
[/\[ai-direct-validate-output\].*校验/, "validate-legacy", "校验输出..."],
[/\[ai-direct-execute\].*repair/, "repair-legacy", "执行修复..."],
];
for (const [pattern, step, label] of stepMap) {
if (pattern.test(text) && step !== lastStep) {
lastStep = step;
broadcast("status", { running: true, step, label });
break;
}
}
});
child.stderr.on("data", data => {
const text = data.toString();
broadcast("output", { stream: "stderr", text, timestamp: Date.now() });
console.error(`[STDERR] ${text}`);
});
child.on("error", err => {
console.error(`[SPAWN ERROR] ${err.message}`);
broadcast("error", { message: `Spawn error: ${err.message}` });
});
child.on("close", code => {
currentProcess = null;
isRunning = false;
stopHeartbeat();
if (code === 0) {
emitConsole(`\n═══════════════════════════════════════\n`, "system");
emitConsole(` ✓ Pipeline 完成\n`, "system");
emitConsole(`═══════════════════════════════════════\n\n`, "system");
} else {
emitConsole(`\n═══════════════════════════════════════\n`, "system");
emitConsole(` ✗ Pipeline 结束 (exit=${code})\n`, "system");
emitConsole(`═══════════════════════════════════════\n\n`, "system");
}
broadcast("status", { running: false, exitCode: code, step: code === 0 ? "complete" : "failed" });
log(`流程结束 (exit=${code})`);
const projects = listPreviewProjects();
const target = projects.find(p => p.name.includes(config.pageName?.toLowerCase() || ""));
if (target) broadcast("files", { project: target.name, files: listGeneratedFiles(target.path) });
});
child.on("error", err => {
currentProcess = null;
isRunning = false;
stopHeartbeat();
broadcast("error", { message: err.message });
broadcast("status", { running: false, exitCode: -1, step: "error" });
});
}
function serveStatic(res, filePath, contentType) {
fs.readFile(filePath, (err, data) => {
if (err) { res.writeHead(404); res.end("Not Found"); return; }
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
});
}
const MIME = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "application/javascript", ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png" };
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://localhost:${PORT}`);
const p = url.pathname;
if (req.method === "GET" && p === "/api/stream") {
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
res.write("data: {\"type\":\"connected\"}\n\n");
clients.add(res);
req.on("close", () => clients.delete(res));
return;
}
if (req.method === "GET" && p === "/api/config") {
res.end(JSON.stringify({ defaults: DEFAULT_CONFIG, modelCandidates: MODEL_CANDIDATES, urlCandidates: URL_CANDIDATES }));
return;
}
if (req.method === "GET" && p === "/api/projects") {
res.end(JSON.stringify({ previewProjects: listPreviewProjects(), bundlePages: listBundlePages() }));
return;
}
if (req.method === "GET" && p === "/api/files") {
const name = url.searchParams.get("project");
if (!name) { res.writeHead(400); res.end("project required"); return; }
res.end(JSON.stringify({ project: name, files: listGeneratedFiles(path.join(repoRoot, PREVIEW_DIR, name)) }));
return;
}
if (req.method === "GET" && p === "/api/file") {
const fp = url.searchParams.get("path");
if (!fp) { res.writeHead(400); res.end("path required"); return; }
const full = path.resolve(path.join(repoRoot, PREVIEW_DIR, fp));
if (!full.startsWith(path.resolve(path.join(repoRoot, PREVIEW_DIR)))) { res.writeHead(403); res.end("forbidden"); return; }
try { res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" }); res.end(await fsp.readFile(full, "utf8")); }
catch { res.writeHead(404); res.end("not found"); }
return;
}
if (req.method === "GET" && p === "/api/status") {
res.end(JSON.stringify({ running: isRunning }));
return;
}
if (req.method === "POST" && p === "/api/generate") {
const config = await parseBody(req);
res.end(JSON.stringify({ ok: true }));
runPipeline(config);
return;
}
if (req.method === "POST" && p === "/api/stop") {
if (currentProcess) currentProcess.kill("SIGTERM");
res.end(JSON.stringify({ ok: true }));
return;
}
if (req.method === "GET" && p === "/api/preview-url") {
res.end(JSON.stringify({ previewUrl }));
return;
}
if (p.startsWith("/preview-proxy/")) {
if (!previewUrl) { res.writeHead(502); res.end("Preview not available yet"); return; }
const target = new URL(p.replace("/preview-proxy/", "") + url.search, previewUrl);
const proxyReq = http.request(target, { method: req.method, headers: { ...req.headers, host: target.host } }, proxyRes => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
});
proxyReq.on("error", () => { res.writeHead(502); res.end("Proxy error"); });
req.pipe(proxyReq);
return;
}
if (p === "/" || p === "/index.html") { serveStatic(res, path.join(__dirname, "ai-direct-server", "index.html"), "text/html; charset=utf-8"); return; }
const staticDir = path.join(__dirname, "ai-direct-server");
const sp = path.join(staticDir, p);
if (path.resolve(sp).startsWith(staticDir) && fs.existsSync(sp)) { serveStatic(res, sp, MIME[path.extname(sp)] || "application/octet-stream"); return; }
res.writeHead(404); res.end("Not Found");
});
server.on("upgrade", (req, socket, head) => {
if (req.url?.startsWith("/preview-proxy-ws/") && previewUrl) {
const targetUrl = new URL(previewUrl);
const wsPath = req.url.replace("/preview-proxy-ws/", "");
const proxySocket = net.connect(Number(targetUrl.port), targetUrl.hostname, () => {
proxySocket.write(`GET /${wsPath} HTTP/1.1\r\nHost: ${targetUrl.host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${req.headers["sec-websocket-key"]}\r\nSec-WebSocket-Version: ${req.headers["sec-websocket-version"]}\r\n\r\n`);
if (head.length > 0) proxySocket.write(head);
socket.pipe(proxySocket);
proxySocket.pipe(socket);
});
proxySocket.on("error", () => socket.destroy());
socket.on("error", () => proxySocket.destroy());
} else {
socket.destroy();
}
});
server.listen(PORT, () => { console.log(`\n[ai-direct-server] Venus AI Console → http://localhost:${PORT}\n`); });