Files

296 lines
9.5 KiB
JavaScript

import { createServer } from "node:http";
import { once } from "node:events";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { resolve, extname, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { MAX_BODY, normalizeRequest } from "./contract.mjs";
import {
SYSTEM_PROMPT,
analysisSchema,
normalizeMultimodal,
} from "../shared/requirements.mjs";
import { sseData } from "../shared/sse.mjs";
const dist = fileURLToPath(new URL("../dist/", import.meta.url));
const types = {
".html": "text/html; charset=utf-8",
".js": "text/javascript",
".css": "text/css",
".json": "application/json",
".png": "image/png",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".woff2": "font/woff2",
};
const json = (res, status, error) => {
res.writeHead(status, {
"Content-Type": "application/json",
"Cache-Control": "no-store",
});
res.end(JSON.stringify({ error }));
};
export function createApp({
apiKey,
model,
fetchImpl = fetch,
serveStatic = false,
}) {
let active = 0;
const rates = new Map();
return createServer(async (req, res) => {
res.setHeader("X-Content-Type-Options", "nosniff");
const url = new URL(req.url || "/", "http://localhost");
if (
/^\/(?:handoff|ai-rules)\//.test(url.pathname) ||
url.pathname === "/downloads/robot-demand-parser-v1.zip"
) {
json(res, 404, "未找到文件。");
return;
}
if (url.pathname === "/api/ai/responses") {
if (req.method !== "POST") {
json(res, 405, "仅支持 POST。");
return;
}
if (req.headers.origin) {
try {
if (new URL(req.headers.origin).host !== req.headers.host) {
json(res, 403, "不允许跨站调用。");
return;
}
} catch {
json(res, 403, "来源不合法。");
return;
}
}
if (!apiKey) {
json(res, 503, "需求整理服务暂不可用,请稍后重试。");
return;
}
if (!req.headers["content-type"]?.startsWith("application/json")) {
json(res, 415, "请发送 JSON。");
return;
}
const ip = req.socket.remoteAddress;
const now = Date.now();
for (const [key, value] of rates)
if (now - value.start > 60000) rates.delete(key);
const rate = rates.get(ip) || { start: now, count: 0 };
if (rate.count >= 20 || active >= 4) {
json(res, 429, "请求过于频繁,请稍后重试。");
return;
}
rate.count++;
rates.set(ip, rate);
if (Number(req.headers["content-length"]) > MAX_BODY) {
json(res, 413, "对话和图片总量超过 40 MiB,请减少图片或新建对话。");
return;
}
active++;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 180000);
const cancel = () => controller.abort();
req.once("aborted", cancel);
res.once("close", cancel);
try {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > MAX_BODY) {
json(res, 413, "对话和图片总量超过 40 MiB,请新建对话。");
return;
}
chunks.push(chunk);
}
let request;
try {
request = normalizeRequest(
JSON.parse(Buffer.concat(chunks).toString("utf8")),
);
} catch (error) {
json(
res,
400,
error instanceof SyntaxError ? "JSON 格式不正确。" : error.message,
);
return;
}
const upstream = await fetchImpl(
"https://ark.cn-beijing.volces.com/api/v3/responses",
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model,
stream: true,
store: false,
max_output_tokens: 16000,
thinking: { type: "enabled" },
text: {
format: {
type: "json_schema",
name: "robot_requirements",
strict: true,
schema: analysisSchema,
},
},
input: [
{
role: "system",
content: [{ type: "input_text", text: SYSTEM_PROMPT }],
},
...request.input,
],
}),
signal: controller.signal,
},
);
if (!upstream.ok) {
await upstream.body?.cancel();
const error =
upstream.status === 429
? "需求整理服务繁忙,请稍后重试。"
: "需求整理服务暂不可用,请稍后重试。";
json(res, 502, error);
return;
}
if (
!upstream.body ||
!upstream.headers.get("content-type")?.includes("text/event-stream")
)
throw new Error("INVALID_STREAM");
res.writeHead(200, {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
});
res.flushHeaders();
const send = async (event) => {
if (!res.write(`data: ${JSON.stringify(event)}\n\n`))
await once(res, "drain", { signal: controller.signal });
};
await send({
type: "analysis.progress",
message: "正在识别信息并整理需求…",
});
let output = "",
finished = false,
writing = false;
for await (const raw of sseData(upstream.body)) {
if (raw === "[DONE]") continue;
const event = JSON.parse(raw);
if (
["error", "response.failed", "response.incomplete"].includes(
event.type,
)
)
throw Error("INCOMPLETE");
if (event.type === "response.output_text.delta") {
output += event.delta || "";
if (output.length > 150000) throw Error("TOO_LONG");
if (!writing) {
writing = true;
await send({
type: "analysis.progress",
message: "正在整理需求清单…",
});
}
}
if (event.type !== "response.completed") continue;
if (event.response?.status !== "completed") throw Error("INCOMPLETE");
const final =
(event.response.output || [])
.filter((item) => item.type === "message")
.flatMap((item) => item.content || [])
.filter((item) => item.type === "output_text")
.map((item) => item.text)
.join("") || output;
if (!final || final.length > 150000) throw Error("INVALID_RESULT");
await send({
type: "analysis.progress",
message: "正在核对需求与冲突…",
});
const result = normalizeMultimodal(
JSON.parse(final),
request.messages,
);
// Only business results reach the browser, never provider events or rule definitions.
delete result.analysis.schemaVersion;
delete result.analysis.catalogVersion;
delete result.analysis.keywordEvidence;
await send({ type: "analysis.completed", result });
finished = true;
break;
}
if (!finished) throw Error("INCOMPLETE");
res.end();
} catch {
if (!res.destroyed) {
if (res.headersSent)
res.end(
'event: error\ndata: {"type":"error","message":"需求解析未完成、结果校验未通过或连接超时,请重试;未生成可提交的匹配数据。"}\n\n',
);
else
json(
res,
502,
controller.signal.aborted
? "AI 请求超时,请重试。"
: "需求整理服务暂不可用,请稍后重试。",
);
}
} finally {
clearTimeout(timeout);
req.off("aborted", cancel);
res.off("close", cancel);
active--;
}
return;
}
if (url.pathname.startsWith("/api/")) {
json(res, 404, "接口不存在。");
return;
}
if (!serveStatic || !["GET", "HEAD"].includes(req.method)) {
json(res, 404, "未找到页面。");
return;
}
try {
const file = resolve(
dist,
"." +
decodeURIComponent(
url.pathname === "/" ? "/index.html" : url.pathname,
),
);
if (!file.startsWith(dist.replace(/\/$/, "") + sep)) {
json(res, 403, "路径不合法。");
return;
}
const info = await stat(file);
if (!info.isFile()) {
json(res, 404, "未找到文件。");
return;
}
res.writeHead(200, {
"Content-Type": types[extname(file)] || "application/octet-stream",
"Content-Length": info.size,
"Cache-Control": url.pathname.startsWith("/assets/")
? "public, max-age=31536000, immutable"
: "no-cache",
});
if (req.method === "HEAD") res.end();
else
createReadStream(file)
.on("error", () => res.destroy())
.pipe(res);
} catch {
json(res, 404, "未找到文件。");
}
});
}