diff --git a/.gitignore b/.gitignore
index da8e5cd..f45dd04 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,7 +7,13 @@ logs/
# Real deployment secrets and shop-specific credentials.
config/shops.json
+config/shops/
config/mail.json
# Optional local runtime files.
*.pid
+
+# Native build outputs and downloaded packages.
+native/bin/
+native/packages/
+dist/
diff --git a/config/products.json b/config/products.json
index 07aa278..26fcfe5 100644
--- a/config/products.json
+++ b/config/products.json
@@ -1,74 +1,69 @@
[
{
"id": 1,
- "name": "汉鼎螺纹钢鲢鳙",
- "aliases": ["螺纹钢鲢","鲢鳙杆"],
+ "name": "证件照打印 一寸二寸",
+ "aliases": ["一寸照", "二寸照", "证件照", "换底色"],
"attributes": {
- "品牌": "汉鼎",
- "适用": "台钓、黑坑、鲢鳙杆",
- "售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
- "赠品": "无备用竿稍,无赠品",
- "售后-退货": "不支持下水试用",
- "硬度": "4.5H",
- "包装": "硬纸筒包装"
+ "规格": "一寸 25×35mm、二寸 35×49mm,可按考试或办证用途排版",
+ "底色": "白底、蓝底、红底都能换",
+ "像素要求": "建议人像清晰、正面免冠,原图不低于 600×800 像素",
+ "工艺": "高清冲印,含裁切排版",
+ "发货时效": "下单后 48 小时内发出,节假日顺延",
+ "包装": "硬卡纸加防水袋包装",
+ "售后-补印": "打印模糊、明显划痕、裁切错误、明显偏色的,凭问题照片核实后免费补印;轻微色差、拍错尺寸或张数不属于质量问题"
}
},
{
"id": 2,
- "name": "汉鼎螺纹钢极轻小综合",
- "aliases": ["螺纹钢极", "小综合竿","鲫鱼竿"],
+ "name": "照片冲印 5寸6寸7寸",
+ "aliases": ["洗照片", "冲印", "5寸照片", "6寸照片"],
"attributes": {
- "品牌": "汉鼎",
- "适用": "台钓、鲫鱼",
- "售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
- "赠品": "无备用竿稍,无赠品",
- "售后-退货": "不支持下水试用",
- "硬度": "3.5H",
- "包装": "硬纸筒包装"
+ "规格": "5寸 89×127mm、6寸 102×152mm、7寸 127×178mm",
+ "相纸": "富士、柯达相纸,光面与绒面可选",
+ "像素要求": "5寸建议不低于 1280×960,6寸不低于 1440×1080",
+ "工艺": "原图调色后冲印,可按需留白边",
+ "发货时效": "下单后 48 小时内发出,节假日顺延",
+ "包装": "防水袋加硬纸板,避免折痕",
+ "售后-补印": "打印模糊、明显划痕、裁切错误、明显偏色的,凭问题照片核实后免费补印;轻微色差、拍错尺寸或张数不属于质量问题"
}
- }
- ,
- {
+ },
+ {
"id": 3,
- "name": "烈火战马pro湖库野钓杆",
- "aliases": ["湖库", "小综合竿"],
+ "name": "照片书 相册定制",
+ "aliases": ["照片书", "相册", "DIY相册", "纪念册"],
"attributes": {
- "品牌": "烈火战马",
- "适用": "台钓、黑坑",
- "售后-配节": "本店旗舰店皆可售后,凭竿身电子保卡条形码可以免费配一节,手把除外;后续配节成本价10-30一节越粗越贵,手把60;运费15一次(包含首次)",
- "赠品": "无备用竿稍,无赠品",
- "硬度": "4H",
- "售后-退货": "不支持下水试用",
- "包装": "礼盒包装"
+ "规格": "软壳、硬壳,常规 20 页 / 30 页",
+ "容量": "按每页 2 张估算,20 页约 40 张,30 页约 60 张",
+ "工艺": "高清印刷,内页覆膜,可协助排版",
+ "制作周期": "下单后 3-5 天制作,制作完成后 48 小时内发出",
+ "包装": "气泡袋加纸箱",
+ "售后-补印": "印刷漏页、装订错位、明显印刷瑕疵的,凭照片核实后免费重做;轻微色差和买家确认过的排版不在重做范围"
}
- }
- ,
+ },
{
"id": 4,
- "name": "汉鼎螺纹钢宗综合杆",
- "aliases": ["螺纹钢宗", "综合竿"],
+ "name": "海报写真打印 A4A3",
+ "aliases": ["海报", "写真", "A3打印", "A4打印"],
"attributes": {
- "品牌": "汉鼎",
- "适用": "台钓、鲫鱼",
- "售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
- "赠品": "无备用竿稍,无赠品",
- "售后-退货": "不支持下水试用",
- "硬度": "4.5H",
- "包装": "硬纸筒包装"
+ "规格": "A4、A3、A2,可按需裁切",
+ "工艺": "写真机打印,可选覆膜",
+ "像素要求": "原图建议 300dpi,尺寸越大越需要高清原图",
+ "发货时效": "下单后 48 小时内发出,节假日顺延",
+ "包装": "卷筒或硬纸板平铺包装",
+ "售后-补印": "打印模糊、明显划痕、裁切错误、明显偏色的,凭问题照片核实后免费补印;轻微色差、拍错尺寸或张数不属于质量问题"
}
- }
- ,
+ },
{
- "id": 4,
- "name": "汉鼎卓越小综合",
- "aliases": ["小综合", "螺纹钢卓越"],
+ "id": 5,
+ "name": "照片塑封 过塑",
+ "aliases": ["塑封", "过塑", "过胶", "封膜"],
"attributes": {
- "品牌": "汉鼎",
- "售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
- "赠品": "带备用竿稍,无其他赠品",
- "售后-退货": "不支持下水试用",
- "硬度": "3.5H",
- "包装": "硬纸筒包装"
+ "规格": "5寸、6寸、7寸、A4 均可塑封",
+ "工艺": "热压过塑,可选圆角",
+ "效果": "防水、防折、表面耐刮",
+ "发货时效": "下单后 48 小时内发出,节假日顺延",
+ "包装": "防水袋加硬纸板",
+ "售后-补印": "打印模糊、明显划痕、裁切错误、明显偏色的,凭问题照片核实后免费补印;轻微色差、拍错尺寸或张数不属于质量问题"
}
}
]
diff --git a/config/system-prompt.md b/config/system-prompt.md
index 55461c3..e6b6e2e 100644
--- a/config/system-prompt.md
+++ b/config/system-prompt.md
@@ -1,5 +1,4 @@
-你是一个专业的拼多多商家后台的客服,你经营的店铺主营渔具,你了解汉鼎、烈火战马等钓竿的各个型号的详细信息。你是资深钓鱼玩家,懂得钓鱼专业术语。你必须基于商品配置、FAQ、真实对话示例和聊天上下文回复,不可虚构参数。
-
+你是一个专业的拼多多商家后台的客服,你经营的店铺是一家照片打印店,主营证件照打印、照片冲印、照片书相册、海报写真和照片塑封。你熟悉常见尺寸、相纸、像素要求和冲印工艺。你必须基于商品配置、知识库、真实对话示例和聊天上下文回复,不可虚构参数。
规则:
- 最简短、清晰、准确的话回复,不需要客套,不要有多余的引导词句,减少"哦"等语气词,避免机械感。
@@ -11,4 +10,4 @@
- 只输出最终客服回复,不输出分析过程、JSON、标题或解释。
- 综合上下文,只回复用户的最后一条消息,且不要说之前回复过的话
- 产品参数要有明确依据,要准确,来源必须是官方数据
-- 介绍产品时不要说售后、赠品相关
\ No newline at end of file
+- 介绍产品时不要说售后、赠品相关
diff --git a/config/tone-examples.json b/config/tone-examples.json
index 3bb8b93..9afcf2a 100644
--- a/config/tone-examples.json
+++ b/config/tone-examples.json
@@ -1,86 +1,86 @@
[
{
- "id": "tone-price-001",
- "scene": "买家问售后",
- "customer": "坏了能不能换新的",
- "goodReply": "哥,烈火战马凭竿身电子保卡条形码可以免费配一节,手把除外;后续配节成本价10-30一节越粗越贵,手把60;运费15一次(包含首次)",
- "notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
+ "id": "tone-size-001",
+ "scene": "买家问证件照尺寸",
+ "customer": "一寸二寸都能打吗",
+ "goodReply": "亲,一寸二寸都能打,白底蓝底红底也可以换,您把原图发我,我帮您排版好再印。",
+ "notes": "证件照按用途排版,先确认尺寸和底色。"
},
{
- "id": "tone-price-002",
- "scene": "买家问售后",
- "customer": "怎么配节",
- "goodReply": "哥,汉鼎如有损坏,凭照片免费全杆配节,但需要您付10元运费就可以啦",
- "notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
+ "id": "tone-size-002",
+ "scene": "买家问冲印尺寸",
+ "customer": "5寸和6寸差多少",
+ "goodReply": "亲,5寸是89×127mm,6寸是102×152mm,6寸比5寸大一圈,放相册5寸够用,摆台6寸更好看。",
+ "notes": ""
},
{
- "id": "tone-price-003",
- "scene": "买家问售后",
- "customer": "全国门店免费配节吗",
- "goodReply": "哥,汉鼎的售后找本店,凭照片免费全杆配节,但需要您付10元运费就可以啦",
- "notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
+ "id": "tone-quality-003",
+ "scene": "买家担心清晰度",
+ "customer": "像素有点低能印清楚吗",
+ "goodReply": "亲,原图越清晰印出来越好,5寸建议不低于1280×960,6寸不低于1440×1080;像素偏低也能印,但放大后可能会虚,您把图发我先帮您看。",
+ "notes": "先看原图再判断,不直接承诺效果。"
},
{
"id": "tone-quality-004",
- "scene": "买家担心真假和质量",
- "customer": "是正品吗",
- "goodReply": "哥,全店所有鱼竿,保证全新正品,防伪可查,假一赔十,您放心,现在就是小店刚开,不赚钱纯用成本价拉新客,全新正品这两点您就放心!",
- "notes": ""
+ "scene": "买家问相纸",
+ "customer": "用的什么相纸",
+ "goodReply": "亲,用的是富士和柯达相纸,光面和绒面都有,光面颜色更亮,绒面不反光也不容易留指纹。",
+ "notes": "按商品配置里实际的相纸品牌回复。"
},
{
- "id": "tone-stock-005",
- "scene": "买家问是否有货",
- "customer": "现在有现货吗",
- "goodReply": "哥,页面能正常下单的一般都有库存,您拍就行哈",
- "notes": ""
+ "id": "tone-quality-005",
+ "scene": "买家问色差",
+ "customer": "印出来会不会偏色",
+ "goodReply": "亲,冲印都会有轻微色差,屏幕和相纸的颜色不会完全一样,我们会按原图调色,偏得明显可以补印。",
+ "notes": "轻微色差属正常,明显偏色核实后补印。"
},
{
"id": "tone-stock-006",
"scene": "买家问发货时间",
"customer": "今天能发吗",
- "goodReply": "哥,今天大概率给您发出,要是仓库忙的实在顾不上,最晚最晚明天提早给您发!",
- "notes": "一般当天12点前下单,大概率当天发,12点后一般第二天发"
+ "goodReply": "亲,现货一般 48 小时内发出,节假日会顺延,急用的话拍前先跟我说一声。",
+ "notes": "下单后48小时内发出,节假日顺延。"
},
{
"id": "tone-stock-007",
- "scene": "买家问运费险",
- "customer": "没有运费险吗",
- "goodReply": "是的哥,现在没有退货包运费,几乎成本价给您发货,就为了新店拉新客,回来的运费成本都包不住哥,但全新正品这方面您就放一百个心!",
- "notes": ""
+ "scene": "买家要加急",
+ "customer": "明天要用能加急吗",
+ "goodReply": "亲,可以帮您加急,拍下后把要用的时间发我,我这边优先安排,具体到达时间以物流为准。",
+ "notes": "加急只优先安排,不承诺物流到达时间。"
},
{
"id": "tone-price-008",
"scene": "买家要优惠",
- "customer": "还能便宜吗",
- "goodReply": "哥,现在的价格已经找不到第二家,新店初开,都是用成本价打销量,一点也不能再优惠啦,请您见谅哈",
- "notes": ""
+ "customer": "洗得多能便宜吗",
+ "goodReply": "亲,价格已经是冲印成本价了,您把张数和尺寸发我,我帮您算总价,能省的都给您省。",
+ "notes": "批量按张数核算,不直接打折。"
},
{
- "id": "tone-price-009",
- "scene": "买家要赠品",
- "customer": "带竿稍吗",
- "goodReply": "新店开张,所有鱼竿都是成本价冲销量,实在没有多余的利润给您赠送东西,抱歉哥",
- "notes": ""
- },
- {
- "id": "tone-quality-10",
- "scene": "买家担心真假和质量",
- "customer": "怎么这么便宜",
- "goodReply": "哥,全店所有鱼竿,保证全新正品,防伪可查,假一赔十,您放心,现在就是小店刚开,不赚钱纯用成本价拉新客,全新正品这两点您就放心!",
- "notes": ""
- },
- {
- "id": "tone-quality-11",
+ "id": "tone-service-009",
"scene": "买家问售后",
- "customer": "能下水吗",
- "goodReply": "不支持哥,新店初开,一分钱不挣就冲销量,全新正品这两点您就放一百个心,有七天无理由退货,您尽管到手查验,但不支持下水哥,拆封退回变二手得倒贴,请您理解哈",
- "notes": "7天无理由退货,但需产品礼盒与杆袋完整,未损坏;竿稍未打结,同时不支持试用;产品不能出现损坏、污染、划痕等"
+ "customer": "印坏了怎么办",
+ "goodReply": "亲,打印模糊、有明显划痕、裁切错或者偏色很明显的,您拍张问题照片发我,核实后免费补印;轻微色差和拍错尺寸这类不算质量问题哈。",
+ "notes": "模糊/划痕/裁切错/明显偏色免费补印,需问题照片;轻微色差、拍错尺寸不补。"
},
{
- "id": "tone-quality-12",
+ "id": "tone-service-010",
+ "scene": "买家问塑封",
+ "customer": "照片能塑封吗",
+ "goodReply": "亲,可以塑封,5寸、6寸、7寸和A4都能做,还能选圆角,塑封后防水不容易折。",
+ "notes": ""
+ },
+ {
+ "id": "tone-service-011",
+ "scene": "买家问相册容量",
+ "customer": "相册能放多少张",
+ "goodReply": "亲,20页的相册大概放40张,30页大概放60张,您把张数发我,我帮您算要多少页。",
+ "notes": "按每页约2张估算。"
+ },
+ {
+ "id": "tone-stock-012",
"scene": "买家问发货地",
"customer": "哪里发货",
- "goodReply": "威海",
- "notes": ""
+ "goodReply": "亲,具体发货地和快递您看下商品页,急用的话我帮您确认能不能加急。",
+ "notes": "发货地按店铺实际填写,不虚构。"
}
]
diff --git a/example/.env.example b/example/.env.example
new file mode 100644
index 0000000..d5323db
--- /dev/null
+++ b/example/.env.example
@@ -0,0 +1,13 @@
+CODEX_API_URL=https://api.openai.com/v1/responses
+CODEX_API_KEY=sk-your-api-key
+CODEX_MODEL=gpt-5.1
+CODEX_CLASSIFIER_MODEL=gpt-4o-mini
+CODEX_API_MODE=responses
+CODEX_PROXY_URL=http://127.0.0.1:7890
+PDD_MAIL_AUTH_CODE=your-smtp-auth-code
+PDD_ASSISTANT_HOST=0.0.0.0
+PDD_CONTROL_TOKEN=your-control-password
+PDD_DAILY_PAUSE_TIME=07:50
+COZE_API_BASE=https://api.coze.cn
+COZE_API_TOKEN=your-coze-service-identity-token
+COZE_BOT_ID=your-coze-bot-id
diff --git a/example/.gitignore b/example/.gitignore
new file mode 100644
index 0000000..da8e5cd
--- /dev/null
+++ b/example/.gitignore
@@ -0,0 +1,13 @@
+node_modules/
+.env
+.env.*
+!.env.example
+*.log
+logs/
+
+# Real deployment secrets and shop-specific credentials.
+config/shops.json
+config/mail.json
+
+# Optional local runtime files.
+*.pid
diff --git a/example/README.md b/example/README.md
new file mode 100644
index 0000000..6341255
--- /dev/null
+++ b/example/README.md
@@ -0,0 +1,544 @@
+# 拼多多商家后台客服回复助手
+
+这是一个本地运行的客服辅助工具,包含两部分:
+
+- `extension/`:Chrome 浏览器插件,运行在拼多多商家后台客服页面中,监听待回复用户、提取聊天记录、回填回复。
+- `server/`:本地 Node.js 服务,接收插件传来的会话,读取商品、FAQ、高危意图、邮件配置,并调用大模型接口或本地兜底规则生成回复。
+
+## 当前行为
+
+- 监听白天的 `ul.five-minute` 待回复列表,也兼容夜间的 `ul.timeout-unreply` 夜间待回复列表。
+- 发现新消息后点击首个可自动处理的用户。
+- 等待 `#msgListContainer` 与 `#replyTextarea` 出现后提取聊天记录,但发送给服务端时只保留 `pid` 商品信息和最近 6 条消息。
+- 发送给本地服务的数据格式为:
+
+```json
+{
+ "pid": "汉鼎螺纹钢极轻小综合鱼竿手杆超轻硬台钓竿 螺纹钢极5.4米",
+ "msgList": [
+ { "usertype": "cus", "msg": "客户的聊天文本" },
+ { "usertype": "sys", "msg": "客服的聊天文本" }
+ ]
+}
+```
+
+- 浏览器插件不再拉取商品库,也不判断商品 ID。
+- 如果历史聊天里有商品卡片,插件会读取最后一个商品卡片上的商品名;如果卡片里有型号/规格,会拼接成 `商品名 + 型号/规格` 放入 `pid`。
+- 如果历史聊天里没有商品卡片,`pid` 为 `0`。
+- 普通会话:
+ - 调试模式:只回填输入框,不自动点击发送。
+ - 自动模式:回填后自动点击发送。
+- 高危会话:
+ - 服务端命中 `config/risk-intents.json` 后不生成回复。
+ - 服务端发送邮件给人工客服。
+ - 插件不会填输入框,也不会点击发送。
+ - 插件会跳过当前需要人工介入的用户,继续监听并处理列表中的其他新消息。
+
+## 启动本地服务
+
+需要 Node.js 18 或更高版本。
+
+在 `D:\code\pdd` 目录运行:
+
+```powershell
+npm start
+```
+
+健康检查:
+
+```text
+http://127.0.0.1:3456/health
+```
+
+服务默认会读取 `config/server.json` 里的监听地址。为了让同一 WiFi 下的 iPhone 能访问控制页,当前配置使用:
+
+```json
+{
+ "host": "0.0.0.0",
+ "port": 3456
+}
+```
+
+启动后控制台会打印局域网地址,例如:
+
+```text
+http://192.168.1.23:3456/control
+```
+
+如果手机打不开,请检查电脑和 iPhone 是否在同一个 WiFi,并允许 Windows 防火墙放行 Node.js 或端口 `3456`。
+
+## 手机暂停/恢复监听
+
+电脑保持本地服务、Chrome 插件、拼多多客服页面都打开。iPhone 连接同一个 WiFi 后,在 Safari 访问服务启动时打印的局域网控制页:
+
+```text
+http://电脑局域网IP:3456/control
+```
+
+页面里有“暂停监听”和“恢复监听”两个按钮。浏览器插件会每 1.5 秒同步一次手机端状态;插件面板里的暂停/恢复按钮仍然会本地立即生效,并异步同步给手机控制页。
+
+如果配置了多家店铺,手机控制页会按多行展示:
+
+```text
+汉鼎主店 监听中 [暂停监听] [恢复监听]
+烈火战马店 已暂停 [暂停监听] [恢复监听]
+```
+
+可选:如果想给手机控制页加密码,在 `.env` 或 `config/server.json` 里设置:
+
+```text
+PDD_CONTROL_TOKEN=你的控制密码
+```
+
+然后手机访问:
+
+```text
+http://电脑局域网IP:3456/control?token=你的控制密码
+```
+
+## 安装浏览器插件
+
+1. 打开 Chrome 扩展管理页:
+
+```text
+chrome://extensions/
+```
+
+2. 打开“开发者模式”。
+3. 点击“加载已解压的扩展程序”。
+4. 选择:
+
+```text
+D:\code\pdd\extension
+```
+
+5. 回到拼多多客服页面并刷新。
+
+## 多店铺配置
+
+服务端店铺配置文件:
+
+```text
+D:\code\pdd\config\shops.json
+```
+
+示例:
+
+```json
+[
+ {
+ "id": "handing-main",
+ "name": "汉鼎主店",
+ "pluginToken": "9f8f2f5b60d04e11a4e7b43d7a8f3c91",
+ "cozeApiBase": "https://api.coze.cn",
+ "cozeApiToken": "扣子服务身份凭证",
+ "cozeApiTokenEnv": "",
+ "cozeBotId": "扣子智能体ID"
+ },
+ {
+ "id": "liehuo-main",
+ "name": "烈火战马店",
+ "pluginToken": "2f80ab0936914e12a1ef90e2b24f16c8",
+ "cozeApiBase": "https://api.coze.cn",
+ "cozeApiToken": "扣子服务身份凭证",
+ "cozeApiTokenEnv": "",
+ "cozeBotId": "扣子智能体ID"
+ }
+]
+```
+
+`pluginToken` 是你自己设置的店铺访问密码。可以用 PowerShell 生成:
+
+```powershell
+[guid]::NewGuid().ToString("N")
+```
+
+每个 Chrome 用户资料夹登录一个拼多多店铺,并在插件面板点击“配置”,分别填写:
+
+```text
+服务地址:http://127.0.0.1:3456
+店铺ID:handing-main
+店铺名:汉鼎主店
+店铺Token:shops.json 里 handing-main 对应的 pluginToken
+```
+
+迁移到云服务器后,服务地址改成你的云端地址,例如:
+
+```text
+https://pdd-ai.example.com
+```
+
+插件每次请求都会带 `shopId` 和店铺 Token。服务端会校验通过后,才允许该插件读取对应店铺的控制状态或调用回复接口。
+
+普通售前回复会优先调用店铺对应的 Coze 智能体。推荐不要把真实 Coze Token 直接写进仓库,可以使用环境变量:
+
+```json
+{
+ "id": "handing-main",
+ "name": "汉鼎主店",
+ "pluginToken": "店铺Token",
+ "cozeApiBase": "https://api.coze.cn",
+ "cozeApiTokenEnv": "COZE_TOKEN_HANDING",
+ "cozeBotId": "扣子智能体ID"
+}
+```
+
+启动服务前设置:
+
+```powershell
+$env:COZE_TOKEN_HANDING="你的扣子服务身份凭证"
+npm start
+```
+
+如果 `cozeApiToken/cozeApiTokenEnv/cozeBotId` 没有配置完整,服务端会回退到原来的模型接口或本地兜底回复。
+
+## 每日自动关闭监听
+
+服务端会在每天 `07:50` 自动把所有店铺切换为暂停监听。配置位置:
+
+```text
+D:\code\pdd\config\server.json
+```
+
+```json
+{
+ "dailyPauseTime": "07:50"
+}
+```
+
+也可以用环境变量覆盖:
+
+```text
+PDD_DAILY_PAUSE_TIME=07:50
+```
+
+注意:这个时间使用服务器本地时区。部署到 Ubuntu 后建议设置为上海时区:
+
+```bash
+sudo timedatectl set-timezone Asia/Shanghai
+timedatectl
+```
+
+## 邮件配置
+
+邮件配置文件:
+
+```text
+D:\code\pdd\config\mail.json
+```
+
+默认不会发送邮件。启用时把 `enabled` 改为 `true`,并设置收件人:
+
+```json
+{
+ "enabled": true,
+ "provider": "qq",
+ "host": "smtp.qq.com",
+ "port": 465,
+ "secure": true,
+ "startTls": false,
+ "user": "your-email@qq.com",
+ "authCodeEnv": "PDD_MAIL_AUTH_CODE",
+ "from": "your-email@qq.com",
+ "senderName": "PDD客服助手",
+ "to": ["owner@example.com"],
+ "subjectPrefix": "[PDD客服高危会话]",
+ "dedupMs": 600000
+}
+```
+
+推荐用环境变量保存邮箱 SMTP 授权码:
+
+```powershell
+$env:PDD_MAIL_AUTH_CODE="你的邮箱SMTP授权码"
+npm start
+```
+
+更多示例见 [docs/email-config.md](D:/code/pdd/docs/email-config.md)。
+
+## 商品配置
+
+编辑 `config/products.json`:
+
+```json
+[
+ {
+ "id": 1,
+ "name": "商品完整标题",
+ "aliases": ["短名称", "关键词", "页面卡片可能出现的词"],
+ "attributes": {
+ "品牌": "品牌名",
+ "售后": "按店铺页面与平台规则执行"
+ }
+ }
+]
+```
+
+商品配置现在由服务端传给大模型作为商品知识,不再由浏览器插件读取。配置变更后,重启本地服务。
+
+## FAQ配置
+
+编辑 `config/faq.json`:
+
+```json
+[
+ {
+ "id": "price-001",
+ "productId": 1,
+ "keywords": ["便宜", "优惠", "少点"],
+ "answer": "您好,{{商品名}}目前按页面活动价为准,能用的优惠会在下单页自动抵扣。"
+ }
+]
+```
+
+`productId` 可选。不填时表示通用 FAQ。
+
+## 真实对话与语气示例
+
+把真实客服对话、希望模型学习的表达风格放在:
+
+```text
+D:\code\pdd\config\tone-examples.json
+```
+
+示例:
+
+```json
+[
+ {
+ "id": "tone-price-001",
+ "scene": "买家问能否便宜",
+ "customer": "这个还能便宜点吗",
+ "goodReply": "您好,目前就是页面活动价,能用的优惠会在下单页自动抵扣,您可以放心拍。",
+ "notes": "语气自然,不承诺额外优惠。"
+ }
+]
+```
+
+这些不是训练数据上传,而是每次请求时作为参考样例传给大模型。建议放 10 到 30 条高质量示例,覆盖常见场景。
+
+## 全局回复规则
+
+编辑:
+
+```text
+D:\code\pdd\config\reply-guidelines.md
+```
+
+这里适合写全局语气要求、禁用话术、平台规则边界、售后表达规范等。
+
+## 高危意图配置
+
+编辑 `config/risk-intents.json`:
+
+```json
+[
+ {
+ "name": "平台外交易",
+ "keywords": ["微信", "vx", "qq", "支付宝", "私下"]
+ }
+]
+```
+
+命中后不会发送 `reply`,而是返回:
+
+```json
+{
+ "action": "manual",
+ "manualRequired": true,
+ "reply": "",
+ "riskIntents": ["平台外交易"]
+}
+```
+
+## 人工接手白名单
+
+编辑:
+
+```text
+D:\code\pdd\config\manual-handoff-whitelist.json
+```
+
+示例:
+
+```json
+[
+ {
+ "name": "退款退货",
+ "semantics": "买家表达退款、退货、退换货、取消订单、仅退款、退差价等诉求。",
+ "keywords": ["退款", "退货", "退换", "仅退款", "退差价", "取消订单"]
+ },
+ {
+ "name": "商品损坏",
+ "semantics": "买家表示商品坏了、断了、裂了、破损、不能用、收到后有问题。",
+ "keywords": ["坏了", "断了", "裂了", "破损", "不能用", "有问题"]
+ }
+]
+```
+
+服务端会先用现有高危意图规则兜底,然后调用大模型根据上下文判断是否命中人工接手白名单。命中后:
+
+- 不生成回复。
+- 不回填输入框。
+- 复用 `config/mail.json` 发送邮件。
+- 插件继续监听其他新消息。
+
+如果模型分类失败,但最近客户消息明显命中 `keywords`,服务端会用关键词兜底转人工。
+
+## 快捷固定回复
+
+编辑:
+
+```text
+D:\code\pdd\config\quick-replies.json
+```
+
+当前内置:
+
+```json
+[
+ {
+ "name": "问候",
+ "match": "exact",
+ "keywords": ["你好", "您好", "在吗", "在"],
+ "reply": "您好,请问有什么需要帮忙的?"
+ },
+ {
+ "name": "确认",
+ "match": "exact",
+ "keywords": ["好的", "行", "ok", "OK", "好"],
+ "reply": "🌹"
+ }
+]
+```
+
+快捷回复在高危判断和大模型调用之前执行,命中后不消耗模型 token。
+
+## 大模型接口配置
+
+默认 `config/server.json` 没有配置模型接口,服务会走本地 FAQ/规则兜底,方便先测试链路。
+
+### 智增增 API
+
+如果使用智增增的 OpenAI 兼容接口,推荐在 `.env` 中配置:
+
+```text
+CODEX_API_URL=https://api.zhizengzeng.com/v1/chat/completions
+ZZZ_API_KEY=你的智增增API Key
+CODEX_MODEL=你在智增增后台可用的模型名
+CODEX_CLASSIFIER_MODEL=你在智增增后台可用的轻量模型名
+CODEX_API_MODE=chat
+```
+
+如果之前为了访问 OpenAI 配过本地代理,但智增增可以直连,可以删除或注释:
+
+```text
+CODEX_PROXY_URL=...
+```
+
+改完后重启本地服务。
+
+### OpenAI API
+
+如果使用 OpenAI Responses API,可设置:
+
+```powershell
+$env:CODEX_API_URL="https://api.openai.com/v1/responses"
+$env:CODEX_API_KEY="你的OpenAI API Key"
+$env:CODEX_MODEL="gpt-5.1"
+$env:CODEX_API_MODE="responses"
+npm start
+```
+
+也可以把这些变量写到项目根目录的 `.env` 文件里,服务启动时会自动读取:
+
+```text
+CODEX_API_URL=https://api.openai.com/v1/responses
+CODEX_API_KEY=你的OpenAI API Key
+CODEX_MODEL=gpt-5.1
+CODEX_CLASSIFIER_MODEL=gpt-4o-mini
+CODEX_API_MODE=responses
+# 如果你的电脑需要通过本地代理访问 OpenAI,例如 Clash 常见端口 7890,可加:
+# CODEX_PROXY_URL=http://127.0.0.1:7890
+```
+
+或者编辑 `config/server.json`:
+
+```json
+{
+ "port": 3456,
+ "apiMode": "responses",
+ "codexApiUrl": "https://api.openai.com/v1/responses",
+ "codexModel": "gpt-5.1",
+ "mockWhenNoApiKey": true,
+ "modelTimeoutMs": 45000
+}
+```
+
+说明:
+
+- `CODEX_API_URL` 是模型接口地址。
+- `CODEX_API_KEY` 是接口密钥。
+- `CODEX_MODEL` 是模型名称。
+- `CODEX_API_MODE=responses` 会发送 `{ model, input: [...] }` 格式。
+- 当前变量名保留 `CODEX_` 是为了兼容你最初说的 Codex/API 服务;接 OpenAI API 时同样可用。
+
+## 页面选择器
+
+当前插件使用的关键页面结构:
+
+```js
+urgentLists: ["ul.five-minute", "ul.timeout-unreply"]
+messageList: "#msgListContainer"
+replyTextarea: "#replyTextarea"
+sendButton: ".send-btn"
+```
+
+如果拼多多页面结构变化,优先修改 `extension/content.js` 顶部的 `selectors`。
+
+## 建议流程
+
+1. 先不配置大模型,只启动本地服务,确认插件能监听、提取、回填。
+2. 配好商品、FAQ、高危意图。
+3. 开启邮件配置,测试高危会话是否能收到邮件。
+4. 接入大模型接口。
+5. 先用调试模式观察回复质量,再切换自动模式。
+
+## Token成本优化
+
+服务端不会再把所有配置每次都发给大模型,而是先在本地检索和裁剪:
+
+- 商品资料:只传和 `pid` 最相关的前 3 个商品候选。
+- FAQ:只传和最近消息、商品信息相关的前 5 条。
+- 真实语气示例:只传最相关的前 3 条。
+- 全局回复规则:默认最多传 1200 个字符。
+- 高危意图:回复模型只接收规则名称,不接收完整配置。
+- 邮件配置:不会传给回复模型。
+- 人工接手分类:本地明确命中关键词就直接转人工;命中排除词就直接放行;只有模糊场景才调用分类模型。
+
+这些数量可在 `config/server.json` 中调整:
+
+```json
+{
+ "manualHandoffClassifierMode": "ambiguous",
+ "maxProductCandidates": 3,
+ "maxFaqItems": 5,
+ "maxToneExamples": 3,
+ "maxReplyGuidelinesChars": 1200,
+ "minReplyDelayMs": 3000
+}
+```
+
+`minReplyDelayMs` 会让服务端从收到请求开始至少等待指定毫秒数再返回回复,默认 3000,降低机器感。
+
+`manualHandoffClassifierMode` 可选:
+
+- `ambiguous`:默认,只在模糊人工接手场景调用分类模型。
+- `always`:每次都调用分类模型,判断更细但更费 token。
+- `off`:完全关闭分类模型,只使用本地关键词和排除词。
+
+服务端日志会打印每次发给回复模型的上下文大小,例如:
+
+```text
+[PDD Assistant] model context ... chars=3500, messages=6, products=2, faq=3, toneExamplesTextChars=260
+```
diff --git a/example/config/faq.json b/example/config/faq.json
new file mode 100644
index 0000000..3c5c191
--- /dev/null
+++ b/example/config/faq.json
@@ -0,0 +1,3 @@
+[
+
+]
diff --git a/example/config/mail.example.json b/example/config/mail.example.json
new file mode 100644
index 0000000..f96e127
--- /dev/null
+++ b/example/config/mail.example.json
@@ -0,0 +1,18 @@
+{
+ "enabled": true,
+ "provider": "qq",
+ "host": "smtp.qq.com",
+ "port": 465,
+ "secure": true,
+ "startTls": false,
+ "rejectUnauthorized": true,
+ "user": "your-email@qq.com",
+ "authCodeEnv": "PDD_MAIL_AUTH_CODE",
+ "authCode": "",
+ "from": "your-email@qq.com",
+ "senderName": "PDD客服助手",
+ "to": ["owner@example.com"],
+ "cc": [],
+ "subjectPrefix": "[PDD客服会话,需人工处理]",
+ "dedupMs": 600000
+}
diff --git a/example/config/manual-handoff-whitelist.json b/example/config/manual-handoff-whitelist.json
new file mode 100644
index 0000000..055c8ee
--- /dev/null
+++ b/example/config/manual-handoff-whitelist.json
@@ -0,0 +1,20 @@
+[
+ {
+ "name": "退款退货",
+ "semantics": "买家表达退款、退货、退换货、取消订单、仅退款、退差价等诉求。",
+ "keywords": ["补发", "漏发", "没发","退款", "退货", "退换", "仅退款", "退差价", "取消订单"],
+ "excludeKeywords": ["退货规则怎么写", "七天无理由吗"]
+ },
+ {
+ "name": "商品损坏",
+ "semantics": "买家表示已收到或已使用的商品坏了、断了、裂了、破损、不能用、收到后有问题。",
+ "keywords": ["坏了", "断了", "裂了", "破损", "不能用", "有问题"],
+ "excludeKeywords": ["容易坏吗", "会不会断", "结实吗", "耐用吗"]
+ },
+ {
+ "name": "物流异常",
+ "semantics": "买家表达没收到、丢件、物流停滞、拒收、地址异常等需要人工核实的情况。",
+ "keywords": ["没收到", "丢件", "物流不动", "拒收", "地址错了"],
+ "excludeKeywords": ["多久到", "什么时候发", "发什么快递"]
+ }
+]
diff --git a/example/config/products.json b/example/config/products.json
new file mode 100644
index 0000000..07aa278
--- /dev/null
+++ b/example/config/products.json
@@ -0,0 +1,74 @@
+[
+ {
+ "id": 1,
+ "name": "汉鼎螺纹钢鲢鳙",
+ "aliases": ["螺纹钢鲢","鲢鳙杆"],
+ "attributes": {
+ "品牌": "汉鼎",
+ "适用": "台钓、黑坑、鲢鳙杆",
+ "售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
+ "赠品": "无备用竿稍,无赠品",
+ "售后-退货": "不支持下水试用",
+ "硬度": "4.5H",
+ "包装": "硬纸筒包装"
+ }
+ },
+ {
+ "id": 2,
+ "name": "汉鼎螺纹钢极轻小综合",
+ "aliases": ["螺纹钢极", "小综合竿","鲫鱼竿"],
+ "attributes": {
+ "品牌": "汉鼎",
+ "适用": "台钓、鲫鱼",
+ "售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
+ "赠品": "无备用竿稍,无赠品",
+ "售后-退货": "不支持下水试用",
+ "硬度": "3.5H",
+ "包装": "硬纸筒包装"
+ }
+ }
+ ,
+ {
+ "id": 3,
+ "name": "烈火战马pro湖库野钓杆",
+ "aliases": ["湖库", "小综合竿"],
+ "attributes": {
+ "品牌": "烈火战马",
+ "适用": "台钓、黑坑",
+ "售后-配节": "本店旗舰店皆可售后,凭竿身电子保卡条形码可以免费配一节,手把除外;后续配节成本价10-30一节越粗越贵,手把60;运费15一次(包含首次)",
+ "赠品": "无备用竿稍,无赠品",
+ "硬度": "4H",
+ "售后-退货": "不支持下水试用",
+ "包装": "礼盒包装"
+ }
+ }
+ ,
+ {
+ "id": 4,
+ "name": "汉鼎螺纹钢宗综合杆",
+ "aliases": ["螺纹钢宗", "综合竿"],
+ "attributes": {
+ "品牌": "汉鼎",
+ "适用": "台钓、鲫鱼",
+ "售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
+ "赠品": "无备用竿稍,无赠品",
+ "售后-退货": "不支持下水试用",
+ "硬度": "4.5H",
+ "包装": "硬纸筒包装"
+ }
+ }
+ ,
+ {
+ "id": 4,
+ "name": "汉鼎卓越小综合",
+ "aliases": ["小综合", "螺纹钢卓越"],
+ "attributes": {
+ "品牌": "汉鼎",
+ "售后-配节": "找本店售后,如有损坏,凭照片免费全杆配节,但需要用户付10元运费",
+ "赠品": "带备用竿稍,无其他赠品",
+ "售后-退货": "不支持下水试用",
+ "硬度": "3.5H",
+ "包装": "硬纸筒包装"
+ }
+ }
+]
diff --git a/example/config/quick-replies.json b/example/config/quick-replies.json
new file mode 100644
index 0000000..45be768
--- /dev/null
+++ b/example/config/quick-replies.json
@@ -0,0 +1,14 @@
+[
+ {
+ "name": "问候",
+ "match": "exact",
+ "keywords": ["你好", "您好", "在吗", "在"],
+ "reply": "您好,请问有什么需要帮忙的?"
+ },
+ {
+ "name": "确认",
+ "match": "exact",
+ "keywords": ["好的", "行", "ok", "OK", "好","👌","哦","噢","嗯","恩","en"],
+ "reply": "🌹🌹🌹"
+ }
+]
diff --git a/example/config/risk-intents.json b/example/config/risk-intents.json
new file mode 100644
index 0000000..3168e93
--- /dev/null
+++ b/example/config/risk-intents.json
@@ -0,0 +1,22 @@
+[
+ {
+ "name": "平台外交易",
+ "keywords": ["微信", "vx", "qq", "支付宝", "转账", "加我", "私下", "线下交易"],
+ "reply": "您好,为保障您的权益,请您通过平台内正常下单和沟通,我这边不能引导平台外交易。"
+ },
+ {
+ "name": "辱骂争议",
+ "keywords": ["投诉", "举报", "差评", "骗子", "假货", "骂"],
+ "reply": "非常抱歉给您带来不好的体验,我这边先帮您核实订单和问题,请您稍等。"
+ },
+ {
+ "name": "敏感隐私",
+ "keywords": ["手机号", "身份证", "银行卡", "密码", "验证码"],
+ "reply": "您好,为保护您的信息安全,请不要在聊天中发送身份证、银行卡、验证码等敏感信息。"
+ },
+ {
+ "name": "default",
+ "keywords": [],
+ "defaultReply": "您好,这个问题我需要为您转人工进一步核实处理,请您稍等一下。"
+ }
+]
diff --git a/example/config/server.json b/example/config/server.json
new file mode 100644
index 0000000..7b3cd78
--- /dev/null
+++ b/example/config/server.json
@@ -0,0 +1,19 @@
+{
+ "port": 3456,
+ "host": "0.0.0.0",
+ "controlToken": "",
+ "dailyPauseTime": "07:50",
+ "apiMode": "responses",
+ "codexApiUrl": "",
+ "codexModel": "",
+ "classifierModel": "",
+ "manualHandoffClassifierMode": "off",
+ "maxProductCandidates": 3,
+ "maxFaqItems": 5,
+ "maxToneExamples": 3,
+ "maxReplyGuidelinesChars": 1200,
+ "minReplyDelayMs": 3000,
+ "proxyUrl": "",
+ "mockWhenNoApiKey": true,
+ "modelTimeoutMs": 45000
+}
diff --git a/example/config/shops.example.json b/example/config/shops.example.json
new file mode 100644
index 0000000..a0e014f
--- /dev/null
+++ b/example/config/shops.example.json
@@ -0,0 +1,10 @@
+[
+ {
+ "id": "shop-1",
+ "name": "示例店铺",
+ "pluginToken": "replace-with-plugin-token",
+ "cozeApiBase": "https://api.coze.cn",
+ "cozeApiToken": "",
+ "cozeBotId": "replace-with-coze-bot-id"
+ }
+]
diff --git a/example/config/system-prompt.md b/example/config/system-prompt.md
new file mode 100644
index 0000000..55461c3
--- /dev/null
+++ b/example/config/system-prompt.md
@@ -0,0 +1,14 @@
+你是一个专业的拼多多商家后台的客服,你经营的店铺主营渔具,你了解汉鼎、烈火战马等钓竿的各个型号的详细信息。你是资深钓鱼玩家,懂得钓鱼专业术语。你必须基于商品配置、FAQ、真实对话示例和聊天上下文回复,不可虚构参数。
+
+
+规则:
+- 最简短、清晰、准确的话回复,不需要客套,不要有多余的引导词句,减少"哦"等语气词,避免机械感。
+- 不引导平台外交易,不索要敏感信息。
+- toneExamples 是常见问题的标准回答,相似的问题直接把参考答案轻微调整或原样输出。
+- 参考 toneExamples 学习客服语气和表达方式。
+- 商品咨询的问题,参考 toneExamples、商品配置作答。
+- payload.pid 可能是商品卡片上的商品名,也可能是“商品名 + 型号/规格”;请结合商品候选信息判断具体商品。
+- 只输出最终客服回复,不输出分析过程、JSON、标题或解释。
+- 综合上下文,只回复用户的最后一条消息,且不要说之前回复过的话
+- 产品参数要有明确依据,要准确,来源必须是官方数据
+- 介绍产品时不要说售后、赠品相关
\ No newline at end of file
diff --git a/example/config/tone-examples.json b/example/config/tone-examples.json
new file mode 100644
index 0000000..3bb8b93
--- /dev/null
+++ b/example/config/tone-examples.json
@@ -0,0 +1,86 @@
+[
+ {
+ "id": "tone-price-001",
+ "scene": "买家问售后",
+ "customer": "坏了能不能换新的",
+ "goodReply": "哥,烈火战马凭竿身电子保卡条形码可以免费配一节,手把除外;后续配节成本价10-30一节越粗越贵,手把60;运费15一次(包含首次)",
+ "notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
+ },
+ {
+ "id": "tone-price-002",
+ "scene": "买家问售后",
+ "customer": "怎么配节",
+ "goodReply": "哥,汉鼎如有损坏,凭照片免费全杆配节,但需要您付10元运费就可以啦",
+ "notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
+ },
+ {
+ "id": "tone-price-003",
+ "scene": "买家问售后",
+ "customer": "全国门店免费配节吗",
+ "goodReply": "哥,汉鼎的售后找本店,凭照片免费全杆配节,但需要您付10元运费就可以啦",
+ "notes": "具体型号售后不同,找到该型号的售后政策回复用户。"
+ },
+ {
+ "id": "tone-quality-004",
+ "scene": "买家担心真假和质量",
+ "customer": "是正品吗",
+ "goodReply": "哥,全店所有鱼竿,保证全新正品,防伪可查,假一赔十,您放心,现在就是小店刚开,不赚钱纯用成本价拉新客,全新正品这两点您就放心!",
+ "notes": ""
+ },
+ {
+ "id": "tone-stock-005",
+ "scene": "买家问是否有货",
+ "customer": "现在有现货吗",
+ "goodReply": "哥,页面能正常下单的一般都有库存,您拍就行哈",
+ "notes": ""
+ },
+ {
+ "id": "tone-stock-006",
+ "scene": "买家问发货时间",
+ "customer": "今天能发吗",
+ "goodReply": "哥,今天大概率给您发出,要是仓库忙的实在顾不上,最晚最晚明天提早给您发!",
+ "notes": "一般当天12点前下单,大概率当天发,12点后一般第二天发"
+ },
+ {
+ "id": "tone-stock-007",
+ "scene": "买家问运费险",
+ "customer": "没有运费险吗",
+ "goodReply": "是的哥,现在没有退货包运费,几乎成本价给您发货,就为了新店拉新客,回来的运费成本都包不住哥,但全新正品这方面您就放一百个心!",
+ "notes": ""
+ },
+ {
+ "id": "tone-price-008",
+ "scene": "买家要优惠",
+ "customer": "还能便宜吗",
+ "goodReply": "哥,现在的价格已经找不到第二家,新店初开,都是用成本价打销量,一点也不能再优惠啦,请您见谅哈",
+ "notes": ""
+ },
+ {
+ "id": "tone-price-009",
+ "scene": "买家要赠品",
+ "customer": "带竿稍吗",
+ "goodReply": "新店开张,所有鱼竿都是成本价冲销量,实在没有多余的利润给您赠送东西,抱歉哥",
+ "notes": ""
+ },
+ {
+ "id": "tone-quality-10",
+ "scene": "买家担心真假和质量",
+ "customer": "怎么这么便宜",
+ "goodReply": "哥,全店所有鱼竿,保证全新正品,防伪可查,假一赔十,您放心,现在就是小店刚开,不赚钱纯用成本价拉新客,全新正品这两点您就放心!",
+ "notes": ""
+ },
+ {
+ "id": "tone-quality-11",
+ "scene": "买家问售后",
+ "customer": "能下水吗",
+ "goodReply": "不支持哥,新店初开,一分钱不挣就冲销量,全新正品这两点您就放一百个心,有七天无理由退货,您尽管到手查验,但不支持下水哥,拆封退回变二手得倒贴,请您理解哈",
+ "notes": "7天无理由退货,但需产品礼盒与杆袋完整,未损坏;竿稍未打结,同时不支持试用;产品不能出现损坏、污染、划痕等"
+ },
+ {
+ "id": "tone-quality-12",
+ "scene": "买家问发货地",
+ "customer": "哪里发货",
+ "goodReply": "威海",
+ "notes": ""
+ }
+]
diff --git a/example/docs/email-config.md b/example/docs/email-config.md
new file mode 100644
index 0000000..be638df
--- /dev/null
+++ b/example/docs/email-config.md
@@ -0,0 +1,92 @@
+# 邮件配置
+
+高危意图命中后,服务端不会生成客服回复,而是发送邮件提醒人工处理。邮件配置位于:
+
+```text
+D:\code\pdd\config\mail.json
+```
+
+## 推荐配置方式
+
+不要把邮箱授权码直接写进仓库。推荐在 `mail.json` 中保留:
+
+```json
+{
+ "authCodeEnv": "PDD_MAIL_AUTH_CODE",
+ "authCode": ""
+}
+```
+
+启动服务前在 PowerShell 设置授权码:
+
+```powershell
+$env:PDD_MAIL_AUTH_CODE="你的邮箱SMTP授权码"
+npm start
+```
+
+## QQ邮箱示例
+
+```json
+{
+ "enabled": true,
+ "provider": "qq",
+ "host": "smtp.qq.com",
+ "port": 465,
+ "secure": true,
+ "startTls": false,
+ "user": "your-email@qq.com",
+ "authCodeEnv": "PDD_MAIL_AUTH_CODE",
+ "from": "your-email@qq.com",
+ "senderName": "PDD客服助手",
+ "to": ["owner@example.com"],
+ "subjectPrefix": "[PDD客服高危会话]",
+ "dedupMs": 600000
+}
+```
+
+## 163邮箱示例
+
+```json
+{
+ "enabled": true,
+ "provider": "163",
+ "host": "smtp.163.com",
+ "port": 465,
+ "secure": true,
+ "startTls": false,
+ "user": "your-email@163.com",
+ "authCodeEnv": "PDD_MAIL_AUTH_CODE",
+ "from": "your-email@163.com",
+ "senderName": "PDD客服助手",
+ "to": ["owner@example.com"],
+ "subjectPrefix": "[PDD客服高危会话]",
+ "dedupMs": 600000
+}
+```
+
+## Gmail示例
+
+```json
+{
+ "enabled": true,
+ "provider": "gmail",
+ "host": "smtp.gmail.com",
+ "port": 465,
+ "secure": true,
+ "startTls": false,
+ "user": "your-email@gmail.com",
+ "authCodeEnv": "PDD_MAIL_AUTH_CODE",
+ "from": "your-email@gmail.com",
+ "senderName": "PDD客服助手",
+ "to": ["owner@example.com"],
+ "subjectPrefix": "[PDD客服高危会话]",
+ "dedupMs": 600000
+}
+```
+
+说明:
+
+- `enabled`:设为 `true` 后才会发送邮件。
+- `authCodeEnv`:读取邮箱授权码的环境变量名。
+- `dedupMs`:同一高危会话邮件去重时间,默认 10 分钟。
+- 大多数国内邮箱需要先在邮箱设置中开启 SMTP,并生成“授权码”,不是登录密码。
diff --git a/example/docs/git-deploy-centos.md b/example/docs/git-deploy-centos.md
new file mode 100644
index 0000000..e03002a
--- /dev/null
+++ b/example/docs/git-deploy-centos.md
@@ -0,0 +1,99 @@
+# Git 部署到 CentOS
+
+## 1. 本地首次推送
+
+在 Windows PowerShell 中进入项目目录:
+
+```powershell
+cd D:\code\pdd
+git init
+git branch -M main
+git add .
+git status
+git commit -m "Initial pdd assistant"
+git remote add origin https://github.com/octopuszycn-droid/pdd_AI.git
+git push -u origin main
+```
+
+`config/shops.json`、`config/mail.json`、`.env` 不会被提交。真实 Token 和邮箱授权码只放服务器本地。
+
+## 2. 服务器克隆
+
+```bash
+cd /opt
+git clone https://github.com/octopuszycn-droid/pdd_AI.git pdd
+cd /opt/pdd
+```
+
+## 3. 创建真实配置
+
+```bash
+cp config/shops.example.json config/shops.json
+cp config/mail.example.json config/mail.json
+vi config/shops.json
+vi config/mail.json
+```
+
+创建 `.env`:
+
+```bash
+cat > /opt/pdd/.env <<'EOF'
+PDD_ASSISTANT_HOST=0.0.0.0
+PDD_ASSISTANT_PORT=3456
+PDD_DAILY_PAUSE_TIME=07:50
+PDD_CONTROL_TOKEN=replace-with-control-password
+COZE_API_TOKEN=replace-with-coze-service-token
+PDD_MAIL_AUTH_CODE=replace-with-mail-auth-code
+EOF
+
+chmod 600 /opt/pdd/.env
+```
+
+## 4. 启动
+
+```bash
+npm start
+```
+
+后台运行用 systemd:
+
+```bash
+cat > /etc/systemd/system/pdd-assistant.service <<'EOF'
+[Unit]
+Description=PDD Customer Service Reply Assistant
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=simple
+WorkingDirectory=/opt/pdd
+EnvironmentFile=/opt/pdd/.env
+ExecStart=/usr/bin/node /opt/pdd/server/index.js
+Restart=always
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target
+EOF
+
+systemctl daemon-reload
+systemctl enable --now pdd-assistant
+```
+
+## 5. 后续更新
+
+本地提交并推送:
+
+```powershell
+git add .
+git commit -m "Update assistant"
+git push
+```
+
+服务器拉取并重启:
+
+```bash
+cd /opt/pdd
+git pull
+systemctl restart pdd-assistant
+```
diff --git a/example/extension/background.js b/example/extension/background.js
new file mode 100644
index 0000000..e1ec09b
--- /dev/null
+++ b/example/extension/background.js
@@ -0,0 +1,83 @@
+"use strict";
+
+chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
+ if (!message || message.source !== "pdd-reply-assistant") return false;
+ const tabId = sender.tab && sender.tab.id;
+ if (!tabId) {
+ sendResponse({ ok: false, error: "missing-tab-id" });
+ return false;
+ }
+
+ handleTrustedInput(tabId, message)
+ .then((result) => sendResponse(result))
+ .catch((error) => sendResponse({ ok: false, error: error.message || String(error) }));
+ return true;
+});
+
+async function handleTrustedInput(tabId, message) {
+ const target = { tabId };
+ await attachDebugger(target);
+ try {
+ if (message.action === "trusted-click") {
+ const x = Number(message.x);
+ const y = Number(message.y);
+ await sendCommand(target, "Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "none" });
+ await sendCommand(target, "Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "left", clickCount: 1 });
+ await sendCommand(target, "Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "left", clickCount: 1 });
+ return { ok: true };
+ }
+
+ if (message.action === "trusted-insert-text") {
+ await sendCommand(target, "Input.insertText", { text: String(message.text || "") });
+ return { ok: true };
+ }
+
+ if (message.action === "trusted-enter") {
+ await sendCommand(target, "Input.dispatchKeyEvent", {
+ type: "keyDown",
+ key: "Enter",
+ code: "Enter",
+ windowsVirtualKeyCode: 13,
+ nativeVirtualKeyCode: 13
+ });
+ await sendCommand(target, "Input.dispatchKeyEvent", {
+ type: "keyUp",
+ key: "Enter",
+ code: "Enter",
+ windowsVirtualKeyCode: 13,
+ nativeVirtualKeyCode: 13
+ });
+ return { ok: true };
+ }
+
+ return { ok: false, error: "unknown-action" };
+ } finally {
+ await detachDebugger(target);
+ }
+}
+
+function attachDebugger(target) {
+ return new Promise((resolve, reject) => {
+ chrome.debugger.attach(target, "1.3", () => {
+ const error = chrome.runtime.lastError;
+ if (error) reject(new Error(error.message));
+ else resolve();
+ });
+ });
+}
+
+function detachDebugger(target) {
+ return new Promise((resolve) => {
+ chrome.debugger.detach(target, () => resolve());
+ });
+}
+
+function sendCommand(target, method, params) {
+ return new Promise((resolve, reject) => {
+ chrome.debugger.sendCommand(target, method, params, (result) => {
+ const error = chrome.runtime.lastError;
+ if (error) reject(new Error(error.message));
+ else resolve(result);
+ });
+ });
+}
diff --git a/example/extension/content.css b/example/extension/content.css
new file mode 100644
index 0000000..e4a365b
--- /dev/null
+++ b/example/extension/content.css
@@ -0,0 +1,213 @@
+#pdd-reply-assistant-root {
+ --pdd-ra-blue: #3b63f6;
+ --pdd-ra-green: #17a56b;
+ --pdd-ra-red: #d93025;
+ --pdd-ra-text: #1f2937;
+ --pdd-ra-muted: #64748b;
+ --pdd-ra-border: #dbe3ef;
+ --pdd-ra-bg: #ffffff;
+ --pdd-ra-soft: #f6f8fb;
+ color: var(--pdd-ra-text);
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif;
+ font-size: 13px;
+ position: fixed;
+ z-index: 2147483647;
+}
+
+#pdd-reply-assistant-root * {
+ box-sizing: border-box;
+}
+
+.pdd-ra-panel {
+ width: 320px;
+ border: 1px solid var(--pdd-ra-border);
+ border-radius: 8px;
+ background: var(--pdd-ra-bg);
+ box-shadow: 0 12px 34px rgba(15, 23, 42, 0.18);
+ overflow: hidden;
+ user-select: none;
+}
+
+.pdd-ra-header {
+ align-items: center;
+ background: #1f2937;
+ color: #fff;
+ cursor: move;
+ display: flex;
+ gap: 8px;
+ height: 38px;
+ padding: 0 10px;
+}
+
+.pdd-ra-title {
+ flex: 1;
+ font-size: 13px;
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.pdd-ra-status {
+ border-radius: 999px;
+ height: 8px;
+ width: 8px;
+}
+
+.pdd-ra-status.is-idle {
+ background: #94a3b8;
+}
+
+.pdd-ra-status.is-listening {
+ background: var(--pdd-ra-green);
+}
+
+.pdd-ra-status.is-busy {
+ background: #f59e0b;
+}
+
+.pdd-ra-status.is-error {
+ background: var(--pdd-ra-red);
+}
+
+.pdd-ra-icon-btn {
+ align-items: center;
+ background: transparent;
+ border: 0;
+ border-radius: 6px;
+ color: inherit;
+ cursor: pointer;
+ display: inline-flex;
+ font-size: 16px;
+ height: 26px;
+ justify-content: center;
+ padding: 0;
+ width: 26px;
+}
+
+.pdd-ra-icon-btn:hover {
+ background: rgba(255, 255, 255, 0.14);
+}
+
+.pdd-ra-body {
+ padding: 10px;
+}
+
+.pdd-ra-controls {
+ align-items: center;
+ display: grid;
+ gap: 8px;
+ grid-template-columns: 1fr 1fr 1fr;
+}
+
+.pdd-ra-button {
+ align-items: center;
+ border: 1px solid var(--pdd-ra-border);
+ border-radius: 7px;
+ background: var(--pdd-ra-soft);
+ color: var(--pdd-ra-text);
+ cursor: pointer;
+ display: inline-flex;
+ font-size: 13px;
+ font-weight: 600;
+ height: 32px;
+ justify-content: center;
+ padding: 0 10px;
+}
+
+.pdd-ra-button:hover {
+ border-color: #a9b8cf;
+}
+
+.pdd-ra-button.is-primary {
+ background: var(--pdd-ra-blue);
+ border-color: var(--pdd-ra-blue);
+ color: #fff;
+}
+
+.pdd-ra-button.is-paused {
+ background: #fff7ed;
+ border-color: #fdba74;
+ color: #9a3412;
+}
+
+.pdd-ra-config {
+ display: none;
+ gap: 8px;
+ margin-top: 10px;
+}
+
+.pdd-ra-config.is-open {
+ display: grid;
+}
+
+.pdd-ra-field {
+ display: grid;
+ gap: 4px;
+}
+
+.pdd-ra-field span {
+ color: var(--pdd-ra-muted);
+ font-size: 12px;
+}
+
+.pdd-ra-field input {
+ border: 1px solid var(--pdd-ra-border);
+ border-radius: 6px;
+ color: var(--pdd-ra-text);
+ font: inherit;
+ height: 30px;
+ outline: none;
+ padding: 0 8px;
+ user-select: text;
+ width: 100%;
+}
+
+.pdd-ra-field input:focus {
+ border-color: var(--pdd-ra-blue);
+ box-shadow: 0 0 0 2px rgba(59, 99, 246, 0.12);
+}
+
+.pdd-ra-meta {
+ color: var(--pdd-ra-muted);
+ font-size: 12px;
+ line-height: 1.45;
+ margin-top: 8px;
+}
+
+.pdd-ra-log {
+ background: #0f172a;
+ border-radius: 7px;
+ color: #dbeafe;
+ height: 168px;
+ line-height: 1.45;
+ margin-top: 10px;
+ overflow: auto;
+ padding: 8px;
+ user-select: text;
+ white-space: pre-wrap;
+}
+
+.pdd-ra-bubble {
+ align-items: center;
+ background: var(--pdd-ra-blue);
+ border: 2px solid #fff;
+ border-radius: 999px;
+ box-shadow: 0 10px 26px rgba(15, 23, 42, 0.22);
+ color: #fff;
+ cursor: move;
+ display: none;
+ font-size: 14px;
+ font-weight: 700;
+ height: 54px;
+ justify-content: center;
+ width: 54px;
+}
+
+#pdd-reply-assistant-root.is-minimized .pdd-ra-panel {
+ display: none;
+}
+
+#pdd-reply-assistant-root.is-minimized .pdd-ra-bubble {
+ display: flex;
+}
diff --git a/example/extension/content.js b/example/extension/content.js
new file mode 100644
index 0000000..fd3dafd
--- /dev/null
+++ b/example/extension/content.js
@@ -0,0 +1,1516 @@
+(() => {
+ "use strict";
+
+ const DEFAULT_SERVER_BASE = "http://127.0.0.1:3456";
+ const STORE_KEY = "pddReplyAssistantState";
+ const CONTROL_POLL_MS = 1500;
+
+ const selectors = {
+ urgentLists: ["ul.five-minute", "ul.timeout-unreply"],
+ answeredList: "ul.already-unreply",
+ messageList: "#msgListContainer",
+ productCards: ".commonCard, .msg-content.good-card.clearfix",
+ replyTextarea: "#replyTextarea",
+ sendButton: ".send-btn"
+ };
+
+ const state = {
+ mode: "debug",
+ paused: false,
+ minimized: false,
+ configOpen: false,
+ processing: false,
+ serverBase: DEFAULT_SERVER_BASE,
+ shopId: "default",
+ shopName: "默认店铺",
+ shopToken: "",
+ configDraft: {
+ serverBase: DEFAULT_SERVER_BASE,
+ shopId: "default",
+ shopName: "默认店铺",
+ shopToken: ""
+ },
+ observer: null,
+ checkTimer: null,
+ controlTimer: null,
+ controlSyncBlockedUntil: 0,
+ remoteControlReady: false,
+ remoteControlWarningShown: false,
+ runId: 0,
+ activeAbortController: null,
+ manualSendCleanup: null,
+ trustedContextWarningShown: false,
+ position: { right: 18, bottom: 18 },
+ manualConversationKeys: new Set(),
+ cardOnlyConversationKeys: new Set(),
+ logLines: []
+ };
+
+ const ui = {
+ root: null,
+ panel: null,
+ bubble: null,
+ status: null,
+ modeBtn: null,
+ pauseBtn: null,
+ configBtn: null,
+ configPanel: null,
+ serverInput: null,
+ shopIdInput: null,
+ shopNameInput: null,
+ shopTokenInput: null,
+ saveConfigBtn: null,
+ meta: null,
+ log: null
+ };
+
+ const dragState = {
+ active: false,
+ dragged: false,
+ startX: 0,
+ startY: 0,
+ startRight: 0,
+ startBottom: 0
+ };
+
+ init();
+
+ async function init() {
+ loadState();
+ resetConfigDraftFromState();
+ buildWidget();
+ renderWidget();
+ startWatching();
+ startRemoteControlPolling();
+ log("助手已启动,正在监听新会话。");
+ }
+
+ function loadState() {
+ try {
+ const raw = localStorage.getItem(STORE_KEY);
+ if (!raw) return;
+ const saved = JSON.parse(raw);
+ if (saved.mode === "debug" || saved.mode === "auto") state.mode = saved.mode;
+ if (typeof saved.paused === "boolean") state.paused = saved.paused;
+ if (typeof saved.minimized === "boolean") state.minimized = saved.minimized;
+ if (typeof saved.configOpen === "boolean") state.configOpen = saved.configOpen;
+ if (saved.position && Number.isFinite(saved.position.right) && Number.isFinite(saved.position.bottom)) {
+ state.position = saved.position;
+ }
+ if (typeof saved.serverBase === "string" && saved.serverBase) {
+ state.serverBase = saved.serverBase.replace(/\/+$/, "");
+ }
+ if (typeof saved.shopId === "string" && saved.shopId) state.shopId = saved.shopId.trim();
+ if (typeof saved.shopName === "string" && saved.shopName) state.shopName = saved.shopName.trim();
+ if (typeof saved.shopToken === "string") state.shopToken = saved.shopToken;
+ } catch (error) {
+ console.warn("[PDD Reply Assistant] failed to load state", error);
+ }
+ }
+
+ function saveState() {
+ localStorage.setItem(
+ STORE_KEY,
+ JSON.stringify({
+ mode: state.mode,
+ paused: state.paused,
+ minimized: state.minimized,
+ configOpen: state.configOpen,
+ position: state.position,
+ serverBase: state.serverBase,
+ shopId: state.shopId,
+ shopName: state.shopName,
+ shopToken: state.shopToken
+ })
+ );
+ }
+
+ function buildWidget() {
+ if (document.getElementById("pdd-reply-assistant-root")) return;
+
+ ui.root = document.createElement("div");
+ ui.root.id = "pdd-reply-assistant-root";
+
+ ui.panel = document.createElement("div");
+ ui.panel.className = "pdd-ra-panel";
+
+ const header = document.createElement("div");
+ header.className = "pdd-ra-header";
+
+ ui.status = document.createElement("span");
+ ui.status.className = "pdd-ra-status is-idle";
+
+ const title = document.createElement("div");
+ title.className = "pdd-ra-title";
+ title.textContent = "PDD客服回复助手";
+
+ const minBtn = document.createElement("button");
+ minBtn.className = "pdd-ra-icon-btn";
+ minBtn.type = "button";
+ minBtn.title = "最小化";
+ minBtn.textContent = "-";
+ minBtn.addEventListener("click", (event) => {
+ event.stopPropagation();
+ state.minimized = true;
+ saveState();
+ renderWidget();
+ });
+
+ header.append(ui.status, title, minBtn);
+
+ const body = document.createElement("div");
+ body.className = "pdd-ra-body";
+
+ const controls = document.createElement("div");
+ controls.className = "pdd-ra-controls";
+
+ ui.modeBtn = document.createElement("button");
+ ui.modeBtn.className = "pdd-ra-button is-primary";
+ ui.modeBtn.type = "button";
+ ui.modeBtn.addEventListener("click", () => {
+ state.mode = state.mode === "debug" ? "auto" : "debug";
+ saveState();
+ renderWidget();
+ log(`已切换为${state.mode === "debug" ? "调试模式" : "自动模式"}。`);
+ });
+
+ ui.pauseBtn = document.createElement("button");
+ ui.pauseBtn.className = "pdd-ra-button";
+ ui.pauseBtn.type = "button";
+ ui.pauseBtn.addEventListener("click", () => {
+ const nextPaused = !state.paused;
+ setPausedState(
+ nextPaused,
+ nextPaused ? "已暂停监听,当前未完成的回复任务已取消。" : "已恢复监听。",
+ { sync: true, source: "browser-panel" }
+ );
+ });
+
+ ui.configBtn = document.createElement("button");
+ ui.configBtn.className = "pdd-ra-button";
+ ui.configBtn.type = "button";
+ ui.configBtn.addEventListener("click", () => {
+ const nextOpen = !state.configOpen;
+ if (nextOpen) resetConfigDraftFromState();
+ state.configOpen = nextOpen;
+ saveState();
+ renderWidget();
+ });
+
+ controls.append(ui.modeBtn, ui.pauseBtn, ui.configBtn);
+
+ ui.configPanel = document.createElement("div");
+ ui.configPanel.className = "pdd-ra-config";
+
+ ui.serverInput = createConfigInput("服务地址", "http://127.0.0.1:3456", "text", "serverBase");
+ ui.shopIdInput = createConfigInput("店铺ID", "handing-main", "text", "shopId");
+ ui.shopNameInput = createConfigInput("店铺名", "汉鼎主店", "text", "shopName");
+ ui.shopTokenInput = createConfigInput("店铺Token", "与服务端 shops.json 一致", "password", "shopToken");
+
+ ui.saveConfigBtn = document.createElement("button");
+ ui.saveConfigBtn.className = "pdd-ra-button is-primary";
+ ui.saveConfigBtn.type = "button";
+ ui.saveConfigBtn.textContent = "保存配置";
+ ui.saveConfigBtn.addEventListener("click", saveShopConfigFromInputs);
+
+ ui.configPanel.append(
+ ui.serverInput.wrapper,
+ ui.shopIdInput.wrapper,
+ ui.shopNameInput.wrapper,
+ ui.shopTokenInput.wrapper,
+ ui.saveConfigBtn
+ );
+
+ ui.meta = document.createElement("div");
+ ui.meta.className = "pdd-ra-meta";
+
+ ui.log = document.createElement("div");
+ ui.log.className = "pdd-ra-log";
+
+ body.append(controls, ui.configPanel, ui.meta, ui.log);
+ ui.panel.append(header, body);
+
+ ui.bubble = document.createElement("div");
+ ui.bubble.className = "pdd-ra-bubble";
+ ui.bubble.title = "点击恢复";
+ ui.bubble.textContent = "PDD";
+ ui.bubble.addEventListener("click", () => {
+ if (dragState.dragged) return;
+ state.minimized = false;
+ saveState();
+ renderWidget();
+ });
+
+ ui.root.append(ui.panel, ui.bubble);
+ document.documentElement.appendChild(ui.root);
+
+ makeDraggable(header);
+ makeDraggable(ui.bubble);
+ }
+
+ function createConfigInput(labelText, placeholder, type = "text", draftKey = "") {
+ const wrapper = document.createElement("label");
+ wrapper.className = "pdd-ra-field";
+
+ const label = document.createElement("span");
+ label.textContent = labelText;
+
+ const input = document.createElement("input");
+ input.type = type;
+ input.placeholder = placeholder;
+ input.autocomplete = "off";
+ input.addEventListener("input", () => {
+ if (draftKey) state.configDraft[draftKey] = input.value;
+ });
+
+ wrapper.append(label, input);
+ return { wrapper, input };
+ }
+
+ function saveShopConfigFromInputs() {
+ updateConfigDraftFromInputs();
+ const serverBase = normalizeServerBase(state.configDraft.serverBase);
+ const shopId = normalizeConfigValue(state.configDraft.shopId);
+ const shopName = normalizeConfigValue(state.configDraft.shopName) || shopId || "默认店铺";
+ const shopToken = String(state.configDraft.shopToken || "").trim();
+
+ if (!serverBase) {
+ log("配置未保存:服务地址不能为空。");
+ return;
+ }
+ if (!shopId) {
+ log("配置未保存:店铺ID不能为空。");
+ return;
+ }
+
+ state.serverBase = serverBase;
+ state.shopId = shopId;
+ state.shopName = shopName;
+ state.shopToken = shopToken;
+ resetConfigDraftFromState();
+ state.remoteControlReady = false;
+ state.remoteControlWarningShown = false;
+ saveState();
+ renderWidget();
+ log(`已保存店铺配置:${state.shopName}(${state.shopId})。`);
+ syncPauseStateToServer("plugin-config-save");
+ }
+
+ function normalizeServerBase(value) {
+ return String(value || "").trim().replace(/\/+$/, "");
+ }
+
+ function normalizeConfigValue(value) {
+ return String(value || "").trim();
+ }
+
+ function resetConfigDraftFromState() {
+ state.configDraft = {
+ serverBase: state.serverBase,
+ shopId: state.shopId,
+ shopName: state.shopName,
+ shopToken: state.shopToken
+ };
+ }
+
+ function updateConfigDraftFromInputs() {
+ state.configDraft.serverBase = ui.serverInput.input.value;
+ state.configDraft.shopId = ui.shopIdInput.input.value;
+ state.configDraft.shopName = ui.shopNameInput.input.value;
+ state.configDraft.shopToken = ui.shopTokenInput.input.value;
+ }
+
+ function renderWidget() {
+ if (!ui.root) return;
+
+ ui.root.classList.toggle("is-minimized", state.minimized);
+ ui.root.style.right = `${state.position.right}px`;
+ ui.root.style.bottom = `${state.position.bottom}px`;
+
+ ui.modeBtn.textContent = state.mode === "debug" ? "调试模式" : "自动模式";
+ ui.pauseBtn.textContent = state.paused ? "恢复监听" : "暂停监听";
+ ui.pauseBtn.classList.toggle("is-paused", state.paused);
+ ui.configBtn.textContent = state.configOpen ? "收起配置" : "配置";
+ ui.configPanel.classList.toggle("is-open", state.configOpen);
+ syncConfigInputs();
+
+ const statusName = state.processing ? "is-busy" : state.paused ? "is-idle" : "is-listening";
+ ui.status.className = `pdd-ra-status ${statusName}`;
+
+ const controlState = state.remoteControlReady ? "手机控制已连接" : "手机控制未连接";
+ ui.meta.textContent = `店铺:${state.shopName || state.shopId}|服务:${state.serverBase}|${controlState}|商品来源:聊天卡片|人工介入:${state.manualConversationKeys.size}个|${state.processing ? "处理中" : state.paused ? "已暂停" : "监听中"}`;
+ ui.log.textContent = state.logLines.join("\n");
+ ui.log.scrollTop = ui.log.scrollHeight;
+ }
+
+ function syncConfigInputs() {
+ if (!state.configOpen) return;
+ syncInputValue(ui.serverInput.input, state.configDraft.serverBase);
+ syncInputValue(ui.shopIdInput.input, state.configDraft.shopId);
+ syncInputValue(ui.shopNameInput.input, state.configDraft.shopName);
+ syncInputValue(ui.shopTokenInput.input, state.configDraft.shopToken);
+ }
+
+ function syncInputValue(input, value) {
+ if (document.activeElement === input) return;
+ input.value = value || "";
+ }
+
+ function makeDraggable(handle) {
+ handle.addEventListener("mousedown", (event) => {
+ if (event.button !== 0) return;
+ const target = event.target;
+ if (target && target.closest && target.closest("button")) return;
+ dragState.active = true;
+ dragState.dragged = false;
+ dragState.startX = event.clientX;
+ dragState.startY = event.clientY;
+ dragState.startRight = state.position.right;
+ dragState.startBottom = state.position.bottom;
+ event.preventDefault();
+ });
+ }
+
+ document.addEventListener("mousemove", (event) => {
+ if (!dragState.active) return;
+ const dx = event.clientX - dragState.startX;
+ const dy = event.clientY - dragState.startY;
+ if (Math.abs(dx) + Math.abs(dy) > 4) dragState.dragged = true;
+ const rootRect = ui.root.getBoundingClientRect();
+ const maxRight = Math.max(8, window.innerWidth - rootRect.width - 8);
+ const maxBottom = Math.max(8, window.innerHeight - rootRect.height - 8);
+ state.position.right = clamp(dragState.startRight - dx, 8, maxRight);
+ state.position.bottom = clamp(dragState.startBottom - dy, 8, maxBottom);
+ renderWidget();
+ });
+
+ document.addEventListener("mouseup", () => {
+ if (!dragState.active) return;
+ dragState.active = false;
+ saveState();
+ setTimeout(() => {
+ dragState.dragged = false;
+ }, 0);
+ });
+
+ function clamp(value, min, max) {
+ return Math.min(max, Math.max(min, value));
+ }
+
+ function startWatching() {
+ if (state.observer) state.observer.disconnect();
+ state.observer = new MutationObserver(() => scheduleCheck(250));
+ state.observer.observe(document.body, {
+ childList: true,
+ subtree: true,
+ characterData: true
+ });
+ scheduleCheck(300);
+ }
+
+ function startRemoteControlPolling() {
+ if (state.controlTimer) window.clearTimeout(state.controlTimer);
+
+ const poll = async () => {
+ await pollRemoteControlState();
+ state.controlTimer = window.setTimeout(poll, CONTROL_POLL_MS);
+ };
+
+ poll();
+ }
+
+ async function pollRemoteControlState() {
+ try {
+ const response = await fetch(`${state.serverBase}/api/control-state?shopId=${encodeURIComponent(state.shopId || "default")}`, {
+ cache: "no-store",
+ headers: getShopAuthHeaders()
+ });
+ const data = await response.json();
+ if (!response.ok || !data?.ok) {
+ throw new Error(data?.error || `HTTP ${response.status}`);
+ }
+
+ state.remoteControlReady = true;
+ state.remoteControlWarningShown = false;
+ renderWidget();
+
+ if (data.updatedBy === "server-start") {
+ syncPauseStateToServer("plugin-start");
+ return;
+ }
+
+ if (Date.now() < state.controlSyncBlockedUntil) return;
+
+ if (typeof data.paused === "boolean" && data.paused !== state.paused) {
+ setPausedState(
+ data.paused,
+ data.paused ? "手机端已暂停监听,当前未完成的回复任务已取消。" : "手机端已恢复监听。",
+ { sync: false, source: "remote-control" }
+ );
+ }
+ } catch (error) {
+ state.remoteControlReady = false;
+ renderWidget();
+ if (!state.remoteControlWarningShown) {
+ state.remoteControlWarningShown = true;
+ console.warn("[PDD Reply Assistant] remote control unavailable", error);
+ log("手机控制暂不可用,本地面板仍可正常操作。");
+ }
+ }
+ }
+
+ async function syncPauseStateToServer(source) {
+ state.controlSyncBlockedUntil = Date.now() + 2500;
+ try {
+ const response = await fetch(`${state.serverBase}/api/control-state`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...getShopAuthHeaders()
+ },
+ body: JSON.stringify({
+ shopId: state.shopId || "default",
+ paused: state.paused,
+ source
+ })
+ });
+ const data = await response.json();
+ if (!response.ok || !data?.ok) {
+ throw new Error(data?.error || `HTTP ${response.status}`);
+ }
+ state.remoteControlReady = true;
+ state.remoteControlWarningShown = false;
+ renderWidget();
+ } catch (error) {
+ state.remoteControlReady = false;
+ renderWidget();
+ if (!state.remoteControlWarningShown) {
+ state.remoteControlWarningShown = true;
+ console.warn("[PDD Reply Assistant] failed to sync control state", error);
+ log("监听状态未同步到手机控制页,本地操作已生效。");
+ }
+ }
+ }
+
+ function setPausedState(paused, message, options = {}) {
+ const shouldSync = options.sync !== false;
+ const source = options.source || "browser-panel";
+
+ if (state.paused === paused) {
+ if (shouldSync) syncPauseStateToServer(source);
+ return;
+ }
+
+ state.paused = paused;
+ saveState();
+
+ if (paused) {
+ cancelCurrentTask(message || "已暂停监听,当前未完成的回复任务已取消。");
+ } else {
+ log(message || "已恢复监听。");
+ renderWidget();
+ scheduleCheck(100);
+ }
+
+ if (shouldSync) syncPauseStateToServer(source);
+ }
+
+ function scheduleCheck(delay) {
+ if (state.paused) return;
+ if (state.checkTimer) window.clearTimeout(state.checkTimer);
+ state.checkTimer = window.setTimeout(checkForNewConversation, delay);
+ }
+
+ async function checkForNewConversation() {
+ if (state.paused || state.processing) return;
+
+ const row = findFirstUrgentConversation();
+ if (!row) return;
+
+ state.processing = true;
+ const runId = ++state.runId;
+ const abortController = new AbortController();
+ state.activeAbortController = abortController;
+ renderWidget();
+
+ try {
+ log("发现待回复用户,正在打开首个可自动处理的会话。");
+ const beforeChatSignature = getChatSignature();
+ await clickConversation(row);
+ ensureTaskActive(runId);
+ await waitForStableChat(beforeChatSignature, row);
+ ensureTaskActive(runId);
+
+ const payload = buildConversationPayload();
+ if (payload?.skip) {
+ markCardOnlyConversation(row);
+ state.processing = false;
+ if (state.activeAbortController === abortController) state.activeAbortController = null;
+ log("最新一条是商品卡片,暂不回复,等待客户继续发送文字消息。");
+ renderWidget();
+ scheduleCheck(500);
+ return;
+ }
+ log(`已提取历史消息${payload.msgList.length}条。`);
+ printPayloadToDebugConsole(payload);
+
+ const result = await requestReply(payload, abortController.signal);
+ ensureTaskActive(runId);
+ if (isManualRequired(result)) {
+ markManualConversation(row);
+ const names = Array.isArray(result.riskIntents) ? result.riskIntents.join("、") : "未知";
+ const emailState = result.email?.sent ? "邮件已发送" : result.email?.deduped ? "邮件已去重" : "邮件未发送";
+ log(`命中高危意图:${names}。不回复此用户,${emailState},继续监听其他新消息。`);
+ state.processing = false;
+ if (state.activeAbortController === abortController) state.activeAbortController = null;
+ renderWidget();
+ scheduleCheck(300);
+ return;
+ }
+
+ const reply = normalizeText(result.reply || result.message || result.text || "");
+ if (!reply) throw new Error("服务返回内容为空");
+
+ ensureTaskActive(runId);
+ await fillReply(reply);
+ ensureTaskActive(runId);
+ if (state.mode === "auto") {
+ const sent = await sendReplyAndVerify(reply);
+ ensureTaskActive(runId);
+ if (sent) {
+ log("已确认自动发送成功,恢复监听。");
+ state.processing = false;
+ if (state.activeAbortController === abortController) state.activeAbortController = null;
+ renderWidget();
+ scheduleCheck(500);
+ } else {
+ state.processing = false;
+ setErrorStatus();
+ setPausedState(true, "自动发送未确认成功,已暂停监听。请人工检查当前会话,避免重复生成。", {
+ sync: true,
+ source: "auto-send-failed"
+ });
+ }
+ } else {
+ log("已回填回复。当前为调试模式,请人工确认后点击发送。");
+ waitForManualSend();
+ }
+ } catch (error) {
+ if (isTaskCanceled(error)) {
+ state.processing = false;
+ if (state.activeAbortController === abortController) state.activeAbortController = null;
+ log("当前回复任务已取消,不会回填或发送。");
+ renderWidget();
+ return;
+ }
+ state.processing = false;
+ if (state.activeAbortController === abortController) state.activeAbortController = null;
+ setErrorStatus();
+ log(`处理失败:${error.message}`);
+ renderWidget();
+ scheduleCheck(1200);
+ }
+ }
+
+ function cancelCurrentTask(message) {
+ state.runId += 1;
+ if (state.checkTimer) {
+ window.clearTimeout(state.checkTimer);
+ state.checkTimer = null;
+ }
+ if (state.activeAbortController) {
+ state.activeAbortController.abort();
+ state.activeAbortController = null;
+ }
+ if (state.manualSendCleanup) {
+ state.manualSendCleanup();
+ state.manualSendCleanup = null;
+ }
+ state.processing = false;
+ log(message);
+ renderWidget();
+ }
+
+ function ensureTaskActive(runId) {
+ if (state.paused || runId !== state.runId) {
+ const error = new Error("task-canceled");
+ error.name = "AbortError";
+ throw error;
+ }
+ }
+
+ function isTaskCanceled(error) {
+ return error && (error.name === "AbortError" || error.message === "task-canceled");
+ }
+
+ function isManualRequired(result) {
+ return Boolean(result && (result.manualRequired || result.action === "manual"));
+ }
+
+ function findFirstUrgentConversation() {
+ for (const list of getUrgentConversationLists()) {
+ const rows = getConversationRows(list).filter((item) => !isManualConversation(item) && !isCardOnlyConversation(item));
+ if (rows.length) return rows[0];
+
+ const fallbackItems = Array.from(list.children)
+ .filter((item) => isVisible(item) && !isManualConversation(item) && !isCardOnlyConversation(item));
+ if (fallbackItems.length) return fallbackItems[0];
+ }
+
+ return null;
+ }
+
+ function getUrgentConversationLists() {
+ return selectors.urgentLists
+ .flatMap((selector) => Array.from(document.querySelectorAll(selector)))
+ .filter((list) => list && isVisible(list));
+ }
+
+ function getConversationRows(list) {
+ const candidates = [
+ ...Array.from(list.children),
+ ...Array.from(list.querySelectorAll("li, [role='listitem'], [class*='user'], [class*='item'], [class*='session'], [class*='conversation']"))
+ ];
+
+ return Array.from(new Set(candidates)).filter(isConversationRow);
+ }
+
+ function isConversationRow(element) {
+ if (!element || !isVisible(element)) return false;
+ const rect = element.getBoundingClientRect();
+ if (rect.width < 120 || rect.height < 36) return false;
+
+ const text = normalizeText(element.innerText || element.textContent || "");
+ if (!text || /^请\s*\d+\s*分钟内回复$/.test(text)) return false;
+
+ const hasAvatar = Boolean(element.querySelector("img, [class*='avatar'], [class*='head']"));
+ const hasMessageLikeText = /[\u4e00-\u9fa5A-Za-z0-9]/.test(text);
+ return hasAvatar && hasMessageLikeText;
+ }
+
+ function isManualConversation(row) {
+ if (!row) return false;
+ if (row.dataset && row.dataset.pddRaManual === "1") return true;
+ const key = getConversationKey(row);
+ return key ? state.manualConversationKeys.has(key) : false;
+ }
+
+ function markManualConversation(row) {
+ if (!row) return;
+ if (row.dataset) row.dataset.pddRaManual = "1";
+ const key = getConversationKey(row);
+ if (key) state.manualConversationKeys.add(key);
+ }
+
+ function isCardOnlyConversation(row) {
+ if (!row) return false;
+ const key = getCardOnlyConversationKey(row);
+ return key ? state.cardOnlyConversationKeys.has(key) : false;
+ }
+
+ function markCardOnlyConversation(row) {
+ if (!row) return;
+ const key = getCardOnlyConversationKey(row);
+ if (key) state.cardOnlyConversationKeys.add(key);
+ }
+
+ function getCardOnlyConversationKey(row) {
+ const base = getConversationKey(row);
+ const preview = normalizeConversationPreview(row);
+ return base || preview ? `${base}|preview:${preview}` : "";
+ }
+
+ function normalizeConversationPreview(row) {
+ return normalizeText(row.innerText || row.textContent || "")
+ .replace(/\d{1,2}:\d{2}(:\d{2})?/g, "")
+ .replace(/\d+\s*秒后超时/g, "")
+ .replace(/请\s*\d+\s*分钟内回复/g, "")
+ .replace(/夜间待回复/g, "")
+ .replace(/超时/g, "")
+ .replace(/\s+/g, "")
+ .slice(0, 160);
+ }
+
+ function getConversationKey(row) {
+ const attrs = ["data-id", "data-uid", "data-user-id", "data-conversation-id", "data-session-id"];
+ for (const attr of attrs) {
+ const value = row.getAttribute?.(attr);
+ if (value) return `${attr}:${value}`;
+ }
+
+ const imgSrc = row.querySelector?.("img")?.getAttribute("src") || "";
+ const text = normalizeText(row.innerText || row.textContent || "")
+ .replace(/\d{1,2}:\d{2}(:\d{2})?/g, "")
+ .replace(/\d+\s*秒后超时/g, "")
+ .replace(/请\s*\d+\s*分钟内回复/g, "")
+ .replace(/超时/g, "")
+ .replace(/\s+/g, "");
+
+ const stableText = text.slice(0, 120);
+ return stableText || imgSrc ? `${imgSrc}|${stableText}` : "";
+ }
+
+ async function clickConversation(row) {
+ log(`准备点击会话:${normalizeText(row.innerText || row.textContent || "").slice(0, 40)}`);
+ row.scrollIntoView({ block: "center", inline: "nearest" });
+ await sleep(80);
+
+ const targets = getClickTargets(row);
+ for (const target of targets) {
+ dispatchClickSequence(target);
+ await sleep(80);
+ }
+ }
+
+ function getClickTargets(row) {
+ const rect = row.getBoundingClientRect();
+ const centerX = rect.left + rect.width / 2;
+ const centerY = rect.top + rect.height / 2;
+ const pointTarget = document.elementFromPoint(centerX, centerY);
+ const candidates = [
+ row,
+ pointTarget,
+ row.querySelector("[class*='item']"),
+ row.querySelector("[class*='avatar']"),
+ row.querySelector("img"),
+ row.firstElementChild
+ ].filter(Boolean);
+
+ return Array.from(new Set(candidates)).filter((target) => target instanceof Element);
+ }
+
+ function dispatchClickSequence(element) {
+ const rect = element.getBoundingClientRect();
+ const clientX = Math.max(rect.left + 4, rect.left + rect.width / 2);
+ const clientY = Math.max(rect.top + 4, rect.top + rect.height / 2);
+ const eventInit = {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ view: window,
+ clientX,
+ clientY,
+ button: 0,
+ buttons: 1
+ };
+
+ if (typeof PointerEvent === "function") {
+ element.dispatchEvent(new PointerEvent("pointerdown", { ...eventInit, pointerId: 1, pointerType: "mouse" }));
+ }
+ element.dispatchEvent(new MouseEvent("mousedown", eventInit));
+ if (typeof PointerEvent === "function") {
+ element.dispatchEvent(new PointerEvent("pointerup", { ...eventInit, pointerId: 1, pointerType: "mouse", buttons: 0 }));
+ }
+ element.dispatchEvent(new MouseEvent("mouseup", { ...eventInit, buttons: 0 }));
+ element.dispatchEvent(new MouseEvent("click", { ...eventInit, buttons: 0 }));
+ if (typeof element.click === "function") element.click();
+ }
+
+ async function waitForStableChat(beforeChatSignature, row) {
+ await waitForElement(selectors.messageList, 10000);
+ await waitForElement(selectors.replyTextarea, 10000);
+ await waitForChatSwitch(beforeChatSignature, row, 2500);
+ await sleep(700);
+ }
+
+ async function waitForChatSwitch(beforeChatSignature, row, timeout) {
+ const started = Date.now();
+ while (Date.now() - started < timeout) {
+ const currentSignature = getChatSignature();
+ if (!beforeChatSignature || currentSignature !== beforeChatSignature || isSelectedConversation(row)) {
+ return;
+ }
+ await sleep(120);
+ }
+ log("点击后未检测到聊天区明显变化,仍继续尝试提取当前聊天内容。");
+ }
+
+ function getChatSignature() {
+ const root = document.querySelector(selectors.messageList);
+ const textarea = document.querySelector(selectors.replyTextarea);
+ return [
+ normalizeText(root ? root.innerText || root.textContent || "" : "").slice(-1200),
+ normalizeText(textarea ? textarea.value || "" : "")
+ ].join("|");
+ }
+
+ function isSelectedConversation(row) {
+ if (!row) return false;
+ const selectedSelector = ".active, .selected, .current, [aria-selected='true'], [class*='active'], [class*='selected'], [class*='current']";
+ return Boolean(row.matches?.(selectedSelector) || row.querySelector?.(selectedSelector));
+ }
+
+ function waitForElement(selector, timeout) {
+ const started = Date.now();
+ return new Promise((resolve, reject) => {
+ const tick = () => {
+ const element = document.querySelector(selector);
+ if (element && isVisible(element)) {
+ resolve(element);
+ return;
+ }
+ if (Date.now() - started > timeout) {
+ reject(new Error(`未找到页面元素:${selector}`));
+ return;
+ }
+ window.setTimeout(tick, 120);
+ };
+ tick();
+ });
+ }
+
+ function buildConversationPayload() {
+ const messageItems = collectMessageItems();
+ const latestItem = getLatestConversationItem(messageItems);
+ const hasPendingCustomerText = hasPendingCustomerMessage(messageItems);
+
+ if (latestItem?.type === "product-card" && !hasPendingCustomerText) {
+ return {
+ skip: true,
+ reason: "latest-product-card",
+ latestProductCard: latestItem.product
+ };
+ }
+ if (latestItem?.type === "product-card" && hasPendingCustomerText) {
+ log("检测到客户文字后有平台商品卡提醒,继续按客户文字处理。");
+ }
+
+ const latestProductCard = extractLatestProductCardInfo();
+ const msgList = extractMessages(4, messageItems);
+ if (latestProductCard?.message) {
+ msgList.unshift({
+ usertype: "cus",
+ msg: latestProductCard.message
+ });
+ }
+ return {
+ msgList
+ };
+ }
+
+ function hasPendingCustomerMessage(messageItems) {
+ const lastSysIndex = findLastIndex(messageItems, (item) => item.usertype === "sys");
+ return messageItems.slice(lastSysIndex + 1).some((item) => item.usertype === "cus" && item.msg);
+ }
+
+ function findLastIndex(items, predicate) {
+ for (let index = items.length - 1; index >= 0; index -= 1) {
+ if (predicate(items[index], index, items)) return index;
+ }
+ return -1;
+ }
+
+ function getLatestConversationItem(messageItems = collectMessageItems()) {
+ const candidates = [
+ ...getProductCardItems(),
+ ...messageItems.map((item) => ({
+ type: "message",
+ top: item.top,
+ bottom: item.bottom,
+ left: item.left,
+ usertype: item.usertype,
+ msg: item.msg
+ }))
+ ];
+
+ if (!candidates.length) return null;
+ candidates.sort((a, b) => a.bottom - b.bottom || a.top - b.top || a.left - b.left);
+ return candidates[candidates.length - 1];
+ }
+
+ function getProductCardItems() {
+ const root = document.querySelector(selectors.messageList);
+ if (!root) return [];
+
+ return Array.from(root.querySelectorAll(selectors.productCards))
+ .filter((element) => isVisible(element))
+ .map((element) => {
+ const rect = element.getBoundingClientRect();
+ const product = parseProductCardInfo(element);
+ return {
+ type: "product-card",
+ element,
+ top: rect.top,
+ bottom: rect.bottom,
+ left: rect.left,
+ product
+ };
+ })
+ .filter((item) => item.product?.message);
+ }
+
+ function printPayloadToDebugConsole(payload) {
+ const json = JSON.stringify(payload, null, 2);
+ console.groupCollapsed("[PDD客服回复助手] 发送给本地服务的聊天结构");
+ console.log(payload);
+ console.log(json);
+ console.groupEnd();
+ log(`调试台已打印聊天结构:msgList=${payload.msgList.length}条。`);
+ }
+
+ function extractLatestProductCardInfo() {
+ const candidates = getProductCardItems();
+ if (!candidates.length) return null;
+
+ candidates.sort((a, b) => a.top - b.top);
+ const latest = candidates[candidates.length - 1].product;
+ log(`读取到最后一个商品卡片:${latest.message}`);
+ return latest;
+ }
+
+ function isProductCardContainer(element, rootRect) {
+ if (!isVisible(element)) return false;
+ if (!element.querySelector?.("img")) return false;
+
+ const rect = element.getBoundingClientRect();
+ if (rect.width < 180 || rect.width > Math.min(620, rootRect.width * 0.75)) return false;
+ if (rect.height < 56 || rect.height > 260) return false;
+
+ const text = normalizeText(element.innerText || element.textContent || "");
+ if (!text || text.length < 8 || text.length > 900) return false;
+ if (!/商品ID|查看商品规格|咨询商品规格|¥\s*\d+|¥\s*\d+/.test(text)) return false;
+ if (!/[\u4e00-\u9fa5A-Za-z0-9]/.test(text)) return false;
+ return true;
+ }
+
+ function parseProductCardInfo(element) {
+ const lines = normalizeText(element.innerText || element.textContent || "")
+ .split(/\n+/)
+ .map((line) => cleanupProductCardLine(line))
+ .filter(Boolean)
+ .filter((line) => !isProductCardNoiseLine(line));
+
+ const uniqueLines = [];
+ for (const line of lines) {
+ if (!uniqueLines.includes(line)) uniqueLines.push(line);
+ }
+
+ const title = uniqueLines.find((line) => isLikelyProductTitle(line));
+ if (!title) return null;
+
+ const modelLine = uniqueLines.find((line) => line !== title && isLikelyProductModel(line, title));
+ const model = modelLine ? cleanupProductModel(modelLine) : "";
+ const message = model && !title.includes(model)
+ ? `这款${title}的${model}`
+ : `这款${title}`;
+
+ return {
+ name: title,
+ model,
+ message
+ };
+ }
+
+ function parseProductCardText(element) {
+ const info = parseProductCardInfo(element);
+ if (!info) return "";
+ return info.model && !info.name.includes(info.model) ? `${info.name} ${info.model}` : info.name;
+ }
+
+ function cleanupProductCardLine(line) {
+ return normalizeText(line)
+ .replace(/^商品ID[::]?\s*\d+\s*复制?$/i, "")
+ .replace(/^商品ID[::]?\s*/i, "")
+ .replace(/\s+/g, " ")
+ .trim();
+ }
+
+ function isProductCardNoiseLine(line) {
+ if (!line) return true;
+ if (/^复制$/.test(line)) return true;
+ if (/^查看商品规格$/.test(line)) return true;
+ if (/^咨询商品规格$/.test(line)) return true;
+ if (/^当前用户来自/.test(line)) return true;
+ if (/^¥|^¥/.test(line)) return true;
+ if (/^\d+\s*\/\s*\d+人团$/.test(line)) return true;
+ if (/商品ID|下单时间|订单编号|实收|复制|备注/.test(line)) return true;
+ return false;
+ }
+
+ function isLikelyProductTitle(line) {
+ if (line.length < 6) return false;
+ if (/^¥|^¥/.test(line)) return false;
+ if (/^\d/.test(line) && line.length < 12) return false;
+ return /[\u4e00-\u9fa5]/.test(line);
+ }
+
+ function isLikelyProductModel(line, title) {
+ if (!line || line === title) return false;
+ if (line.length > 80) return false;
+ if (/^\(|^(/.test(line)) return false;
+ if (/^\d+\s*\/\s*\d+人团$/.test(line)) return false;
+ if (/¥|¥/.test(line)) return false;
+ if (title.includes(line)) return false;
+ return /\d+(\.\d+)?\s*(米|m|M|号|斤|克|g|G)|规格|型号|颜色|尺码|套餐|单竿|套装/.test(line);
+ }
+
+ function cleanupProductModel(line) {
+ return normalizeText(line)
+ .split(/[((,,]/)[0]
+ .replace(/规格[::]?/g, "")
+ .replace(/型号[::]?/g, "")
+ .trim();
+ }
+
+ function collectMessageItems() {
+ const root = document.querySelector(selectors.messageList);
+ if (!root) return [];
+
+ const rootRect = root.getBoundingClientRect();
+ const all = Array.from(root.querySelectorAll("*"));
+ const raw = [];
+
+ for (const element of all) {
+ if (!isVisible(element)) continue;
+ if (isInsideSpecificProductCard(element)) continue;
+ const text = normalizeText(element.innerText || element.textContent || "");
+ if (!isLikelyChatText(text)) continue;
+ if (hasChildWithSameText(element, text)) continue;
+ if (looksLikeProductCard(element, text)) continue;
+
+ const rect = element.getBoundingClientRect();
+ if (rect.width < 24 || rect.height < 12) continue;
+
+ const centerX = rect.left + rect.width / 2;
+ const rootCenterX = rootRect.left + rootRect.width / 2;
+ const distanceFromCenter = Math.abs(centerX - rootCenterX);
+ if (distanceFromCenter < rootRect.width * 0.08 && text.length < 24) continue;
+
+ raw.push({
+ top: rect.top,
+ bottom: rect.bottom,
+ left: rect.left,
+ usertype: centerX > rootCenterX ? "sys" : "cus",
+ msg: text
+ });
+ }
+
+ raw.sort((a, b) => a.top - b.top || a.left - b.left);
+
+ const deduped = [];
+ for (const item of raw) {
+ const last = deduped[deduped.length - 1];
+ if (last && last.usertype === item.usertype && last.msg === item.msg && Math.abs(last.top - item.top) < 12) {
+ continue;
+ }
+ if (deduped.some((old) => old.usertype === item.usertype && old.msg === item.msg && Math.abs(old.top - item.top) < 24)) {
+ continue;
+ }
+ deduped.push(item);
+ }
+
+ return deduped;
+ }
+
+ function extractMessages(limit = 6, messageItems = collectMessageItems()) {
+ return messageItems.slice(-limit).map(({ usertype, msg }) => ({ usertype, msg }));
+ }
+
+ function isInsideSpecificProductCard(element) {
+ return Boolean(element.closest?.(selectors.productCards));
+ }
+
+ function isLikelyChatText(text) {
+ if (!text) return false;
+ if (text.length > 600) return false;
+ if (/^\d{4}年\d{1,2}月\d{1,2}日/.test(text)) return false;
+ if (/^\d{1,2}:\d{2}(:\d{2})?$/.test(text)) return false;
+ if (/^(未读|已读|来自手机端|主账号|发送)$/.test(text)) return false;
+ if (/当前用户来自/.test(text)) return false;
+ if (/邀请关注|邀请下单|小额打款|小额收款|邀请开票/.test(text)) return false;
+ if (/订单编号|下单时间|实收|复制|备注|催支付/.test(text)) return false;
+ return /[\u4e00-\u9fa5A-Za-z0-9]/.test(text);
+ }
+
+ function looksLikeProductCard(element, text) {
+ if (/¥\s*\d+/.test(text)) return true;
+ if (/商品详情页|购买力|下单数/.test(text)) return true;
+ const imgCount = element.querySelectorAll ? element.querySelectorAll("img").length : 0;
+ return imgCount > 0 && text.length > 12;
+ }
+
+ function hasChildWithSameText(element, text) {
+ return Array.from(element.children || []).some((child) => normalizeText(child.innerText || child.textContent || "") === text);
+ }
+
+ async function requestReply(payload, signal) {
+ const response = await fetch(`${state.serverBase}/api/reply`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...getShopAuthHeaders()
+ },
+ signal,
+ body: JSON.stringify({
+ ...payload,
+ shopId: state.shopId || "default",
+ shopName: state.shopName || state.shopId || "默认店铺"
+ })
+ });
+ if (!response.ok) {
+ const detail = await safeReadText(response);
+ throw new Error(`本地服务返回 ${response.status}${detail ? `:${detail}` : ""}`);
+ }
+ return response.json();
+ }
+
+ function getShopAuthHeaders() {
+ const headers = {
+ "X-Shop-Id": state.shopId || "default"
+ };
+ if (state.shopToken) headers["X-Shop-Token"] = state.shopToken;
+ return headers;
+ }
+
+ async function safeReadText(response) {
+ try {
+ return (await response.text()).slice(0, 200);
+ } catch (_) {
+ return "";
+ }
+ }
+
+ async function fillReply(reply) {
+ const textarea = await waitForElement(selectors.replyTextarea, 5000);
+ textarea.focus();
+ await sleep(80);
+ setTextareaValue(textarea, "");
+ dispatchTextInputEvents(textarea, "");
+
+ const trustedInput = await requestTrustedTextInput(reply);
+ await sleep(180);
+ if (trustedInput && normalizeText(textarea.value || "").includes(normalizeText(reply).slice(0, 20))) {
+ log("已使用真实输入事件写入回复。");
+ return;
+ }
+
+ if (trustedInput) {
+ log("真实输入事件未写入到输入框,改用页面脚本回填。");
+ }
+ setTextareaValue(textarea, reply);
+ dispatchTextInputEvents(textarea, reply);
+ await sleep(180);
+ }
+
+ function setTextareaValue(textarea, value) {
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set;
+ if (setter) {
+ setter.call(textarea, value);
+ } else {
+ textarea.value = value;
+ }
+ }
+
+ function dispatchTextInputEvents(textarea, value) {
+ textarea.focus();
+ textarea.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true, data: "" }));
+ textarea.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: value }));
+ if (typeof InputEvent === "function") {
+ textarea.dispatchEvent(new InputEvent("beforeinput", {
+ bubbles: true,
+ cancelable: true,
+ inputType: value ? "insertText" : "deleteContentBackward",
+ data: value
+ }));
+ textarea.dispatchEvent(new InputEvent("input", {
+ bubbles: true,
+ inputType: value ? "insertText" : "deleteContentBackward",
+ data: value
+ }));
+ } else {
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ textarea.dispatchEvent(new Event("change", { bubbles: true }));
+ textarea.dispatchEvent(new KeyboardEvent("keyup", { bubbles: true, key: value ? "Process" : "Backspace" }));
+ }
+
+ async function sendReplyAndVerify(reply) {
+ const textarea = await waitForElement(selectors.replyTextarea, 5000);
+ const beforeChatSignature = getChatSignature();
+ const beforeMessageCount = getMessageNodeCount();
+ const beforeValue = normalizeText(textarea.value || "");
+
+ if (!beforeValue) {
+ log("发送前输入框为空,已取消自动发送。");
+ return false;
+ }
+
+ await clickSendButton();
+ const buttonSent = await waitForSendSuccess({
+ reply,
+ textarea,
+ beforeChatSignature,
+ beforeMessageCount,
+ timeout: 2800
+ });
+ if (buttonSent) return true;
+
+ log("按钮发送未确认成功,尝试使用回车发送。");
+ await pressEnterToSend(textarea);
+ return waitForSendSuccess({
+ reply,
+ textarea,
+ beforeChatSignature,
+ beforeMessageCount,
+ timeout: 4200
+ });
+ }
+
+ async function clickSendButton() {
+ const button = await waitForElement(selectors.sendButton, 5000);
+ if (isDisabledSendButton(button)) {
+ log("发送按钮看起来处于不可用状态,仍会尝试真实点击和回车兜底。");
+ }
+ button.scrollIntoView({ block: "center", inline: "center" });
+ await sleep(80);
+ const trusted = await requestTrustedClick(button);
+ if (!trusted) {
+ log("真实点击不可用,改用页面脚本点击。");
+ dispatchClickSequence(button);
+ const pointTarget = elementFromCenter(button);
+ if (pointTarget && pointTarget !== button) dispatchClickSequence(pointTarget);
+ }
+ await sleep(500);
+ return true;
+ }
+
+ async function pressEnterToSend(textarea) {
+ textarea.focus();
+ await sleep(80);
+ const trusted = await requestTrustedEnter();
+ if (!trusted) {
+ textarea.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, key: "Enter", code: "Enter", keyCode: 13, which: 13 }));
+ textarea.dispatchEvent(new KeyboardEvent("keypress", { bubbles: true, cancelable: true, key: "Enter", code: "Enter", keyCode: 13, which: 13 }));
+ textarea.dispatchEvent(new KeyboardEvent("keyup", { bubbles: true, cancelable: true, key: "Enter", code: "Enter", keyCode: 13, which: 13 }));
+ }
+ await sleep(500);
+ }
+
+ async function waitForSendSuccess({ reply, textarea, beforeChatSignature, beforeMessageCount, timeout = 5000 }) {
+ const started = Date.now();
+ const expected = normalizeForMatch(reply).slice(0, 80);
+
+ while (Date.now() - started < timeout) {
+ await sleep(160);
+
+ const currentValue = normalizeText(textarea.value || "");
+ const currentSignature = getChatSignature();
+ const currentMessageCount = getMessageNodeCount();
+ const chatText = normalizeForMatch(getChatText());
+
+ const inputCleared = !currentValue;
+ const chatChanged = currentSignature !== beforeChatSignature;
+ const messageAdded = currentMessageCount > beforeMessageCount;
+ const replyAppeared = expected && chatText.includes(expected);
+
+ if (inputCleared && (chatChanged || messageAdded || replyAppeared)) {
+ return true;
+ }
+ if (replyAppeared && (chatChanged || messageAdded)) {
+ return true;
+ }
+ }
+
+ log("自动发送校验失败:输入框未清空或聊天区未出现新发送消息。");
+ return false;
+ }
+
+ function elementFromCenter(element) {
+ const rect = element.getBoundingClientRect();
+ return document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
+ }
+
+ async function requestTrustedTextInput(text) {
+ return requestTrustedAction({
+ action: "trusted-insert-text",
+ text
+ });
+ }
+
+ async function requestTrustedClick(element) {
+ const rect = element.getBoundingClientRect();
+ return requestTrustedAction({
+ action: "trusted-click",
+ x: rect.left + rect.width / 2,
+ y: rect.top + rect.height / 2
+ });
+ }
+
+ async function requestTrustedEnter() {
+ return requestTrustedAction({ action: "trusted-enter" });
+ }
+
+ function requestTrustedAction(payload) {
+ return new Promise((resolve) => {
+ let runtime = null;
+ try {
+ runtime = globalThis.chrome?.runtime || null;
+ } catch (error) {
+ reportTrustedActionUnavailable(error);
+ resolve(false);
+ return;
+ }
+
+ if (!runtime || typeof runtime.sendMessage !== "function") {
+ resolve(false);
+ return;
+ }
+
+ let done = false;
+ let timer = 0;
+ const finish = (value) => {
+ if (done) return;
+ done = true;
+ window.clearTimeout(timer);
+ resolve(value);
+ };
+
+ timer = window.setTimeout(() => {
+ finish(false);
+ }, 2500);
+
+ try {
+ runtime.sendMessage({ source: "pdd-reply-assistant", ...payload }, (response) => {
+ let error = null;
+ try {
+ error = runtime.lastError || null;
+ } catch (lastError) {
+ error = lastError;
+ }
+
+ if (done) return;
+ if (error || !response?.ok) {
+ reportTrustedActionUnavailable(error || response?.error);
+ finish(false);
+ return;
+ }
+
+ finish(true);
+ });
+ } catch (error) {
+ reportTrustedActionUnavailable(error);
+ finish(false);
+ }
+ });
+ }
+
+ function reportTrustedActionUnavailable(error) {
+ const message = typeof error === "string" ? error : error?.message || "";
+ if (!message) return;
+
+ if (/Extension context invalidated/i.test(message)) {
+ if (!state.trustedContextWarningShown) {
+ state.trustedContextWarningShown = true;
+ log("插件上下文已更新,已降级为普通输入/点击;刷新客服页面可恢复真实操作。");
+ }
+ return;
+ }
+
+ log(`真实操作不可用:${message}`);
+ }
+
+ function isDisabledSendButton(button) {
+ if (!button) return true;
+ const classText = String(button.className || "").toLowerCase();
+ const ariaDisabled = button.getAttribute("aria-disabled") === "true";
+ const disabledAttr = button.hasAttribute("disabled");
+ const style = window.getComputedStyle(button);
+ return ariaDisabled || disabledAttr || /disabled|disable/.test(classText) || style.pointerEvents === "none";
+ }
+
+ function getMessageNodeCount() {
+ const root = document.querySelector(selectors.messageList);
+ if (!root) return 0;
+ return Array.from(root.querySelectorAll("*")).filter((element) => {
+ const text = normalizeText(element.innerText || element.textContent || "");
+ if (!text) return false;
+ if (hasChildWithSameText(element, text)) return false;
+ return isLikelyChatText(text) || looksLikeProductCard(element, text);
+ }).length;
+ }
+
+ function getChatText() {
+ const root = document.querySelector(selectors.messageList);
+ return normalizeText(root ? root.innerText || root.textContent || "" : "");
+ }
+
+ function waitForManualSend() {
+ const button = document.querySelector(selectors.sendButton);
+ const textarea = document.querySelector(selectors.replyTextarea);
+ if (!button && !textarea) {
+ state.processing = false;
+ log("未找到发送按钮和输入框,已恢复监听。");
+ renderWidget();
+ scheduleCheck(500);
+ return;
+ }
+
+ let finished = false;
+ if (state.manualSendCleanup) state.manualSendCleanup();
+ const cleanup = () => {
+ button?.removeEventListener("click", onClick, true);
+ textarea?.removeEventListener("keydown", onKeyDown, true);
+ };
+ state.manualSendCleanup = cleanup;
+
+ const finish = (reason) => {
+ if (finished) return;
+ finished = true;
+ cleanup();
+ if (state.manualSendCleanup === cleanup) state.manualSendCleanup = null;
+ if (state.paused) {
+ state.processing = false;
+ renderWidget();
+ return;
+ }
+ state.processing = false;
+ log(`检测到人工${reason}发送,恢复监听。`);
+ renderWidget();
+ scheduleCheck(500);
+ };
+
+ const onClick = () => finish("点击");
+ const onKeyDown = (event) => {
+ if (event.key !== "Enter") return;
+ if (event.shiftKey || event.ctrlKey || event.altKey || event.metaKey || event.isComposing) return;
+ window.setTimeout(() => finish("回车"), 80);
+ };
+
+ button?.addEventListener("click", onClick, true);
+ textarea?.addEventListener("keydown", onKeyDown, true);
+ }
+
+ function isVisible(element) {
+ if (!element || !(element instanceof Element)) return false;
+ const rect = element.getBoundingClientRect();
+ const style = window.getComputedStyle(element);
+ return rect.width > 0 && rect.height > 0 && style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
+ }
+
+ function normalizeText(value) {
+ return String(value || "")
+ .replace(/\u00a0/g, " ")
+ .replace(/[ \t]+/g, " ")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+ }
+
+ function normalizeForMatch(value) {
+ return normalizeText(value).replace(/\s+/g, "").toLowerCase();
+ }
+
+ function sleep(ms) {
+ return new Promise((resolve) => window.setTimeout(resolve, ms));
+ }
+
+ function log(message) {
+ const time = new Date().toLocaleTimeString("zh-CN", { hour12: false });
+ state.logLines.push(`[${time}] ${message}`);
+ if (state.logLines.length > 80) state.logLines.shift();
+ renderWidget();
+ }
+
+ function setErrorStatus() {
+ if (ui.status) ui.status.className = "pdd-ra-status is-error";
+ }
+})();
diff --git a/example/extension/manifest.json b/example/extension/manifest.json
new file mode 100644
index 0000000..a81c5a4
--- /dev/null
+++ b/example/extension/manifest.json
@@ -0,0 +1,27 @@
+{
+ "manifest_version": 3,
+ "name": "PDD客服自动回复助手",
+ "description": "监听拼多多商家后台客服新会话,调用本地服务生成回复并回填发送。",
+ "version": "0.1.0",
+ "permissions": ["storage", "debugger"],
+ "host_permissions": [
+ "http://127.0.0.1:3456/*",
+ "http://localhost:3456/*",
+ "http://*/*",
+ "https://*/*",
+ "https://mms.pinduoduo.com/*"
+ ],
+ "background": {
+ "service_worker": "background.js"
+ },
+ "content_scripts": [
+ {
+ "matches": [
+ "https://mms.pinduoduo.com/*"
+ ],
+ "js": ["content.js"],
+ "css": ["content.css"],
+ "run_at": "document_idle"
+ }
+ ]
+}
diff --git a/example/package.json b/example/package.json
new file mode 100644
index 0000000..41174fb
--- /dev/null
+++ b/example/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "pdd-customer-service-reply-assistant",
+ "version": "0.1.0",
+ "private": true,
+ "description": "拼多多商家后台客服自动回复浏览器插件与本地服务。",
+ "scripts": {
+ "start": "node server/index.js",
+ "dev": "node server/index.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+}
diff --git a/example/server/index.js b/example/server/index.js
new file mode 100644
index 0000000..da6c8cc
--- /dev/null
+++ b/example/server/index.js
@@ -0,0 +1,2311 @@
+"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();
+}
diff --git a/extension/content.css b/extension/content.css
index e4a365b..4e21c53 100644
--- a/extension/content.css
+++ b/extension/content.css
@@ -62,6 +62,11 @@
background: var(--pdd-ra-green);
}
+/* 调试模式:蓝色,和自动模式的绿色区分开 */
+.pdd-ra-status.is-debug {
+ background: #3b82f6;
+}
+
.pdd-ra-status.is-busy {
background: #f59e0b;
}
@@ -125,10 +130,23 @@
color: #fff;
}
+/* 模式按钮:自动=绿、调试=蓝,靠颜色区分而不是只看文字 */
+.pdd-ra-button.is-auto {
+ background: var(--pdd-ra-green);
+ border-color: var(--pdd-ra-green);
+ color: #fff;
+}
+
+.pdd-ra-button.is-debug {
+ background: #3b82f6;
+ border-color: #3b82f6;
+ color: #fff;
+}
+
.pdd-ra-button.is-paused {
- background: #fff7ed;
- border-color: #fdba74;
- color: #9a3412;
+ background: #f59e0b;
+ border-color: #f59e0b;
+ color: #fff;
}
.pdd-ra-config {
@@ -181,13 +199,30 @@
color: #dbeafe;
height: 168px;
line-height: 1.45;
- margin-top: 10px;
+ margin-top: 6px;
overflow: auto;
padding: 8px;
user-select: text;
white-space: pre-wrap;
}
+.pdd-ra-logtools {
+ align-items: center;
+ display: flex;
+ gap: 8px;
+ margin-top: 10px;
+}
+
+.pdd-ra-logtools .pdd-ra-button {
+ font-size: 12px;
+ padding: 4px 10px;
+}
+
+.pdd-ra-loghint {
+ color: var(--pdd-ra-muted);
+ font-size: 11px;
+}
+
.pdd-ra-bubble {
align-items: center;
background: var(--pdd-ra-blue);
diff --git a/extension/content.js b/extension/content.js
index fd3dafd..a585151 100644
--- a/extension/content.js
+++ b/extension/content.js
@@ -3,7 +3,14 @@
const DEFAULT_SERVER_BASE = "http://127.0.0.1:3456";
const STORE_KEY = "pddReplyAssistantState";
+ const IMAGE_INDEX_KEY = "pddReplyAssistantImageIndex";
const CONTROL_POLL_MS = 1500;
+ // 买家连续发图:末尾连续图片达到该数量就先等静默,避免每来一张回一次
+ const IMAGE_BURST_MIN = 3;
+ const IMAGE_BURST_SETTLE_MS = 4000;
+ const IMAGE_BURST_MAX_ROUNDS = 4;
+ // 纯图片会话在该时长内只确认一次,100 张图也不会刷出上百条回复
+ const IMAGE_ACK_COOLDOWN_MS = 60000;
const selectors = {
urgentLists: ["ul.five-minute", "ul.timeout-unreply"],
@@ -39,11 +46,74 @@
runId: 0,
activeAbortController: null,
manualSendCleanup: null,
+ // 调试模式回填后等人工发送,此时不算「处理中」
+ awaitingManualSend: false,
trustedContextWarningShown: false,
position: { right: 18, bottom: 18 },
manualConversationKeys: new Set(),
cardOnlyConversationKeys: new Set(),
- logLines: []
+ logLines: [],
+ // 归档设置从本地服务拉取(模型页改完立即生效,不用重建 EXE)
+ runtime: {
+ historyLimit: 6,
+ imageOutputDir: "",
+ imageSaveEnabled: true,
+ imageAssignMode: "hybrid",
+ imageConcurrentMs: 60000,
+ imageBatchGapMs: 180000,
+ imageHistoryLeadMs: 600000,
+ imageCountCheck: true,
+ imageReviewEnabled: true,
+ imageKeepOrderTab: true,
+ // 数量不符时是否给买家回复差值(文案可配置)
+ imageReceiptReplyEnabled: false,
+ receiptShortageReply: "",
+ receiptOverflowReply: "",
+ // 买家说「第2张替换掉 / 第3张删掉」时自动调整已保存的图片
+ imageAdjustEnabled: true,
+ imageAdjustReplyEnabled: true,
+ adjustReplaceReply: "",
+ adjustDeleteReply: "",
+ // 指令识别词(逗号分隔),由图片保存页下发
+ imageAdjustReplaceWords: "替换,换成,换掉,换一张,换一下,换下,更换,改成,改为,换个",
+ imageAdjustDeleteWords: "删掉,删除,去掉,不要,不想要,不需要,不用,取消,移除,删了",
+ imageAdjustResendWords: "重新发,重发,再发一张,补发",
+ imageAdjustPointWords: "这个,这张,那张,这幅,那幅,这张图,这个图,它",
+ imageAdjustNegativeWords: "不要,不用,不需要,无需,别,勿",
+ // 图片指纹(dHash)汉明距离阈值,越小越严格
+ imageAdjustMatchThreshold: 8,
+ // 指令识别方式:rules 只用固定词;hybrid 固定词没命中时问模型;ai 优先问模型
+ imageAdjustMode: "rules",
+ imageAdjustAiConfidence: 0.75,
+ // 切换页签/页面时的随机等待区间(毫秒)
+ minPageDelayMs: 150,
+ maxPageDelayMs: 400,
+ // 参与归属与模型上下文的订单状态(正常/已完成/退款售后)
+ orderStatusNormal: true,
+ orderStatusDone: true,
+ orderStatusRefund: true,
+ // 开场说明:命中条件时先单独发一段规则说明(可带配图)
+ greeting: { enabled: false, onFirst: true, onOrder: true, text: "", images: [] },
+ // 命中高危意图后是否把该会话标记为转人工(后续消息不再自动回复)
+ riskStopOnHit: true
+ },
+ greetedConversations: new Set(),
+ greetedOrders: new Set(),
+ // 仅图片会话最近一次确认回复的时间,避免连发图片时反复回复
+ imageAckAt: new Map(),
+ imageAckLogAt: 0,
+ // 图片数量不符时待回复买家的差值通知
+ receiptNotes: [],
+ currentConversationKey: "",
+ // 已处理过的图片调整指令(会话 + 消息时间 + 原文),防止轮询时重复替换/删除
+ adjustHandled: new Set(),
+ // 模型识别结果缓存(同一句指令只问一次模型)
+ aiAdjustCache: new Map(),
+ // 本轮刚完成图片调整,用于跳过模型回复(key 匹配当前会话)
+ lastAdjustReply: null,
+ // 当前这一轮处理的日志与对话,结束后按「日期/店铺/用户」落盘
+ activeRunLog: null,
+ archivedImageUrls: new Set()
};
const ui = {
@@ -73,10 +143,15 @@
startBottom: 0
};
+ // 日志批量落盘队列(必须早于 init 声明,初始化时就会写第一条日志)
+ let logQueue = [];
+ let logFlushTimer = 0;
+
init();
async function init() {
loadState();
+ loadArchivedImageIndex();
resetConfigDraftFromState();
buildWidget();
renderWidget();
@@ -125,6 +200,28 @@
);
}
+ // 已归档图片索引落盘:页面刷新/软件重启后不再重复下载、重复编号
+ function loadArchivedImageIndex() {
+ try {
+ const raw = localStorage.getItem(IMAGE_INDEX_KEY);
+ if (!raw) return;
+ const list = JSON.parse(raw);
+ if (Array.isArray(list)) state.archivedImageUrls = new Set(list.slice(-3000));
+ } catch (error) {
+ console.warn("[PDD Reply Assistant] failed to load image index", error);
+ }
+ }
+
+ function persistArchivedImageIndex() {
+ try {
+ const list = Array.from(state.archivedImageUrls).slice(-3000);
+ localStorage.setItem(IMAGE_INDEX_KEY, JSON.stringify(list));
+ } catch (error) {
+ // 配额满时丢弃索引,下一次重新扫一遍,不影响归档
+ console.warn("[PDD Reply Assistant] failed to save image index", error);
+ }
+ }
+
function buildWidget() {
if (document.getElementById("pdd-reply-assistant-root")) return;
@@ -172,6 +269,8 @@
saveState();
renderWidget();
log(`已切换为${state.mode === "debug" ? "调试模式" : "自动模式"}。`);
+ // mode 一起上报,桌面 UI 的选项卡圆点才能区分自动/调试
+ syncPauseStateToServer("browser-panel");
});
ui.pauseBtn = document.createElement("button");
@@ -227,7 +326,20 @@
ui.log = document.createElement("div");
ui.log.className = "pdd-ra-log";
- body.append(controls, ui.configPanel, ui.meta, ui.log);
+ // 日志面板本身不好选中,提供一键复制,并在后台按日期落盘
+ ui.logTools = document.createElement("div");
+ ui.logTools.className = "pdd-ra-logtools";
+ ui.copyLogBtn = document.createElement("button");
+ ui.copyLogBtn.className = "pdd-ra-button";
+ ui.copyLogBtn.type = "button";
+ ui.copyLogBtn.textContent = "复制日志";
+ ui.copyLogBtn.addEventListener("click", copyLogs);
+ ui.logHint = document.createElement("span");
+ ui.logHint.className = "pdd-ra-loghint";
+ ui.logHint.textContent = "同时保存到 data\\logs\\plugin-日期.txt";
+ ui.logTools.append(ui.copyLogBtn, ui.logHint);
+
+ body.append(controls, ui.configPanel, ui.meta, ui.logTools, ui.log);
ui.panel.append(header, body);
ui.bubble = document.createElement("div");
@@ -293,6 +405,12 @@
saveState();
renderWidget();
log(`已保存店铺配置:${state.shopName}(${state.shopId})。`);
+ // 回写 shops.json,避免只在本地 localStorage 生效、重启被主界面配置覆盖
+ fetch(`${state.serverBase}/api/shop-config`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ shopId: state.shopId, shopName: state.shopName, pluginToken: state.shopToken })
+ }).catch(() => {});
syncPauseStateToServer("plugin-config-save");
}
@@ -327,18 +445,25 @@
ui.root.style.right = `${state.position.right}px`;
ui.root.style.bottom = `${state.position.bottom}px`;
+ // 模式按钮用颜色区分,不只靠文字变化:自动=绿、调试=蓝
ui.modeBtn.textContent = state.mode === "debug" ? "调试模式" : "自动模式";
+ ui.modeBtn.classList.toggle("is-auto", state.mode !== "debug");
+ ui.modeBtn.classList.toggle("is-debug", state.mode === "debug");
+ ui.modeBtn.title = state.mode === "debug" ? "调试模式:只回填内容,需人工确认发送" : "自动模式:生成后直接发送";
ui.pauseBtn.textContent = state.paused ? "恢复监听" : "暂停监听";
ui.pauseBtn.classList.toggle("is-paused", state.paused);
ui.configBtn.textContent = state.configOpen ? "收起配置" : "配置";
ui.configPanel.classList.toggle("is-open", state.configOpen);
syncConfigInputs();
- const statusName = state.processing ? "is-busy" : state.paused ? "is-idle" : "is-listening";
+ // 调试模式等待人工发送时不算「处理中」,否则圆点会一直停在黄色
+ const busy = state.processing && !state.awaitingManualSend;
+ const statusName = busy ? "is-busy" : state.paused ? "is-idle" : state.mode === "debug" ? "is-debug" : "is-listening";
ui.status.className = `pdd-ra-status ${statusName}`;
+ const statusText = busy ? "处理中" : state.awaitingManualSend ? "待人工发送" : state.paused ? "已暂停" : state.mode === "debug" ? "调试监听中" : "自动监听中";
const controlState = state.remoteControlReady ? "手机控制已连接" : "手机控制未连接";
- ui.meta.textContent = `店铺:${state.shopName || state.shopId}|服务:${state.serverBase}|${controlState}|商品来源:聊天卡片|人工介入:${state.manualConversationKeys.size}个|${state.processing ? "处理中" : state.paused ? "已暂停" : "监听中"}`;
+ ui.meta.textContent = `店铺:${state.shopName || state.shopId}|服务:${state.serverBase}|${controlState}|商品来源:聊天卡片|人工介入:${state.manualConversationKeys.size}个|${statusText}`;
ui.log.textContent = state.logLines.join("\n");
ui.log.scrollTop = ui.log.scrollHeight;
}
@@ -471,6 +596,7 @@
body: JSON.stringify({
shopId: state.shopId || "default",
paused: state.paused,
+ mode: state.mode,
source
})
});
@@ -531,6 +657,21 @@
const runId = ++state.runId;
const abortController = new AbortController();
state.activeAbortController = abortController;
+ // 每轮处理单独记录,结束后写入「日期/店铺/用户」目录,方便按用户复盘
+ state.currentConversationKey = getConversationKey(row);
+ state.activeRunLog = {
+ key: state.currentConversationKey,
+ user: conversationDisplayName(row, state.currentConversationKey),
+ runId,
+ startedAt: Date.now(),
+ mode: state.mode,
+ outcome: "",
+ reply: "",
+ imageCount: 0,
+ orderCount: 0,
+ messages: [],
+ lines: []
+ };
renderWidget();
try {
@@ -541,26 +682,110 @@
await waitForStableChat(beforeChatSignature, row);
ensureTaskActive(runId);
- const payload = buildConversationPayload();
+ const payload = await buildConversationPayload();
+ if (state.activeRunLog && Array.isArray(payload?.msgList)) {
+ state.activeRunLog.messages = payload.msgList.map((item) => ({
+ usertype: item.usertype,
+ msg: item.msg,
+ t: item.t || 0
+ }));
+ state.activeRunLog.orderCount = Array.isArray(payload.orders) ? payload.orders.length : 0;
+ }
if (payload?.skip) {
- markCardOnlyConversation(row);
+ const waitingImage = payload.reason === "waiting-adjust-image";
+ if (!waitingImage) markCardOnlyConversation(row);
state.processing = false;
if (state.activeAbortController === abortController) state.activeAbortController = null;
- log("最新一条是商品卡片,暂不回复,等待客户继续发送文字消息。");
+ if (state.activeRunLog) {
+ state.activeRunLog.outcome = waitingImage
+ ? "等待买家发送替换用的新图"
+ : "最新是商品卡片,跳过本轮";
+ }
+ log(waitingImage
+ ? "买家已发出图片替换指令,等待新图到达后再处理。"
+ : "最新一条是商品卡片,暂不回复,等待客户继续发送文字消息。");
renderWidget();
- scheduleCheck(500);
+ scheduleCheck(waitingImage ? 1200 : 500);
return;
}
log(`已提取历史消息${payload.msgList.length}条。`);
printPayloadToDebugConsole(payload);
+ // 买家连发图片/视频时,同一会话在冷却期内只确认一次,避免上百张刷出上百条回复
+ const conversationKey = getConversationKey(row);
+ const onlyMedia = isMediaOnlyBatch(payload.msgList);
+ const pendingNote = onlyMedia
+ ? state.receiptNotes.find((note) => note.key === conversationKey)
+ : null;
+ // 图片调整成功的确认文案:即使带着文字指令,也不该再让模型补一段回复
+ const adjustNote = state.receiptNotes.find(
+ (note) => note.key === conversationKey && note.kind === "adjust"
+ );
+ const adjustHandledNow = Boolean(state.lastAdjustReply
+ && state.lastAdjustReply.key === conversationKey
+ && Date.now() - state.lastAdjustReply.at < 60000);
+ if (adjustHandledNow) state.lastAdjustReply = null;
+ // 差值文案为空时不能吞掉本轮回复,交回模型处理
+ const pendingReceipt = Boolean(pendingNote && buildReceiptText(pendingNote));
+ const adjustReceipt = Boolean(adjustNote && buildReceiptText(adjustNote));
+ // 有数量差值要回复时不受连发冷却限制,保证买家能看到最新数量
+ if (!pendingReceipt && !adjustReceipt && onlyMedia
+ && Date.now() - (state.imageAckAt.get(conversationKey) || 0) < IMAGE_ACK_COOLDOWN_MS) {
+ if (Date.now() - state.imageAckLogAt > 20000) {
+ state.imageAckLogAt = Date.now();
+ log("买家还在连续发送图片/视频,冷却期内本轮不重复回复。");
+ }
+ state.processing = false;
+ if (state.activeAbortController === abortController) state.activeAbortController = null;
+ if (state.activeRunLog) state.activeRunLog.outcome = "买家连续发图冷却中,跳过本轮";
+ renderWidget();
+ scheduleCheck(8000);
+ return;
+ }
+
+ // 自动模式下纯图片且数量与规格不符,或刚完成图片调整:直接回复对应文案,不调用模型
+ if ((pendingReceipt || adjustReceipt) && state.mode === "auto") {
+ const noteText = adjustReceipt ? buildReceiptText(adjustNote) : buildReceiptText(pendingNote);
+ if (state.activeRunLog) state.activeRunLog.reply = noteText;
+ await sendReceiptNotes(runId);
+ ensureTaskActive(runId);
+ state.imageAckAt.set(conversationKey, Date.now());
+ log(adjustReceipt
+ ? "图片替换已生效,已直接回复确认,不再发送其他文字。"
+ : "图片数量与规格不符,已直接回复差值,不再发送其他文字。");
+ if (state.activeRunLog) {
+ state.activeRunLog.outcome = adjustReceipt ? "仅回复图片替换确认" : "仅回复图片数量差值";
+ }
+ state.processing = false;
+ if (state.activeAbortController === abortController) state.activeAbortController = null;
+ renderWidget();
+ scheduleCheck(500);
+ return;
+ }
+
+ // 调整完成但没配置确认文案时也不调模型,避免对「把这个换成这个」再生成一段解释
+ if (adjustHandledNow && state.mode === "auto") {
+ log("图片替换已完成,本轮不再调用模型回复。");
+ if (state.activeRunLog) state.activeRunLog.outcome = "图片替换完成,未调用模型";
+ state.processing = false;
+ if (state.activeAbortController === abortController) state.activeAbortController = null;
+ renderWidget();
+ scheduleCheck(500);
+ return;
+ }
+
const result = await requestReply(payload, abortController.signal);
ensureTaskActive(runId);
if (isManualRequired(result)) {
- markManualConversation(row);
+ // 高危意图是否停止该会话的自动回复由设置决定;模型判定转人工时始终停止
+ const hitRisk = Array.isArray(result.riskIntents) && result.riskIntents.length > 0;
+ if (!hitRisk || state.runtime.riskStopOnHit !== false) markManualConversation(row);
const names = Array.isArray(result.riskIntents) ? result.riskIntents.join("、") : "未知";
const emailState = result.email?.sent ? "邮件已发送" : result.email?.deduped ? "邮件已去重" : "邮件未发送";
- log(`命中高危意图:${names}。不回复此用户,${emailState},继续监听其他新消息。`);
+ log(`命中高危意图:${names}。不回复此用户,${emailState},${hitRisk && state.runtime.riskStopOnHit === false ? "后续消息继续自动回复" : "该会话后续不再自动回复"}。`);
+ if (state.activeRunLog) {
+ state.activeRunLog.outcome = hitRisk ? `命中高危意图,转人工(${names})` : "模型判定转人工";
+ }
state.processing = false;
if (state.activeAbortController === abortController) state.activeAbortController = null;
renderWidget();
@@ -569,21 +794,58 @@
}
const reply = normalizeText(result.reply || result.message || result.text || "");
- if (!reply) throw new Error("服务返回内容为空");
+ const images = Array.isArray(result.images)
+ ? result.images.filter((image) => image && (image.file || image.name)).slice(0, 9)
+ : [];
+ if (!reply && !images.length) throw new Error("服务返回内容为空");
+ if (state.activeRunLog) {
+ state.activeRunLog.reply = reply;
+ state.activeRunLog.imageCount = images.length;
+ }
ensureTaskActive(runId);
- await fillReply(reply);
+ // 开场说明:命中条件时先单独发文字/配图,再发正式回复(仅自动模式会真正发送)
+ const greeting = state.mode === "auto" ? pickGreeting(payload, row) : null;
+ if (greeting) {
+ if (greeting.text) {
+ await fillReply(greeting.text);
+ ensureTaskActive(runId);
+ if (!(await sendReplyAndVerify(greeting.text))) throw new Error("开场说明发送未确认成功");
+ log("已先发送开场说明文字。");
+ await sleep(pageDelayMs() + 200);
+ ensureTaskActive(runId);
+ }
+ if (greeting.images.length) {
+ if (!(await sendImageMessages(greeting.images))) throw new Error("开场说明配图发送失败");
+ log("已先发送开场说明配图。");
+ await sleep(pageDelayMs() + 200);
+ ensureTaskActive(runId);
+ }
+ }
+
+ if (reply) await fillReply(reply);
+ else await clearReplyInput();
ensureTaskActive(runId);
if (state.mode === "auto") {
- const sent = await sendReplyAndVerify(reply);
+ let sent = true;
+ if (reply) sent = await sendReplyAndVerify(reply);
+ if (sent && images.length) {
+ ensureTaskActive(runId);
+ sent = await sendImageMessages(images);
+ }
ensureTaskActive(runId);
if (sent) {
+ // 纯媒体批次记一次确认时间,后续连发的图片/视频不再逐条回复
+ if (onlyMedia) state.imageAckAt.set(conversationKey, Date.now());
+ await sendReceiptNotes(runId);
log("已确认自动发送成功,恢复监听。");
+ if (state.activeRunLog) state.activeRunLog.outcome = "已自动回复并确认发送";
state.processing = false;
if (state.activeAbortController === abortController) state.activeAbortController = null;
renderWidget();
scheduleCheck(500);
} else {
+ if (state.activeRunLog) state.activeRunLog.outcome = "自动发送未确认,已暂停监听";
state.processing = false;
setErrorStatus();
setPausedState(true, "自动发送未确认成功,已暂停监听。请人工检查当前会话,避免重复生成。", {
@@ -592,13 +854,29 @@
});
}
} else {
+ if (state.activeRunLog) state.activeRunLog.outcome = "调试模式,已回填待人工发送";
log("已回填回复。当前为调试模式,请人工确认后点击发送。");
+ if (images.length) log(`本次回复附带 ${images.length} 张配图,调试模式下请手动上传发送。`);
+ // 调试模式不自动发差值通知,把当前会话的文案打到日志里方便人工发送
+ const receiptKey = state.currentConversationKey || "";
+ const pendingReceipts = state.receiptNotes.filter((note) => note.key === receiptKey);
+ if (pendingReceipts.length) {
+ state.receiptNotes = state.receiptNotes.filter((note) => note.key !== receiptKey);
+ pendingReceipts.forEach((note) => {
+ const text = buildReceiptText(note);
+ if (text) log(`[调试] 订单 ${note.orderNo} 待回复:${text}`);
+ });
+ }
+ // 等人工发送期间不算「处理中」,状态圆点改为调试色而不是一直黄色
+ state.awaitingManualSend = true;
+ renderWidget();
waitForManualSend();
}
} catch (error) {
if (isTaskCanceled(error)) {
state.processing = false;
if (state.activeAbortController === abortController) state.activeAbortController = null;
+ if (state.activeRunLog) state.activeRunLog.outcome = "任务已取消";
log("当前回复任务已取消,不会回填或发送。");
renderWidget();
return;
@@ -606,9 +884,12 @@
state.processing = false;
if (state.activeAbortController === abortController) state.activeAbortController = null;
setErrorStatus();
+ if (state.activeRunLog) state.activeRunLog.outcome = `处理失败:${error.message}`;
log(`处理失败:${error.message}`);
renderWidget();
scheduleCheck(1200);
+ } finally {
+ finishRunLog(runId);
}
}
@@ -627,6 +908,7 @@
state.manualSendCleanup = null;
}
state.processing = false;
+ state.awaitingManualSend = false;
log(message);
renderWidget();
}
@@ -750,11 +1032,73 @@
return stableText || imgSrc ? `${imgSrc}|${stableText}` : "";
}
+ function shortHash(value) {
+ let hash = 0;
+ const text = String(value || "");
+ for (let index = 0; index < text.length; index += 1) {
+ hash = ((hash << 5) - hash + text.charCodeAt(index)) | 0;
+ }
+ return (hash >>> 0).toString(16).padStart(8, "0").slice(0, 6);
+ }
+
+ // 日志目录用「可读昵称 + 会话短哈希」,既方便找人又不会因重名串目录
+ function conversationDisplayName(row, conversationKey) {
+ const lines = String(row?.innerText || row?.textContent || "")
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .filter((line) => !/^\d{1,2}:\d{2}(:\d{2})?$/.test(line))
+ .filter((line) => !/^\d+$/.test(line))
+ .filter((line) => !/(请\s*\d+\s*分钟内回复|夜间待回复|超时)/.test(line));
+ const name = (lines[0] || "")
+ .replace(/[\\/:*?"<>|\s]+/g, "")
+ .slice(0, 20);
+ return `${name || "用户"}_${shortHash(conversationKey || lines.join("|"))}`;
+ }
+
+ // 把本轮处理记录(含对话上下文与每步日志)写到「日期/店铺/用户」目录
+ function finishRunLog(runId) {
+ const run = state.activeRunLog;
+ if (!run || run.runId !== runId) return;
+ state.activeRunLog = null;
+ const payload = {
+ shopId: state.shopId || "default",
+ user: run.user,
+ conversationKey: run.key,
+ runId: run.runId,
+ mode: run.mode,
+ startedAt: formatClock(run.startedAt),
+ finishedAt: formatClock(Date.now()),
+ outcome: run.outcome || "处理结束",
+ reply: run.reply || "",
+ imageCount: run.imageCount || 0,
+ orderCount: run.orderCount || 0,
+ messages: run.messages,
+ lines: run.lines
+ };
+ try {
+ fetch(`${state.serverBase}/api/conversation-log`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...getShopAuthHeaders() },
+ body: JSON.stringify(payload)
+ }).catch(() => {});
+ } catch (_) {
+ // 服务没起时忽略,面板里仍保留本轮日志
+ }
+ }
+
async function clickConversation(row) {
log(`准备点击会话:${normalizeText(row.innerText || row.textContent || "").slice(0, 40)}`);
row.scrollIntoView({ block: "center", inline: "nearest" });
await sleep(80);
+ // 真实点击优先:CDP Input 派发的事件 isTrusted 天然为真,还会带上 user activation
+ const pointTarget = elementFromCenter(row) || row;
+ if (await requestTrustedClick(pointTarget)) {
+ await sleep(80);
+ return;
+ }
+
const targets = getClickTargets(row);
for (const target of targets) {
dispatchClickSequence(target);
@@ -859,8 +1203,35 @@
});
}
- function buildConversationPayload() {
+ async function buildConversationPayload() {
+ await ensureRuntimeConfig();
+ // 买家连发图片时先等一小段静默,避免刚收到几张就抢先回复
+ await waitForImageBurstSettle();
+ // 0 表示读取全部:向上滚动把历史消息加载进 DOM 后再一次性收集
+ if (state.runtime.historyLimit === 0) await expandMessageHistory();
+
+ // 订单面板数据同时给「图片归属」和「模型上下文」,只读一次
+ const orders = await readOrderPanelWithAutoSwitch().catch(() => []);
+ log(orders.length ? `订单面板:读取到 ${orders.length} 个订单。` : "订单面板:未读取到订单。");
const messageItems = collectMessageItems();
+
+ // 纯图片/视频批次先把归档做完,数量差值回复才能在本轮直接发出去,避免先冒出一段无关文字;
+ // 带图片调整指令的会话也要等归档完成再决定怎么回复。
+ const adjustIntent = await resolveImageAdjustment(messageItems);
+ if (isMediaOnlyBatch(messageItems) || adjustIntent) {
+ try {
+ const outcome = await archiveChatImages(orders, messageItems);
+ if (outcome === "wait") {
+ return { skip: true, reason: "waiting-adjust-image", msgList: [] };
+ }
+ } catch (error) {
+ log(`图片归档失败:${error?.message || error}`);
+ }
+ } else {
+ // 含文字的会话不阻塞模型回复,归档失败只记日志
+ archiveChatImages(orders, messageItems).catch((error) => log(`图片归档失败:${error?.message || error}`));
+ }
+
const latestItem = getLatestConversationItem(messageItems);
const hasPendingCustomerText = hasPendingCustomerMessage(messageItems);
@@ -876,23 +1247,109 @@
}
const latestProductCard = extractLatestProductCardInfo();
- const msgList = extractMessages(4, messageItems);
+ const limit = state.runtime.historyLimit;
+ const msgList = extractMessages(limit, messageItems);
if (latestProductCard?.message) {
msgList.unshift({
usertype: "cus",
msg: latestProductCard.message
});
}
+ // 商品卡片也占一条,保证发给后端的总数不超过设置的条数
+ if (limit > 0 && msgList.length > limit) msgList.splice(0, msgList.length - limit);
return {
- msgList
+ msgList,
+ orders: compactOrdersForPayload(orders)
};
}
+ // 只带模型需要的字段,避免把整个订单对象塞进提示词
+ function compactOrdersForPayload(orders) {
+ if (!Array.isArray(orders) || !orders.length) return [];
+ return orders.slice(-10).map((order) => ({
+ orderSn: order.orderSn,
+ orderTime: order.orderTime ? formatClock(order.orderTime) : "",
+ status: order.status || "",
+ afterSale: order.afterSale ? "有售后" : "无售后",
+ goods: (order.goods || []).slice(0, 5).map((item) => ({
+ name: String(item.name || "").slice(0, 60),
+ spec: String(item.spec || "").slice(0, 60),
+ num: item.num || 1
+ }))
+ }));
+ }
+
+ function formatClock(epochMs) {
+ const d = new Date(epochMs);
+ const pad = (n) => String(n).padStart(2, "0");
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
+ }
+
function hasPendingCustomerMessage(messageItems) {
const lastSysIndex = findLastIndex(messageItems, (item) => item.usertype === "sys");
return messageItems.slice(lastSysIndex + 1).some((item) => item.usertype === "cus" && item.msg);
}
+ // 末尾连续发送的图片张数(遇到文字或客服消息就停)
+ function trailingCustomerImageCount(messageItems) {
+ let count = 0;
+ for (let i = messageItems.length - 1; i >= 0; i -= 1) {
+ const item = messageItems[i];
+ if (item.usertype !== "cus" || item.msg !== "[图片]") break;
+ count += 1;
+ }
+ return count;
+ }
+
+ // 买家一次发很多照片时,等发完再回复;最多等 IMAGE_BURST_MAX_ROUNDS 轮
+ async function waitForImageBurstSettle() {
+ for (let round = 0; round < IMAGE_BURST_MAX_ROUNDS; round += 1) {
+ const items = collectMessageItems();
+ const images = trailingCustomerImageCount(items);
+ if (images < IMAGE_BURST_MIN) return;
+ log(`买家已连续发送 ${images} 张图片,等待 ${IMAGE_BURST_SETTLE_MS / 1000} 秒确认发完再回复。`);
+ await sleep(IMAGE_BURST_SETTLE_MS);
+ if (collectMessageItems().length <= items.length) return;
+ }
+ }
+
+ // 最近一条客服消息之后的买家消息是否只有图片/视频(没有文字),用于避免连发时反复回复
+ function isMediaOnlyBatch(msgList) {
+ const list = Array.isArray(msgList) ? msgList : [];
+ let lastSysIndex = -1;
+ list.forEach((item, index) => {
+ if (item && item.usertype === "sys") lastSysIndex = index;
+ });
+ const pending = list.slice(lastSysIndex + 1).filter((item) => item && item.usertype === "cus");
+ if (!pending.length) return false;
+ return pending.every((item) => /^\[(图片|视频)\](x\d+)?$/.test(item.msg));
+ }
+
+ // 开场说明:会话里还没有客服消息(首次咨询)或出现没发过的订单号时,先发一次
+ function pickGreeting(payload, row) {
+ const cfg = state.runtime.greeting;
+ if (!cfg || !cfg.enabled) return null;
+ const text = normalizeText(cfg.text || "");
+ const images = Array.isArray(cfg.images) ? cfg.images : [];
+ if (!text && !images.length) return null;
+
+ const key = row ? getConversationKey(row) : "";
+ const messages = Array.isArray(payload?.msgList) ? payload.msgList : [];
+ const noSysMessage = !messages.some((item) => item && item.usertype === "sys");
+ const firstNeeded = cfg.onFirst && noSysMessage && !(key && state.greetedConversations.has(key));
+
+ const orderSns = (Array.isArray(payload?.orders) ? payload.orders : [])
+ .map((order) => String((order && order.orderSn) || ""))
+ .filter(Boolean);
+ const newOrders = cfg.onOrder ? orderSns.filter((sn) => !state.greetedOrders.has(sn)) : [];
+
+ if (!firstNeeded && !newOrders.length) return null;
+ if (key) state.greetedConversations.add(key);
+ newOrders.forEach((sn) => state.greetedOrders.add(sn));
+ log(`触发开场说明(${firstNeeded ? "首次咨询" : "新订单"})。`);
+ return { text, images };
+ }
+
function findLastIndex(items, predicate) {
for (let index = items.length - 1; index >= 0; index -= 1) {
if (predicate(items[index], index, items)) return index;
@@ -1052,17 +1509,156 @@
.trim();
}
+ // 只认视频/播放器相关类名,避免 display、replay 这类同形子串误判
+ function isVideoClass(cls) {
+ if (/video|player/i.test(cls)) return true;
+ return /(^|[-_ ])play([-_ ]|$)/i.test(cls)
+ || /play[-_]?(btn|icon|mask|overlay|button|circle)/i.test(cls);
+ }
+
+ // 只缓存「命中视频」的行:负结果不缓存,避免封面图稍后才加载时被判成图片
+ const VIDEO_ROW_CACHE = new WeakMap();
+ const VIDEO_ROW_LOGGED = new WeakSet();
+
+ // 视频消息在拼多多聊天里常是「大封面图 + 播放按钮/时长提示」,类名随构建经常变,
+ // 所以按整条消息行判断;命中后整行按视频处理,封面图也不计入照片数量和归档
+ function isVideoMessageRow(row) {
+ if (!row || row.nodeType !== 1) return false;
+ if (VIDEO_ROW_CACHE.get(row) === true) return true;
+ let result = Boolean(row.querySelector("video"));
+ if (!result) {
+ result = Array.from(row.querySelectorAll('[class*="video"], [class*="Video"], [class*="player"], [class*="Player"], [class*="play"], [class*="Play"]'))
+ .some((item) => {
+ const cls = String(item.className || "");
+ if (!isVideoClass(cls)) return false;
+ if (/avatar|icon|emoji|face|logo|qrcode|banner|audio|voice|display/i.test(cls)) return false;
+ const r = item.getBoundingClientRect();
+ return r.width >= 24 && r.height >= 24;
+ });
+ }
+ if (!result) {
+ result = Boolean(row.querySelector('[title*="视频"], [aria-label*="视频"]'));
+ }
+ if (!result) {
+ // 有「视频/点击播放/时长」提示且同一行里挂着封面大图,才是视频气泡;
+ // 只有文字没有图的消息不按视频处理,避免把买家说的“视频”当视频消息
+ const hasCover = Array.from(row.querySelectorAll("img")).some((img) => {
+ const r = img.getBoundingClientRect();
+ return isVisible(img) && r.width >= 60 && r.height >= 48;
+ });
+ if (hasCover) {
+ const text = normalizeText(row.innerText || row.textContent || "");
+ result = /视频|点击播放|正在播放/.test(text) || /^\d{1,2}:\d{2}(:\d{2})?$/.test(text);
+ }
+ }
+ if (result) VIDEO_ROW_CACHE.set(row, true);
+ return result;
+ }
+
+ // 视频消息在 DOM 里常带时长/封面文本,不能当买家文字处理,统一用 [视频] 占位
+ function collectChatVideos(root) {
+ const out = [];
+ const seen = new Set();
+ const push = (element) => {
+ if (!element || seen.has(element) || !isVisible(element)) return;
+ if (element.closest(selectors.productCards)) return;
+ const rect = element.getBoundingClientRect();
+ if (rect.width < 80 || rect.height < 60) return;
+ seen.add(element);
+ out.push({ element, top: rect.top, bottom: rect.bottom, left: rect.left, right: rect.right });
+ };
+ root.querySelectorAll("video").forEach(push);
+ // 先按整条消息行判定(类名不可靠时靠行内提示文字 + 封面图兜底)
+ root.querySelectorAll('li.onemsg, [id^="middlePanel_list_"]').forEach((row) => {
+ if (!isVideoMessageRow(row)) return;
+ if (!VIDEO_ROW_LOGGED.has(row)) {
+ VIDEO_ROW_LOGGED.add(row);
+ log("识别到视频消息,已忽略它的封面图和提示文字。");
+ }
+ push(row);
+ });
+ // 视频气泡不一定是