为什么改:应用建的协同群只能代答,销售在群里发文件、@人、问报价都对不上人; 本次把群对话交给智价通BOT,应用只负责拉群和解散群,并把几处销售已反馈的口径补齐。 群与身份: - 新增 group_bot 短协调(Redis 带环境前缀):记录 BOT 已接管群、当前关联工单、 @BOT 指令窗口与窗口外先到的附件,只做协调不当六态,六态仍在主账。 - 群里没有 @BOT 的文字不回;非 @ 文字断开当前单关联,之后必须重新 @BOT 带工单号。 - 先发文件再 @BOT 也认:窗口外附件先缓冲,等 @BOT 认领后补办。 - 会话存档只补附件、不重复办理 BOT 已办的同一句文字,避免同一条消息回两遍。 - 入站 from.userid 是加密 open_userid 时按官方接口换明文(带 Redis 缓存), 否则与主账 sales_wecom_id 永远比不上,航线本人会被判成「不是本人」。 - 桥侧只认本群 req_id,不再借用别的群 req_id,避免测服把话发进别的群。 报价单: - 建群后只发字段摘要和成交卡,Excel/PDF 等群里 @BOT 说「生成报价单」再出; 多段逐段出,没价出空白表;出表后补推成交跟进不涨 deal_version、不重置等待计时。 - 陆运转人工先选业务类型和报价场景再建群,按选定模板名直取,不再靠关键词猜。 - 空运舱位只回一条时直接出该条报价,不再发选择卡。 字段与金额: - 客户名称改为海/空/陆询价非必填,有值写回工单列,后台列表、报价单与 factsJson 一致。 - 空运新增计费重投影:体积重=CBM×166.7,计费重=max(毛重,体积重); TMS 无价、航线手工按 KG 报价时按计费重×单价算整票金额,群摘要与报价单同公式。 - 陆运报价附加条件统一到 land_quote_condition:未含税/含0税/未含燃油/含燃油费, 燃油只乘主运费,不乘提货送货报关等杂费;跨境整车无备注列时追加到底部备注事项。 - 海运拼柜不适用箱型箱量:不进必填、不进补问、不出站,改回整柜可再用。 - 海运提货地址/派送地址改为非必填,写了才出站(placeOfReceipt/deliveryAddress), 禁止从港口或贸易条款反推地址;TMS 查不到价时把 TMS 原话透给销售。 - 中港集拼与跨境集拼同口径:按体积+毛重,不采车型数量;修正被国内拼车别名抢单。 - 报关费区只收报关类费目;口岸海关监管费+接驳费按车型列回填固定行。 主账与后台: - 看板处理量按协同群处理人统计;下线「平均报价销售额」;处理人搜索先把姓名换回企微 id。 - 「转人工」筛选同时兼容旧六态与新 collab_mode=handoff,新版单不再漏。 - 报价单客户名称、提货/派送地址、空运计费重、拼柜空箱型按新口径填表。 - 新增协同成员查询支持与 AIR_NEED_WO v2 迁移脚本。 文档:04 补海运/空运/陆运必填与地址口径,10 补地址出站规则,12 补测服独立应用 1000015 的部署与切换记录。 Co-authored-by: Cursor <cursoragent@cursor.com>
221 lines
9.2 KiB
Python
221 lines
9.2 KiB
Python
"""
|
||
通道消费循环:inbox → RouteDecision → dispatch → handler;outbox → 企微发送。
|
||
|
||
本文件职责:在 HTTP 进程内独立线程跑快路径,不与 LibreOffice 串队。
|
||
禁止:在回调请求线程调用本循环的阻塞逻辑;禁止 Redis 全局单例锁。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import dataclasses
|
||
import logging
|
||
import threading
|
||
from typing import Optional
|
||
|
||
from agent.channel.outbox.sender import PERMANENT_SEND_ERRORS, WeComAppClient
|
||
from agent.channel.queue import get_message_store
|
||
from agent.config import Settings
|
||
from agent.routing import IntentRouter
|
||
from agent.routing.dispatch import dispatch_inbound
|
||
|
||
logger = logging.getLogger(__name__)
|
||
# 避免 httpx 把 access_token / secret 打进 INFO
|
||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||
|
||
|
||
def _normalize_group_sender(message):
|
||
"""
|
||
把 AIBOT 群入站的加密 open_userid 换回明文 userid(2026-11-19 真机问题)。
|
||
|
||
为什么放在 inbox 工作线程而不是回调里:
|
||
- 回调必须秒回;换 ID 会打企微 HTTPS(有缓存,但首次仍要一次网络往返),
|
||
只能放在消费线程,绝不进 FastAPI 请求线程。
|
||
只处理 `chat_type=group` 且来源是 AIBOT 的消息:
|
||
- 私聊出站要按 touser 发,改 sender_id 会发错人;
|
||
- 会话存档(wshoto)本来就是明文,不需要换。
|
||
|
||
返回值:(归一后的消息, 身份是否可信)
|
||
- 可信=1:明文自带,或已换成明文 → 后面的成交/报价/锁舱门禁可以照常判。
|
||
- 可信=0:确实是加密 ID 但换不到 → 不得据此判「不是本人」,
|
||
去重逻辑必须放行会话存档那条(明文)来补办。
|
||
|
||
副作用:可能打企微接口(3 秒超时)、写 Redis 短缓存;不改主账、不写六态。
|
||
"""
|
||
raw = dict(message.raw or {})
|
||
source = str(raw.get("source") or "").strip().lower()
|
||
if (message.chat_type or "") != "group" or source not in {"aibot", "aibot_bridge"}:
|
||
return message, True
|
||
from agent.channel.wecom.open_userid import looks_like_open_userid, resolve_open_userid
|
||
|
||
if not looks_like_open_userid(message.sender_id):
|
||
# 明文 ID(机器人创建者是超管,或本链路本来就没加密):不用管。
|
||
return message, True
|
||
try:
|
||
plain, status = resolve_open_userid(message.sender_id)
|
||
except Exception: # noqa: BLE001 - 归一失败不能把消息丢掉,必须走存档兜底
|
||
logger.warning("群入站 ID 归一异常,按换不到处理", exc_info=True)
|
||
plain, status = message.sender_id, "unresolved"
|
||
|
||
|
||
if status == "resolved":
|
||
new_raw = dict(raw)
|
||
# 保留原始加密 ID:排障要能对上企微后台,也便于以后回放。
|
||
new_raw["sender_open_userid"] = message.sender_id
|
||
new_raw["sender_id_source"] = "open_userid_resolved"
|
||
new_raw["sender_identity_trusted"] = "1"
|
||
return dataclasses.replace(message, sender_id=plain, raw=new_raw), True
|
||
if status == "unresolved":
|
||
new_raw = dict(raw)
|
||
new_raw["sender_id_source"] = "open_userid_unresolved"
|
||
new_raw["sender_identity_trusted"] = "0"
|
||
return dataclasses.replace(message, raw=new_raw), False
|
||
return message, True
|
||
|
||
|
||
class ChannelRuntime:
|
||
"""
|
||
企微通道运行时:inbox/outbox 各一条守护线程。
|
||
|
||
启动时机:FastAPI lifespan;停止:进程退出。
|
||
inbox:私聊自由文字走 DeepSeek A 认意图(本线程,非回调);群消息和点卡不进模型。
|
||
"""
|
||
|
||
def __init__(self, settings: Settings) -> None:
|
||
self._settings = settings
|
||
self._store = get_message_store()
|
||
self._stop = threading.Event()
|
||
self._threads: list[threading.Thread] = []
|
||
# 开网后销售原话交给模型认「续办/新询价」;未开网才走 stub。
|
||
self._router = IntentRouter(allow_network=bool(settings.llm_allow_network))
|
||
agent_id = int(settings.wecom_agent_id or "0") or 0
|
||
self._client = WeComAppClient(
|
||
corp_id=settings.wecom_corp_id,
|
||
secret=settings.wecom_secret,
|
||
agent_id=agent_id,
|
||
)
|
||
notify_id = int(getattr(settings, "wecom_notify_agent_id", "") or "0") or 0
|
||
notify_secret = str(getattr(settings, "wecom_notify_secret", "") or "").strip()
|
||
self._notify_client = None
|
||
if notify_id and notify_secret:
|
||
self._notify_client = WeComAppClient(
|
||
corp_id=settings.wecom_corp_id,
|
||
secret=notify_secret,
|
||
agent_id=notify_id,
|
||
)
|
||
|
||
@property
|
||
def store(self):
|
||
return self._store
|
||
|
||
def start(self) -> None:
|
||
"""启动 inbox/outbox 消费线程。"""
|
||
self._stop.clear()
|
||
self._threads = [
|
||
threading.Thread(target=self._inbox_loop, name="wecom-inbox", daemon=True),
|
||
threading.Thread(target=self._outbox_loop, name="wecom-outbox", daemon=True),
|
||
]
|
||
for t in self._threads:
|
||
t.start()
|
||
logger.info("ChannelRuntime 已启动(inbox/outbox 独立线程;dispatch 分发)")
|
||
|
||
def stop(self) -> None:
|
||
self._stop.set()
|
||
|
||
def _inbox_loop(self) -> None:
|
||
while not self._stop.is_set():
|
||
item = self._store.claim_inbound()
|
||
if item is None:
|
||
self._store.wait_inbox(1.0)
|
||
continue
|
||
try:
|
||
message = item.message
|
||
# 群入站先做「加密 ID → 明文」归一:成交/报价/锁舱都靠这个身份判人。
|
||
# 放在这里(消费线程)而不是回调线程,保证回调仍然秒回。
|
||
# 可信标记写进 raw(sender_identity_trusted),由 dispatch 决定去重是否放行。
|
||
message = _normalize_group_sender(message)[0]
|
||
# 群消息由 dispatch 按 BOT/存档分流,不消耗 DeepSeek A,避免空运群先卡 2~3 秒。
|
||
if (message.chat_type or "") == "group":
|
||
from agent.routing.decision import RouteDecision
|
||
|
||
decision = RouteDecision(intent="ordinary_text_other")
|
||
elif (message.msg_type or "text").lower() == "image":
|
||
from agent.routing.decision import RouteDecision
|
||
|
||
# 私聊图片不进 DeepSeek A(正文为空会被判闲聊)。
|
||
decision = RouteDecision(intent="image_inquiry", confidence=1.0)
|
||
else:
|
||
decision = self._router.route_inbound(
|
||
text=message.content or "",
|
||
sender_id=message.sender_id or "",
|
||
event=str((message.raw or {}).get("event") or ""),
|
||
)
|
||
dispatch_inbound(message, decision)
|
||
self._store.complete_inbound(item.id)
|
||
except Exception as exc: # noqa: BLE001
|
||
logger.exception("inbox 处理失败 id=%s", item.id)
|
||
self._store.complete_inbound(item.id, error=str(exc))
|
||
|
||
def _outbox_loop(self) -> None:
|
||
while not self._stop.is_set():
|
||
item = self._store.claim_outbound()
|
||
if item is None:
|
||
self._store.wait_outbox(1.0)
|
||
continue
|
||
# 过期丢弃:超过 30 分钟的出站不再发(对齐「过期不计业务成功」)
|
||
import time
|
||
|
||
if time.time() - item.created_at > 1800:
|
||
logger.warning("outbox 过期丢弃 id=%s", item.id)
|
||
self._store.complete_outbound(item.id)
|
||
continue
|
||
payload = getattr(item, "payload", None) or {}
|
||
client = self._client
|
||
if payload.get("wecom_app") == "notify":
|
||
if self._notify_client is None:
|
||
logger.error("询价消息服务未配置,成交通知丢弃 id=%s", item.id)
|
||
self._store.complete_outbound(
|
||
item.id, error="notify_app_missing", permanent=True
|
||
)
|
||
continue
|
||
client = self._notify_client
|
||
result = client.send_outbound(
|
||
touser=item.touser,
|
||
content=item.content,
|
||
payload=payload,
|
||
)
|
||
if result.ok:
|
||
self._store.complete_outbound(item.id)
|
||
elif result.errcode in PERMANENT_SEND_ERRORS:
|
||
logger.error(
|
||
"outbox 永久失败不再重试 id=%s err=%s:%s",
|
||
item.id,
|
||
result.errcode,
|
||
result.errmsg,
|
||
)
|
||
self._store.complete_outbound(
|
||
item.id,
|
||
error=f"permanent:{result.errcode}:{result.errmsg}",
|
||
permanent=True,
|
||
)
|
||
else:
|
||
self._store.complete_outbound(
|
||
item.id,
|
||
error=f"{result.errcode}:{result.errmsg}",
|
||
)
|
||
|
||
|
||
_RUNTIME: Optional[ChannelRuntime] = None
|
||
|
||
|
||
def get_channel_runtime() -> Optional[ChannelRuntime]:
|
||
return _RUNTIME
|
||
|
||
|
||
def start_channel_runtime(settings: Settings) -> ChannelRuntime:
|
||
"""幂等启动通道运行时。"""
|
||
global _RUNTIME
|
||
if _RUNTIME is None:
|
||
_RUNTIME = ChannelRuntime(settings)
|
||
_RUNTIME.start()
|
||
return _RUNTIME
|