"use strict";
const http = require("node:http");
const fs = require("node:fs");
const path = require("node:path");
const crypto = require("node:crypto");
const net = require("node:net");
const tls = require("node:tls");
const os = require("node:os");
const { URL } = require("node:url");
const ROOT_DIR = path.resolve(__dirname, "..");
const CONFIG_DIR = path.join(ROOT_DIR, "config");
const manualAlertCache = new Map();
loadDotEnv(path.join(ROOT_DIR, ".env"));
const serverConfig = loadJson("server.json", {});
const port = Number(process.env.PDD_ASSISTANT_PORT || serverConfig.port || 3456);
const host = String(process.env.PDD_ASSISTANT_HOST || serverConfig.host || "127.0.0.1");
const dailyPauseTime = String(process.env.PDD_DAILY_PAUSE_TIME || serverConfig.dailyPauseTime || "07:50");
const controlStates = new Map();
const jsonHeaders = {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
"Access-Control-Allow-Headers": "Content-Type,Authorization,X-Control-Token,X-Shop-Id,X-Shop-Token"
};
const htmlHeaders = {
"Content-Type": "text/html; charset=utf-8",
"Access-Control-Allow-Origin": "*"
};
const server = http.createServer(async (req, res) => {
try {
if (req.method === "OPTIONS") {
res.writeHead(204, jsonHeaders);
res.end();
return;
}
const url = new URL(req.url, "http://127.0.0.1");
if (req.method === "GET" && url.pathname === "/health") {
sendJson(res, 200, { ok: true, time: new Date().toISOString() });
return;
}
if (req.method === "GET" && url.pathname === "/control") {
const auth = authorizeControlRequest(req, url);
if (!auth.ok) {
sendHtml(res, 401, renderControlAuthFailedPage(auth.reason));
return;
}
sendHtml(res, 200, renderControlPage(url));
return;
}
if (req.method === "GET" && url.pathname === "/api/control-state") {
const shopId = getRequestedShopId(req, url);
if (shopId) {
const auth = authorizeShopRequest(req, url);
if (!auth.ok) {
sendJson(res, auth.status || 401, { ok: false, error: auth.reason });
return;
}
sendJson(res, 200, getControlStatePayload(auth.shop));
return;
}
const auth = authorizeControlRequest(req, url);
if (!auth.ok) {
sendJson(res, 401, { ok: false, error: auth.reason });
return;
}
sendJson(res, 200, getAllControlStatesPayload());
return;
}
if (req.method === "POST" && url.pathname === "/api/control-state") {
const payload = await readJsonBody(req);
const auth = authorizeControlOrShopRequest(req, url, payload);
if (!auth.ok) {
sendJson(res, auth.status || 401, { ok: false, error: auth.reason });
return;
}
if (typeof payload.paused !== "boolean") {
sendJson(res, 400, { ok: false, error: "paused 必须是 boolean" });
return;
}
const state = getShopControlState(auth.shop);
state.paused = payload.paused;
state.updatedAt = new Date().toISOString();
state.updatedBy = normalizeControlSource(payload.source || payload.updatedBy || "remote");
sendJson(res, 200, getControlStatePayload(auth.shop));
return;
}
if (req.method === "GET" && url.pathname === "/debug/config") {
const config = loadJson("server.json", {});
sendJson(res, 200, {
apiUrl: process.env.CODEX_API_URL || config.codexApiUrl || "",
hasApiKey: Boolean(process.env.CODEX_API_KEY || config.codexApiKey || process.env.ZZZ_API_KEY || process.env.OPENAI_API_KEY),
model: process.env.CODEX_MODEL || config.codexModel || "",
classifierModel: process.env.CODEX_CLASSIFIER_MODEL || config.classifierModel || process.env.CODEX_MODEL || config.codexModel || "",
apiMode: process.env.CODEX_API_MODE || config.apiMode || "responses",
proxyUrl: maskProxyUrl(getProxyUrl(config)),
mockWhenNoApiKey: config.mockWhenNoApiKey !== false,
shops: loadShops().map((shop) => ({ id: shop.id, name: shop.name })),
port
});
return;
}
if (req.method === "GET" && url.pathname === "/api/products") {
const products = loadJson("products.json", []);
sendJson(res, 200, {
products: products.map((item) => ({
id: item.id,
name: item.name,
aliases: item.aliases || []
}))
});
return;
}
if (req.method === "POST" && url.pathname === "/api/reply") {
const payload = await readJsonBody(req);
const auth = authorizeShopRequest(req, url, payload);
if (!auth.ok) {
sendJson(res, auth.status || 401, { ok: false, error: auth.reason });
return;
}
const result = await withMinimumDelay(() => handleReply({
...payload,
shopId: auth.shop.id,
shopName: auth.shop.name
}), getMinReplyDelayMs());
sendJson(res, 200, result);
return;
}
sendJson(res, 404, { error: "Not found" });
} catch (error) {
sendJson(res, 500, { error: error.message || "Internal server error" });
}
});
server.listen(port, host, () => {
const localUrl = `http://127.0.0.1:${port}`;
console.log(`[PDD Assistant] Local server listening on ${localUrl}`);
if (host === "0.0.0.0" || host === "::") {
for (const url of getLanUrls(port)) {
console.log(`[PDD Assistant] LAN control page: ${url}/control`);
}
} else {
console.log(`[PDD Assistant] Bound host: ${host}`);
}
scheduleDailyPauseAllShops();
});
function sendJson(res, status, data) {
res.writeHead(status, jsonHeaders);
res.end(JSON.stringify(data));
}
function sendHtml(res, status, html) {
res.writeHead(status, htmlHeaders);
res.end(html);
}
function getControlStatePayload(shop) {
const state = getShopControlState(shop);
return {
ok: true,
shopId: shop.id,
shopName: shop.name,
paused: state.paused,
updatedAt: state.updatedAt,
updatedBy: state.updatedBy,
tokenRequired: Boolean(getControlToken()),
serverTime: new Date().toISOString()
};
}
function getAllControlStatesPayload() {
return {
ok: true,
shops: loadShops().map((shop) => getControlStatePayload(shop)),
tokenRequired: Boolean(getControlToken()),
serverTime: new Date().toISOString()
};
}
function getShopControlState(shop) {
if (!controlStates.has(shop.id)) {
controlStates.set(shop.id, {
paused: false,
updatedAt: new Date().toISOString(),
updatedBy: "server-start"
});
}
return controlStates.get(shop.id);
}
function pauseAllShops(source = "daily-auto-pause") {
const now = new Date().toISOString();
for (const shop of loadShops()) {
const state = getShopControlState(shop);
state.paused = true;
state.updatedAt = now;
state.updatedBy = source;
}
console.log(`[PDD Assistant] ${source}: paused all shops at ${now}`);
}
function scheduleDailyPauseAllShops() {
const nextAt = getNextDailyTime(dailyPauseTime);
if (!nextAt) {
console.warn(`[PDD Assistant] invalid dailyPauseTime: ${dailyPauseTime}`);
return;
}
const delay = Math.max(1000, nextAt.getTime() - Date.now());
console.log(`[PDD Assistant] daily auto pause scheduled at ${formatLocalDateTime(nextAt)} (${dailyPauseTime})`);
setTimeout(() => {
pauseAllShops("daily-auto-pause");
scheduleDailyPauseAllShops();
}, delay);
}
function getNextDailyTime(value) {
const match = String(value || "").trim().match(/^(\d{1,2}):(\d{2})$/);
if (!match) return null;
const hour = Number(match[1]);
const minute = Number(match[2]);
if (hour < 0 || hour > 23 || minute < 0 || minute > 59) return null;
const next = new Date();
next.setHours(hour, minute, 0, 0);
if (next.getTime() <= Date.now()) {
next.setDate(next.getDate() + 1);
}
return next;
}
function formatLocalDateTime(date) {
const pad = (value) => String(value).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}
function loadShops() {
const raw = loadJson("shops.json", []);
const shops = (Array.isArray(raw) ? raw : [])
.map((item, index) => normalizeShop(item, index))
.filter(Boolean);
if (shops.length) return shops;
return [normalizeShop({ id: "default", name: "默认店铺", pluginToken: "" }, 0)];
}
function normalizeShop(item, index) {
if (!item || typeof item !== "object") return null;
const id = String(item.id || item.shopId || "").trim();
if (!id) return null;
return {
...item,
id,
name: String(item.name || item.shopName || `店铺${index + 1}`).trim(),
pluginToken: String(item.pluginToken || item.token || "").trim()
};
}
function getRequestedShopId(req, url, payload = {}) {
return String(
payload.shopId ||
url.searchParams.get("shopId") ||
req.headers["x-shop-id"] ||
""
).trim();
}
function getRequestedShopToken(req, url, payload = {}) {
const auth = String(req.headers.authorization || "").trim();
const bearer = auth.toLowerCase().startsWith("bearer ") ? auth.slice(7).trim() : "";
return String(
payload.shopToken ||
payload.pluginToken ||
req.headers["x-shop-token"] ||
bearer ||
url.searchParams.get("shopToken") ||
""
).trim();
}
function findShop(shopId) {
const shops = loadShops();
if (shopId) return shops.find((shop) => shop.id === shopId) || null;
if (shops.length === 1) return shops[0];
return null;
}
function authorizeShopRequest(req, url, payload = {}) {
const shopId = getRequestedShopId(req, url, payload);
const shop = findShop(shopId);
if (!shop) {
return {
ok: false,
status: 401,
reason: shopId ? `未知店铺:${shopId}` : "请先配置店铺ID"
};
}
if (!shop.pluginToken) return { ok: true, shop };
const token = getRequestedShopToken(req, url, payload);
if (safeTokenEqual(token, shop.pluginToken)) return { ok: true, shop };
return { ok: false, status: 401, reason: "店铺Token不正确或缺失" };
}
function authorizeControlOrShopRequest(req, url, payload = {}) {
const controlAuth = authorizeControlRequest(req, url, payload);
if (controlAuth.ok) {
const shop = findShop(getRequestedShopId(req, url, payload));
if (!shop) {
return { ok: false, status: 400, reason: "请提供有效店铺ID" };
}
return { ok: true, shop };
}
return authorizeShopRequest(req, url, payload);
}
function authorizeControlRequest(req, url, payload = {}) {
const token = getControlToken();
if (!token) return { ok: true };
const provided = String(
url.searchParams.get("token") ||
req.headers["x-control-token"] ||
payload.token ||
""
).trim();
if (safeTokenEqual(provided, token)) return { ok: true };
return { ok: false, reason: "控制密码不正确或缺失" };
}
function getControlToken() {
const config = loadJson("server.json", {});
return String(process.env.PDD_CONTROL_TOKEN || config.controlToken || "").trim();
}
function safeTokenEqual(a, b) {
try {
const left = Buffer.from(String(a));
const right = Buffer.from(String(b));
return left.length === right.length && crypto.timingSafeEqual(left, right);
} catch (_) {
return false;
}
}
function isLoopbackAddress(address) {
return address === "::1" || address === "127.0.0.1" || address.startsWith("127.") || address.startsWith("::ffff:127.");
}
function normalizeControlSource(value) {
return String(value || "remote")
.replace(/[^\w.\-\u4e00-\u9fa5]/g, "")
.slice(0, 40) || "remote";
}
function renderControlAuthFailedPage(reason) {
return `
PDD客服助手控制台
无法打开控制台
${escapeHtml(reason)}
如果配置了 controlToken,请用 /control?token=你的密码 访问。
`;
}
function renderControlPage(url) {
const token = url.searchParams.get("token") || "";
return `
PDD客服助手控制台
`;
}
function escapeHtml(value) {
return String(value || "")
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function getLanUrls(port) {
const urls = [];
const interfaces = os.networkInterfaces();
for (const list of Object.values(interfaces)) {
for (const item of list || []) {
if (item.family !== "IPv4" || item.internal) continue;
urls.push(`http://${item.address}:${port}`);
}
}
return urls;
}
async function withMinimumDelay(task, minDelayMs) {
const started = Date.now();
const result = await task();
const remaining = minDelayMs - (Date.now() - started);
if (remaining > 0) await sleep(remaining);
return result;
}
function getMinReplyDelayMs() {
const config = loadJson("server.json", {});
return Math.max(0, Number(process.env.PDD_MIN_REPLY_DELAY_MS || config.minReplyDelayMs || 3000));
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function loadDotEnv(filePath) {
if (!fs.existsSync(filePath)) return;
const content = fs.readFileSync(filePath, "utf8");
for (const line of content.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const equalsIndex = trimmed.indexOf("=");
if (equalsIndex <= 0) continue;
const key = trimmed.slice(0, equalsIndex).trim();
let value = trimmed.slice(equalsIndex + 1).trim();
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
if (!process.env[key]) process.env[key] = value;
}
}
function loadJson(fileName, fallback) {
const filePath = path.join(CONFIG_DIR, fileName);
try {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
} catch (error) {
if (error.code === "ENOENT") return fallback;
throw new Error(`读取配置失败 ${fileName}: ${error.message}`);
}
}
function loadText(fileName, fallback = "") {
const filePath = path.join(CONFIG_DIR, fileName);
try {
return fs.readFileSync(filePath, "utf8");
} catch (error) {
if (error.code === "ENOENT") return fallback;
throw new Error(`读取配置失败 ${fileName}: ${error.message}`);
}
}
function readJsonBody(req) {
return new Promise((resolve, reject) => {
let body = "";
req.on("data", (chunk) => {
body += chunk;
if (body.length > 1024 * 1024) {
reject(new Error("请求体过大"));
req.destroy();
}
});
req.on("end", () => {
try {
resolve(body ? JSON.parse(body) : {});
} catch (error) {
reject(new Error(`JSON格式错误: ${error.message}`));
}
});
req.on("error", reject);
});
}
async function handleReply(payload) {
validatePayload(payload);
const requestId = crypto.randomUUID();
const shopId = String(payload.shopId || "default");
const shopName = String(payload.shopName || shopId);
const shop = findShop(shopId) || { id: shopId, name: shopName };
const config = loadJson("server.json", {});
const products = loadJson("products.json", []);
const faq = loadJson("faq.json", []);
const quickReplies = loadJson("quick-replies.json", []);
const toneExamples = loadJson("tone-examples.json", []);
const manualHandoffConfig = loadJson("manual-handoff-whitelist.json", []);
const riskConfig = loadJson("risk-intents.json", []);
const mailConfig = loadJson("mail.json", {});
const systemPrompt = loadText("system-prompt.md", "");
const replyGuidelines = loadText("reply-guidelines.md", "");
const messages = normalizeMessages(payload.msgList || payload["对话列表"] || []);
const payloadPid = normalizePid(payload.pid ?? payload["商品id"] ?? 0);
const messageProductReference = extractProductReferenceFromMessages(messages);
const pid = payloadPid && payloadPid !== 0 ? payloadPid : messageProductReference || 0;
const product = findProductByPid(pid, products);
const productCandidates = rankProductCandidates(pid, products).slice(0, Number(config.maxProductCandidates || 3));
const latestCustomerMessage = [...messages].reverse().find((item) => item.usertype === "cus")?.msg || "";
const quickReply = matchQuickReply(latestCustomerMessage, quickReplies);
if (quickReply) {
return {
requestId,
action: "reply",
manualRequired: false,
reply: quickReply.reply,
shopId,
shopName,
pid,
riskIntents: [],
source: "quick-reply",
quickReply: quickReply.name
};
}
const riskIntents = detectRiskIntents(latestCustomerMessage, riskConfig);
if (riskIntents.length) {
const email = await sendManualAlert({
requestId,
mailConfig,
riskIntents,
product,
pid,
messages
});
return {
requestId,
action: "manual",
manualRequired: true,
reply: "",
shopId,
shopName,
pid,
riskIntents: riskIntents.map((item) => item.name),
email,
source: "risk-manual-alert"
};
}
const manualHandoffDecision = await detectManualHandoff({
requestId,
config,
pid,
product,
productCandidates,
messages,
latestCustomerMessage,
manualHandoffConfig
});
if (manualHandoffDecision.manualRequired) {
const handoffIntents = manualHandoffDecision.matches.map((name) => ({
name,
keywords: [],
reason: manualHandoffDecision.reason
}));
const email = await sendManualAlert({
requestId,
mailConfig,
riskIntents: handoffIntents,
product,
pid,
messages
});
return {
requestId,
action: "manual",
manualRequired: true,
reply: "",
shopId,
shopName,
pid,
riskIntents: manualHandoffDecision.matches,
manualHandoff: manualHandoffDecision,
email,
source: manualHandoffDecision.source
};
}
const contextMsgList = messages.map((item) => ({
usertype: item.usertype,
msg: item.msg
}));
const conversationSearchText = [String(pid || ""), ...messages.map((item) => item.msg)].join("\n");
const selectedFaq = rankFaq(conversationSearchText, faq, pid).slice(0, Number(config.maxFaqItems || 5)).map(compactFaqItem);
const selectedToneExamples = rankToneExamples(conversationSearchText, toneExamples)
.slice(0, Number(config.maxToneExamples || 3));
const modelContext = {
payload: { msgList: contextMsgList },
shop: { id: shopId, name: shopName },
productReference: pid,
productSearchText: buildProductSearchText(pid, product, productCandidates),
product: compactProduct(product),
productCandidates: productCandidates.map(compactProduct),
faq: selectedFaq,
toneExamplesText: formatToneExamplesAsQaText(selectedToneExamples),
replyGuidelines: compactText(replyGuidelines, Number(config.maxReplyGuidelinesChars || 1200)),
riskIntentNames: riskConfig.map((item) => item.name).filter(Boolean)
};
logModelContextStats(requestId, modelContext);
const cozeReply = await maybeCallCoze({
requestId,
config,
shop,
context: modelContext,
latestCustomerMessage
});
if (cozeReply) {
return {
requestId,
action: "reply",
manualRequired: false,
reply: cozeReply,
shopId,
shopName,
pid,
riskIntents: [],
source: "coze"
};
}
const modelReply = await maybeCallModel({
requestId,
config,
systemPrompt,
context: modelContext
});
if (modelReply) {
return {
requestId,
action: "reply",
manualRequired: false,
reply: modelReply,
shopId,
shopName,
pid,
riskIntents: [],
source: "model"
};
}
return {
requestId,
action: "reply",
manualRequired: false,
reply: buildFallbackReply({
latestCustomerMessage,
product,
productReference: pid,
faq: modelContext.faq
}),
shopId,
shopName,
pid,
riskIntents: [],
source: "local-fallback"
};
}
function validatePayload(payload) {
if (!payload || typeof payload !== "object") {
throw new Error("请求体必须是对象");
}
if (!Array.isArray(payload.msgList) && !Array.isArray(payload["对话列表"])) {
throw new Error("缺少字段:msgList");
}
}
function normalizeMessages(messages) {
return messages
.filter((item) => item && (item.usertype === "cus" || item.usertype === "sys"))
.map((item) => ({
usertype: item.usertype,
msg: String(item.msg ?? item.mes ?? "").trim()
}))
.filter((item) => item.msg)
.slice(-6);
}
function extractProductReferenceFromMessages(messages) {
const productMessage = (Array.isArray(messages) ? messages : [])
.find((item) => item?.usertype === "cus" && /^这款.+/.test(String(item.msg || "").trim()));
if (!productMessage) return "";
return String(productMessage.msg || "")
.replace(/^这款/, "")
.replace(/^(.+?)的(.+)$/, "$1 $2")
.trim();
}
function detectRiskIntents(text, riskConfig) {
const normalized = normalizeForMatch(text);
if (!normalized) return [];
return riskConfig.filter((item) => {
const keywords = Array.isArray(item.keywords) ? item.keywords : [];
return keywords.some((keyword) => normalized.includes(normalizeForMatch(keyword)));
});
}
function matchQuickReply(text, quickReplies) {
const normalized = normalizeForQuickReply(text);
if (!normalized) return null;
for (const rule of Array.isArray(quickReplies) ? quickReplies : []) {
const keywords = Array.isArray(rule.keywords) ? rule.keywords : [];
const matchMode = rule.match || "exact";
const matched = keywords.some((keyword) => {
const normalizedKeyword = normalizeForQuickReply(keyword);
if (!normalizedKeyword) return false;
if (matchMode === "includes") return normalized.includes(normalizedKeyword);
return normalized === normalizedKeyword;
});
if (matched) {
return {
name: rule.name || "quick-reply",
reply: String(rule.reply || "")
};
}
}
return null;
}
function normalizeForQuickReply(value) {
return String(value || "")
.replace(/[。!?!?,,.~~\s]/g, "")
.toLowerCase()
.trim();
}
function normalizeText(value) {
return String(value || "")
.replace(/\r\n?/g, "\n")
.replace(/\u00a0/g, " ")
.replace(/[ \t]+/g, " ")
.replace(/\n{3,}/g, "\n\n")
.trim();
}
async function detectManualHandoff({
requestId,
config,
pid,
product,
productCandidates,
messages,
latestCustomerMessage,
manualHandoffConfig
}) {
const rules = normalizeManualHandoffRules(manualHandoffConfig);
if (!rules.length) {
return { manualRequired: false, matches: [], reason: "", source: "manual-handoff-disabled" };
}
const localDecision = analyzeManualHandoffLocally(messages, rules);
if (localDecision.manualRequired || localDecision.skipClassifier) {
return localDecision;
}
const classifierMode = config.manualHandoffClassifierMode || "ambiguous";
if (classifierMode === "off") {
return { manualRequired: false, matches: [], reason: "分类模型已关闭", source: "manual-handoff-classifier-off" };
}
if (classifierMode !== "always" && !localDecision.needsClassifier) {
return { manualRequired: false, matches: [], reason: "无人工接手信号", source: "manual-handoff-local-no-match" };
}
const modelDecision = await maybeCallManualHandoffClassifier({
requestId,
config,
pid,
product,
productCandidates,
messages,
latestCustomerMessage,
rules
});
if (modelDecision) {
if (modelDecision.manualRequired && !localDecision.needsClassifier && classifierMode === "always") {
return {
manualRequired: false,
matches: [],
reason: "模型命中但无本地人工接手信号,已过滤",
source: "manual-handoff-model-filtered"
};
}
return modelDecision;
}
const fallbackMatches = detectManualHandoffByKeywords(messages, rules);
if (fallbackMatches.length) {
return {
manualRequired: true,
matches: fallbackMatches,
reason: "模型分类失败,关键词兜底命中",
source: "manual-handoff-keyword-fallback"
};
}
return { manualRequired: false, matches: [], reason: "", source: "manual-handoff-no-match" };
}
function analyzeManualHandoffLocally(messages, rules) {
const recentCustomerText = getRecentCustomerText(messages);
const normalized = normalizeForMatch(recentCustomerText);
if (!normalized) {
return { manualRequired: false, matches: [], reason: "", source: "manual-handoff-empty", skipClassifier: true };
}
const excludedRules = rules.filter((rule) => rule.excludeKeywords.some((keyword) => normalized.includes(normalizeForMatch(keyword))));
if (excludedRules.length) {
return {
manualRequired: false,
matches: [],
reason: `命中排除词:${excludedRules.map((rule) => rule.name).join("、")}`,
source: "manual-handoff-local-excluded",
skipClassifier: true
};
}
const keywordMatches = rules
.filter((rule) => rule.keywords.some((keyword) => isManualKeywordHit(keyword, normalized)))
.map((rule) => rule.name);
if (keywordMatches.length) {
return {
manualRequired: true,
matches: keywordMatches,
reason: "本地关键词命中",
source: "manual-handoff-keyword"
};
}
return {
manualRequired: false,
matches: [],
reason: "",
source: "manual-handoff-local-ambiguous",
needsClassifier: hasManualHandoffSignal(normalized)
};
}
function getRecentCustomerText(messages) {
return messages
.filter((item) => item.usertype === "cus")
.slice(-5)
.map((item) => item.msg)
.join("\n");
}
function hasManualHandoffSignal(normalizedText) {
const signals = [
"不要了",
"不想要",
"寄回",
"换一个",
"换货",
"赔偿",
"补偿",
"怎么处理",
"处理一下",
"帮我处理",
"给个说法",
"收到有问题",
"到货有问题",
"联系人工",
"人工客服"
];
return signals.some((signal) => normalizedText.includes(normalizeForMatch(signal)));
}
function isManualKeywordHit(keyword, normalizedText) {
const normalizedKeyword = normalizeForMatch(keyword);
if (!isUsableManualKeyword(normalizedKeyword)) return false;
return normalizedText.includes(normalizedKeyword);
}
function isUsableManualKeyword(normalizedKeyword) {
if (!normalizedKeyword) return false;
if (normalizedKeyword.length < 2) return false;
if (!/[\u4e00-\u9fa5A-Za-z0-9]/.test(normalizedKeyword)) return false;
const weakKeywords = new Set(["问题", "处理", "人工", "客服", "配件", "竿稍", "质量", "发货"]);
return !weakKeywords.has(normalizedKeyword);
}
function normalizeManualHandoffRules(config) {
const list = Array.isArray(config) ? config : [];
return list
.map((item, index) => {
if (typeof item === "string") {
return {
name: item,
semantics: item,
keywords: [item],
examples: []
};
}
if (!item || typeof item !== "object") return null;
const name = String(item.name || item.scene || `人工接手规则${index + 1}`).trim();
const keywords = Array.isArray(item.keywords) ? item.keywords.map(String).filter(Boolean) : [];
const examples = Array.isArray(item.examples) ? item.examples.map(String).filter(Boolean) : [];
const excludeKeywords = Array.isArray(item.excludeKeywords) ? item.excludeKeywords.map(String).filter(Boolean) : [];
const negativeExamples = Array.isArray(item.negativeExamples) ? item.negativeExamples.map(String).filter(Boolean) : [];
return {
name,
semantics: String(item.semantics || item.description || name).trim(),
keywords,
examples,
excludeKeywords,
negativeExamples
};
})
.filter((item) => item && item.name);
}
function detectManualHandoffByKeywords(messages, rules) {
const recentCustomerText = getRecentCustomerText(messages);
const normalized = normalizeForMatch(recentCustomerText);
if (!normalized) return [];
return rules
.filter((rule) => {
const excluded = rule.excludeKeywords.some((keyword) => normalized.includes(normalizeForMatch(keyword)));
if (excluded) return false;
return rule.keywords.some((keyword) => isManualKeywordHit(keyword, normalized));
})
.map((rule) => rule.name);
}
async function maybeCallManualHandoffClassifier({
requestId,
config,
pid,
product,
productCandidates,
messages,
latestCustomerMessage,
rules
}) {
const apiUrl = process.env.CODEX_API_URL || config.codexApiUrl;
const apiKey = process.env.CODEX_API_KEY || config.codexApiKey || process.env.ZZZ_API_KEY || process.env.OPENAI_API_KEY;
const model = process.env.CODEX_CLASSIFIER_MODEL || config.classifierModel || process.env.CODEX_MODEL || config.codexModel;
const mockWhenNoApiKey = config.mockWhenNoApiKey !== false;
if (!apiUrl || !model || (!apiKey && mockWhenNoApiKey)) {
return null;
}
const apiMode = process.env.CODEX_API_MODE || config.apiMode || "responses";
const { body, parser } = buildManualHandoffModelRequest({
apiMode,
model,
requestId,
pid,
product,
productCandidates,
messages,
latestCustomerMessage,
rules
});
const headers = { "Content-Type": "application/json" };
if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), Number(config.modelTimeoutMs || 45000));
try {
const response = await postJson(apiUrl, {
headers,
body,
timeoutMs: Number(config.modelTimeoutMs || 45000),
proxyUrl: getProxyUrl(config),
signal: controller.signal
});
if (response.status < 200 || response.status >= 300) {
console.error("[PDD Assistant] manual handoff classifier failed", response.status, response.data);
return null;
}
return parseManualHandoffDecision(parser(response.data), rules, messages);
} catch (error) {
console.error("[PDD Assistant] manual handoff classifier error", formatModelError(error));
return null;
} finally {
clearTimeout(timeout);
}
}
function buildManualHandoffModelRequest({
apiMode,
model,
requestId,
pid,
product,
productCandidates,
messages,
latestCustomerMessage,
rules
}) {
const systemContent = [
"你是客服会话人工接手分类器。",
"请根据完整上下文判断买家语义是否命中人工接手白名单。",
"命中包括直接关键词、同义表达、委婉表达和上下文含义,不要只做字面匹配。",
"只有买家明确表达需要人工处理、售后处理、退款退货、已购买后的损坏问题、物流异常时才判定命中。",
"售前咨询不要判定命中。例如询问是否赠送配件、是否带备用竿稍、商品规格型号、是否结实耐用、发货时效、优惠价格,都不是人工接手。",
"如果语义更像普通售前咨询,即使提到配件、竿稍、质量、发货,也必须返回 manualRequired=false。",
"每条规则的 negativeExamples 和 excludeKeywords 是反例或排除词,命中这些表达时倾向 false。",
"只输出JSON,不要输出解释文本。",
"JSON格式:{\"manualRequired\":true或false,\"matches\":[\"规则名\"],\"reason\":\"不超过30字\"}"
].join("\n");
const userContent = JSON.stringify({
requestId,
pid,
product: compactProduct(product),
productCandidates: productCandidates.map(compactProduct),
latestCustomerMessage,
msgList: messages,
manualHandoffWhitelist: rules
}, null, 2);
if (apiMode === "chat") {
return {
body: {
model,
messages: [
{ role: "system", content: systemContent },
{ role: "user", content: userContent }
]
},
parser: parseChatResponse
};
}
if (apiMode === "custom") {
return {
body: {
model,
systemPrompt: systemContent,
context: JSON.parse(userContent),
instruction: "判断是否需要人工接手,只输出JSON。"
},
parser: parseLooseResponse
};
}
return {
body: {
model,
input: [
{ role: "system", content: systemContent },
{ role: "user", content: userContent }
]
},
parser: parseResponsesResponse
};
}
function parseManualHandoffDecision(text, rules, messages) {
const parsed = parseJsonFromText(text);
if (!parsed || typeof parsed !== "object") return null;
const recentCustomerText = messages
.filter((item) => item.usertype === "cus")
.slice(-5)
.map((item) => item.msg)
.join("\n");
const normalizedRecentText = normalizeForMatch(recentCustomerText);
const ruleNames = new Set(rules.map((rule) => rule.name));
const matches = Array.isArray(parsed.matches)
? parsed.matches.map(String).filter((name) => ruleNames.has(name))
.filter((name) => {
const rule = rules.find((item) => item.name === name);
if (!rule) return false;
return !rule.excludeKeywords.some((keyword) => normalizedRecentText.includes(normalizeForMatch(keyword)));
})
: [];
const hasLocalSignal = hasManualHandoffSignal(normalizedRecentText) || matches.some((name) => {
const rule = rules.find((item) => item.name === name);
return rule ? rule.keywords.some((keyword) => isManualKeywordHit(keyword, normalizedRecentText)) : false;
});
const manualRequired = Boolean(parsed.manualRequired) && matches.length > 0 && hasLocalSignal;
return {
manualRequired,
matches: manualRequired ? matches : [],
reason: manualRequired ? String(parsed.reason || "").slice(0, 80) : "模型命中但缺少本地信号,已过滤",
source: manualRequired ? "manual-handoff-model" : "manual-handoff-model-filtered"
};
}
function parseJsonFromText(text) {
const raw = String(text || "").trim();
if (!raw) return null;
try {
return JSON.parse(raw);
} catch (_) {
const start = raw.indexOf("{");
const end = raw.lastIndexOf("}");
if (start === -1 || end === -1 || end <= start) return null;
try {
return JSON.parse(raw.slice(start, end + 1));
} catch (error) {
return null;
}
}
}
async function sendManualAlert({ requestId, mailConfig, riskIntents, product, pid, messages }) {
if (!mailConfig || mailConfig.enabled !== true) {
return { sent: false, reason: "mail-disabled" };
}
const fingerprint = buildManualAlertFingerprint({ riskIntents, pid, messages });
const dedupMs = Number(mailConfig.dedupMs || 10 * 60 * 1000);
const cachedAt = manualAlertCache.get(fingerprint);
if (cachedAt && Date.now() - cachedAt < dedupMs) {
return { sent: false, deduped: true, reason: "duplicate-risk-alert" };
}
const riskNames = riskIntents.map((item) => item.name).join("、");
const latestCustomerMessage = [...messages].reverse().find((item) => item.usertype === "cus")?.msg || "";
const subject = `${mailConfig.subjectPrefix || "[PDD客服高危会话]"} ${riskNames}`;
const text = [
"检测到需要人工介入的拼多多客服会话,插件不会自动回复该买家。",
"",
`请求ID:${requestId}`,
`命中意图:${riskNames}`,
`商品信息:${pid || 0}`,
`匹配商品:${product?.name || "未匹配"}`,
`客户最新消息:${latestCustomerMessage || "无"}`,
"",
"完整对话:",
...messages.map((item, index) => `${index + 1}. ${item.usertype === "cus" ? "客户" : "客服"}:${item.msg}`)
].join("\n");
try {
await sendSmtpMail(mailConfig, { subject, text });
manualAlertCache.set(fingerprint, Date.now());
return { sent: true, deduped: false };
} catch (error) {
console.error("[PDD Assistant] manual alert email failed", error);
return { sent: false, reason: "send-failed", error: error.message };
}
}
function buildManualAlertFingerprint({ riskIntents, pid, messages }) {
const latest = messages.slice(-6).map((item) => `${item.usertype}:${item.msg}`).join("\n");
const riskNames = riskIntents.map((item) => item.name).join(",");
return crypto.createHash("sha256").update(`${pid}|${riskNames}|${latest}`).digest("hex");
}
async function sendSmtpMail(config, mail) {
const host = config.host;
const port = Number(config.port || (config.secure ? 465 : 587));
const secure = config.secure === true;
const user = config.user;
const password = getMailPassword(config);
const from = config.from || user;
const to = normalizeAddressList(config.to);
const cc = normalizeAddressList(config.cc);
const recipients = [...to, ...cc];
if (!host || !port || !from || recipients.length === 0) {
throw new Error("邮件配置不完整:host/port/from/to 必填");
}
if (user && !password) {
throw new Error(`邮件授权码为空,请配置环境变量 ${config.authCodeEnv || "PDD_MAIL_AUTH_CODE"} 或 mail.json authCode`);
}
let socket = secure
? tls.connect({ host, port, servername: host, rejectUnauthorized: config.rejectUnauthorized !== false })
: net.connect({ host, port });
let conn = new SmtpConnection(socket);
await conn.ready();
await expectSmtp(conn.readResponse(), [220], "connect");
await smtpCommand(conn, `EHLO ${mailDomain(config)}`, [250]);
if (!secure && config.startTls !== false) {
await smtpCommand(conn, "STARTTLS", [220]);
socket = tls.connect({ socket, servername: host, rejectUnauthorized: config.rejectUnauthorized !== false });
conn = new SmtpConnection(socket);
await conn.ready();
await smtpCommand(conn, `EHLO ${mailDomain(config)}`, [250]);
}
if (user) {
await smtpCommand(conn, "AUTH LOGIN", [334]);
await smtpCommand(conn, Buffer.from(user, "utf8").toString("base64"), [334]);
await smtpCommand(conn, Buffer.from(password, "utf8").toString("base64"), [235]);
}
await smtpCommand(conn, `MAIL FROM:<${extractEmail(from)}>`, [250]);
for (const recipient of recipients) {
await smtpCommand(conn, `RCPT TO:<${extractEmail(recipient)}>`, [250, 251]);
}
await smtpCommand(conn, "DATA", [354]);
conn.write(composeEmail(config, mail, from, to, cc));
await expectSmtp(conn.readResponse(), [250], "DATA body");
await smtpCommand(conn, "QUIT", [221]);
conn.close();
}
function getMailPassword(config) {
if (config.authCodeEnv && process.env[config.authCodeEnv]) return process.env[config.authCodeEnv];
return config.authCode || config.password || process.env.PDD_MAIL_AUTH_CODE || "";
}
function normalizeAddressList(value) {
if (!value) return [];
if (Array.isArray(value)) return value.filter(Boolean).map(String);
return String(value).split(",").map((item) => item.trim()).filter(Boolean);
}
function mailDomain(config) {
return config.heloDomain || os.hostname() || "localhost";
}
function extractEmail(value) {
const match = String(value || "").match(/<([^>]+)>/);
return (match ? match[1] : value).trim();
}
function composeEmail(config, mail, from, to, cc) {
const headers = [
`From: ${formatAddress(from, config.senderName)}`,
`To: ${to.map((item) => formatAddress(item)).join(", ")}`,
cc.length ? `Cc: ${cc.map((item) => formatAddress(item)).join(", ")}` : "",
`Subject: ${mimeHeader(mail.subject)}`,
`Date: ${new Date().toUTCString()}`,
"MIME-Version: 1.0",
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: base64"
].filter(Boolean);
return `${headers.join("\r\n")}\r\n\r\n${wrapBase64(Buffer.from(mail.text, "utf8").toString("base64"))}\r\n.\r\n`;
}
function formatAddress(address, displayName) {
const email = extractEmail(address);
if (!displayName) return email;
return `${mimeHeader(displayName)} <${email}>`;
}
function mimeHeader(value) {
return `=?UTF-8?B?${Buffer.from(String(value || ""), "utf8").toString("base64")}?=`;
}
function wrapBase64(value) {
return String(value).match(/.{1,76}/g)?.join("\r\n") || "";
}
async function smtpCommand(conn, command, allowedCodes) {
conn.write(`${command}\r\n`);
return expectSmtp(conn.readResponse(), allowedCodes, command);
}
async function expectSmtp(responsePromise, allowedCodes, action) {
const response = await responsePromise;
if (!allowedCodes.includes(response.code)) {
throw new Error(`SMTP ${action} 失败:${response.lines.join(" | ")}`);
}
return response;
}
class SmtpConnection {
constructor(socket) {
this.socket = socket;
this.buffer = "";
this.lines = [];
this.waiter = null;
this.socket.setEncoding("utf8");
this.socket.on("data", (chunk) => {
this.buffer += chunk;
this.flush();
});
this.socket.on("error", (error) => {
if (this.waiter) {
this.waiter.reject(error);
this.waiter = null;
}
});
}
ready() {
if (this.socket.readyState === "open") return Promise.resolve();
const eventName = this.socket.encrypted ? "secureConnect" : "connect";
return new Promise((resolve, reject) => {
this.socket.once(eventName, resolve);
this.socket.once("error", reject);
});
}
readResponse() {
return new Promise((resolve, reject) => {
this.waiter = { resolve, reject };
this.flush();
});
}
write(data) {
this.socket.write(data);
}
close() {
this.socket.end();
}
flush() {
if (!this.waiter) return;
let index = this.buffer.indexOf("\r\n");
while (index >= 0) {
const line = this.buffer.slice(0, index);
this.buffer = this.buffer.slice(index + 2);
this.lines.push(line);
const match = line.match(/^(\d{3})([ -])/);
if (match && match[2] === " ") {
const response = {
code: Number(match[1]),
lines: this.lines
};
this.lines = [];
const waiter = this.waiter;
this.waiter = null;
waiter.resolve(response);
return;
}
index = this.buffer.indexOf("\r\n");
}
}
}
function normalizePid(value) {
if (value === undefined || value === null || value === "") return 0;
if (typeof value === "number") return Number.isFinite(value) ? value : 0;
const text = String(value).trim();
if (!text || text === "0") return 0;
return text;
}
function findProductByPid(pid, products) {
const numericPid = Number(pid);
if (Number.isFinite(numericPid) && numericPid > 0) {
return products.find((item) => Number(item.id) === numericPid) || null;
}
const ranked = rankProductCandidates(pid, products);
return ranked[0] || null;
}
function rankProductCandidates(pid, products) {
const query = normalizeForMatch(pid);
if (!query || query === "0") return [];
return products
.map((product) => {
const terms = [product.name, ...(Array.isArray(product.aliases) ? product.aliases : [])]
.filter(Boolean)
.map(String);
const score = terms.reduce((total, term) => {
const normalizedTerm = normalizeForMatch(term);
if (!normalizedTerm) return total;
if (query.includes(normalizedTerm)) return total + 3;
if (normalizedTerm.includes(query)) return total + 2;
const hit = normalizedTerm.length >= 2 && query.includes(normalizedTerm.slice(0, Math.min(8, normalizedTerm.length)));
return total + (hit ? 1 : 0);
}, 0);
return { product, score };
})
.filter((item) => item.score > 0)
.sort((a, b) => b.score - a.score)
.map((item) => item.product);
}
function rankFaq(text, faq, productId) {
const normalized = normalizeForMatch(text);
return faq
.map((item) => {
const keywords = Array.isArray(item.keywords) ? item.keywords : [];
const productMatch = !item.productId || Number(item.productId) === Number(productId);
const score = keywords.reduce((total, keyword) => {
return total + (normalized.includes(normalizeForMatch(keyword)) ? 1 : 0);
}, 0) + (productMatch ? 0.2 : 0);
return { ...item, score };
})
.filter((item) => item.score > 0)
.sort((a, b) => b.score - a.score);
}
function rankToneExamples(text, examples) {
const normalized = normalizeForMatch(text);
const terms = extractQueryTerms(text);
return (Array.isArray(examples) ? examples : [])
.map((item) => {
const haystack = normalizeForMatch([
item.scene,
item.customer,
item.goodReply,
item.notes,
...(Array.isArray(item.keywords) ? item.keywords : [])
].filter(Boolean).join("\n"));
const keywordScore = Array.isArray(item.keywords)
? item.keywords.reduce((total, keyword) => total + (normalized.includes(normalizeForMatch(keyword)) ? 3 : 0), 0)
: 0;
const termScore = terms.reduce((total, term) => total + (haystack.includes(term) ? 1 : 0), 0);
const sceneScore = item.scene && normalized.includes(normalizeForMatch(item.scene)) ? 2 : 0;
return { ...item, score: keywordScore + termScore + sceneScore };
})
.filter((item) => item.score > 0)
.sort((a, b) => b.score - a.score);
}
function extractQueryTerms(text) {
const normalized = String(text || "")
.replace(/[^\u4e00-\u9fa5A-Za-z0-9]+/g, " ")
.split(/\s+/)
.map((item) => normalizeForMatch(item))
.filter((item) => item.length >= 2 && item.length <= 12);
const commonTerms = ["便宜", "优惠", "价格", "发货", "现货", "正品", "质量", "保真", "竿稍", "赠品", "配件", "型号", "规格", "退款", "退货", "售后"];
const source = normalizeForMatch(text);
for (const term of commonTerms) {
if (source.includes(normalizeForMatch(term))) normalized.push(normalizeForMatch(term));
}
return Array.from(new Set(normalized)).slice(0, 20);
}
function compactProduct(product) {
if (!product) return null;
return removeEmpty({
id: product.id,
name: product.name,
aliases: Array.isArray(product.aliases) ? product.aliases.slice(0, 8) : undefined,
attributes: compactObject(product.attributes, 30)
});
}
function buildProductSearchText(pid, product, productCandidates) {
const lines = [];
if (pid && pid !== 0) {
lines.push(`商品卡片:${pid}`);
}
if (product?.name) {
lines.push(`本地匹配商品:${product.name}`);
}
for (const item of Array.isArray(productCandidates) ? productCandidates.slice(0, 3) : []) {
const aliases = Array.isArray(item.aliases) && item.aliases.length
? `;别名:${item.aliases.slice(0, 6).join("、")}`
: "";
if (item.name) lines.push(`候选商品:${item.name}${aliases}`);
}
return Array.from(new Set(lines)).join("\n");
}
function compactFaqItem(item) {
return removeEmpty({
id: item.id,
productId: item.productId,
keywords: Array.isArray(item.keywords) ? item.keywords.slice(0, 8) : undefined,
question: item.question,
answer: item.answer
});
}
function compactToneExample(item) {
return removeEmpty({
id: item.id,
scene: item.scene,
customer: item.customer,
goodReply: item.goodReply,
notes: item.notes
});
}
function formatToneExamplesAsQaText(examples) {
return (Array.isArray(examples) ? examples : [])
.map((item) => {
const compacted = compactToneExample(item);
const lines = [];
if (compacted.scene) lines.push(`场景:${compacted.scene}`);
if (compacted.customer) lines.push(`Q:${compacted.customer}`);
if (compacted.goodReply) lines.push(`A:${compacted.goodReply}`);
if (compacted.notes) lines.push(`备注:${compacted.notes}`);
return lines.join("\n");
})
.filter(Boolean)
.join("\n\n");
}
function compactText(text, maxChars) {
const value = String(text || "").trim();
if (!maxChars || value.length <= maxChars) return value;
return `${value.slice(0, maxChars)}\n...`;
}
function compactObject(value, maxKeys) {
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
return Object.fromEntries(Object.entries(value).slice(0, maxKeys).map(([key, item]) => {
if (typeof item === "string") return [key, compactText(item, 500)];
return [key, item];
}));
}
function removeEmpty(value) {
return Object.fromEntries(Object.entries(value).filter(([, item]) => {
if (item === undefined || item === null || item === "") return false;
if (Array.isArray(item) && item.length === 0) return false;
return true;
}));
}
function logModelContextStats(requestId, context) {
const text = JSON.stringify(context);
console.log(
`[PDD Assistant] model context ${requestId}: chars=${text.length}, ` +
`messages=${context.payload?.msgList?.length || 0}, ` +
`products=${context.productCandidates?.length || 0}, ` +
`faq=${context.faq?.length || 0}, toneExamplesTextChars=${context.toneExamplesText?.length || 0}`
);
}
async function maybeCallCoze({ requestId, config, shop, context, latestCustomerMessage }) {
const cozeConfig = getShopCozeConfig(shop);
if (!cozeConfig.apiBase || !cozeConfig.apiToken || !cozeConfig.botId) return null;
const timeoutMs = Number(config.cozeTimeoutMs || config.modelTimeoutMs || 45000);
const pollIntervalMs = Number(config.cozePollIntervalMs || 1200);
const maxPolls = Number(config.cozeMaxPolls || 30);
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${cozeConfig.apiToken}`
};
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const prompt = buildCozeCustomerQuery({
requestId,
context,
latestCustomerMessage
});
const createResponse = await postJson(`${cozeConfig.apiBase}/v3/chat`, {
headers,
body: {
bot_id: cozeConfig.botId,
user_id: buildCozeUserId(shop),
stream: false,
additional_messages: [
{
role: "user",
content: prompt,
content_type: "text"
}
]
},
timeoutMs,
proxyUrl: "",
signal: controller.signal
});
if (!isCozeOk(createResponse)) {
console.error("[PDD Assistant] coze create chat failed", createResponse.status, createResponse.data);
throw new Error(`Coze 创建会话失败:${formatCozeError(createResponse)}`);
}
const chatId = createResponse.data?.data?.id;
const conversationId = createResponse.data?.data?.conversation_id;
if (!chatId || !conversationId) {
console.error("[PDD Assistant] coze create chat missing ids", createResponse.data);
throw new Error("Coze 创建会话失败:响应缺少 chat_id 或 conversation_id");
}
for (let attempt = 0; attempt < maxPolls; attempt += 1) {
await sleep(attempt === 0 ? 300 : pollIntervalMs);
const statusResponse = await getJson(
`${cozeConfig.apiBase}/v3/chat/retrieve?conversation_id=${encodeURIComponent(conversationId)}&chat_id=${encodeURIComponent(chatId)}`,
{ headers, signal: controller.signal }
);
if (!isCozeOk(statusResponse)) {
console.error("[PDD Assistant] coze retrieve chat failed", statusResponse.status, statusResponse.data);
throw new Error(`Coze 查询会话失败:${formatCozeError(statusResponse)}`);
}
const status = String(statusResponse.data?.data?.status || "").toLowerCase();
if (status === "completed") {
const messageResponse = await getJson(
`${cozeConfig.apiBase}/v3/chat/message/list?conversation_id=${encodeURIComponent(conversationId)}&chat_id=${encodeURIComponent(chatId)}`,
{ headers, signal: controller.signal }
);
if (!isCozeOk(messageResponse)) {
console.error("[PDD Assistant] coze message list failed", messageResponse.status, messageResponse.data);
throw new Error(`Coze 获取消息失败:${formatCozeError(messageResponse)}`);
}
return cleanupReply(parseCozeAnswer(messageResponse.data));
}
if (["failed", "requires_action", "canceled"].includes(status)) {
console.error("[PDD Assistant] coze chat ended without answer", status, statusResponse.data);
throw new Error(`Coze 会话未完成:${status}`);
}
}
console.error("[PDD Assistant] coze chat timeout", { requestId, maxPolls, pollIntervalMs });
throw new Error("Coze 会话超时");
} catch (error) {
console.error("[PDD Assistant] coze request error", formatModelError(error));
return "";
} finally {
clearTimeout(timeout);
}
}
function getShopCozeConfig(shop) {
const tokenEnv = shop.cozeApiTokenEnv || shop.cozeTokenEnv || "";
const tokenFromEnv = tokenEnv ? process.env[tokenEnv] : "";
return {
apiBase: normalizeCozeApiBase(process.env.COZE_API_BASE || shop.cozeApiBase || "https://api.coze.cn"),
apiToken: tokenFromEnv || shop.cozeApiToken || shop.cozeToken || process.env.COZE_API_TOKEN || "",
botId: String(shop.cozeBotId || shop.botId || process.env.COZE_BOT_ID || "").trim()
};
}
function normalizeCozeApiBase(value) {
const raw = String(value || "").trim().replace(/\/+$/, "");
if (!raw) return "";
return raw
.replace(/\/v3\/chat(?:\/.*)?$/i, "")
.replace(/\/v1\/chat(?:\/.*)?$/i, "");
}
function buildCozeUserId(shop) {
return `pdd-${String(shop.id || "default").replace(/[^\w-]/g, "-").slice(0, 48)}`;
}
function buildCozeCustomerQuery({ requestId, context, latestCustomerMessage }) {
const msgList = Array.isArray(context.payload?.msgList) ? context.payload.msgList : [];
const workflowInput = buildCozeWorkflowInput({ context, latestCustomerMessage, msgList });
const faqSearchText = buildCozeFaqSearchText(latestCustomerMessage, msgList);
return [
"WORKFLOW_INPUT_JSON:",
JSON.stringify(workflowInput, null, 2),
"",
"调用工作流时请严格按上方 JSON 映射变量:",
"- latest_question -> 工作流 latest_question",
"- product_context -> 工作流 product_context",
"- chat_history -> 工作流 chat_history",
"",
`FAQ检索关键词:${faqSearchText}`,
"请根据知识库和上下文生成一句可以直接发给拼多多买家的客服回复。",
"如果客户最新问题是通用问题或标准话术问题,例如正品、防伪、发货、售后配节、价格、赠品、包装、发票、优惠、保修等,请优先检索并参考知识库文件“标准FAQ.md”。",
"如果“标准FAQ.md”中有同义或近似问题,优先使用其中的标准回答和语气,再结合商品上下文做必要补充。",
"知识库检索时必须优先使用“当前商品卡片信息”和“客户最新问题”共同判断商品型号/规格。",
"如果当前商品卡片信息包含型号、米数、套餐、规格,请优先匹配对应型号的话术;不要笼统回复“规格参数未提供”。",
"只有当前商品为0且最近聊天也没有商品线索时,才可以说明需要客户提供具体规格。",
"只输出最终回复,不要输出分析过程。",
`请求ID:${requestId}`,
`店铺:${context.shop?.name || context.shop?.id || ""}`,
`客户最新问题:${workflowInput.latest_question || "无"}`,
`当前商品卡片信息:${workflowInput.product_context || "无"}`,
"最近聊天:",
workflowInput.chat_history || "无"
].join("\n");
}
function buildCozeWorkflowInput({ context, latestCustomerMessage, msgList }) {
return {
latest_question: normalizeText(latestCustomerMessage || ""),
product_context: buildCozeProductContext(context),
chat_history: formatCozeChatHistory(msgList)
};
}
function buildCozeProductContext(context) {
const productReference = context.productReference && context.productReference !== 0
? String(context.productReference)
: "";
const productSearchText = normalizeText(context.productSearchText || "");
return Array.from(new Set([productReference, productSearchText].filter(Boolean))).join("\n");
}
function formatCozeChatHistory(msgList) {
return (Array.isArray(msgList) ? msgList : [])
.map((item) => {
const role = item.usertype === "sys" ? "客服" : "客户";
return `${role}:${item.msg}`;
})
.join("\n");
}
function buildCozeFaqSearchText(latestCustomerMessage, msgList) {
const latest = normalizeText(latestCustomerMessage || "");
const recentCustomerMessages = [...msgList]
.reverse()
.filter((item) => item.usertype === "cus" && item.msg)
.slice(0, 3)
.map((item) => item.msg);
const aliases = buildFaqAliasKeywords(latest);
return Array.from(new Set([latest, ...aliases, ...recentCustomerMessages].filter(Boolean))).join(";") || "无";
}
function buildFaqAliasKeywords(text) {
const normalized = normalizeForMatch(text);
const groups = [
{
hit: ["正品", "真假", "防伪", "假货", "全新"],
aliases: ["是正品吗", "是不是正品", "防伪可查吗", "假一赔十吗"]
},
{
hit: ["发货", "哪里发", "多久发", "今天能发", "什么时候发"],
aliases: ["哪里发货", "今天能发吗", "什么时候发货", "多久发货"]
},
{
hit: ["配节", "竿稍", "竿节", "备用", "售后"],
aliases: ["可以配节吗", "带备用竿稍吗", "售后怎么配节", "竿稍怎么配"]
},
{
hit: ["便宜", "优惠", "少点", "价格"],
aliases: ["怎么这么便宜", "可以优惠吗", "价格还能少吗"]
},
{
hit: ["赠品", "送什么", "带什么"],
aliases: ["有赠品吗", "送什么东西", "带备用配件吗"]
}
];
const aliases = [];
for (const group of groups) {
if (group.hit.some((keyword) => normalized.includes(normalizeForMatch(keyword)))) {
aliases.push(...group.aliases);
}
}
return aliases;
}
function parseCozeAnswer(data) {
const messages = Array.isArray(data?.data) ? data.data : [];
const answer = messages.find((item) => item?.type === "answer" && item?.role === "assistant");
if (answer?.content) return answer.content;
const assistant = [...messages].reverse().find((item) => item?.role === "assistant" && item?.content);
if (assistant?.content) return assistant.content;
return parseLooseResponse(data);
}
function isCozeOk(response) {
const code = response.data?.code;
return response.status >= 200 && response.status < 300 && (code === undefined || code === 0);
}
function formatCozeError(response) {
const data = response?.data || {};
const parts = [];
if (response?.status) parts.push(`HTTP ${response.status}`);
if (data.code !== undefined) parts.push(`code ${data.code}`);
if (data.msg) parts.push(data.msg);
if (data.detail?.logid) parts.push(`logid ${data.detail.logid}`);
return parts.join(",") || "未知错误";
}
async function maybeCallModel({ requestId, config, systemPrompt, context }) {
const apiUrl = process.env.CODEX_API_URL || config.codexApiUrl;
const apiKey = process.env.CODEX_API_KEY || config.codexApiKey || process.env.ZZZ_API_KEY || process.env.OPENAI_API_KEY;
const model = process.env.CODEX_MODEL || config.codexModel;
const mockWhenNoApiKey = config.mockWhenNoApiKey !== false;
if (!apiUrl || !model || (!apiKey && mockWhenNoApiKey)) {
return "";
}
const apiMode = process.env.CODEX_API_MODE || config.apiMode || "responses";
const { body, parser } = buildModelRequest({ apiMode, model, systemPrompt, context, requestId });
const headers = {
"Content-Type": "application/json"
};
if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), Number(config.modelTimeoutMs || 45000));
try {
const response = await postJson(apiUrl, {
headers,
body,
timeoutMs: Number(config.modelTimeoutMs || 45000),
proxyUrl: getProxyUrl(config),
signal: controller.signal
});
if (response.status < 200 || response.status >= 300) {
console.error("[PDD Assistant] model request failed", response.status, response.data);
return "";
}
return cleanupReply(parser(response.data));
} catch (error) {
console.error("[PDD Assistant] model request error", formatModelError(error));
return "";
} finally {
clearTimeout(timeout);
}
}
function getProxyUrl(config) {
return process.env.CODEX_PROXY_URL || process.env.HTTPS_PROXY || process.env.HTTP_PROXY || config.proxyUrl || "";
}
function maskProxyUrl(proxyUrl) {
if (!proxyUrl) return "";
try {
const parsed = new URL(proxyUrl);
if (parsed.username) parsed.username = "***";
if (parsed.password) parsed.password = "***";
return parsed.toString();
} catch (_) {
return proxyUrl.replace(/\/\/([^:@/]+):([^@/]+)@/, "//***:***@");
}
}
async function postJson(apiUrl, { headers, body, timeoutMs, proxyUrl, signal }) {
if (proxyUrl) {
return postJsonViaProxy(apiUrl, { headers, body, timeoutMs, proxyUrl, signal });
}
const response = await fetch(apiUrl, {
method: "POST",
headers,
body: JSON.stringify(body),
signal
});
const data = await response.json().catch(async () => ({ raw: await response.text() }));
return { status: response.status, data };
}
async function getJson(apiUrl, { headers, signal }) {
const response = await fetch(apiUrl, {
method: "GET",
headers,
signal
});
const data = await response.json().catch(async () => ({ raw: await response.text() }));
return { status: response.status, data };
}
function postJsonViaProxy(apiUrl, { headers, body, timeoutMs, proxyUrl, signal }) {
return new Promise((resolve, reject) => {
const target = new URL(apiUrl);
const proxy = new URL(proxyUrl);
if (target.protocol !== "https:") {
reject(new Error("代理模式目前仅支持 HTTPS 模型接口"));
return;
}
const proxyPort = Number(proxy.port || (proxy.protocol === "https:" ? 443 : 80));
const connectOptions = {
host: proxy.hostname,
port: proxyPort
};
const proxySocket = proxy.protocol === "https:"
? tls.connect({ ...connectOptions, servername: proxy.hostname })
: net.connect(connectOptions);
const timer = setTimeout(() => {
proxySocket.destroy(new Error(`模型请求代理连接超时:${timeoutMs}ms`));
}, timeoutMs);
const abort = () => {
proxySocket.destroy(new Error("模型请求已取消"));
};
signal?.addEventListener("abort", abort, { once: true });
proxySocket.once(proxy.protocol === "https:" ? "secureConnect" : "connect", () => {
const authHeader = proxy.username
? `Proxy-Authorization: Basic ${Buffer.from(`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`).toString("base64")}\r\n`
: "";
proxySocket.write(
`CONNECT ${target.hostname}:443 HTTP/1.1\r\n` +
`Host: ${target.hostname}:443\r\n` +
authHeader +
"Connection: keep-alive\r\n\r\n"
);
});
let connectBuffer = Buffer.alloc(0);
proxySocket.on("data", function onConnectData(chunk) {
connectBuffer = Buffer.concat([connectBuffer, Buffer.from(chunk)]);
const headerEnd = connectBuffer.indexOf("\r\n\r\n");
if (headerEnd === -1) return;
proxySocket.off("data", onConnectData);
const header = connectBuffer.slice(0, headerEnd).toString("utf8");
const rest = connectBuffer.slice(headerEnd + 4);
if (!/^HTTP\/1\.[01] 2\d\d/.test(header)) {
cleanup();
proxySocket.destroy();
reject(new Error(`代理 CONNECT 失败:${header.split("\r\n")[0] || header}`));
return;
}
const tlsSocket = tls.connect({
socket: proxySocket,
servername: target.hostname
}, () => {
if (rest.length) tlsSocket.unshift(rest);
sendHttpsRequestOverSocket(tlsSocket, target, headers, body, timeoutMs)
.then((result) => {
cleanup();
resolve(result);
})
.catch((error) => {
cleanup();
reject(error);
});
});
tlsSocket.once("error", (error) => {
cleanup();
reject(error);
});
});
proxySocket.once("error", (error) => {
cleanup();
reject(error);
});
function cleanup() {
clearTimeout(timer);
signal?.removeEventListener("abort", abort);
}
});
}
function sendHttpsRequestOverSocket(socket, target, headers, body, timeoutMs) {
return new Promise((resolve, reject) => {
const requestBody = JSON.stringify(body);
const requestHeaders = {
...headers,
Host: target.hostname,
"Content-Length": Buffer.byteLength(requestBody)
};
const headerText = [
`POST ${target.pathname}${target.search} HTTP/1.1`,
...Object.entries(requestHeaders).map(([key, value]) => `${key}: ${value}`),
"Connection: close",
"",
requestBody
].join("\r\n");
let response = Buffer.alloc(0);
const timer = setTimeout(() => {
socket.destroy(new Error(`模型请求超时:${timeoutMs}ms`));
}, timeoutMs);
socket.on("data", (chunk) => {
response = Buffer.concat([response, Buffer.from(chunk)]);
});
socket.once("end", () => {
clearTimeout(timer);
try {
resolve(parseHttpResponse(response));
} catch (error) {
reject(error);
}
});
socket.once("error", (error) => {
clearTimeout(timer);
reject(error);
});
socket.write(headerText);
});
}
function parseHttpResponse(buffer) {
const headerEnd = buffer.indexOf("\r\n\r\n");
if (headerEnd === -1) throw new Error("模型接口响应格式异常:缺少响应头");
const headerText = buffer.slice(0, headerEnd).toString("utf8");
const bodyBuffer = buffer.slice(headerEnd + 4);
const status = Number(headerText.match(/^HTTP\/1\.[01]\s+(\d+)/)?.[1] || 0);
const headers = Object.fromEntries(
headerText
.split("\r\n")
.slice(1)
.map((line) => {
const index = line.indexOf(":");
return index > -1 ? [line.slice(0, index).trim().toLowerCase(), line.slice(index + 1).trim()] : null;
})
.filter(Boolean)
);
let body = bodyBuffer;
if (/chunked/i.test(headers["transfer-encoding"] || "")) {
body = decodeChunkedBody(bodyBuffer);
}
const text = body.toString("utf8");
let data;
try {
data = text ? JSON.parse(text) : {};
} catch (_) {
data = { raw: text };
}
return { status, data };
}
function decodeChunkedBody(buffer) {
let offset = 0;
const chunks = [];
while (offset < buffer.length) {
const lineEnd = buffer.indexOf("\r\n", offset);
if (lineEnd === -1) break;
const sizeText = buffer.slice(offset, lineEnd).toString("ascii").split(";")[0];
const size = parseInt(sizeText, 16);
if (!size) break;
const start = lineEnd + 2;
const end = start + size;
chunks.push(buffer.slice(start, end));
offset = end + 2;
}
return Buffer.concat(chunks);
}
function formatModelError(error) {
const cause = error?.cause;
const details = {
message: error?.message || String(error),
name: error?.name,
code: error?.code || cause?.code,
errno: error?.errno || cause?.errno,
syscall: error?.syscall || cause?.syscall,
hostname: error?.hostname || cause?.hostname,
causeMessage: cause?.message,
causeName: cause?.name
};
return JSON.stringify(details);
}
function buildModelRequest({ apiMode, model, systemPrompt, context, requestId }) {
const userContent = [
"请根据以下上下文生成一句可以直接发给拼多多买家的客服回复。",
"要求:中文、简洁、礼貌、不要编造未给出的承诺,不要输出分析过程。",
`请求ID:${requestId}`,
JSON.stringify(context, null, 2)
].join("\n\n");
if (apiMode === "chat") {
return {
body: {
model,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userContent }
]
},
parser: parseChatResponse
};
}
if (apiMode === "custom") {
return {
body: {
model,
systemPrompt,
context,
instruction: "生成一句可直接发送给买家的客服回复。"
},
parser: parseLooseResponse
};
}
return {
body: {
model,
input: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userContent }
]
},
parser: parseResponsesResponse
};
}
function parseResponsesResponse(data) {
if (typeof data.output_text === "string") return data.output_text;
if (Array.isArray(data.output)) {
for (const outputItem of data.output) {
if (!Array.isArray(outputItem.content)) continue;
for (const content of outputItem.content) {
if (typeof content.text === "string") return content.text;
}
}
}
return parseLooseResponse(data);
}
function parseChatResponse(data) {
return data?.choices?.[0]?.message?.content || parseLooseResponse(data);
}
function parseLooseResponse(data) {
return data?.reply || data?.message || data?.text || data?.data?.reply || data?.data?.message || "";
}
function cleanupReply(text) {
return String(text || "")
.replace(/^["“]|["”]$/g, "")
.replace(/\n{3,}/g, "\n\n")
.trim()
.slice(0, 1200);
}
function buildFallbackReply({ latestCustomerMessage, product, productReference, faq }) {
const matchedFaq = faq[0];
if (matchedFaq && matchedFaq.answer) return fillProductPlaceholders(matchedFaq.answer, product);
const productName = product?.name || (productReference && productReference !== 0 ? String(productReference) : "");
const text = normalizeForMatch(latestCustomerMessage);
if (/你好|您好|在吗|在不/.test(text)) {
return productName
? `您好,在的,您咨询的是${productName},请问有什么可以帮您?`
: "您好,在的,请问有什么可以帮您?";
}
if (/便宜|优惠|少点|最低|价格/.test(text)) {
return productName
? `您好,${productName}目前按页面活动价为准,店铺有优惠会自动显示,您可以放心拍。`
: "您好,商品价格以页面活动价为准,店铺有优惠会自动显示,您可以放心拍。";
}
return productName
? `您好,您咨询的是${productName},我这边已收到您的问题,马上帮您核实。`
: "您好,已收到您的问题,我这边马上帮您核实。";
}
function fillProductPlaceholders(text, product) {
return String(text || "").replace(/\{\{商品名\}\}/g, product?.name || "这款商品");
}
function sanitizeMailConfig(config) {
if (!config || typeof config !== "object") return {};
const cloned = { ...config };
if (cloned.password) cloned.password = "***";
if (cloned.authCode) cloned.authCode = "***";
return cloned;
}
function normalizeForMatch(value) {
return String(value || "")
.replace(/\s+/g, "")
.toLowerCase();
}