Files
inquiry_robot/aibot-bridge/long_connection.cjs
T
linmianxunandCursor d9b2029c47 协同群改为智价通BOT接管对话,报价单按需生成;补客户名称、计费重与陆运报价条件
为什么改:应用建的协同群只能代答,销售在群里发文件、@人、问报价都对不上人;
本次把群对话交给智价通BOT,应用只负责拉群和解散群,并把几处销售已反馈的口径补齐。

群与身份:
- 新增 group_bot 短协调(Redis 带环境前缀):记录 BOT 已接管群、当前关联工单、
  @BOT 指令窗口与窗口外先到的附件,只做协调不当六态,六态仍在主账。
- 群里没有 @BOT 的文字不回;非 @ 文字断开当前单关联,之后必须重新 @BOT 带工单号。
- 先发文件再 @BOT 也认:窗口外附件先缓冲,等 @BOT 认领后补办。
- 会话存档只补附件、不重复办理 BOT 已办的同一句文字,避免同一条消息回两遍。
- 入站 from.userid 是加密 open_userid 时按官方接口换明文(带 Redis 缓存),
  否则与主账 sales_wecom_id 永远比不上,航线本人会被判成「不是本人」。
- 桥侧只认本群 req_id,不再借用别的群 req_id,避免测服把话发进别的群。

报价单:
- 建群后只发字段摘要和成交卡,Excel/PDF 等群里 @BOT 说「生成报价单」再出;
  多段逐段出,没价出空白表;出表后补推成交跟进不涨 deal_version、不重置等待计时。
- 陆运转人工先选业务类型和报价场景再建群,按选定模板名直取,不再靠关键词猜。
- 空运舱位只回一条时直接出该条报价,不再发选择卡。

字段与金额:
- 客户名称改为海/空/陆询价非必填,有值写回工单列,后台列表、报价单与 factsJson 一致。
- 空运新增计费重投影:体积重=CBM×166.7,计费重=max(毛重,体积重);
  TMS 无价、航线手工按 KG 报价时按计费重×单价算整票金额,群摘要与报价单同公式。
- 陆运报价附加条件统一到 land_quote_condition:未含税/含0税/未含燃油/含燃油费,
  燃油只乘主运费,不乘提货送货报关等杂费;跨境整车无备注列时追加到底部备注事项。
- 海运拼柜不适用箱型箱量:不进必填、不进补问、不出站,改回整柜可再用。
- 海运提货地址/派送地址改为非必填,写了才出站(placeOfReceipt/deliveryAddress),
  禁止从港口或贸易条款反推地址;TMS 查不到价时把 TMS 原话透给销售。
- 中港集拼与跨境集拼同口径:按体积+毛重,不采车型数量;修正被国内拼车别名抢单。
- 报关费区只收报关类费目;口岸海关监管费+接驳费按车型列回填固定行。

主账与后台:
- 看板处理量按协同群处理人统计;下线「平均报价销售额」;处理人搜索先把姓名换回企微 id。
- 「转人工」筛选同时兼容旧六态与新 collab_mode=handoff,新版单不再漏。
- 报价单客户名称、提货/派送地址、空运计费重、拼柜空箱型按新口径填表。
- 新增协同成员查询支持与 AIR_NEED_WO v2 迁移脚本。

文档:04 补海运/空运/陆运必填与地址口径,10 补地址出站规则,12 补测服独立应用 1000015 的部署与切换记录。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-23 14:18:22 +08:00

