落地并存测服全端:智能体 Graph/路由、后台切 8180、主账与部署脚本齐备,便于线上重发与验收。
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
"""
|
||||
AIBOT 入站入口:桥进程把长连接消息转到本路由。
|
||||
|
||||
本文件职责:校验 bridge token、归一 InboundMessage、入 inbox 快回。
|
||||
禁止:在本请求线程调 LLM / Graph / 出站企微。
|
||||
路径:/internal/aibot/inbound(对齐 prompt/13)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from agent.channel.queue import get_message_store
|
||||
from agent.channel.wecom.models import InboundMessage
|
||||
from agent.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/internal/aibot", tags=["aibot"])
|
||||
|
||||
|
||||
class AibotInboundBody(BaseModel):
|
||||
"""桥转发的归一字段(桥侧已解析,智能体不再调企微换 ID)。"""
|
||||
|
||||
sender_id: str = Field(description="企微 userid,必须来自 AIBOT 报文")
|
||||
message_id: str
|
||||
content: str = ""
|
||||
msg_type: str = "text"
|
||||
chat_id: str = ""
|
||||
chat_type: str = "group"
|
||||
agent_id: str = ""
|
||||
create_time: int = 0
|
||||
media: dict[str, Any] = Field(default_factory=dict)
|
||||
raw: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
def _check_bridge_token(x_token: Optional[str]) -> None:
|
||||
s = get_settings()
|
||||
expected = (getattr(s, "wecom_aibot_bridge_token", None) or "").strip()
|
||||
if not expected:
|
||||
if (s.ytd_env or "").lower() == "prod":
|
||||
raise HTTPException(status_code=503, detail="AIBOT bridge token 未配置")
|
||||
logger.warning("aibot inbound:未配置 bridge token,test 跳过校验")
|
||||
return
|
||||
if (x_token or "").strip() != expected:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
@router.get("/ping")
|
||||
def aibot_ping() -> dict[str, str]:
|
||||
return {"status": "ok", "channel": "aibot"}
|
||||
|
||||
|
||||
@router.post("/inbound")
|
||||
def aibot_inbound(
|
||||
body: AibotInboundBody,
|
||||
x_aibot_bridge_token: Optional[str] = Header(
|
||||
default=None, alias="X-Aibot-Bridge-Token"
|
||||
),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
接收桥转发入站:无 sender_id 拒绝;其余入 inbox。
|
||||
"""
|
||||
_check_bridge_token(x_aibot_bridge_token)
|
||||
msg = InboundMessage(
|
||||
sender_id=body.sender_id.strip(),
|
||||
message_id=body.message_id.strip(),
|
||||
content=body.content or "",
|
||||
msg_type=body.msg_type or "text",
|
||||
chat_id=body.chat_id or "",
|
||||
chat_type=body.chat_type or "group",
|
||||
agent_id=body.agent_id or "",
|
||||
create_time=int(body.create_time or 0),
|
||||
media=body.media or {},
|
||||
raw=body.raw or {},
|
||||
)
|
||||
if not msg.has_sender():
|
||||
raise HTTPException(status_code=400, detail="missing_sender_id")
|
||||
if not msg.message_id:
|
||||
raise HTTPException(status_code=400, detail="missing_message_id")
|
||||
|
||||
ok, info = get_message_store().enqueue_inbound(msg)
|
||||
logger.info(
|
||||
"aibot.inbound ok=%s info=%s sender=%s msg_id=%s",
|
||||
ok,
|
||||
info,
|
||||
msg.sender_id,
|
||||
msg.message_id,
|
||||
)
|
||||
return {"status": "accepted" if ok else "duplicate", "detail": info}
|
||||
@@ -1,18 +1,102 @@
|
||||
"""
|
||||
主账唤醒桥接路由(合并原 bridge_api)。
|
||||
|
||||
本文件职责:接收主账鉴权后的 wake 事件,入队由 Worker 结构化 resume。
|
||||
本文件职责:校验 callback token,接收结构化 wake,写入 Redis Stream 后快回。
|
||||
禁止:在本请求线程跑完整 Graph;禁止本包直连 MySQL / TMS。
|
||||
Worker:jobs.wake_consumer 认领后 GraphRuntime.wake_from_worker。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from agent.config import get_settings
|
||||
from agent.graph.wake import WorkerWakePayload
|
||||
from agent.jobs.wake_consumer import enqueue_wake
|
||||
from agent.redis_coord import get_redis_runtime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/internal/bridge", tags=["bridge"])
|
||||
|
||||
|
||||
class BridgeWakeBody(BaseModel):
|
||||
"""主账 → 智能体结构化唤醒。"""
|
||||
|
||||
thread_id: str
|
||||
inquiry_no: str
|
||||
quote_version: int = 0
|
||||
wait_version: int = 0
|
||||
kind: str = Field(description="如 recognition_done / pdf_done / ledger_transition")
|
||||
detail: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
def _expected_token() -> str:
|
||||
s = get_settings()
|
||||
return (s.agent_callback_token or s.inquiry_agent_callback_token or "").strip()
|
||||
|
||||
|
||||
def _check_token(authorization: Optional[str], x_agent_token: Optional[str]) -> None:
|
||||
expected = _expected_token()
|
||||
if not expected:
|
||||
if (get_settings().ytd_env or "").lower() == "prod":
|
||||
raise HTTPException(status_code=503, detail="callback token 未配置")
|
||||
logger.warning("bridge:未配置 callback token,test 允许空校验(仅骨架)")
|
||||
return
|
||||
provided = (x_agent_token or "").strip()
|
||||
if not provided and authorization:
|
||||
auth = authorization.strip()
|
||||
if auth.lower().startswith("bearer "):
|
||||
provided = auth[7:].strip()
|
||||
else:
|
||||
provided = auth
|
||||
if provided != expected:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
@router.get("/ping")
|
||||
def bridge_ping() -> dict[str, str]:
|
||||
"""主账唤醒路径占位;正式实现需校验 AGENT_CALLBACK_TOKEN。"""
|
||||
return {"status": "ok", "channel": "bridge", "note": "scaffold-only"}
|
||||
return {"status": "ok", "channel": "bridge"}
|
||||
|
||||
|
||||
@router.post("/wake")
|
||||
def bridge_wake(
|
||||
body: BridgeWakeBody,
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
x_agent_callback_token: Optional[str] = Header(
|
||||
default=None, alias="X-Agent-Callback-Token"
|
||||
),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
接收结构化 wake:校验后写入 Redis Stream,立即返回。
|
||||
|
||||
不在此 invoke Graph。
|
||||
"""
|
||||
_check_token(authorization, x_agent_callback_token)
|
||||
try:
|
||||
payload = WorkerWakePayload(
|
||||
thread_id=body.thread_id,
|
||||
inquiry_no=body.inquiry_no,
|
||||
quote_version=body.quote_version,
|
||||
wait_version=body.wait_version,
|
||||
kind=body.kind,
|
||||
detail=body.detail,
|
||||
)
|
||||
entry_id = enqueue_wake(get_redis_runtime().client, payload)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("bridge.wake 入队失败")
|
||||
raise HTTPException(status_code=503, detail=f"enqueue_failed:{exc}") from exc
|
||||
|
||||
logger.info(
|
||||
"bridge.wake 已入队 Redis thread=%s kind=%s id=%s",
|
||||
body.thread_id,
|
||||
body.kind,
|
||||
entry_id,
|
||||
)
|
||||
return {"status": "accepted", "entry_id": entry_id}
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
"""
|
||||
clarification / H5 token 绑定(骨架)。
|
||||
|
||||
本文件职责:签发与校验一次性 token;优先写 PG clarification_binding,无库则内存。
|
||||
禁止:URL 携带 userid;身份以绑定时的 sender_id 为准。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
from agent.config import get_settings
|
||||
from agent.runtime_db import assert_safe_database, connect_psycopg
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# H5 TTL 30 分钟(prompt/14)
|
||||
DEFAULT_TTL_SECONDS = 30 * 60
|
||||
|
||||
|
||||
@dataclass
|
||||
class ClarificationRecord:
|
||||
token: str
|
||||
thread_id: str
|
||||
wait_version: int
|
||||
sender_id: str
|
||||
allowed_actions: list[str]
|
||||
expires_at: float
|
||||
consumed: bool = False
|
||||
|
||||
|
||||
_MEM: dict[str, ClarificationRecord] = {}
|
||||
_MEM_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def issue_token(
|
||||
*,
|
||||
thread_id: str,
|
||||
wait_version: int,
|
||||
sender_id: str,
|
||||
allowed_actions: list[str],
|
||||
ttl_seconds: int = DEFAULT_TTL_SECONDS,
|
||||
) -> str:
|
||||
"""
|
||||
签发 clarification token。
|
||||
|
||||
副作用:写 PG 或内存;返回随机 token(不进 URL 的 userid)。
|
||||
"""
|
||||
token = secrets.token_urlsafe(24)
|
||||
expires = time.time() + ttl_seconds
|
||||
rec = ClarificationRecord(
|
||||
token=token,
|
||||
thread_id=thread_id,
|
||||
wait_version=wait_version,
|
||||
sender_id=sender_id,
|
||||
allowed_actions=list(allowed_actions),
|
||||
expires_at=expires,
|
||||
)
|
||||
if _try_pg_insert(rec, ttl_seconds):
|
||||
return token
|
||||
with _MEM_LOCK:
|
||||
_MEM[token] = rec
|
||||
logger.info("clarification 内存签发 thread=%s wait=%s", thread_id, wait_version)
|
||||
return token
|
||||
|
||||
|
||||
def validate_token(
|
||||
token: str,
|
||||
*,
|
||||
action: str = "",
|
||||
consume: bool = False,
|
||||
) -> Optional[ClarificationRecord]:
|
||||
"""
|
||||
校验 token:存在、未过期、未消费;若指定 action 须在允许集合。
|
||||
|
||||
consume=True:一次性消费。
|
||||
"""
|
||||
if not (token or "").strip():
|
||||
return None
|
||||
rec = _try_pg_load(token) or _mem_load(token)
|
||||
if rec is None:
|
||||
return None
|
||||
if rec.consumed or rec.expires_at < time.time():
|
||||
return None
|
||||
if action and action not in rec.allowed_actions:
|
||||
return None
|
||||
if consume:
|
||||
_consume(token)
|
||||
rec.consumed = True
|
||||
return rec
|
||||
|
||||
|
||||
def _mem_load(token: str) -> Optional[ClarificationRecord]:
|
||||
with _MEM_LOCK:
|
||||
return _MEM.get(token)
|
||||
|
||||
|
||||
def _consume(token: str) -> None:
|
||||
if _try_pg_consume(token):
|
||||
return
|
||||
with _MEM_LOCK:
|
||||
rec = _MEM.get(token)
|
||||
if rec:
|
||||
rec.consumed = True
|
||||
|
||||
|
||||
def _try_pg_insert(rec: ClarificationRecord, ttl_seconds: int) -> bool:
|
||||
settings = get_settings()
|
||||
dsn = settings.resolve_pg_dsn()
|
||||
if not dsn:
|
||||
return False
|
||||
try:
|
||||
assert_safe_database(dsn)
|
||||
expires = datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds)
|
||||
import json
|
||||
|
||||
with connect_psycopg(dsn) as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO clarification_binding (
|
||||
token, thread_id, wait_version, sender_id, allowed_actions, expires_at
|
||||
) VALUES (%s, %s, %s, %s, %s::jsonb, %s)
|
||||
""",
|
||||
(
|
||||
rec.token,
|
||||
rec.thread_id,
|
||||
rec.wait_version,
|
||||
rec.sender_id,
|
||||
json.dumps(rec.allowed_actions, ensure_ascii=False),
|
||||
expires,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("clarification PG 写入失败,改用内存:%s", exc)
|
||||
return False
|
||||
|
||||
|
||||
def _try_pg_load(token: str) -> Optional[ClarificationRecord]:
|
||||
settings = get_settings()
|
||||
dsn = settings.resolve_pg_dsn()
|
||||
if not dsn:
|
||||
return None
|
||||
try:
|
||||
with connect_psycopg(dsn) as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT thread_id, wait_version, sender_id, allowed_actions,
|
||||
EXTRACT(EPOCH FROM expires_at), consumed_at
|
||||
FROM clarification_binding WHERE token = %s
|
||||
""",
|
||||
(token,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
actions = row[3]
|
||||
if isinstance(actions, str):
|
||||
import json
|
||||
|
||||
actions = json.loads(actions)
|
||||
return ClarificationRecord(
|
||||
token=token,
|
||||
thread_id=str(row[0]),
|
||||
wait_version=int(row[1]),
|
||||
sender_id=str(row[2]),
|
||||
allowed_actions=list(actions or []),
|
||||
expires_at=float(row[4] or 0),
|
||||
consumed=row[5] is not None,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _try_pg_consume(token: str) -> bool:
|
||||
settings = get_settings()
|
||||
dsn = settings.resolve_pg_dsn()
|
||||
if not dsn:
|
||||
return False
|
||||
try:
|
||||
with connect_psycopg(dsn) as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE clarification_binding
|
||||
SET consumed_at = NOW()
|
||||
WHERE token = %s AND consumed_at IS NULL
|
||||
""",
|
||||
(token,),
|
||||
)
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
@@ -1,22 +1,79 @@
|
||||
"""
|
||||
H5 补问 / 附件上传通道。
|
||||
|
||||
本文件职责:挂载 /inquiry-form 相关壳路由;字段快照与流程状态在 Graph/PG,不在本包。
|
||||
禁止:从 URL 读 userid;禁止在本包改六态或直连 TMS。
|
||||
本文件职责:挂载 /inquiry-form;用 clarification token 绑定身份(URL 禁止 userid)。
|
||||
禁止:从 URL 读 userid;禁止在本包改六态或直连 TMS;禁止同步 invoke Graph。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from agent.channel.clarification import validate_token
|
||||
from agent.handlers.card_action import handle_card_action
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/inquiry-form", tags=["h5"])
|
||||
|
||||
|
||||
class H5SubmitBody(BaseModel):
|
||||
"""H5 提交体:业务字段放 fields;身份只认服务端 token 绑定。"""
|
||||
|
||||
action: str = Field(default="submit_clarify")
|
||||
fields: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
@router.get("/ping")
|
||||
def h5_ping() -> dict[str, str]:
|
||||
"""
|
||||
H5 路由占位探测。
|
||||
"""存活探测。"""
|
||||
return {"status": "ok", "channel": "h5"}
|
||||
|
||||
正式页用一次性 token;骨架不校验 token、不落库。
|
||||
|
||||
@router.get("/{token}")
|
||||
def h5_open(token: str) -> dict[str, Any]:
|
||||
"""
|
||||
return {"status": "ok", "channel": "h5", "note": "scaffold-only"}
|
||||
打开补问页:校验 token 未过期。
|
||||
|
||||
返回允许动作与 wait_version;不返回内部异常栈。
|
||||
"""
|
||||
rec = validate_token(token)
|
||||
if rec is None:
|
||||
raise HTTPException(status_code=410, detail="表单已过期或无效,请回企微重新打开")
|
||||
return {
|
||||
"status": "ok",
|
||||
"thread_id": rec.thread_id,
|
||||
"wait_version": rec.wait_version,
|
||||
"allowed_actions": rec.allowed_actions,
|
||||
"note": "骨架:字段列表后续按合同生成",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{token}/submit")
|
||||
def h5_submit(token: str, body: H5SubmitBody) -> dict[str, Any]:
|
||||
"""
|
||||
提交补问:消费 token,转入 card_action 骨架(不跑整图)。
|
||||
|
||||
副作用:token 一次性;入队/Handler 后续接 Worker。
|
||||
"""
|
||||
rec = validate_token(token, action=body.action or "submit_clarify", consume=True)
|
||||
if rec is None:
|
||||
raise HTTPException(status_code=410, detail="表单已过期或无效,请回企微重新打开")
|
||||
handle_card_action(
|
||||
sender_id=rec.sender_id,
|
||||
thread_id=rec.thread_id,
|
||||
wait_version=rec.wait_version,
|
||||
action=body.action or "submit_clarify",
|
||||
payload=body.fields,
|
||||
)
|
||||
logger.info(
|
||||
"h5.submit ok thread=%s wait=%s action=%s",
|
||||
rec.thread_id,
|
||||
rec.wait_version,
|
||||
body.action,
|
||||
)
|
||||
return {"status": "accepted", "thread_id": rec.thread_id}
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
"""
|
||||
PostgreSQL inbox / outbox 账本。
|
||||
|
||||
本文件职责:落 agent_inbox / agent_outbox;按条认领 + 超时回收。
|
||||
调用:需已执行 migrations/001_runtime_core_v1.sql。
|
||||
禁止:在回调线程跑长事务;单次操作短 SQL。
|
||||
线程:每个方法短连接或共用连接需自行串行;本实现每操作用独立短连接,避免跨线程共享 cursor。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
from agent.channel.queue import InboxItem, OutboxItem, TaskState
|
||||
from agent.channel.wecom.models import InboundMessage
|
||||
from agent.runtime_db import assert_safe_database, connect_psycopg
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class PostgresMessageStore:
|
||||
"""
|
||||
PG 消息账本。
|
||||
|
||||
claim_timeout_sec:认领超时后可被其他消费者回收。
|
||||
claimed_by:本进程标识,便于排查。
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dsn: str,
|
||||
*,
|
||||
claim_timeout_sec: float = 120.0,
|
||||
worker_id: str = "",
|
||||
) -> None:
|
||||
assert_safe_database(dsn)
|
||||
self._dsn = dsn
|
||||
self._claim_timeout = claim_timeout_sec
|
||||
self._worker_id = worker_id or f"pid-{threading.get_ident()}"
|
||||
self._inbox_event = threading.Event()
|
||||
self._outbox_event = threading.Event()
|
||||
|
||||
def enqueue_inbound(self, message: InboundMessage) -> tuple[bool, str]:
|
||||
"""写入 agent_inbox;message_id 唯一冲突视为重复。"""
|
||||
if not message.has_sender():
|
||||
return False, "missing_sender_id"
|
||||
item_id = str(uuid.uuid4())
|
||||
payload = json.dumps(message.to_dict(), ensure_ascii=False)
|
||||
try:
|
||||
with connect_psycopg(self._dsn) as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO agent_inbox (
|
||||
id, message_id, sender_id, chat_id, chat_type, payload, state
|
||||
) VALUES (%s, %s, %s, %s, %s, %s::jsonb, 'pending')
|
||||
""",
|
||||
(
|
||||
item_id,
|
||||
message.message_id,
|
||||
message.sender_id,
|
||||
message.chat_id,
|
||||
message.chat_type,
|
||||
payload,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
self._inbox_event.set()
|
||||
logger.info(
|
||||
"pg inbox 入队 id=%s msg_id=%s sender=%s",
|
||||
item_id,
|
||||
message.message_id,
|
||||
message.sender_id,
|
||||
)
|
||||
return True, item_id
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# unique_violation
|
||||
if "unique" in str(exc).lower() or "duplicate" in str(exc).lower():
|
||||
return False, "duplicate_message_id"
|
||||
logger.exception("pg inbox 入队失败")
|
||||
raise
|
||||
|
||||
def claim_inbound(self) -> Optional[InboxItem]:
|
||||
"""认领一条 pending 或超时 claimed。"""
|
||||
timeout = int(self._claim_timeout)
|
||||
with connect_psycopg(self._dsn) as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
WITH cte AS (
|
||||
SELECT id FROM agent_inbox
|
||||
WHERE state = 'pending'
|
||||
OR (
|
||||
state = 'claimed'
|
||||
AND claimed_at IS NOT NULL
|
||||
AND claimed_at < NOW() - (%s || ' seconds')::interval
|
||||
)
|
||||
ORDER BY created_at
|
||||
FOR UPDATE SKIP LOCKED
|
||||
LIMIT 1
|
||||
)
|
||||
UPDATE agent_inbox i
|
||||
SET state = 'claimed',
|
||||
claimed_at = NOW(),
|
||||
claimed_by = %s,
|
||||
attempts = attempts + 1,
|
||||
updated_at = NOW()
|
||||
FROM cte
|
||||
WHERE i.id = cte.id
|
||||
RETURNING i.id, i.payload, i.attempts, i.last_error, i.claimed_at
|
||||
""",
|
||||
(str(timeout), self._worker_id),
|
||||
).fetchone()
|
||||
conn.commit()
|
||||
if not row:
|
||||
self._inbox_event.clear()
|
||||
return None
|
||||
payload = row[1]
|
||||
if isinstance(payload, str):
|
||||
payload = json.loads(payload)
|
||||
msg = InboundMessage.from_dict(dict(payload))
|
||||
claimed_at = row[4]
|
||||
ts = claimed_at.timestamp() if hasattr(claimed_at, "timestamp") else time.time()
|
||||
return InboxItem(
|
||||
id=str(row[0]),
|
||||
message=msg,
|
||||
state=TaskState.CLAIMED,
|
||||
claimed_at=ts,
|
||||
attempts=int(row[2] or 0),
|
||||
last_error=str(row[3] or ""),
|
||||
)
|
||||
|
||||
def complete_inbound(self, item_id: str, *, error: str = "") -> None:
|
||||
state = "failed" if error else "done"
|
||||
with connect_psycopg(self._dsn) as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE agent_inbox
|
||||
SET state = %s, last_error = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(state, error or "", item_id),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def enqueue_outbound(
|
||||
self,
|
||||
*,
|
||||
touser: str,
|
||||
content: str,
|
||||
dedupe_key: str = "",
|
||||
) -> tuple[bool, str]:
|
||||
if not touser or not content:
|
||||
return False, "invalid_outbox"
|
||||
item_id = str(uuid.uuid4())
|
||||
try:
|
||||
with connect_psycopg(self._dsn) as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO agent_outbox (
|
||||
id, dedupe_key, touser, content, payload, state
|
||||
) VALUES (%s, %s, %s, %s, '{}'::jsonb, 'pending')
|
||||
""",
|
||||
(item_id, dedupe_key or "", touser, content),
|
||||
)
|
||||
conn.commit()
|
||||
self._outbox_event.set()
|
||||
logger.info("pg outbox 入队 id=%s touser=%s", item_id, touser)
|
||||
return True, item_id
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if dedupe_key and (
|
||||
"unique" in str(exc).lower() or "duplicate" in str(exc).lower()
|
||||
):
|
||||
return False, "duplicate_outbox"
|
||||
logger.exception("pg outbox 入队失败")
|
||||
raise
|
||||
|
||||
def claim_outbound(self) -> Optional[OutboxItem]:
|
||||
timeout = int(self._claim_timeout)
|
||||
with connect_psycopg(self._dsn) as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
WITH cte AS (
|
||||
SELECT id FROM agent_outbox
|
||||
WHERE state = 'pending'
|
||||
OR (
|
||||
state = 'claimed'
|
||||
AND claimed_at IS NOT NULL
|
||||
AND claimed_at < NOW() - (%s || ' seconds')::interval
|
||||
)
|
||||
ORDER BY created_at
|
||||
FOR UPDATE SKIP LOCKED
|
||||
LIMIT 1
|
||||
)
|
||||
UPDATE agent_outbox o
|
||||
SET state = 'claimed',
|
||||
claimed_at = NOW(),
|
||||
claimed_by = %s,
|
||||
attempts = attempts + 1,
|
||||
updated_at = NOW()
|
||||
FROM cte
|
||||
WHERE o.id = cte.id
|
||||
RETURNING o.id, o.touser, o.content, o.attempts, o.last_error,
|
||||
o.created_at, o.dedupe_key, o.claimed_at
|
||||
""",
|
||||
(str(timeout), self._worker_id),
|
||||
).fetchone()
|
||||
conn.commit()
|
||||
if not row:
|
||||
self._outbox_event.clear()
|
||||
return None
|
||||
created = row[5]
|
||||
created_ts = created.timestamp() if hasattr(created, "timestamp") else time.time()
|
||||
claimed = row[7]
|
||||
claimed_ts = claimed.timestamp() if hasattr(claimed, "timestamp") else time.time()
|
||||
return OutboxItem(
|
||||
id=str(row[0]),
|
||||
touser=str(row[1]),
|
||||
content=str(row[2]),
|
||||
state=TaskState.CLAIMED,
|
||||
claimed_at=claimed_ts,
|
||||
attempts=int(row[3] or 0),
|
||||
last_error=str(row[4] or ""),
|
||||
created_at=created_ts,
|
||||
dedupe_key=str(row[6] or ""),
|
||||
)
|
||||
|
||||
def complete_outbound(
|
||||
self, item_id: str, *, error: str = "", permanent: bool = False
|
||||
) -> None:
|
||||
with connect_psycopg(self._dsn) as conn:
|
||||
if error:
|
||||
row = conn.execute(
|
||||
"SELECT attempts FROM agent_outbox WHERE id = %s",
|
||||
(item_id,),
|
||||
).fetchone()
|
||||
attempts = int(row[0]) if row else 0
|
||||
if permanent or attempts >= 5:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE agent_outbox
|
||||
SET state = 'failed', last_error = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(error, item_id),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE agent_outbox
|
||||
SET state = 'pending', claimed_at = NULL, claimed_by = '',
|
||||
last_error = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(error, item_id),
|
||||
)
|
||||
self._outbox_event.set()
|
||||
else:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE agent_outbox
|
||||
SET state = 'done', last_error = '', updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(item_id,),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def wait_inbox(self, timeout: float = 1.0) -> None:
|
||||
self._inbox_event.wait(timeout=timeout)
|
||||
|
||||
def wait_outbox(self, timeout: float = 1.0) -> None:
|
||||
self._outbox_event.wait(timeout=timeout)
|
||||
|
||||
def stats(self) -> dict[str, Any]:
|
||||
with connect_psycopg(self._dsn) as conn:
|
||||
inbox = conn.execute(
|
||||
"SELECT COUNT(*) FROM agent_inbox WHERE state IN ('pending','claimed')"
|
||||
).fetchone()
|
||||
outbox = conn.execute(
|
||||
"SELECT COUNT(*) FROM agent_outbox WHERE state IN ('pending','claimed')"
|
||||
).fetchone()
|
||||
return {
|
||||
"backend": "postgres",
|
||||
"inbox": int(inbox[0] if inbox else 0),
|
||||
"outbox": int(outbox[0] if outbox else 0),
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
进程内 inbox / outbox 队列(骨架过渡实现)。
|
||||
进程内 / PostgreSQL inbox·outbox 账本。
|
||||
|
||||
本文件职责:回调快写入队、按条认领、message_id 去重;后续可替换为 PostgreSQL 表。
|
||||
本文件职责:定义任务结构、Memory 实现、按配置选择后端工厂。
|
||||
禁止:Redis 全局 Worker 单例锁;禁止在回调线程里等 LLM。
|
||||
为何先用内存:先打通「收消息→回复」联调;落 PG 迁移不挡本迭代验收。
|
||||
有 PG_DSN 且 MESSAGE_STORE_BACKEND=postgres|auto 时用表;否则内存(本机联调)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +15,7 @@ import uuid
|
||||
from collections import OrderedDict
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, Optional
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from agent.channel.wecom.models import InboundMessage
|
||||
|
||||
@@ -207,6 +207,7 @@ class MemoryMessageStore:
|
||||
def stats(self) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
return {
|
||||
"backend": "memory",
|
||||
"inbox": len(self._inbox),
|
||||
"outbox": len(self._outbox),
|
||||
"seen_msg": len(self._seen_msg),
|
||||
@@ -218,15 +219,55 @@ class MemoryMessageStore:
|
||||
store.popitem(last=False)
|
||||
|
||||
|
||||
# 进程内单例:HTTP 回调与消费线程共享(同进程)。多进程部署时必须换 PG。
|
||||
_STORE: Optional[MemoryMessageStore] = None
|
||||
MessageStoreImpl = Union[MemoryMessageStore, Any]
|
||||
|
||||
_STORE: Optional[MessageStoreImpl] = None
|
||||
_STORE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def get_message_store() -> MemoryMessageStore:
|
||||
"""获取进程内消息账本单例。"""
|
||||
def get_message_store() -> MessageStoreImpl:
|
||||
"""
|
||||
获取消息账本单例。
|
||||
|
||||
MESSAGE_STORE_BACKEND=postgres 且 PG 可用 → PostgresMessageStore;
|
||||
auto 有 DSN 则尝试 PG,失败回退内存;memory 强制内存。
|
||||
"""
|
||||
global _STORE
|
||||
with _STORE_LOCK:
|
||||
if _STORE is None:
|
||||
_STORE = MemoryMessageStore()
|
||||
_STORE = _create_store()
|
||||
return _STORE
|
||||
|
||||
|
||||
def reset_message_store_for_tests() -> None:
|
||||
"""仅自检用:清空单例。"""
|
||||
global _STORE
|
||||
with _STORE_LOCK:
|
||||
_STORE = None
|
||||
|
||||
|
||||
def _create_store() -> MessageStoreImpl:
|
||||
from agent.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
backend = (getattr(settings, "message_store_backend", None) or "auto").strip().lower()
|
||||
dsn = settings.resolve_pg_dsn()
|
||||
|
||||
use_pg = backend == "postgres" or (backend == "auto" and bool(dsn))
|
||||
if use_pg and dsn:
|
||||
try:
|
||||
from agent.channel.pg_store import PostgresMessageStore
|
||||
from agent.runtime_db import assert_safe_database
|
||||
|
||||
assert_safe_database(dsn)
|
||||
store = PostgresMessageStore(dsn)
|
||||
store.stats()
|
||||
logger.info("消息账本后端=postgres")
|
||||
return store
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if backend == "postgres":
|
||||
raise
|
||||
logger.warning("PG 消息账本不可用,回退内存:%s", exc)
|
||||
|
||||
logger.info("消息账本后端=memory")
|
||||
return MemoryMessageStore()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
通道消费循环:inbox → echo handler;outbox → 企微发送。
|
||||
通道消费循环:inbox → RouteDecision → dispatch → handler;outbox → 企微发送。
|
||||
|
||||
本文件职责:在 HTTP 进程内独立线程跑快路径,不与 LibreOffice 串队。
|
||||
禁止:在回调请求线程调用本循环的阻塞逻辑;禁止 Redis 全局单例锁。
|
||||
@@ -12,9 +12,10 @@ import threading
|
||||
from typing import Optional
|
||||
|
||||
from agent.channel.outbox.sender import PERMANENT_SEND_ERRORS, WeComAppClient
|
||||
from agent.channel.queue import MemoryMessageStore, get_message_store
|
||||
from agent.channel.queue import get_message_store
|
||||
from agent.config import Settings
|
||||
from agent.handlers.echo_text import handle_echo_text
|
||||
from agent.routing import IntentRouter
|
||||
from agent.routing.dispatch import dispatch_inbound
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
# 避免 httpx 把 access_token / secret 打进 INFO
|
||||
@@ -26,6 +27,7 @@ class ChannelRuntime:
|
||||
企微通道运行时:inbox/outbox 各一条守护线程。
|
||||
|
||||
启动时机:FastAPI lifespan;停止:进程退出。
|
||||
inbox:IntentRouter.route(默认 stub)→ dispatch 查表;无业务分支森林。
|
||||
"""
|
||||
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
@@ -33,6 +35,7 @@ class ChannelRuntime:
|
||||
self._store = get_message_store()
|
||||
self._stop = threading.Event()
|
||||
self._threads: list[threading.Thread] = []
|
||||
self._router = IntentRouter(allow_network=False)
|
||||
agent_id = int(settings.wecom_agent_id or "0") or 0
|
||||
self._client = WeComAppClient(
|
||||
corp_id=settings.wecom_corp_id,
|
||||
@@ -41,7 +44,7 @@ class ChannelRuntime:
|
||||
)
|
||||
|
||||
@property
|
||||
def store(self) -> MemoryMessageStore:
|
||||
def store(self):
|
||||
return self._store
|
||||
|
||||
def start(self) -> None:
|
||||
@@ -53,7 +56,7 @@ class ChannelRuntime:
|
||||
]
|
||||
for t in self._threads:
|
||||
t.start()
|
||||
logger.info("ChannelRuntime 已启动(inbox/outbox 独立线程)")
|
||||
logger.info("ChannelRuntime 已启动(inbox/outbox 独立线程;dispatch 分发)")
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stop.set()
|
||||
@@ -65,12 +68,11 @@ class ChannelRuntime:
|
||||
self._store.wait_inbox(1.0)
|
||||
continue
|
||||
try:
|
||||
handle_echo_text(
|
||||
item.message,
|
||||
self._store,
|
||||
ytd_env=self._settings.ytd_env,
|
||||
reply_template=self._settings.wecom_callback_reply_text,
|
||||
decision = self._router.route(
|
||||
text=item.message.content or "",
|
||||
sender_id=item.message.sender_id or "",
|
||||
)
|
||||
dispatch_inbound(item.message, decision)
|
||||
self._store.complete_inbound(item.id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("inbox 处理失败 id=%s", item.id)
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
消息账本协议:inbox / outbox 认领接口。
|
||||
|
||||
Memory 与 Postgres 实现共用此协议,通道运行时不依赖具体后端。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional, Protocol
|
||||
|
||||
from agent.channel.queue import InboxItem, OutboxItem
|
||||
from agent.channel.wecom.models import InboundMessage
|
||||
|
||||
|
||||
class MessageStore(Protocol):
|
||||
"""inbox/outbox 账本协议。"""
|
||||
|
||||
def enqueue_inbound(self, message: InboundMessage) -> tuple[bool, str]: ...
|
||||
|
||||
def claim_inbound(self) -> Optional[InboxItem]: ...
|
||||
|
||||
def complete_inbound(self, item_id: str, *, error: str = "") -> None: ...
|
||||
|
||||
def enqueue_outbound(
|
||||
self,
|
||||
*,
|
||||
touser: str,
|
||||
content: str,
|
||||
dedupe_key: str = "",
|
||||
) -> tuple[bool, str]: ...
|
||||
|
||||
def claim_outbound(self) -> Optional[OutboxItem]: ...
|
||||
|
||||
def complete_outbound(
|
||||
self, item_id: str, *, error: str = "", permanent: bool = False
|
||||
) -> None: ...
|
||||
|
||||
def wait_inbox(self, timeout: float = 1.0) -> None: ...
|
||||
|
||||
def wait_outbox(self, timeout: float = 1.0) -> None: ...
|
||||
|
||||
def stats(self) -> dict[str, Any]: ...
|
||||
@@ -35,3 +35,34 @@ class InboundMessage:
|
||||
def has_sender(self) -> bool:
|
||||
"""是否具备可进入业务的发送人身份。"""
|
||||
return bool(self.sender_id and self.sender_id.strip())
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""序列化进 PG JSONB;不含密钥。"""
|
||||
return {
|
||||
"sender_id": self.sender_id,
|
||||
"message_id": self.message_id,
|
||||
"content": self.content,
|
||||
"msg_type": self.msg_type,
|
||||
"chat_id": self.chat_id,
|
||||
"chat_type": self.chat_type,
|
||||
"agent_id": self.agent_id,
|
||||
"create_time": self.create_time,
|
||||
"media": self.media,
|
||||
"raw": self.raw,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> "InboundMessage":
|
||||
"""从 JSONB / dict 还原。"""
|
||||
return cls(
|
||||
sender_id=str(data.get("sender_id") or ""),
|
||||
message_id=str(data.get("message_id") or ""),
|
||||
content=str(data.get("content") or ""),
|
||||
msg_type=str(data.get("msg_type") or "text"),
|
||||
chat_id=str(data.get("chat_id") or ""),
|
||||
chat_type=str(data.get("chat_type") or "single"),
|
||||
agent_id=str(data.get("agent_id") or ""),
|
||||
create_time=int(data.get("create_time") or 0),
|
||||
media=dict(data.get("media") or {}),
|
||||
raw=dict(data.get("raw") or {}),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user