🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
fix(qq): qq group @ into LobeHub and reply in window (#22921)
Arvin Xuf9bcf152f035
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex 1b3d176ab43..6d920309cc8 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -45,6 +45,11 @@ export const RedisKeyNamespace = {* can use them even when another one received the message.*/BOT_REPLY: 'bot-reply',+ /**+ * QQ passive-reply windows: the inbound message a bot may answer, the replies spent, and the+ * text a closed window could not carry.+ */+ QQ_PASSIVE: 'qq-passive',/*** AI generation related keys (agent welcome, placeholders, etc.)*/@@ -305,6 +310,22 @@ export const RedisKeys = {workspaceRescanClaim: (userId: string, pool: string, deviceId: string, cwd: string): string =>`workspace_rescan_claim:v1:${userId}:${pool}:${deviceId}:${cwd}`,},+ /**+ * QQ passive-reply scope — see {@link RedisKeyNamespace.QQ_PASSIVE}. `{key}` is+ * `{applicationId}:{threadId}`.+ */+ qqPassive: {+ /**+ * The inbound message that opened the current window, the replies spent in it.+ * Full key: qq-passive:window:v1:{applicationId}:{threadId}+ */+ window: (key: string): string => `window:v1:${key}`,+ /**+ * The reply a closed window could not carry, waiting for the next inbound message.+ * Full key: qq-passive:pending:v1:{applicationId}:{threadId}+ */+ pending: (key: string): string => `pending:v1:${key}`,+ },} as const;/**@@ -322,6 +343,7 @@ export const RedisKeyScopeNamespace = {botWake: RedisKeyNamespace.BOT_WAKE,integrations: RedisKeyNamespace.INTEGRATIONS,lobechat: RedisKeyNamespace.LOBEHUB,+ qqPassive: RedisKeyNamespace.QQ_PASSIVE,sendPathCache: RedisKeyNamespace.SEND_PATH_CACHE,} as const satisfies Record<keyof typeof RedisKeys,diff --git a/apps/server/src/services/bot/platforms/qq/client.ts b/apps/server/src/services/bot/platforms/qq/client.tsindex e3fd50b9ad8..8da1106c23f 100644--- a/apps/server/src/services/bot/platforms/qq/client.ts+++ b/apps/server/src/services/bot/platforms/qq/client.ts@@ -1,5 +1,11 @@import type { QQAdapter } from '@lobechat/chat-adapter-qq';-import { createQQAdapter, QQApiClient } from '@lobechat/chat-adapter-qq';+import {+ createQQAdapter,+ isQQActiveRateLimited,+ isQQDuplicateReply,+ isQQPassiveExpired,+ QQApiClient,+} from '@lobechat/chat-adapter-qq';import type { Chat as ChatBot, Message } from 'chat';import debug from 'debug';@@ -9,6 +15,7 @@ import {getRuntimeStatusErrorMessage,updateBotRuntimeStatus,} from '@/server/services/gateway/runtimeStatus';+import { redisService } from '@/server/services/redis';import { stripMarkdown } from '../stripMarkdown';import {@@ -22,6 +29,12 @@ import {type ValidationResult,} from '../types';import { formatUsageStats } from '../utils';+import {+ deferQQReply,+ reserveQQReply,+ sendQQMessageActive,+ sendQQMessageInSlot,+} from './passiveReply';import { sendQQAttachments } from './sendAttachments';const log = debug('bot-platform:qq:bot');@@ -42,32 +55,40 @@ function extractThreadType(platformThreadId: string): string {return platformThreadId.split(':')[1] || 'group';}+/**+ * Text send, cheapest transport first: a passive reply inside the inbound message's window, then+ * an active message (QQ accepts those, rate limited per bot and per group), and only when both are+ * unavailable park the text for the next inbound message.+ */async function sendQQMessage(api: QQApiClient,+ applicationId: string,+ platformThreadId: string,threadType: string,targetId: string,content: string,): Promise<void> {- switch (threadType) {- case 'group': {- await api.sendGroupMessage(targetId, content);- return;- }- case 'guild': {- await api.sendGuildMessage(targetId, content);- return;- }- case 'c2c': {- await api.sendC2CMessage(targetId, content);- return;- }- case 'dms': {- await api.sendDmsMessage(targetId, content);+ const slot = await reserveQQReply(applicationId, platformThreadId, threadType);++ if (slot) {+ try {+ await sendQQMessageInSlot(api, threadType, targetId, content, slot);return;+ } catch (error) {+ if (isQQDuplicateReply(error)) return;+ if (!isQQPassiveExpired(error)) throw error;++ log('passive window refused a reply in %s, retrying as active', platformThreadId);}- default: {- await api.sendGroupMessage(targetId, content);- }+ }++ try {+ await sendQQMessageActive(api, threadType, targetId, content);+ } catch (error) {+ if (!isQQActiveRateLimited(error)) throw error;++ log('active-message quota exhausted in %s, deferring', platformThreadId);+ await deferQQReply(applicationId, platformThreadId, content);}}@@ -262,12 +283,14 @@ class QQGatewayClient implements PlatformClient {qq: createQQAdapter({appId: this.config.applicationId,clientSecret: this.config.credentials.appSecret,+ passiveStore: redisService.qqPassive,}),};}getMessenger(platformThreadId: string): PlatformMessenger {const api = new QQApiClient(this.config.applicationId, this.config.credentials.appSecret);+ const applicationId = this.config.applicationId;const targetId = extractChatId(platformThreadId);const threadType = extractThreadType(platformThreadId);return {@@ -278,11 +301,18 @@ class QQGatewayClient implements PlatformClient {await sendQQAttachments(api, threadType, targetId, attachments, text);return;}- await sendQQMessage(api, threadType, targetId, text);+ await sendQQMessage(api, applicationId, platformThreadId, threadType, targetId, text);},editMessage: (_messageId, content) =>// QQ does not support editing — send a new message as fallback- sendQQMessage(api, threadType, targetId, messengerContentText(content)),+ sendQQMessage(+ api,+ applicationId,+ platformThreadId,+ threadType,+ targetId,+ messengerContentText(content),+ ),// QQ Bot API doesn't support reactions or typingremoveReaction: () => Promise.resolve(),};@@ -370,12 +400,14 @@ class QQWebhookClient implements PlatformClient {qq: createQQAdapter({appId: this.config.applicationId,clientSecret: this.config.credentials.appSecret,+ passiveStore: redisService.qqPassive,}),};}getMessenger(platformThreadId: string): PlatformMessenger {const api = new QQApiClient(this.config.applicationId, this.config.credentials.appSecret);+ const applicationId = this.config.applicationId;const targetId = extractChatId(platformThreadId);const threadType = extractThreadType(platformThreadId);return {@@ -386,10 +418,17 @@ class QQWebhookClient implements PlatformClient {await sendQQAttachments(api, threadType, targetId, attachments, text);return;}- await sendQQMessage(api, threadType, targetId, text);+ await sendQQMessage(api, applicationId, platformThreadId, threadType, targetId, text);},editMessage: (_messageId, content) =>- sendQQMessage(api, threadType, targetId, messengerContentText(content)),+ sendQQMessage(+ api,+ applicationId,+ platformThreadId,+ threadType,+ targetId,+ messengerContentText(content),+ ),removeReaction: () => Promise.resolve(),};}diff --git a/apps/server/src/services/bot/platforms/qq/passiveReply.ts b/apps/server/src/services/bot/platforms/qq/passiveReply.tsnew file mode 100644index 00000000000..ed3673ae978--- /dev/null+++ b/apps/server/src/services/bot/platforms/qq/passiveReply.ts@@ -0,0 +1,113 @@+import type {+ QQApiClient,+ QQPassiveSlot,+ QQPassiveThreadType,+} from '@lobechat/chat-adapter-qq';+import { QQ_PASSIVE_LIMITS } from '@lobechat/chat-adapter-qq';+import debug from 'debug';++import { redisService } from '@/server/services/redis';++const log = debug('bot-platform:qq:passive');++/** Key shape shared with the adapter's own window bookkeeping: `{applicationId}:{threadId}`. */+export const passiveKeyOf = (applicationId: string, platformThreadId: string): string =>+ `${applicationId}:${platformThreadId}`;++const limitsFor = (threadType: string) =>+ QQ_PASSIVE_LIMITS[threadType as QQPassiveThreadType] ?? QQ_PASSIVE_LIMITS.group;++/**+ * Reserve one reply inside the conversation's passive window.+ *+ * A passive reply carries the `msg_id` of an inbound message and costs no quota. QQ also accepts+ * active messages, but those are rate limited (per bot and per group, and a group receives at most+ * 1000 messages a day), so the passive slot is tried first.+ */+export const reserveQQReply = async (+ applicationId: string,+ platformThreadId: string,+ threadType: string,+): Promise<QQPassiveSlot | null> => {+ const key = passiveKeyOf(applicationId, platformThreadId);++ return redisService.qqPassive.reserve(key, limitsFor(threadType));+};++/** Park a reply the current window could not carry, so the next inbound message delivers it. */+export const deferQQReply = async (+ applicationId: string,+ platformThreadId: string,+ content: string,+): Promise<void> => {+ if (!content.trim()) return;++ log('passive window closed for %s, deferring reply (%d chars)', platformThreadId, content.length);+ await redisService.qqPassive.savePending(+ passiveKeyOf(applicationId, platformThreadId),+ content,+ );+};++/** Text send that carries the reserved slot's `msg_id` / `msg_seq`. */+export const sendQQMessageInSlot = async (+ api: QQApiClient,+ threadType: string,+ targetId: string,+ content: string,+ slot: QQPassiveSlot,+): Promise<void> => {+ const options = { eventId: slot.eventId, msgId: slot.msgId, msgSeq: slot.seq };++ switch (threadType) {+ case 'group': {+ await api.sendGroupMessage(targetId, content, options);+ return;+ }+ case 'guild': {+ await api.sendGuildMessage(targetId, content, options);+ return;+ }+ case 'c2c': {+ await api.sendC2CMessage(targetId, content, options);+ return;+ }+ case 'dms': {+ await api.sendDmsMessage(targetId, content, options);+ return;+ }+ default: {+ await api.sendGroupMessage(targetId, content, options);+ }+ }+};++/** Uncoupled send — QQ's active-message path, subject to its frequency cap. */+export const sendQQMessageActive = async (+ api: QQApiClient,+ threadType: string,+ targetId: string,+ content: string,+): Promise<void> => {+ switch (threadType) {+ case 'group': {+ await api.sendGroupMessage(targetId, content);+ return;+ }+ case 'guild': {+ await api.sendGuildMessage(targetId, content);+ return;+ }+ case 'c2c': {+ await api.sendC2CMessage(targetId, content);+ return;+ }+ case 'dms': {+ await api.sendDmsMessage(targetId, content);+ return;+ }+ default: {+ await api.sendGroupMessage(targetId, content);+ }+ }+};diff --git a/apps/server/src/services/bot/platforms/qq/protocol-spec.md b/apps/server/src/services/bot/platforms/qq/protocol-spec.mdindex 2a14d30a97c..8b0588c6e86 100644--- a/apps/server/src/services/bot/platforms/qq/protocol-spec.md+++ b/apps/server/src/services/bot/platforms/qq/protocol-spec.md@@ -164,28 +164,25 @@ QQ 机器人消息分为两类:- 单聊被动回复窗口:60 分钟,每条用户消息最多回复 5 次。- 频道被动回复窗口:5 分钟。-**主动消息**:机器人在无用户触发的情况下主动下发。受严格频率限制。+**主动消息**:机器人在无用户触发的情况下主动下发。**没有下线**,但受频率限制(QQ 官方文档 v2「发送群聊消息」接口,2026-10-28 更新)。-- 单聊主动消息:每月每用户 4 条。-- 群聊主动消息:每月每群 4 条。-- 频道主动消息:每日每子频道 20 条,每日最多推送 2 个子频道。-- 频道私信主动消息:每日每用户 2 条,每日累计 200 条。+- Bot 维度(发送方):企业认证 / 个人身份证认证 60 条/分钟;未认证 30 条/分钟。+- 单关系维度(接收方):20 条/分钟,每个群 1 天最多接收 1000 条。+- 超频控返回 `40034100`(主动消息发送超过频控限制);无权限返回 `40034105`(主动消息发送失败,无权限)。+- 频道主动消息:每日每子频道 20 条,每日最多推送 2 个子频道;频道私信:每日每用户 2 条,每日累计 200 条。+- 用户可以在客户端关闭机器人的主动消息。-注意:2025 年 4 月 21 日起主动推送能力已下线。用户可在客户端关闭机器人的主动消息。--> **⚠ 重要限制:主动消息已不可用(2025 年 4 月起)**+> **⚠ 更正(2026-11)**>-> 自 2025 年 4 月 21 日起,QQ 开放平台已**全面下线**机器人主动消息能力。这意味着:+> 本文档早前版本写着「2025-04-21 起主动推送能力已全面下线,所有消息必须是被动回复」,这是**错的**。官方 v2 接口现在给出的是主动消息的频控规则:主动消息可用,只是受限;只有超频控或无权限时才会被拒(`40034100` / `40034105`)。>-> 1. **所有消息必须是被动回复**:机器人只能在收到用户消息后,通过携带触发消息的 `msg_id` 进行回复。不携带 `msg_id` 的发送请求会被服务端以频率限制错误拒绝。-> 2. **message tool 的 `sendMessage` 操作无法可靠工作**:message tool 的执行上下文中不携带触发用户消息的 `msg_id`,因此无法构造合法的被动回复请求。即使 API 调用本身格式正确,也会因缺少 `msg_id` 被服务端拒绝。-> 3. **实际影响**:在服务适配器实现中,`sendMessage` 已被标记为不支持(`unsupported`)。所有需要主动发送消息的场景在 QQ 平台上均无法实现。+> 因此发送策略应是**被动优先、主动兜底**:先带 `msg_id` 做被动回复;窗口关闭(群 5 分钟)或 5 条回复用尽后,改发主动消息;主动消息也被频控拒绝时,才把内容留到下一条入站消息再补发。实现见 `packages/chat-adapter-qq/src/adapter.ts`。**工程建议**- 优先使用被动回复模式,在收到事件后立即回复。- 被动回复必须携带 `msg_id`(回复某条消息)或 `event_id`(回复某个事件),二选一。-- 主动消息不带 `msg_id` 和 `event_id`。+- 主动消息不带 `msg_id` 和 `event_id`,受频控;作为被动窗口之外的兜底。- HTTP 请求超时建议至少设置 5 秒。### 4.3 消息去重机制diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.tsindex 15974a5cd10..7e1774638e2 100644--- a/apps/server/src/services/redis/index.ts+++ b/apps/server/src/services/redis/index.ts@@ -7,6 +7,7 @@ import { botWake } from './botWake';import { deviceSystemInfo } from './deviceSystemInfo';import { linear } from './linear';import { pageCollab } from './pageCollab';+import { qqPassive } from './qqPassive';import { skillTools } from './skillTools';import { steerQueue } from './steerQueue';import { taskRunDelivery } from './taskRunDelivery';@@ -24,6 +25,7 @@ export const redisService = {deviceSystemInfo,linear,pageCollab,+ qqPassive,skillTools,steerQueue,taskRunDelivery,diff --git a/apps/server/src/services/redis/qqPassive.test.ts b/apps/server/src/services/redis/qqPassive.test.tsnew file mode 100644index 00000000000..e047b606c3a--- /dev/null+++ b/apps/server/src/services/redis/qqPassive.test.ts@@ -0,0 +1,93 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getRedisServiceClient } from './client';+import { qqPassive } from './qqPassive';++vi.mock('./client', () => ({ getRedisServiceClient: vi.fn() }));++const mockedGetClient = vi.mocked(getRedisServiceClient);++const createRedis = (stored?: string) => {+ const store = new Map<string, string>();+ if (stored) store.set('pending', stored);++ return {+ // Mirrors PENDING_TAKE_SCRIPT: read and delete in one step.+ eval: vi.fn(async () => {+ const text = store.get('pending');+ store.delete('pending');++ return text ?? null;+ }),+ set: vi.fn(async (_key: string, value: string, options?: { nx?: boolean }) => {+ if (options?.nx && store.has('pending')) return null;+ store.set('pending', value);++ return 'OK';+ }),+ store,+ };+};++const KEY = 'qq:group:123';++describe('qqPassive pending replies', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('drains a reply parked while Redis was down once Redis answers again', async () => {+ mockedGetClient.mockResolvedValue(null as any);+ await qqPassive.savePending(KEY, 'answer parked during the outage');++ // Redis is back, but this instance's copy never reached it, so the read is empty.+ mockedGetClient.mockResolvedValue(createRedis() as any);++ await expect(qqPassive.takePending(KEY)).resolves.toBe('answer parked during the outage');+ // The drained copy must not come back on the next flush.+ await expect(qqPassive.takePending(KEY)).resolves.toBeUndefined();+ });++ it('sends the newer local reply first and keeps the older Redis one', async () => {+ mockedGetClient.mockResolvedValue(null as any);+ await qqPassive.savePending(KEY, 'reply parked during the outage');++ const redis = createRedis('reply parked before the outage');+ mockedGetClient.mockResolvedValue(redis as any);++ // The local copy was written later, so it goes out first and the older one is handed back.+ await expect(qqPassive.takePending(KEY)).resolves.toBe('reply parked during the outage');+ expect(redis.store.get('pending')).toBe('reply parked before the outage');+ await expect(qqPassive.takePending(KEY)).resolves.toBe('reply parked before the outage');+ await expect(qqPassive.takePending(KEY)).resolves.toBeUndefined();+ });++ it('keeps a newer local reply when an older claimed one is restored', async () => {+ mockedGetClient.mockResolvedValue(null as any);+ await qqPassive.savePending(KEY, 'reply parked during the outage');++ const redis = createRedis();+ mockedGetClient.mockResolvedValue(redis as any);+ await qqPassive.restorePending(KEY, 'claimed before the outage');++ // Redis holds the restored copy, but the newer local reply must still go out first.+ expect(redis.store.get('pending')).toBe('claimed before the outage');+ await expect(qqPassive.takePending(KEY)).resolves.toBe('reply parked during the outage');+ await expect(qqPassive.takePending(KEY)).resolves.toBe('claimed before the outage');+ });++ it('drops the local copy once Redis accepts the same reply', async () => {+ mockedGetClient.mockResolvedValue(null as any);+ await qqPassive.savePending(KEY, 'parked locally');++ const redis = createRedis();+ mockedGetClient.mockResolvedValue(redis as any);+ await qqPassive.savePending(KEY, 'parked locally');++ expect(redis.store.get('pending')).toBe('parked locally');+ // A stale duplicate must not be re-sent after the write succeeded.+ await expect(qqPassive.takePending(KEY)).resolves.toBe('parked locally');+ await expect(qqPassive.takePending(KEY)).resolves.toBeUndefined();+ });+});diff --git a/apps/server/src/services/redis/qqPassive.ts b/apps/server/src/services/redis/qqPassive.tsnew file mode 100644index 00000000000..d9a4d2b5e57--- /dev/null+++ b/apps/server/src/services/redis/qqPassive.ts@@ -0,0 +1,271 @@+import type {+ QQPassiveLimits,+ QQPassiveSlot,+ QQPassiveStore,+ QQPassiveToken,+} from '@lobechat/chat-adapter-qq';++import { RedisKeys } from '@/server/modules/Redis';++import { getRedisServiceClient } from './client';++const getClient = () => getRedisServiceClient('qqPassive');++// The longest passive window is C2C's 60 minutes. The key outlives it so a late reservation still+// finds the window and answers "closed" rather than "never opened".+const WINDOW_TTL_SECONDS = 65 * 60;+// A deferred reply waits for the next inbound message in that conversation, which may be tomorrow.+const PENDING_TTL_SECONDS = 24 * 60 * 60;++/**+ * Opens a window, unless the same inbound message already has one.+ * KEYS[1] = window hash; ARGV = msgId, now (ms), eventId, ttl (s).+ *+ * QQ redelivers webhooks, and a redelivery must keep the replies already spent: restarting the+ * counter would reuse `(msg_id, msg_seq)` pairs that QQ rejects as duplicates, which the send path+ * reads as "already delivered" and drops.+ * Returns 1 when a window was written, 0 when the existing one was kept.+ */+const OPEN_SCRIPT = `+local current = redis.call('HGET', KEYS[1], 'msgId')+if current and ARGV[1] ~= '' and current == ARGV[1] then return 0 end+redis.call('DEL', KEYS[1])+redis.call('HSET', KEYS[1], 'at', ARGV[2], 'eventId', ARGV[3], 'msgId', ARGV[1], 'seq', '0')+redis.call('EXPIRE', KEYS[1], ARGV[4])+return 1+`;++/**+ * Claims a parked reply. Reading and deleting must be one step: two instances flushing the same+ * conversation would otherwise both read the text and send it twice, and a `savePending()` landing+ * between a GET and a DEL would be lost.+ * KEYS[1] = pending key. Returns the text, or nil.+ */+const PENDING_TAKE_SCRIPT = `+local text = redis.call('GET', KEYS[1])+if not text then return nil end+redis.call('DEL', KEYS[1])+return text+`;++/**+ * Takes the next reply slot of a window.+ * KEYS[1] = window hash; ARGV = now (ms), windowMs, maxReplies.+ * Returns `{eventId, msgId, seq}` or nil when the window is closed or out of replies.+ */+const RESERVE_SCRIPT = `+local at = redis.call('HGET', KEYS[1], 'at')+if not at then return nil end+if tonumber(ARGV[1]) - tonumber(at) > tonumber(ARGV[2]) then+ redis.call('DEL', KEYS[1])+ return nil+end+local seq = redis.call('HINCRBY', KEYS[1], 'seq', 1)+if seq > tonumber(ARGV[3]) then return nil end+return {+ redis.call('HGET', KEYS[1], 'eventId') or '',+ redis.call('HGET', KEYS[1], 'msgId') or '',+ tostring(seq)+}+`;++interface LocalWindow {+ at: number;+ eventId?: string;+ msgId?: string;+ seq: number;+}++/**+ * In-process stand-in for when Redis is unavailable or switched off. It only sees what this+ * instance handled, so it is a best-effort degradation, not a second source of truth.+ *+ * Written out here rather than imported from the adapter package: this module sits in the Redis+ * barrel every service imports, and a runtime import of `@lobechat/chat-adapter-qq` would drag the+ * adapter (and `chat` itself) into callers that never touch QQ.+ */+/**+ * The in-process store plus a way to drop a parked reply. Redis owns the slot whenever it answers,+ * so a copy written here during an outage is stale as soon as Redis takes the same key again.+ */+interface LocalStore extends QQPassiveStore {+ dropPending: (key: string) => void;+}++const createLocalStore = (): LocalStore => {+ const windows = new Map<string, LocalWindow>();+ const pending = new Map<string, string>();++ return {+ open: async (key: string, token: QQPassiveToken) => {+ windows.set(key, { at: token.at, eventId: token.eventId, msgId: token.msgId, seq: 0 });+ },++ reserve: async (key: string, limits: QQPassiveLimits, now = Date.now()) => {+ const window = windows.get(key);+ if (!window) return null;+ if (now - window.at > limits.windowMs) {+ windows.delete(key);+ return null;+ }+ if (window.seq >= limits.maxReplies) return null;++ window.seq += 1;++ return { at: window.at, eventId: window.eventId, msgId: window.msgId, seq: window.seq };+ },++ savePending: async (key: string, text: string) => {+ pending.set(key, text);+ },++ takePending: async (key: string) => {+ const text = pending.get(key);+ pending.delete(key);++ return text;+ },++ restorePending: async (key: string, text: string) => {+ if (pending.has(key)) return;+ pending.set(key, text);+ },++ dropPending: (key: string) => {+ pending.delete(key);+ },+ };+};++const local = createLocalStore();++const parseSlot = (raw: unknown, now: number): QQPassiveSlot | null => {+ if (!Array.isArray(raw) || raw.length < 3) return null;++ const [eventId, msgId, seq] = raw.map((value) => String(value ?? ''));+ const parsedSeq = Number(seq);+ if (!Number.isFinite(parsedSeq) || parsedSeq < 1) return null;++ return { at: now, eventId: eventId || undefined, msgId: msgId || undefined, seq: parsedSeq };+};++/**+ * QQ's passive-reply window, shared by every instance: the inbound message a bot is allowed to+ * answer, how many replies of its five are spent, and the text a closed window could not carry.+ * Kept in Redis because the inbound webhook and the agent's later completion can land on+ * different instances.+ */+export const qqPassive: QQPassiveStore = {+ async open(key, token) {+ const redis = await getClient();+ if (!redis) {+ await local.open(key, token);+ return;+ }++ try {+ await redis.eval(+ OPEN_SCRIPT,+ 1,+ RedisKeys.qqPassive.window(key),+ token.msgId ?? '',+ String(token.at),+ token.eventId ?? '',+ String(WINDOW_TTL_SECONDS),+ );+ } catch {+ // A lost window costs the reply, not the message: fall back to what this instance knows.+ await local.open(key, token);+ }+ },++ async reserve(key, limits, now = Date.now()) {+ const redis = await getClient();+ if (!redis) return local.reserve(key, limits, now);++ try {+ const raw = await redis.eval(+ RESERVE_SCRIPT,+ 1,+ RedisKeys.qqPassive.window(key),+ String(now),+ String(limits.windowMs),+ String(limits.maxReplies),+ );++ return parseSlot(raw, now);+ } catch {+ return local.reserve(key, limits, now);+ }+ },++ async savePending(key, text) {+ const redis = await getClient();+ if (!redis) {+ await local.savePending(key, text);+ return;+ }++ try {+ await redis.set(RedisKeys.qqPassive.pending(key), text, { ex: PENDING_TTL_SECONDS });+ // Redis holds the slot again; anything parked here during the outage was superseded by it.+ local.dropPending(key);+ } catch {+ await local.savePending(key, text);+ }+ },++ async takePending(key) {+ const redis = await getClient();+ if (!redis) return local.takePending(key);++ try {+ const text = await redis.eval(PENDING_TAKE_SCRIPT, 1, RedisKeys.qqPassive.pending(key));++ // `savePending()` parks here only while this instance cannot reach Redis, so a copy found+ // here is a reply Redis never took — written after whatever Redis still holds, since a+ // write that reaches Redis always clears this slot. It has to be sent, and the older Redis+ // one kept for the next flush rather than dropped with it.+ const localText = await local.takePending(key);+ const redisText = typeof text === 'string' && text ? text : undefined;++ if (!localText) return redisText;+ if (!redisText || redisText === localText) return localText;++ // The take script already removed the older reply, so put it back: newest first, and+ // neither answer is lost.+ try {+ await redis.set(RedisKeys.qqPassive.pending(key), redisText, {+ ex: PENDING_TTL_SECONDS,+ nx: true,+ });+ } catch {+ await local.restorePending(key, redisText);+ }++ return localText;+ } catch {+ return local.takePending(key);+ }+ },++ async restorePending(key, text) {+ const redis = await getClient();+ if (!redis) {+ await local.restorePending(key, text);+ return;+ }++ try {+ // `nx`: a reply parked while this one was in flight is newer and must win.+ await redis.set(RedisKeys.qqPassive.pending(key), text, {+ ex: PENDING_TTL_SECONDS,+ nx: true,+ });+ // The local slot is deliberately left alone: it only ever holds a reply Redis never took,+ // written after this one was claimed, so dropping it here would delete the newest answer.+ } catch {+ await local.restorePending(key, text);+ }+ },+};diff --git a/packages/chat-adapter-qq/src/adapter.mention.test.ts b/packages/chat-adapter-qq/src/adapter.mention.test.tsnew file mode 100644index 00000000000..d79b173135e--- /dev/null+++ b/packages/chat-adapter-qq/src/adapter.mention.test.ts@@ -0,0 +1,158 @@+import type { StateAdapter } from 'chat';+import { Chat } from 'chat';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createQQAdapter } from './adapter';+import { QQ_EVENT_TYPES, QQ_OP_CODES } from './types';++/** Minimal in-memory `StateAdapter`; production wires ioredis. */+const createMemoryState = (): StateAdapter => {+ const values = new Map<string, unknown>();+ const lists = new Map<string, unknown[]>();+ const queues = new Map<string, unknown[]>();+ const subscribed = new Set<string>();++ return {+ acquireLock: async (threadId) => ({ expiresAt: Number.MAX_SAFE_INTEGER, threadId, token: 't' }),+ appendToList: async (key, value) => {+ lists.set(key, [...(lists.get(key) ?? []), value]);+ },+ connect: async () => {},+ delete: async (key) => {+ values.delete(key);+ },+ dequeue: async (threadId) => (queues.get(threadId)?.shift() as any) ?? null,+ disconnect: async () => {},+ enqueue: async (threadId, entry) => {+ const queue = [...(queues.get(threadId) ?? []), entry];+ queues.set(threadId, queue);+ return queue.length;+ },+ extendLock: async () => true,+ forceReleaseLock: async () => {},+ get: async <T,>(key: string) => (values.get(key) ?? null) as T | null,+ getList: async <T,>(key: string) => (lists.get(key) ?? []) as T[],+ isSubscribed: async (threadId) => subscribed.has(threadId),+ queueDepth: async (threadId) => queues.get(threadId)?.length ?? 0,+ releaseLock: async () => {},+ set: async (key, value) => {+ values.set(key, value);+ },+ setIfNotExists: async (key, value) => {+ if (values.has(key)) return false;+ values.set(key, value);+ return true;+ },+ subscribe: async (threadId) => {+ subscribed.add(threadId);+ },+ unsubscribe: async (threadId) => {+ subscribed.delete(threadId);+ },+ };+};++/** QQ's auth + bot-info endpoints; everything else is never reached in these tests. */+const stubQQHttp = () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: any) => {+ const url = String(input);+ const json = { 'content-type': 'application/json' };+ if (url.includes('getAppAccessToken')) {+ return new Response(JSON.stringify({ access_token: 'token', expires_in: 7200 }), {+ headers: json,+ status: 200,+ });+ }+ if (url.endsWith('/users/@me')) {+ return new Response(JSON.stringify({ id: 'BOT_USER_ID', username: 'qq-bot' }), {+ headers: json,+ status: 200,+ });+ }+ return new Response('{}', { headers: json, status: 200 });+ }),+ );+};++const makeRequest = (body: unknown) =>+ new Request('http://localhost/webhook', {+ body: JSON.stringify(body),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ });++const dispatch = (t: string, d: Record<string, any>) => ({+ d: {+ author: { id: 'user_1' },+ content: '帮我看看这个',+ group_openid: 'group_1',+ id: 'msg_1',+ timestamp: '2026-11-12T10:00:00Z',+ ...d,+ },+ id: 'event_1',+ op: QQ_OP_CODES.DISPATCH,+ t,+});++const waitFor = async (predicate: () => boolean, timeoutMs = 2000) => {+ const startedAt = Date.now();+ while (!predicate()) {+ if (Date.now() - startedAt > timeoutMs) throw new Error('timed out waiting for handler');+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+};++describe('QQ group @-mention routing (real chat-sdk)', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('fires onNewMention for GROUP_AT_MESSAGE_CREATE', async () => {+ stubQQHttp();++ const adapter = createQQAdapter({ appId: 'app', clientSecret: 'secret' });+ const chat = new Chat({ adapters: { qq: adapter }, state: createMemoryState(), userName: 'qq-bot' });+ await chat.initialize();++ const seen: string[] = [];+ chat.onNewMention(async (_thread, message) => {+ seen.push(message.text);+ });++ await adapter.handleWebhook(makeRequest(dispatch(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {})));+ await waitFor(() => seen.length === 1);++ // The @ marker itself is stripped from a group message's content by QQ — the text the agent+ // sees is the bare question.+ expect(seen[0]).toBe('帮我看看这个');+ });++ it('does not treat a c2c message as an @-mention event type but still reaches a DM handler', async () => {+ stubQQHttp();++ const adapter = createQQAdapter({ appId: 'app', clientSecret: 'secret' });+ const chat = new Chat({ adapters: { qq: adapter }, state: createMemoryState(), userName: 'qq-bot' });+ await chat.initialize();++ let mentions = 0;+ let dms = 0;+ chat.onNewMention(async () => {+ mentions += 1;+ });+ chat.onDirectMessage(async () => {+ dms += 1;+ });++ await adapter.handleWebhook(+ makeRequest(+ dispatch(QQ_EVENT_TYPES.C2C_MESSAGE_CREATE, { group_openid: undefined }),+ ),+ );+ await waitFor(() => dms === 1);++ expect(mentions).toBe(0);+ });+});diff --git a/packages/chat-adapter-qq/src/adapter.passive.test.ts b/packages/chat-adapter-qq/src/adapter.passive.test.tsnew file mode 100644index 00000000000..57972478473--- /dev/null+++ b/packages/chat-adapter-qq/src/adapter.passive.test.ts@@ -0,0 +1,267 @@+import type { StateAdapter } from 'chat';+import { Chat } from 'chat';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createQQAdapter } from './adapter';+import { QQ_DEFERRED_PREFIX } from './passive';+import { QQ_EVENT_TYPES, QQ_OP_CODES } from './types';++/** Minimal in-memory `StateAdapter`; production wires ioredis. */+const createMemoryState = (): StateAdapter => {+ const values = new Map<string, unknown>();+ const lists = new Map<string, unknown[]>();+ const queues = new Map<string, unknown[]>();+ const subscribed = new Set<string>();++ return {+ acquireLock: async (threadId) => ({ expiresAt: Number.MAX_SAFE_INTEGER, threadId, token: 't' }),+ appendToList: async (key, value) => {+ lists.set(key, [...(lists.get(key) ?? []), value]);+ },+ connect: async () => {},+ delete: async (key) => {+ values.delete(key);+ },+ dequeue: async (threadId) => (queues.get(threadId)?.shift() as any) ?? null,+ disconnect: async () => {},+ enqueue: async (threadId, entry) => {+ const queue = [...(queues.get(threadId) ?? []), entry];+ queues.set(threadId, queue);+ return queue.length;+ },+ extendLock: async () => true,+ forceReleaseLock: async () => {},+ get: async <T,>(key: string) => (values.get(key) ?? null) as T | null,+ getList: async <T,>(key: string) => (lists.get(key) ?? []) as T[],+ isSubscribed: async (threadId) => subscribed.has(threadId),+ queueDepth: async (threadId) => queues.get(threadId)?.length ?? 0,+ releaseLock: async () => {},+ set: async (key, value) => {+ values.set(key, value);+ },+ setIfNotExists: async (key, value) => {+ if (values.has(key)) return false;+ values.set(key, value);+ return true;+ },+ subscribe: async (threadId) => {+ subscribed.add(threadId);+ },+ unsubscribe: async (threadId) => {+ subscribed.delete(threadId);+ },+ };+};++const SEND_PATH = '/v2/groups/group_1/messages';++/** QQ's auth and bot-info endpoints; send calls are recorded so the body can be asserted. */+const stubQQHttp = ({+ activeLimited = false,+ failContent,+ failNext = 0,+}: { activeLimited?: boolean; failContent?: string; failNext?: number } = {}) => {+ const sent: Array<Record<string, any>> = [];+ let failuresLeft = failNext;++ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: any, init?: any) => {+ const url = String(input);+ const json = { 'content-type': 'application/json' };++ if (url.includes(SEND_PATH)) {+ const body = JSON.parse(String(init?.body ?? '{}'));+ // `failNext` mimics a transient QQ 5xx for the first N sends carrying `failContent`.+ const shouldFail =+ failContent !== undefined &&+ failuresLeft > 0 &&+ String(body.content ?? '').includes(failContent);+ if (shouldFail) {+ failuresLeft -= 1;+ return new Response(JSON.stringify({ message: '所有server busy' }), {+ headers: json,+ status: 500,+ });+ }+ sent.push(body);+ // `activeLimited` mimics QQ's frequency cap: an uncoupled send is refused.+ if (activeLimited && !body.msg_id) {+ return new Response(+ JSON.stringify({ code: 40034100, message: '主动消息发送超过频控限制' }),+ { headers: json, status: 403 },+ );+ }+ return new Response(JSON.stringify({ id: `sent_${sent.length}`, timestamp: 'now' }), {+ headers: json,+ status: 200,+ });+ }+ if (url.includes('getAppAccessToken')) {+ return new Response(JSON.stringify({ access_token: 'token', expires_in: 7200 }), {+ headers: json,+ status: 200,+ });+ }+ if (url.endsWith('/users/@me')) {+ return new Response(JSON.stringify({ id: 'BOT_USER_ID', username: 'qq-bot' }), {+ headers: json,+ status: 200,+ });+ }++ return new Response('{}', { headers: json, status: 200 });+ }),+ );++ return sent;+};++const makeRequest = (body: unknown) =>+ new Request('http://localhost/webhook', {+ body: JSON.stringify(body),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ });++const inbound = (msgId: string, content = '帮我看看') => ({+ d: {+ author: { id: 'user_1' },+ content,+ group_openid: 'group_1',+ id: msgId,+ timestamp: '2026-11-12T10:00:00Z',+ },+ id: `event_${msgId}`,+ op: QQ_OP_CODES.DISPATCH,+ t: QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE,+});++describe('QQ passive replies', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ const setup = async () => {+ const sent = stubQQHttp();+ const adapter = createQQAdapter({ appId: 'app', clientSecret: 'secret' });+ const chat = new Chat({+ adapters: { qq: adapter },+ state: createMemoryState(),+ userName: 'qq-bot',+ });+ await chat.initialize();++ return { adapter, sent };+ };++ it('answers inside the inbound message\'s window', async () => {+ const { adapter, sent } = await setup();+ await adapter.handleWebhook(makeRequest(inbound('msg_1')));++ await adapter.postMessage('qq:group:group_1', '答案是 42');++ expect(sent).toHaveLength(1);+ expect(sent[0]).toMatchObject({ content: '答案是 42', msg_id: 'msg_1', msg_seq: 1 });+ });++ it('numbers every reply in one window', async () => {+ const { adapter, sent } = await setup();+ await adapter.handleWebhook(makeRequest(inbound('msg_1')));++ await adapter.postMessage('qq:group:group_1', 'a');+ await adapter.postMessage('qq:group:group_1', 'b');++ expect(sent.map((body) => body.msg_seq)).toEqual([1, 2]);+ });++ it('falls back to an active message once the five replies are spent', async () => {+ const { adapter, sent } = await setup();+ await adapter.handleWebhook(makeRequest(inbound('msg_1')));+ for (let i = 0; i < 5; i++) {+ await adapter.postMessage('qq:group:group_1', `chunk ${i}`);+ }++ await adapter.postMessage('qq:group:group_1', '最后一段');++ // Still delivered — QQ accepts active messages, it only rate limits them.+ expect(sent).toHaveLength(6);+ expect(sent[5].content).toBe('最后一段');+ expect(sent[5].msg_id).toBeUndefined();+ expect(sent[5].msg_seq).toBeUndefined();+ });++ it('parks the text when the active quota is exhausted too, and delivers it on the next message', async () => {+ const sent = stubQQHttp({ activeLimited: true });+ const adapter = createQQAdapter({ appId: 'app', clientSecret: 'secret' });+ const chat = new Chat({+ adapters: { qq: adapter },+ state: createMemoryState(),+ userName: 'qq-bot',+ });+ await chat.initialize();++ await adapter.handleWebhook(makeRequest(inbound('msg_1')));+ for (let i = 0; i < 5; i++) {+ await adapter.postMessage('qq:group:group_1', `chunk ${i}`);+ }++ const before = sent.length;+ await adapter.postMessage('qq:group:group_1', '最后一段');++ expect(sent.length).toBe(before + 1);++ await adapter.handleWebhook(makeRequest(inbound('msg_2')));++ // Passive again: the parked text goes out first, on the new window.+ expect(sent.at(-1)).toMatchObject({+ content: `${QQ_DEFERRED_PREFIX}最后一段`,+ msg_id: 'msg_2',+ msg_seq: 1,+ });+ });++ it('retries a deferred reply when its delivery fails instead of losing it', async () => {+ const sent = stubQQHttp({+ activeLimited: true,+ failContent: QQ_DEFERRED_PREFIX,+ failNext: 1,+ });+ const adapter = createQQAdapter({ appId: 'app', clientSecret: 'secret' });+ const chat = new Chat({+ adapters: { qq: adapter },+ state: createMemoryState(),+ userName: 'qq-bot',+ });+ await chat.initialize();++ // Spend the window, then park the sixth answer on the active-quota cap.+ await adapter.handleWebhook(makeRequest(inbound('msg_1')));+ for (let i = 0; i < 5; i++) {+ await adapter.postMessage('qq:group:group_1', `chunk ${i}`);+ }+ await adapter.postMessage('qq:group:group_1', '最后一段');++ // The flush on msg_2 hits a transient 5xx: the webhook still succeeds, the text stays parked.+ await adapter.handleWebhook(makeRequest(inbound('msg_2')));+ expect(sent.filter((body) => String(body.content).includes(QQ_DEFERRED_PREFIX))).toHaveLength(+ 0,+ );++ // The next inbound message retries the restored text.+ await adapter.handleWebhook(makeRequest(inbound('msg_3')));+ expect(sent.at(-1)).toMatchObject({+ content: `${QQ_DEFERRED_PREFIX}最后一段`,+ msg_id: 'msg_3',+ msg_seq: 1,+ });+ });++ it('sends nothing for a thread that never received an inbound message', async () => {+ const { adapter, sent } = await setup();++ await adapter.postMessage('qq:group:never_seen', 'hello');++ expect(sent).toHaveLength(0);+ });+});diff --git a/packages/chat-adapter-qq/src/adapter.test.ts b/packages/chat-adapter-qq/src/adapter.test.tsindex 6adbbe5c8da..2c3d1c576f9 100644--- a/packages/chat-adapter-qq/src/adapter.test.ts+++ b/packages/chat-adapter-qq/src/adapter.test.ts@@ -210,6 +210,51 @@ describe('QQAdapter', () => {});});+ // ---------- @-mention flag ----------++ describe('@-mention flag', () => {+ const messageOf = async (payload: QQWebhookPayload) => {+ await adapter.handleWebhook(makeRequest(payload));+ const factory = vi.mocked(mockChat.processMessage).mock.calls.at(-1)?.[2];+ return factory?.();+ };++ it('marks a group @ event as a mention', async () => {+ const message = await messageOf(+ makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {}),+ );++ expect(message?.isMention).toBe(true);+ });++ it('marks a guild @ event as a mention', async () => {+ const message = await messageOf(+ makeWebhookPayload(QQ_EVENT_TYPES.AT_MESSAGE_CREATE, {+ channel_id: 'channel_1',+ group_openid: undefined,+ }),+ );++ expect(message?.isMention).toBe(true);+ });++ it('leaves a c2c message unflagged — chat-sdk marks DMs itself', async () => {+ const message = await messageOf(+ makeWebhookPayload(QQ_EVENT_TYPES.C2C_MESSAGE_CREATE, { group_openid: undefined }),+ );++ expect(message?.isMention).toBe(false);+ });++ it('keeps the raw content free of the mention marker', async () => {+ const message = await messageOf(+ makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, { content: '帮我看看' }),+ );++ expect(message?.text).toBe('帮我看看');+ });+ });+// ---------- attachment mapping ----------describe('attachment mapping', () => {@@ -403,6 +448,30 @@ describe('QQAdapter', () => {const message = adapter.parseMessage(raw);expect(message.threadId).toBe('qq:c2c:user_123');});++ it('marks a group message as a mention', () => {+ const message = adapter.parseMessage(makeQQRawMessage({ group_openid: 'g1' }));++ expect(message.isMention).toBe(true);+ });++ it('marks a guild message that carries the bot marker as a mention', () => {+ (adapter as any)._botUserId = 'BOT_USER_ID';+ const message = adapter.parseMessage(+ makeQQRawMessage({ channel_id: 'ch1', content: '<@!BOT_USER_ID> hello' }),+ );++ expect(message.isMention).toBe(true);+ });++ it('leaves a guild message addressed to someone else unflagged', () => {+ (adapter as any)._botUserId = 'BOT_USER_ID';+ const message = adapter.parseMessage(+ makeQQRawMessage({ channel_id: 'ch1', content: '<@!SOMEONE_ELSE> hello' }),+ );++ expect(message.isMention).toBe(false);+ });});// ---------- fetchAttachmentData ----------diff --git a/packages/chat-adapter-qq/src/adapter.ts b/packages/chat-adapter-qq/src/adapter.tsindex 214b05f9dea..11bd61ff883 100644--- a/packages/chat-adapter-qq/src/adapter.ts+++ b/packages/chat-adapter-qq/src/adapter.ts@@ -18,23 +18,50 @@ import mime from 'mime';import { QQApiClient } from './api';import { signWebhookResponse } from './crypto';+import { isQQActiveRateLimited, isQQDuplicateReply, isQQPassiveExpired } from './errors';import { QQFormatConverter } from './format-converter';import { QQGatewayConnection } from './gateway';+import {+ createMemoryQQPassiveStore,+ QQ_DEFERRED_PREFIX,+ QQ_PASSIVE_LIMITS,+ type QQPassiveSlot,+ type QQPassiveStore,+ type QQPassiveThreadType,+} from './passive';import type {QQAdapterConfig,QQAttachment,QQRawMessage,QQThreadId,+ QQSendMessageResponse,QQWebhookEventData,QQWebhookPayload,} from './types';import { QQ_EVENT_TYPES, QQ_OP_CODES } from './types';+/**+ * QQ event types that only fire when the bot itself was @-mentioned.+ *+ * chat-sdk's own `detectMention()` scans `message.text` for an `@name` / `<@!id>` marker, and+ * neither survives here: QQ already strips the "@bot" prefix from a group message's content, and+ * this adapter strips whatever `<@!…>` markers remain before parsing. Without the explicit flag+ * `onNewMention` never fires, so a group @-mention is routed as ordinary channel chatter (and,+ * with no watch keyword and bot-wake off, silently dropped).+ */+const BOT_MENTION_EVENT_TYPES = new Set<string>([+ QQ_EVENT_TYPES.AT_MESSAGE_CREATE,+ QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE,+]);+export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {readonly name = 'qq';private readonly api: QQApiClient;+ private readonly appId: string;private readonly clientSecret: string;private readonly formatConverter: QQFormatConverter;+ /** Tracks each conversation's passive-reply window; see `passive.ts`. */+ private readonly passive: QQPassiveStore;private _userName: string;private _botUserId?: string;private chat!: ChatInstance;@@ -50,8 +77,10 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {constructor(config: QQAdapterConfig & { userName?: string }) {this.api = new QQApiClient(config.appId, config.clientSecret);+ this.appId = config.appId;this.clientSecret = config.clientSecret;this.formatConverter = new QQFormatConverter();+ this.passive = config.passiveStore ?? createMemoryQQPassiveStore();this._userName = config.userName || 'qq-bot';}@@ -134,6 +163,16 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {return Response.json({ ok: true });}+ // Every inbound message opens (or restarts) the passive-reply window the answer prefers: a+ // passive reply costs no quota, an active one is rate limited per bot and per group. A reply+ // parked because both were unavailable goes out first, before the new message is answered.+ await this.passive.open(this.passiveKey(threadId), {+ at: Date.now(),+ eventId: payload.id,+ msgId: eventData.id,+ });+ await this.flushDeferred(threadId, this.threadTypeOf(threadId));+// Create message via factoryconst messageFactory = () => this.parseRawEvent(eventData, threadId, eventType!);@@ -221,39 +260,200 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {const { type, id, guildId } = this.decodeThreadId(threadId);const text = this.formatConverter.renderPostable(message);- let response;+ const response = await this.sendReply(threadId, type, id, guildId, text);+ if (!response) {+ return {+ id: `qq-deferred-${Date.now()}`,+ raw: {+ author: { id: this._botUserId || '' },+ content: text,+ id: '',+ timestamp: new Date().toISOString(),+ } as QQRawMessage,+ threadId,+ };+ }++ return {+ id: response.id,+ raw: {+ author: { id: this._botUserId || '' },+ content: text,+ id: response.id,+ timestamp: response.timestamp,+ } as QQRawMessage,+ threadId,+ };+ }++ // ------------------------------------------------------------------+ // Passive reply window+ // ------------------------------------------------------------------++ private passiveKey(threadId: string): string {+ return `${this.appId}:${threadId}`;+ }++ private threadTypeOf(threadId: string): QQPassiveThreadType {+ return this.decodeThreadId(threadId).type;+ }++ /**+ * Send one reply, cheapest transport first.+ *+ * A passive reply (inside the inbound message's window) costs no quota; once the window closes+ * or its five replies are spent, QQ still accepts an active message — it is rate limited per bot+ * and per group, not forbidden — so the reply goes out uncoupled. Only when that quota is gone+ * too does the text get parked for the next inbound message.+ *+ * @returns the sent message, or undefined when the text was parked instead.+ */+ private async sendReply(+ threadId: string,+ type: QQPassiveThreadType,+ id: string,+ guildId: string | undefined,+ text: string,+ ): Promise<QQSendMessageResponse | undefined> {+ const slot = await this.reserveReplySlot(threadId, type);++ if (slot) {+ try {+ return await this.sendInThread(type, id, guildId, text, slot);+ } catch (error) {+ if (isQQDuplicateReply(error)) {+ // QQ already has this (msg_id, msg_seq): the text is in the chat, do not repeat it.+ this.logger?.warn('QQ rejected a duplicate reply in %s, keeping the first', threadId);+ return undefined;+ }+ if (!isQQPassiveExpired(error)) throw error;++ this.logger?.warn('QQ passive window refused a reply in %s, retrying as active', threadId);+ }+ }++ return this.sendAsActiveMessage(threadId, type, id, guildId, text);+ }++ /** Uncoupled send, subject to QQ's active-message frequency cap. */+ private async sendAsActiveMessage(+ threadId: string,+ type: QQPassiveThreadType,+ id: string,+ guildId: string | undefined,+ text: string,+ ): Promise<QQSendMessageResponse | undefined> {+ try {+ return await this.sendInThread(type, id, guildId, text, undefined);+ } catch (error) {+ if (!isQQActiveRateLimited(error)) throw error;++ // Bot-wide / per-group quota is exhausted right now: wait for the next inbound message,+ // which reopens a free window.+ this.logger?.warn('QQ active-message quota exhausted in %s, deferring', threadId);+ await this.deferReply(threadId, text);+ return undefined;+ }+ }++ /** One reply slot inside the conversation's window, or null when nothing may go out passively. */+ private async reserveReplySlot(+ threadId: string,+ type: QQPassiveThreadType,+ ): Promise<QQPassiveSlot | null> {+ try {+ return await this.passive.reserve(this.passiveKey(threadId), QQ_PASSIVE_LIMITS[type]);+ } catch (error) {+ this.logger?.warn('QQ passive window lookup failed for %s: %O', threadId, error);+ return null;+ }+ }++ private async sendInThread(+ type: QQPassiveThreadType,+ id: string,+ guildId: string | undefined,+ text: string,+ slot: QQPassiveSlot | undefined,+ ) {+ const options = slot && { eventId: slot.eventId, msgId: slot.msgId, msgSeq: slot.seq };+switch (type) {case 'group': {- response = await this.api.sendGroupMessage(id, text);- break;+ return this.api.sendGroupMessage(id, text, options);}case 'guild': {- response = await this.api.sendGuildMessage(id, text);- break;+ return this.api.sendGuildMessage(id, text, options);}case 'c2c': {- response = await this.api.sendC2CMessage(id, text);- break;+ return this.api.sendC2CMessage(id, text, options);}case 'dms': {- response = await this.api.sendDmsMessage(guildId || id, text);- break;+ return this.api.sendDmsMessage(guildId || id, text, options);}default: {throw new Error(`Unknown thread type: ${type}`);}}+ }- return {- id: response.id,- raw: {- author: { id: this._botUserId || '' },- content: text,- id: response.id,- timestamp: response.timestamp,- } as QQRawMessage,+ /** Park text the current window cannot carry, so the next inbound message delivers it. */+ private async deferReply(threadId: string, text: string): Promise<void> {+ if (!text.trim()) return;++ this.logger?.warn(+ 'QQ passive window closed for %s, deferring reply (%d chars)',threadId,- };+ text.length,+ );++ try {+ await this.passive.savePending(this.passiveKey(threadId), text);+ } catch (error) {+ this.logger?.error('QQ failed to park a deferred reply for %s: %O', threadId, error);+ }+ }++ /**+ * Deliver a reply the previous window could not carry. Runs when the next inbound message opens+ * a fresh window, so the reader gets the missed answer before the new one.+ */+ private async flushDeferred(threadId: string, type: QQPassiveThreadType): Promise<void> {+ let text: string | undefined;+ try {+ text = await this.passive.takePending(this.passiveKey(threadId));+ } catch (error) {+ this.logger?.warn('QQ failed to read a deferred reply for %s: %O', threadId, error);+ return;+ }+ if (!text?.trim()) return;++ const { id, guildId } = this.decodeThreadId(threadId);+ try {+ const sent = await this.sendReply(+ threadId,+ type,+ id,+ guildId,+ `${QQ_DEFERRED_PREFIX}${text}`,+ );+ if (sent) this.logger?.info('QQ delivered a deferred reply in %s', threadId);+ } catch (error) {+ this.logger?.error('QQ failed to deliver a deferred reply in %s: %O', threadId, error);+ await this.restoreDeferred(threadId, text);+ }+ }++ /**+ * Put a claimed reply back after its delivery failed. `takePending()` deletes the text before+ * the send, so without this a transient QQ 5xx or a network error loses the answer for good.+ */+ private async restoreDeferred(threadId: string, text: string): Promise<void> {+ try {+ await this.passive.restorePending(this.passiveKey(threadId), text);+ } catch (error) {+ this.logger?.error('QQ failed to restore a deferred reply for %s: %O', threadId, error);+ }}async editMessage(@@ -326,6 +526,9 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {},formatted,id: raw.id,+ // A group message can only reach the bot through GROUP_AT_MESSAGE_CREATE, so it is always a+ // mention; a guild message keeps the `<@!id>` marker in its raw content.+ isMention: !!raw.group_openid || this.contentMentionsBot(raw.content),metadata: {dateSent: new Date(raw.timestamp),edited: false,@@ -336,10 +539,19 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {});}+ /** Whether the raw content carries a `<@!botUserId>` marker for this bot. */+ private contentMentionsBot(content?: string): boolean {+ if (!content || !this._botUserId) return false;++ const escapedId = this._botUserId.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');++ return new RegExp(`<@!?${escapedId}>`).test(content);+ }+private async parseRawEvent(data: QQWebhookEventData,threadId: string,- _eventType: string,+ eventType: string,): Promise<Message<QQRawMessage>> {const content = data.content || '';const cleanText = this.formatConverter.cleanMentions(content);@@ -374,6 +586,9 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {author,formatted,id: data.id || '',+ // Both AT_MESSAGE_CREATE (guild) and GROUP_AT_MESSAGE_CREATE only reach the bot when it was+ // @-mentioned — see BOT_MENTION_EVENT_TYPES. c2c / dms are DMs, which chat-sdk marks itself.+ isMention: BOT_MENTION_EVENT_TYPES.has(eventType),metadata: {dateSent: new Date(data.timestamp || Date.now()),edited: false,diff --git a/packages/chat-adapter-qq/src/errors.ts b/packages/chat-adapter-qq/src/errors.tsnew file mode 100644index 00000000000..9ddc9352799--- /dev/null+++ b/packages/chat-adapter-qq/src/errors.ts@@ -0,0 +1,35 @@+/**+ * QQ's own error codes, read off the failed request.+ *+ * The API client throws `QQ API <method> <path> failed: <status> <body>`, so the numeric code is+ * in the message — see the error table on+ * https://bot.q.qq.com/wiki/develop/api-v2/autogen/api/v2_groups_group_openid_messages.post.html+ */+const errorText = (error: unknown): string =>+ error instanceof Error ? error.message : String(error);++const hasCode = (error: unknown, codes: readonly string[]): boolean => {+ const text = errorText(error);++ return codes.some((code) => text.includes(code));+};++/**+ * The passive reply was refused because its window closed or its five replies are spent.+ * 40034128 = 被动回复时间或次数超限, 40034005 / 304103 = the msg_id has expired.+ */+export const isQQPassiveExpired = (error: unknown): boolean =>+ hasCode(error, ['40034128', '40034005', '304103', '40034026']);++/**+ * The active message was refused by the frequency cap.+ * 40034100 = 主动消息发送超过频控限制, 40034105 = 主动消息发送失败,无权限.+ */+export const isQQActiveRateLimited = (error: unknown): boolean =>+ hasCode(error, ['40034100', '40034105']);++/**+ * A duplicate `msg_id` + `msg_seq` pair. Retrying the same slot is useless, so the caller should+ * treat it as "this reply will not go out" rather than retrying.+ */+export const isQQDuplicateReply = (error: unknown): boolean => hasCode(error, ['40054005']);diff --git a/packages/chat-adapter-qq/src/index.ts b/packages/chat-adapter-qq/src/index.tsindex 56b1c5913d5..247f244c7b5 100644--- a/packages/chat-adapter-qq/src/index.ts+++ b/packages/chat-adapter-qq/src/index.ts@@ -1,9 +1,22 @@export { createQQAdapter, QQAdapter } from './adapter';export { QQApiClient } from './api';export { signWebhookResponse } from './crypto';+export { isQQActiveRateLimited, isQQDuplicateReply, isQQPassiveExpired } from './errors';export { QQFormatConverter } from './format-converter';export type { GatewayLogger, QQGatewayOptions } from './gateway';export { QQGatewayConnection } from './gateway';+export {+ createMemoryQQPassiveStore,+ QQ_DEFERRED_PREFIX,+ QQ_PASSIVE_LIMITS,+} from './passive';+export type {+ QQPassiveLimits,+ QQPassiveSlot,+ QQPassiveStore,+ QQPassiveThreadType,+ QQPassiveToken,+} from './passive';export type {QQAccessTokenResponse,QQAdapterConfig,diff --git a/packages/chat-adapter-qq/src/passive.test.ts b/packages/chat-adapter-qq/src/passive.test.tsnew file mode 100644index 00000000000..6ef7e736d82--- /dev/null+++ b/packages/chat-adapter-qq/src/passive.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from 'vitest';++import { createMemoryQQPassiveStore, QQ_PASSIVE_LIMITS } from './passive';++const LIMITS = QQ_PASSIVE_LIMITS.group;+const AT = 1_700_000_000_000;++describe('QQ passive window', () => {+ it('hands out reply slots up to the per-message budget', async () => {+ const store = createMemoryQQPassiveStore();+ await store.open('app:thread', { at: AT, msgId: 'msg_1' });++ const seqs: number[] = [];+ for (let i = 0; i < LIMITS.maxReplies; i++) {+ const slot = await store.reserve('app:thread', LIMITS, AT + 1000);+ seqs.push(slot!.seq);+ }++ expect(seqs).toEqual([1, 2, 3, 4, 5]);+ expect(await store.reserve('app:thread', LIMITS, AT + 1000)).toBeNull();+ });++ it('carries the inbound message id on every slot', async () => {+ const store = createMemoryQQPassiveStore();+ await store.open('app:thread', { at: AT, eventId: 'evt_1', msgId: 'msg_1' });++ const slot = await store.reserve('app:thread', LIMITS, AT + 1000);++ expect(slot).toMatchObject({ eventId: 'evt_1', msgId: 'msg_1' });+ });++ it('closes the window once it has expired', async () => {+ const store = createMemoryQQPassiveStore();+ await store.open('app:thread', { at: AT, msgId: 'msg_1' });++ expect(await store.reserve('app:thread', LIMITS, AT + LIMITS.windowMs + 1)).toBeNull();+ });++ it('reopens with a fresh budget on the next inbound message', async () => {+ const store = createMemoryQQPassiveStore();+ await store.open('app:thread', { at: AT, msgId: 'msg_1' });+ for (let i = 0; i < LIMITS.maxReplies; i++) {+ await store.reserve('app:thread', LIMITS, AT + 1000);+ }++ await store.open('app:thread', { at: AT + 2000, msgId: 'msg_2' });+ const slot = await store.reserve('app:thread', LIMITS, AT + 3000);++ expect(slot).toMatchObject({ msgId: 'msg_2', seq: 1 });+ });++ it('keeps the replies already spent when the same message is redelivered', async () => {+ const store = createMemoryQQPassiveStore();+ await store.open('app:thread', { at: AT, msgId: 'msg_1' });+ await store.reserve('app:thread', LIMITS, AT + 1000);++ // QQ redelivers the webhook: its own window must survive.+ await store.open('app:thread', { at: AT + 2000, msgId: 'msg_1' });+ const slot = await store.reserve('app:thread', LIMITS, AT + 3000);++ expect(slot).toMatchObject({ msgId: 'msg_1', seq: 2 });+ });++ it('never hands out a slot for an unknown thread', async () => {+ const store = createMemoryQQPassiveStore();++ expect(await store.reserve('app:unknown', LIMITS, AT)).toBeNull();+ });++ it('puts a claimed text back when delivery failed, but never over a newer reply', async () => {+ const store = createMemoryQQPassiveStore();+ await store.savePending('app:thread', 'claimed');++ expect(await store.takePending('app:thread')).toBe('claimed');+ await store.restorePending('app:thread', 'claimed');++ expect(await store.takePending('app:thread')).toBe('claimed');++ // A newer answer was parked while the claimed one was in flight: keep the newer one.+ await store.savePending('app:thread', 'newer');+ await store.restorePending('app:thread', 'claimed');++ expect(await store.takePending('app:thread')).toBe('newer');+ });++ it('keeps only the newest deferred text and hands it over once', async () => {+ const store = createMemoryQQPassiveStore();+ await store.savePending('app:thread', 'first');+ await store.savePending('app:thread', 'second');++ expect(await store.takePending('app:thread')).toBe('second');+ expect(await store.takePending('app:thread')).toBeUndefined();+ });+});diff --git a/packages/chat-adapter-qq/src/passive.ts b/packages/chat-adapter-qq/src/passive.tsnew file mode 100644index 00000000000..8f760dbdbb6--- /dev/null+++ b/packages/chat-adapter-qq/src/passive.ts@@ -0,0 +1,122 @@+/**+ * QQ's passive-reply window.+ *+ * Since 2025-04-21 QQ has no active-message channel: a bot may only send by answering an inbound+ * message through that message's `msg_id` / `event_id`, and only inside a fixed window with a+ * fixed number of replies per inbound message. Anything outside it is rejected by the server, so+ * the window has to be tracked rather than guessed at send time.+ *+ * The window is per conversation (a group or a C2C pair), not per message: opening a new inbound+ * message restarts it.+ */++export type QQPassiveThreadType = 'c2c' | 'dms' | 'group' | 'guild';++export interface QQPassiveLimits {+ /** Replies one inbound message may carry. */+ maxReplies: number;+ /** How long after the inbound message a reply is still accepted; ms. */+ windowMs: number;+}++/**+ * Limits from the QQ bot docs: a group window is 5 minutes / 5 replies, C2C 60 minutes / 5+ * replies; guild and DMS only bound the window (they carry no `msg_seq`).+ */+export const QQ_PASSIVE_LIMITS: Record<QQPassiveThreadType, QQPassiveLimits> = {+ c2c: { maxReplies: 5, windowMs: 60 * 60 * 1000 },+ dms: { maxReplies: Number.MAX_SAFE_INTEGER, windowMs: 5 * 60 * 1000 },+ group: { maxReplies: 5, windowMs: 5 * 60 * 1000 },+ guild: { maxReplies: Number.MAX_SAFE_INTEGER, windowMs: 5 * 60 * 1000 },+};++/** What the inbound message that opened the current window carried. */+export interface QQPassiveToken {+ /** Epoch ms the inbound message arrived. */+ at: number;+ eventId?: string;+ msgId?: string;+}++/** One reserved reply slot. */+export interface QQPassiveSlot extends QQPassiveToken {+ /** 1-based reply counter within this window (`msg_seq`). */+ seq: number;+}++/**+ * Where a thread's passive window lives. Implementations never throw: a bot that loses its window+ * state must degrade to "cannot send", not to a failed webhook.+ */+export interface QQPassiveStore {+ /** Start a new window for `key` from an inbound message. */+ open(key: string, token: QQPassiveToken): Promise<void>;+ /** Take the next reply slot, or null when the window is closed or out of replies. */+ reserve(key: string, limits: QQPassiveLimits, now?: number): Promise<QQPassiveSlot | null>;+ /** Claim the text that a closed window could not carry, so the next one can deliver it. */+ takePending(key: string): Promise<string | undefined>;+ /** Park text that could not be delivered. Only the newest one is kept. */+ savePending(key: string, text: string): Promise<void>;+ /**+ * Put a claimed text back after its delivery failed, so the next inbound message retries it.+ * Never replaces a pending reply parked afterwards: the newer answer is the one the reader wants.+ */+ restorePending(key: string, text: string): Promise<void>;+}++interface Window {+ at: number;+ eventId?: string;+ msgId?: string;+ seq: number;+}++/** In-process store: enough for tests and for a single-instance deployment. */+export const createMemoryQQPassiveStore = (): QQPassiveStore => {+ const windows = new Map<string, Window>();+ const pending = new Map<string, string>();++ return {+ open: async (key, token) => {+ const window = windows.get(key);+ // A redelivered inbound message must not restart its own budget: its first replies already+ // carry (msg_id, msg_seq 1..n), and reusing a sequence is rejected as a duplicate.+ if (window && token.msgId && window.msgId === token.msgId) return;++ // A new inbound message restarts the window (and its reply budget).+ windows.set(key, { at: token.at, eventId: token.eventId, msgId: token.msgId, seq: 0 });+ },++ reserve: async (key, limits, now = Date.now()) => {+ const window = windows.get(key);+ if (!window) return null;+ if (now - window.at > limits.windowMs) {+ windows.delete(key);+ return null;+ }+ if (window.seq >= limits.maxReplies) return null;++ window.seq += 1;+ return { at: window.at, eventId: window.eventId, msgId: window.msgId, seq: window.seq };+ },++ savePending: async (key, text) => {+ pending.set(key, text);+ },++ takePending: async (key) => {+ const text = pending.get(key);+ pending.delete(key);+ return text;+ },++ restorePending: async (key, text) => {+ // A reply parked after this one was claimed is newer; keep it and drop the older text.+ if (pending.has(key)) return;+ pending.set(key, text);+ },+ };+};++/** The prefix a delivered-late reply carries, so the reader knows why it is out of order. */+export const QQ_DEFERRED_PREFIX = '(上一条回复没发出去,补上)\n\n';diff --git a/packages/chat-adapter-qq/src/types.ts b/packages/chat-adapter-qq/src/types.tsindex 24a3d5be6aa..232f25a6053 100644--- a/packages/chat-adapter-qq/src/types.ts+++ b/packages/chat-adapter-qq/src/types.ts@@ -1,6 +1,13 @@+import type { QQPassiveStore } from './passive';+export interface QQAdapterConfig {appId: string;clientSecret: string;+ /**+ * Tracks each conversation's passive-reply window (see `passive.ts`). Defaults to an in-process+ * store, which only works for a single instance — a multi-instance deployment passes a shared one.+ */+ passiveStore?: QQPassiveStore;}export interface QQThreadId {