551 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* AIBOT 长连接(只传输,无工单状态)。
*
* 本文件职责:
* - WECOM_AIBOT_ENABLED=true 时连 wss://openws.work.weixin.qq.com
* - 订阅后:入站 aibot_msg_callback 转发智能体;出站 /send-group 走 aibot_send_msg
* - 同一 Bot 只能一条长连接;并存期默认关,勿与现网 8813 双连
*
* 禁止:写工单/六态/Graph。密钥只读环境变量,不打日志。
*/
"use strict";
const crypto = require("crypto");
const { buildGroupMessageFrame, pickReplyReqId } = require("./group_message_frame.cjs");
function generateReqId(prefix) {
const timestamp = Date.now();
const random = crypto.randomBytes(4).toString("hex");
return `${prefix}_${timestamp}_${random}`;
}
function loadWs() {
try {
return require("ws");
} catch (_) {
return null;
}
}
/**
* @param {object} opts
* @param {boolean} opts.enabled
* @param {(payloadText: string) => Promise<object>} opts.forwardToAgent
* @param {() => boolean} [opts.shouldStop]
*/
function startLongConnectionLoop(opts) {
const enabled = !!opts.enabled;
const forwardToAgent = opts.forwardToAgent;
const shouldStop = opts.shouldStop || (() => false);
const botId = String(process.env.WECOM_AIBOT_BOT_ID || "").trim();
const secret = String(process.env.WECOM_AIBOT_SECRET || "").trim();
const wsUrl =
process.env.WECOM_AIBOT_WS_URL || "wss://openws.work.weixin.qq.com";
const state = {
ws: null,
connected: false,
subscribed: false,
lastError: "",
pending: new Map(),
lastCallback: new Map(),
heartbeatTimer: null,
reconnectTimer: null,
stop: () => {},
};
function status() {
return {
enabled,
connected: state.connected,
subscribed: state.subscribed,
lastError: state.lastError,
hasCredentials: Boolean(botId && secret),
};
}
function sendWs(payload, reqId) {
return new Promise((resolve, reject) => {
if (!state.ws || state.ws.readyState !== 1 || !state.subscribed) {
const err = new Error("ws_offline");
err.code = "ws_offline";
reject(err);
return;
}
const timer = setTimeout(() => {
state.pending.delete(reqId);
const err = new Error("send_timeout");
err.code = "send_timeout";
reject(err);
}, 8000);
state.pending.set(reqId, { resolve, reject, timer });
state.ws.send(JSON.stringify(payload));
});
}
function sendGroupMessage({ chatId, content, callbackReqId }) {
const text = String(content || "");
const fromCaller = String(callbackReqId || "").trim();
const chatKey = String(chatId || "").trim();
const fromChat = state.lastCallback.get(chatKey) || "";
// 只用本群 req_id:跨群回退会把话发到别的群(企微按 req_id 投递)。
const replyReqId = pickReplyReqId({
fromCaller,
fromChat,
});
// 用这次 @ 的 req_id 回 aibot_respond_msg,群里才会引用原消息。
const reqId = replyReqId || generateReqId("aibot_send_msg");
const frame = buildGroupMessageFrame({
chatId,
content: text,
callbackReqId: replyReqId,
reqId,
});
// eslint-disable-next-line no-console
console.log(
"[aibot-long-connection] 出站 cmd=",
frame.cmd,
"chat=",
chatKey || "-",
"hasReq=",
Boolean(replyReqId)
);
return sendWs(frame, reqId);
}
/**
* 空运群发报价模板:分片上传后 aibot_send_msg file。
* 单个分片不超过 512KB(编码前)。
*/
async function sendGroupFile({ chatId, filename, fileB64, fileBytes }) {
const buf = Buffer.isBuffer(fileBytes)
? fileBytes
: Buffer.from(String(fileB64 || ""), "base64");
const name = String(filename || "quote.xlsx").trim() || "quote.xlsx";
if (!chatId || !buf.length) {
const err = new Error("file_empty");
err.code = "file_empty";
throw err;
}
const chunkSize = 400 * 1024;
const totalChunks = Math.max(1, Math.ceil(buf.length / chunkSize));
const md5 = crypto.createHash("md5").update(buf).digest("hex");
const initReq = generateReqId("aibot_upload_media_init");
const init = await sendWs(
{
cmd: "aibot_upload_media_init",
headers: { req_id: initReq },
body: {
type: "file",
filename: name,
total_size: buf.length,
total_chunks: totalChunks,
md5,
},
},
initReq
);
const uploadId = String((init.body && init.body.upload_id) || "").trim();
if (!uploadId) {
const err = new Error("upload_init_failed");
err.code = "upload_init_failed";
throw err;
}
for (let i = 0; i < totalChunks; i += 1) {
const slice = buf.subarray(i * chunkSize, Math.min(buf.length, (i + 1) * chunkSize));
const chunkReq = generateReqId("aibot_upload_media_chunk");
await sendWs(
{
cmd: "aibot_upload_media_chunk",
headers: { req_id: chunkReq },
body: {
upload_id: uploadId,
chunk_index: i,
base64_data: slice.toString("base64"),
},
},
chunkReq
);
}
const finishReq = generateReqId("aibot_upload_media_finish");
const finished = await sendWs(
{
cmd: "aibot_upload_media_finish",
headers: { req_id: finishReq },
body: { upload_id: uploadId },
},
finishReq
);
const mediaId = String((finished.body && finished.body.media_id) || "").trim();
if (!mediaId) {
const err = new Error("upload_finish_failed");
err.code = "upload_finish_failed";
throw err;
}
const sendReq = generateReqId("aibot_send_msg");
return sendWs(
{
cmd: "aibot_send_msg",
headers: { req_id: sendReq },
body: {
chatid: chatId,
chat_type: 2,
msgtype: "file",
file: { media_id: mediaId },
},
},
sendReq
);
}
if (!enabled) {
// eslint-disable-next-line no-console
console.log("[aibot-long-connection] 未启用(WECOM_AIBOT_ENABLED=false),不连企微");
return { stop: () => {}, sendGroupMessage, sendGroupFile, status };
}
if (!botId || !secret) {
state.lastError = "missing_bot_credentials";
// eslint-disable-next-line no-console
console.warn(
"[aibot-long-connection] 已启用但缺少 WECOM_AIBOT_BOT_ID / WECOM_AIBOT_SECRET,无法订阅"
);
return { stop: () => {}, sendGroupMessage, sendGroupFile, status };
}
const WebSocket = loadWs();
if (!WebSocket) {
state.lastError = "ws_package_missing";
// eslint-disable-next-line no-console
console.warn("[aibot-long-connection] 未安装 ws 包,请在 aibot-bridge 目录执行 npm install");
return { stop: () => {}, sendGroupMessage, sendGroupFile, status };
}
function startHeartbeat() {
stopHeartbeat();
state.heartbeatTimer = setInterval(() => {
if (!state.ws || state.ws.readyState !== 1) {
return;
}
try {
state.ws.send(
JSON.stringify({
cmd: "ping",
headers: { req_id: generateReqId("ping") },
})
);
} catch (_) {
/* ignore */
}
}, 25000);
}
function stopHeartbeat() {
if (state.heartbeatTimer) {
clearInterval(state.heartbeatTimer);
state.heartbeatTimer = null;
}
}
function scheduleReconnect() {
if (shouldStop() || state.reconnectTimer) {
return;
}
state.reconnectTimer = setTimeout(() => {
state.reconnectTimer = null;
connect();
}, 5000);
}
function settlePending(reqId, errcode, errmsg, frame) {
const wait = state.pending.get(reqId);
if (!wait) {
return;
}
clearTimeout(wait.timer);
state.pending.delete(reqId);
if (Number(errcode) === 0) {
wait.resolve({ ok: true, body: (frame && frame.body) || {}, frame: frame || {} });
return;
}
const err = new Error(errmsg || "send_failed");
err.code = "wecom_error";
err.errcode = errcode;
wait.reject(err);
}
/**
* 把企微智能机器人回调归一成智能体入站结构。
*
* 2026-11-19 补(真机问题:@BOT 换行带图时正文变空):
* - 群聊里图片/文件/视频的独立回调企微不推,@ 带图只会来 mixed(文字+图片);
* - 以前只读 body.text,mixed 的正文和图片地址全丢,智能体把空正文当文字去要工单号。
* 这里把 mixed 的多段文字拼成 content,把图片地址放进 media(加密 URL、5 分钟过期,
* 只用于判断「只有图没有字」,不在这里下载)。
* 文件消息官方不给文件名,只有加密 URL,因此群聊文件仍只走会话存档。
*/
function normalizeInbound(frame) {
const body = frame.body || {};
const from = body.from || {};
const msgType = String(body.msgtype || "text");
let text = (body.text && body.text.content) || "";
const media = {};
if (msgType === "mixed") {
const items =
body.mixed && Array.isArray(body.mixed.msg_item) ? body.mixed.msg_item : [];
const texts = [];
const images = [];
for (const item of items) {
if (!item || typeof item !== "object") {
continue;
}
if (item.msgtype === "text" && item.text && item.text.content) {
texts.push(String(item.text.content));
}
if (item.msgtype === "image" && item.image && item.image.url) {
images.push(String(item.image.url));
}
}
if (!text && texts.length) {
text = texts.join("\n");
}
if (images.length) {
media.image_count = images.length;
media.image_urls = images;
}
} else if (body.image && body.image.url) {
media.image_count = 1;
media.image_url = String(body.image.url);
} else if (body.video && body.video.url) {
media.video_url = String(body.video.url);
} else if (body.file && body.file.url) {
media.file_url = String(body.file.url);
}
return {
sender_id: String(from.userid || "").trim(),
message_id: String(body.msgid || (frame.headers && frame.headers.req_id) || "").trim(),
content: text,
msg_type: msgType,
chat_id: String(body.chatid || "").trim(),
chat_type: body.chattype === "single" ? "c2c" : "group",
media,
raw: {
source: "aibot",
aibot_req_id: frame.headers && frame.headers.req_id,
},
};
}
function handleFrame(raw) {
let frame;
try {
frame = JSON.parse(raw);
} catch (_) {
return;
}
const reqId = frame.headers && frame.headers.req_id;
// 出站 ACK 带 chatid,不能当成入站,否则会盖掉这次 @ 的 req_id,群里就没有引用。
if (reqId && state.pending.has(reqId)) {
settlePending(reqId, frame.errcode, frame.errmsg, frame);
return;
}
if (frame.cmd === "aibot_event_callback") {
const ev = (frame.body && frame.body.event && frame.body.event.eventtype) || "";
// eslint-disable-next-line no-console
console.warn("[aibot-long-connection] 事件", ev || "-");
if (ev === "disconnected_event") {
state.lastError = "kicked_by_new_connection";
}
return;
}
const bodyHint = frame.body || {};
const looksLikeInbound = Boolean(
frame.cmd === "aibot_msg_callback" ||
(bodyHint.msgid && (bodyHint.from || (bodyHint.text && bodyHint.text.content)))
);
if (looksLikeInbound) {
// eslint-disable-next-line no-console
console.log(
"[aibot-long-connection] 收到入站 cmd=",
frame.cmd || "-",
"msgid=",
bodyHint.msgid || "-",
"chat=",
bodyHint.chatid || "-"
);
const inbound = normalizeInbound(frame);
const chatKey = inbound.chat_id || String(bodyHint.chatid || "").trim();
if (reqId && chatKey) {
state.lastCallback.set(chatKey, reqId);
}
const officialBody = Object.assign({}, frame.body || {}, {
aibot_direct: true,
aibot_req_id: reqId || "",
});
const payload = inbound.sender_id
? Object.assign({}, officialBody, {
sender_id: inbound.sender_id,
message_id: inbound.message_id,
content: inbound.content,
chat_id: inbound.chat_id,
chat_type: inbound.chat_type,
// 2026-11-19:mixed 的图片地址等元信息必须一起转,否则智能体只看到空正文。
media: inbound.media || {},
})
: officialBody;
if (!payload.sender_id && !payload.from) {
return;
}
Promise.resolve(forwardToAgent(JSON.stringify(payload))).catch((e) => {
// eslint-disable-next-line no-console
console.warn("[aibot-long-connection] 转发入站失败", String(e && e.message ? e.message : e));
});
}
}
function connect() {
if (shouldStop()) {
return;
}
// eslint-disable-next-line no-console
console.warn(
"[aibot-long-connection] 即将连接企微长连接;请确认现网 8813 已停,避免双连"
);
const ws = new WebSocket(wsUrl);
state.ws = ws;
ws.on("open", () => {
state.connected = true;
state.lastError = "";
const reqId = generateReqId("aibot_subscribe");
ws.send(
JSON.stringify({
cmd: "aibot_subscribe",
headers: { req_id: reqId },
body: { bot_id: botId, secret },
})
);
// eslint-disable-next-line no-console
console.log("[aibot-long-connection] 已发订阅 req_id前缀=aibot_subscribe");
});
ws.on("message", (buf) => {
const text = Buffer.isBuffer(buf) ? buf.toString("utf8") : String(buf);
let frame;
try {
frame = JSON.parse(text);
} catch (_) {
// eslint-disable-next-line no-console
console.warn("[aibot-long-connection] 非JSON帧 len=", text.length);
handleFrame(text);
return;
}
// eslint-disable-next-line no-console
const reqPrefix = String((frame.headers && frame.headers.req_id) || "").split("_").slice(0, 2).join("_");
console.log(
"[aibot-long-connection] 帧 cmd=",
frame.cmd || "-",
"req=",
reqPrefix || "-",
"keys=",
Object.keys(frame).join(","),
"errcode=",
frame.errcode,
"errmsg=",
frame.errmsg || ""
);
if (frame.cmd === "ping") {
try {
ws.send(
JSON.stringify({
cmd: "pong",
headers: frame.headers || {},
})
);
} catch (_) {
/* ignore */
}
}
const ackReq = String((frame.headers && frame.headers.req_id) || "");
if (ackReq.startsWith("aibot_subscribe") && Number(frame.errcode) === 0 && !state.subscribed) {
state.subscribed = true;
startHeartbeat();
// eslint-disable-next-line no-console
console.log("[aibot-long-connection] 订阅成功");
} else if (
ackReq.startsWith("aibot_subscribe") &&
frame.errcode !== undefined &&
Number(frame.errcode) !== 0
) {
state.lastError = "subscribe_failed_" + String(frame.errcode);
// eslint-disable-next-line no-console
console.warn("[aibot-long-connection] 订阅失败 errcode=", frame.errcode);
}
handleFrame(text);
});
ws.on("close", (code, reason) => {
stopHeartbeat();
state.connected = false;
state.subscribed = false;
state.ws = null;
// eslint-disable-next-line no-console
console.warn(
"[aibot-long-connection] 连接关闭 code=",
code,
"reason=",
reason ? String(reason).slice(0, 120) : ""
);
if (!shouldStop()) {
scheduleReconnect();
}
});
ws.on("error", (e) => {
state.lastError = "ws_error";
// eslint-disable-next-line no-console
console.warn("[aibot-long-connection] 连接错误", String(e && e.message ? e.message : e));
});
ws.on("ping", () => {
try {
ws.pong();
} catch (_) {
/* ignore */
}
});
}
connect();
state.stop = () => {
stopHeartbeat();
if (state.reconnectTimer) {
clearTimeout(state.reconnectTimer);
state.reconnectTimer = null;
}
if (state.ws) {
try {
state.ws.close();
} catch (_) {
/* ignore */
}
state.ws = null;
}
state.connected = false;
state.subscribed = false;
};
return {
stop: state.stop,
sendGroupMessage,
sendGroupFile,
status,
/**
* 测试注入:模拟 SDK 收到一帧已解析 JSON,只做转发。
* @param {object|string} frame
*/
injectFrameForTest: async (frame) => {
const text = typeof frame === "string" ? frame : JSON.stringify(frame);
return forwardToAgent(text);
},
};
}
module.exports = { startLongConnectionLoop };