@botharness/im-provider 4.32.0-botharness.21 → 4.32.0-botharness.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,33 @@
1
- import { isQqAddressedGroupMessage } from './external-addressing.mjs';
1
+ import { isQqAddressedGroupMessage, isQqAddressedMessage, isQqDirectMessage } from './external-addressing.mjs';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { ApiError, getNextMsgSeq, messagePath } from '@tencent-connect/qqbot-nodejs/protocol';
4
4
  import { QqNativeReplyObservations, qqNativeIdentifier as identifier } from './native-reply-observations.mjs';
5
5
  import { qqSourceAttachments, readQqSourceAttachment, checkedQqImageFile, uploadQqCheckedMedia } from './external-images.mjs';
6
- import { checkedQqGenericFile, qqQuotedFileMessage } from './external-files.mjs';
6
+ import { checkedQqGenericFile, qqQuotedMessage } from './external-files.mjs';
7
+ import { qqAttachmentLabel, qqReadableAttachments, qqSkippedAttachmentNotes } from './external-attachments.mjs';
7
8
  import { qqVoiceMessage } from './external-voice.mjs';
8
9
  import { qqExternalMentions } from './external-mentions.mjs';
9
10
 
10
11
  export function qqRefusal(code) { return Object.assign(new Error(code), { code }); }
11
12
 
13
+ // QQ rejects a rate-limited post outright, so the same msg_seq is retried
14
+ // after a short backoff; any other outcome is returned to the caller as is.
15
+ const RATE_LIMIT_RETRY_DELAYS_MS = Object.freeze([1_000, 3_000]);
16
+ const POST_QUEUE_WAIT_MS = 30_000;
17
+ // QQ's passive reply rules: C2C replies stay open for 60 minutes and four replies, group replies for five and five.
18
+ const PASSIVE_REPLY_WINDOW_MS = Object.freeze({ c2c: 60 * 60_000, group: 5 * 60_000 });
19
+ const PASSIVE_REPLY_BUDGET = Object.freeze({ c2c: 4, group: 5 });
20
+
21
+ function retryDelay(ms, signal) {
22
+ return new Promise((resolve, reject) => {
23
+ if (signal?.aborted) { reject(qqRefusal('cancelled')); return; }
24
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, ms);
25
+ timer.unref?.();
26
+ const abort = () => { clearTimeout(timer); reject(qqRefusal('cancelled')); };
27
+ signal?.addEventListener('abort', abort, { once: true });
28
+ });
29
+ }
30
+
12
31
  function nativeReplyFailure(error) {
13
32
  if (!(error instanceof ApiError)) return qqRefusal('reply-result-unknown');
14
33
  const code = Number(error.bizCode);
@@ -42,18 +61,21 @@ export function verifiedQqAccount(appId, user) {
42
61
 
43
62
  /** QQ group and member OpenIDs belong to this authenticated application. */
44
63
  export function normalizeQqExternalText(message, { botId, account, ordinaryText = false }) {
45
- const addressed = isQqAddressedGroupMessage(message);
64
+ const direct = isQqDirectMessage(message);
65
+ const addressed = direct || isQqAddressedGroupMessage(message);
46
66
  const ordinary = ordinaryText === true && message?.kind === 'group'
47
67
  && message.rawEventType === 'GROUP_MESSAGE_CREATE';
48
68
  if (!(addressed || ordinary)
49
69
  || message.senderIsBot || message.senderId === account.userId
50
70
  || message.attachments?.length || message.msgElements?.length
51
71
  || (message.msgType !== undefined && message.msgType !== 0)) return null;
72
+ const conversationId = direct ? message.senderId : message.groupOpenid;
52
73
  if (!identifier(message.messageId) || !identifier(message.senderId)
53
- || !identifier(message.groupOpenid) || typeof message.content !== 'string'
74
+ || !identifier(conversationId) || (direct && message.groupOpenid !== undefined)
75
+ || typeof message.content !== 'string'
54
76
  || !message.content.trim() || message.content.length > 16000
55
- || message.replyTarget?.scope !== 'group'
56
- || message.replyTarget.targetId !== message.groupOpenid
77
+ || message.replyTarget?.scope !== (direct ? 'c2c' : 'group')
78
+ || message.replyTarget.targetId !== conversationId
57
79
  || message.replyTarget.msgId !== message.messageId)
58
80
  throw qqRefusal('invalid-inbound');
59
81
  const at = new Date(message.timestamp);
@@ -63,13 +85,29 @@ export function normalizeQqExternalText(message, { botId, account, ordinaryText
63
85
  actor: { kind: 'user', id: message.senderId,
64
86
  ...(typeof message.senderName === 'string' && message.senderName.trim()
65
87
  ? { name: message.senderName.slice(0, 512) } : {}) },
66
- conversation: { kind: 'group', id: message.groupOpenid },
67
- mentions: qqExternalMentions(message, account), mentionedAccount: addressed, at: at.toISOString(), text: message.content,
68
- reply: { messageId: message.messageId, conversationId: message.groupOpenid, actorId: message.senderId },
88
+ conversation: { kind: direct ? 'dm' : 'group', id: conversationId },
89
+ mentions: direct ? [] : qqExternalMentions(message, account), mentionedAccount: !direct && addressed,
90
+ at: at.toISOString(), text: message.content,
91
+ reply: { messageId: message.messageId, conversationId, actorId: message.senderId },
69
92
  replay: { kind: 'provider-redelivery', resumeCursor: false, gapPossible: true },
70
93
  });
71
94
  }
72
95
 
96
+ /**
97
+ * Attachments this consumer cannot read are named in the text instead of
98
+ * dropping the whole message, and an @ with no text still reaches the Bot.
99
+ */
100
+ function withReadableAttachments(message, options) {
101
+ if (typeof message?.content !== 'string') return message;
102
+ const { readable, skipped } = qqReadableAttachments(message.attachments, options);
103
+ const notes = qqSkippedAttachmentNotes(skipped);
104
+ const caption = message.content.trim();
105
+ const content = notes.length ? [...(caption ? [message.content] : []), ...notes].join('\n')
106
+ : !caption && !readable.length && isQqAddressedGroupMessage(message) ? '[Mentioned the Bot with no text]'
107
+ : message.content;
108
+ return { ...message, content, attachments: readable.length ? readable : undefined };
109
+ }
110
+
73
111
  /** Bounded, process-local source proof, never a second durable Inbox or history. */
74
112
  export class QqExternalConsumer {
75
113
  #bot;
@@ -82,8 +120,12 @@ export class QqExternalConsumer {
82
120
  #sourceVoiceTranscripts;
83
121
  #sourceVoiceAudio;
84
122
  #ordinaryText;
123
+ #directMessages;
124
+ #rateLimitRetryDelaysMs;
85
125
  #sources = new Map();
86
- constructor({ bot, account, botId, accept, sourceImages = () => false, sourceFiles = () => false, sourceVoiceTranscripts = () => false, sourceVoiceAudio = () => false, ordinaryText = () => false, reportNativeObservation = () => {}, reportNativeFrame, nativeUser }) {
126
+ #posts = new Map();
127
+ constructor({ bot, account, botId, accept, sourceImages = () => false, sourceFiles = () => false, sourceVoiceTranscripts = () => false, sourceVoiceAudio = () => false, ordinaryText = () => false, directMessages = () => false, reportNativeObservation = () => {}, reportNativeFrame, nativeUser, rateLimitRetryDelaysMs = RATE_LIMIT_RETRY_DELAYS_MS }) {
128
+ this.#rateLimitRetryDelaysMs = rateLimitRetryDelaysMs;
87
129
  this.#bot = bot; this.#account = account; this.#botId = botId; this.#accept = accept;
88
130
  this.#observations = new QqNativeReplyObservations({ account, report: reportNativeObservation,
89
131
  reportFrame: reportNativeFrame, nativeUser });
@@ -92,22 +134,33 @@ export class QqExternalConsumer {
92
134
  this.#sourceVoiceTranscripts = sourceVoiceTranscripts;
93
135
  this.#sourceVoiceAudio = sourceVoiceAudio;
94
136
  this.#ordinaryText = ordinaryText;
137
+ this.#directMessages = directMessages;
95
138
  }
96
139
  recordNativeReceipt(receipt, signal) {
97
140
  this.#observations.sent(receipt.conversationId, receipt.messageId, signal);
98
141
  }
99
142
  async accept(message, signal) {
100
143
  this.#observations.receive(message, signal);
101
- const addressed = isQqAddressedGroupMessage(message);
144
+ // Private messages stay unadmitted until the consumer opts into them.
145
+ if (isQqDirectMessage(message) && this.#directMessages() !== true) return;
146
+ const addressed = isQqAddressedMessage(message);
102
147
  const voice = addressed && (this.#sourceVoiceTranscripts() === true || this.#sourceVoiceAudio() === true)
103
148
  ? qqVoiceMessage(message, { sourceVoiceTranscripts: this.#sourceVoiceTranscripts() === true }) : undefined;
104
- const quoted = addressed && !voice && this.#sourceFiles() === true ? qqQuotedFileMessage(message) : undefined;
149
+ const ordinary = !addressed && this.#ordinaryText() === true && message?.kind === 'group'
150
+ && message.rawEventType === 'GROUP_MESSAGE_CREATE' && !message.senderIsBot
151
+ && message.senderId !== this.#account.userId;
152
+ const sourceImages = addressed && this.#sourceImages() === true;
153
+ const sourceFiles = addressed && this.#sourceFiles() === true;
154
+ const quoted = voice || !(addressed || ordinary) ? undefined
155
+ : qqQuotedMessage(message, { sourceImages, sourceFiles, ordinary });
105
156
  message = quoted?.message ?? message;
106
157
  message = voice?.message ?? message;
107
- const mediaEnabled = addressed && (this.#sourceImages() === true || this.#sourceFiles() === true) && message?.attachments?.length;
158
+ if (!voice && (addressed || ordinary)) message = withReadableAttachments(message, { sourceImages, sourceFiles });
159
+ const mediaEnabled = addressed && message?.attachments?.length;
108
160
  const base = normalizeQqExternalText(mediaEnabled ? { ...message, attachments: undefined,
109
161
  content: typeof message.content === 'string' && !message.content.trim()
110
- ? message.attachments.every(file => file?.content_type === 'file') ? '[File]' : '[Image]' : message.content } : message,
162
+ ? `[${message.attachments.map(qqAttachmentLabel).map(label => label[0].toUpperCase() + label.slice(1)).join('] [')}]`
163
+ : message.content } : message,
111
164
  { botId: this.#botId, account: this.#account, ordinaryText: this.#ordinaryText() === true });
112
165
  const media = base && voice && this.#sourceVoiceAudio() === true
113
166
  ? qqSourceAttachments(voice.nativeMessage, base, { sourceImages: false, sourceVoiceAudio: true, referenceKey: voice.referenceKey })
@@ -137,9 +190,11 @@ export class QqExternalConsumer {
137
190
  }
138
191
  qualify(route, signal) {
139
192
  const source = this.#source(route, signal);
140
- if (!source.event.mentionedAccount) throw qqRefusal('capability-unavailable');
141
- if (Date.now() - Date.parse(source.event.at) >= 5 * 60_000) throw qqRefusal('reply-window-expired');
142
- if (source.attempts >= 5) throw qqRefusal('reply-limit-exceeded');
193
+ const direct = source.event.conversation.kind === 'dm';
194
+ if (!direct && !source.event.mentionedAccount) throw qqRefusal('capability-unavailable');
195
+ if (Date.now() - Date.parse(source.event.at) >= PASSIVE_REPLY_WINDOW_MS[direct ? 'c2c' : 'group'])
196
+ throw qqRefusal('reply-window-expired');
197
+ if (source.attempts >= PASSIVE_REPLY_BUDGET[direct ? 'c2c' : 'group']) throw qqRefusal('reply-limit-exceeded');
143
198
  return structuredClone(source.event.reply);
144
199
  }
145
200
  async readImage(route, attachment, options = {}) {
@@ -158,6 +213,43 @@ export class QqExternalConsumer {
158
213
  throw qqRefusal('source-unavailable');
159
214
  } });
160
215
  }
216
+ #scope(qualified) {
217
+ return this.#sources.get(qualified.messageId)?.event.conversation.kind === 'dm' ? 'c2c' : 'group';
218
+ }
219
+ /** Posts to one conversation run one at a time; a rate-limited post backs off and retries. */
220
+ #post(qualified, body, signal, assertSendable) {
221
+ const conversationId = qualified.conversationId;
222
+ const scope = this.#scope(qualified);
223
+ const previous = this.#posts.get(`${scope}:${conversationId}`) ?? Promise.resolve();
224
+ const run = async () => {
225
+ for (let retry = 0; ; retry++) {
226
+ assertSendable();
227
+ let token;
228
+ try { token = await this.#bot.api.getToken(); }
229
+ catch { throw qqRefusal('source-unavailable'); }
230
+ assertSendable();
231
+ this.#sources.get(qualified.messageId).attempts++;
232
+ try {
233
+ return await this.#bot.apiClient.request(token, 'POST', messagePath(scope, conversationId), body);
234
+ } catch (error) {
235
+ const failure = nativeReplyFailure(error);
236
+ if (failure.code !== 'reply-rate-limited' || retry >= this.#rateLimitRetryDelaysMs.length) throw failure;
237
+ // A rate-limited post was refused, so it does not spend the passive reply budget.
238
+ const source = this.#sources.get(qualified.messageId);
239
+ if (source) source.attempts--;
240
+ await retryDelay(this.#rateLimitRetryDelaysMs[retry], signal);
241
+ }
242
+ }
243
+ };
244
+ // A stalled earlier post must not hold the group's later replies past their window.
245
+ const current = Promise.race([previous, retryDelay(POST_QUEUE_WAIT_MS).catch(() => undefined)])
246
+ .catch(() => undefined).then(run);
247
+ const tail = current.catch(() => undefined);
248
+ const key = `${scope}:${conversationId}`;
249
+ this.#posts.set(key, tail);
250
+ tail.then(() => { if (this.#posts.get(key) === tail) this.#posts.delete(key); });
251
+ return current;
252
+ }
161
253
  async replyFile(route, file, { signal, beforeSend, verifyAccount } = {}) {
162
254
  const qualified = this.qualify(route, signal);
163
255
  if (typeof beforeSend !== 'function' || typeof verifyAccount !== 'function') throw qqRefusal('bad-request');
@@ -165,23 +257,16 @@ export class QqExternalConsumer {
165
257
  const bytes = image ? checkedQqImageFile(file) : checkedQqGenericFile(file);
166
258
  if (beforeSend() !== true) throw qqRefusal('stale-route');
167
259
  if (signal?.aborted) throw qqRefusal('cancelled');
168
- const target = { scope: 'group', targetId: qualified.conversationId, msgId: qualified.messageId };
260
+ const target = { scope: this.#scope(qualified), targetId: qualified.conversationId, msgId: qualified.messageId };
169
261
  const fileInfo = await uploadQqCheckedMedia(this.#bot, target, file, bytes, signal, image ? 1 : 4);
170
262
  await verifyAccount();
171
- this.qualify(qualified, signal);
172
- let token;
173
- try { token = await this.#bot.api.getToken(); }
174
- catch { throw qqRefusal('source-unavailable'); }
175
- this.qualify(qualified, signal);
176
- if (beforeSend() !== true) throw qqRefusal('stale-route');
177
- if (signal?.aborted) throw qqRefusal('cancelled');
178
- this.#sources.get(qualified.messageId).attempts++;
179
- let response;
180
- try {
181
- response = await this.#bot.apiClient.request(token, 'POST', messagePath('group', qualified.conversationId),
182
- { msg_type: 7, media: { file_info: fileInfo }, msg_id: qualified.messageId,
183
- msg_seq: getNextMsgSeq(qualified.messageId) });
184
- } catch (error) { throw nativeReplyFailure(error); }
263
+ const response = await this.#post(qualified,
264
+ { msg_type: 7, media: { file_info: fileInfo }, msg_id: qualified.messageId,
265
+ msg_seq: getNextMsgSeq(qualified.messageId) }, signal, () => {
266
+ this.qualify(qualified, signal);
267
+ if (beforeSend() !== true) throw qqRefusal('stale-route');
268
+ if (signal?.aborted) throw qqRefusal('cancelled');
269
+ });
185
270
  if (signal?.aborted || !identifier(response?.id)) throw qqRefusal('reply-result-unknown');
186
271
  this.#observations.sent(qualified.conversationId, response.id, signal, response);
187
272
  return { sent: true, receipt: { version: 1, messageId: response.id, conversationId: qualified.conversationId } };
@@ -190,21 +275,16 @@ export class QqExternalConsumer {
190
275
  const qualified = this.qualify(route, signal);
191
276
  if (typeof text !== 'string' || !text.trim() || text.length > 4000 || mentionUserIds?.length)
192
277
  throw qqRefusal('bad-request');
193
- // sendText awaits token acquisition internally. Prepare the token first so
194
- // revocation and expiry are checked immediately before the message POST.
195
- let token;
196
- try { token = await this.#bot.api.getToken(); }
197
- catch { throw qqRefusal('source-unavailable'); }
198
- if (signal?.aborted) throw qqRefusal('cancelled');
199
- this.qualify(qualified, signal);
200
- if (beforeSend !== undefined && beforeSend() !== true) throw qqRefusal('stale-route');
201
- if (signal?.aborted) throw qqRefusal('cancelled');
202
- this.#sources.get(qualified.messageId).attempts++;
203
- let response;
204
- try {
205
- response = await this.#bot.apiClient.request(token, 'POST', messagePath('group', qualified.conversationId),
206
- { msg_type: 0, content: text, msg_id: qualified.messageId, msg_seq: getNextMsgSeq(qualified.messageId) });
207
- } catch (error) { throw nativeReplyFailure(error); }
278
+ // The token is prepared before the fence so revocation and expiry are
279
+ // checked immediately before the message POST, including on a retry.
280
+ const response = await this.#post(qualified,
281
+ { msg_type: 0, content: text, msg_id: qualified.messageId, msg_seq: getNextMsgSeq(qualified.messageId) },
282
+ signal, () => {
283
+ if (signal?.aborted) throw qqRefusal('cancelled');
284
+ this.qualify(qualified, signal);
285
+ if (beforeSend !== undefined && beforeSend() !== true) throw qqRefusal('stale-route');
286
+ if (signal?.aborted) throw qqRefusal('cancelled');
287
+ });
208
288
  // Once dispatch begins, cancellation or a missing response cannot prove non-delivery.
209
289
  if (signal?.aborted || !identifier(response?.id)) throw qqRefusal('reply-result-unknown');
210
290
  this.#observations.sent(qualified.conversationId, response.id, signal, response);
@@ -1,6 +1,15 @@
1
- import { isQqAddressedGroupMessage } from './external-addressing.mjs';
1
+ import { isQqAddressedMessage, isQqDirectMessage } from './external-addressing.mjs';
2
2
  import { QQ_EXTERNAL_IMAGE_LIMIT } from './external-images.mjs';
3
3
  import { qqNativeIdentifier } from './native-reply-observations.mjs';
4
+ import { qqAttachmentLabel, qqReadableAttachments, qqSkippedAttachmentNotes } from './external-attachments.mjs';
5
+
6
+ // Same rendering as the SDK contentSanitizer applies to the top-level body.
7
+ function qqFaceText(text) {
8
+ return text.replace(/<faceType=\d+,faceId="[^"]*",ext="([^"]*)">/g, (tag, ext) => {
9
+ try { return `【表情: ${JSON.parse(Buffer.from(ext, 'base64').toString('utf-8')).text || '未知表情'}】`; }
10
+ catch { return tag; }
11
+ });
12
+ }
4
13
 
5
14
  const refusal = (code, reason) => Object.assign(new Error(code), { code, ...(reason ? { reason } : {}) });
6
15
 
@@ -14,13 +23,8 @@ export function checkedQqGenericFile(file) {
14
23
  if (file.bytes.byteLength > QQ_EXTERNAL_IMAGE_LIMIT) throw refusal('artifact-too-large');
15
24
  return Buffer.from(file.bytes);
16
25
  }
17
- export function qqQuotedFileMessage(message) {
18
- return qqQuotedMediaMessage(message, { accepts: files => files.every(file => file?.content_type === 'file'), label: 'file' });
19
- }
20
-
21
- /** Shared native quote authority; each media owner supplies its own category policy. */
22
- export function qqQuotedMediaMessage(message, { accepts, label, requireCaption = true }) {
23
- if (message?.msgType !== 103) return undefined;
26
+ /** Verified single quoted element of a native quote; throws a visible refusal otherwise. */
27
+ function qqQuotedElement(message, { ordinary = false } = {}) {
24
28
  const raw = message.raw;
25
29
  const elements = raw?.msg_elements;
26
30
  const element = Array.isArray(elements) && elements.length === 1 ? elements[0] : undefined;
@@ -28,9 +32,11 @@ export function qqQuotedMediaMessage(message, { accepts, label, requireCaption =
28
32
  const refs = Array.isArray(raw?.message_scene?.ext)
29
33
  ? raw.message_scene.ext.filter(value => typeof value === 'string' && value.split('=', 1)[0].trim() === 'ref_msg_idx')
30
34
  .map(value => value.slice(value.indexOf('=') + 1).trim()) : [];
31
- if (!isQqAddressedGroupMessage(message)
35
+ if (!(ordinary ? message?.kind === 'group' && message.rawEventType === 'GROUP_MESSAGE_CREATE'
36
+ : isQqAddressedMessage(message))
32
37
  || raw?.message_type !== 103 || raw.id !== message.messageId || raw.group_openid !== message.groupOpenid
33
- || raw.author?.member_openid !== message.senderId || raw.author?.bot === true)
38
+ || (isQqDirectMessage(message) ? raw.author?.user_openid : raw.author?.member_openid) !== message.senderId
39
+ || raw.author?.bot === true)
34
40
  throw refusal('invalid-inbound', 'quote-envelope-invalid');
35
41
  if (!qqNativeIdentifier(key) || message.refMsgIdx !== key || refs.some(value => value !== key))
36
42
  throw refusal('invalid-inbound', 'quote-reference-invalid');
@@ -38,13 +44,47 @@ export function qqQuotedMediaMessage(message, { accepts, label, requireCaption =
38
44
  || (raw.attachments !== undefined && (!Array.isArray(raw.attachments) || raw.attachments.length))
39
45
  || !Array.isArray(message.msgElements) || message.msgElements.length !== 1
40
46
  || message.msgElements[0]?.msg_idx !== key
47
+ || (message.msgElements[0]?.attachments?.length ?? 0) !== (element.attachments?.length ?? 0)
41
48
  || Object.keys(element).some(field => !['msg_idx', 'content', 'message_type', 'attachments'].includes(field))
42
49
  || (element.message_type !== undefined && (!Number.isSafeInteger(element.message_type)
43
50
  || element.message_type < 0))
44
- || !Array.isArray(element.attachments) || !element.attachments.length
45
- || !accepts(element.attachments)
46
- || typeof message.content !== 'string' || (requireCaption && !message.content.trim()))
51
+ || (element.attachments !== undefined && !Array.isArray(element.attachments))
52
+ || (element.content !== undefined && typeof element.content !== 'string')
53
+ || typeof message.content !== 'string')
54
+ throw refusal('invalid-inbound', 'quote-elements-invalid');
55
+ return { key, element };
56
+ }
57
+
58
+ /** Shared native quote authority; each media owner supplies its own category policy. */
59
+ export function qqQuotedMediaMessage(message, { accepts, label, requireCaption = true }) {
60
+ if (message?.msgType !== 103) return undefined;
61
+ const { key, element } = qqQuotedElement(message);
62
+ if (!element.attachments?.length || !accepts(element.attachments)
63
+ || (requireCaption && !message.content.trim()))
47
64
  throw refusal('invalid-inbound', 'quote-elements-invalid');
48
65
  return { referenceKey: key, message: { ...message, msgType: 0, msgElements: undefined,
49
66
  content: `${message.content}\n[Quoted ${label}]`, attachments: element.attachments } };
50
67
  }
68
+
69
+ /**
70
+ * A quote keeps its quoted text and every quoted attachment: readable ones are
71
+ * attached under the quote's reference, the rest are named in the text.
72
+ * Ordinary (unaddressed) quotes are admitted as text only.
73
+ */
74
+ export function qqQuotedMessage(message, { sourceImages = false, sourceFiles = false, ordinary = false } = {}) {
75
+ if (message?.msgType !== 103) return undefined;
76
+ const { key, element } = qqQuotedElement(message, { ordinary });
77
+ const { readable, skipped } = qqReadableAttachments(element.attachments,
78
+ ordinary ? {} : { sourceImages, sourceFiles });
79
+ // The SDK sanitizer only rewrites the top-level body, so quoted QQ faces are rendered here.
80
+ const quoted = qqFaceText(element.content ?? '').trim();
81
+ const caption = message.content.trim();
82
+ const lines = ['[Quoted message]', ...(quoted ? [quoted] : []),
83
+ ...readable.map(file => `[Quoted ${qqAttachmentLabel(file)}]`),
84
+ ...qqSkippedAttachmentNotes(skipped, { quoted: true })];
85
+ const content = `${caption ? `${caption}\n\n` : ''}${lines.join('\n')}`;
86
+ if (content.length > 16000) throw refusal('invalid-inbound', 'quote-elements-invalid');
87
+ return { ...(readable.length ? { referenceKey: key } : {}),
88
+ message: { ...message, msgType: 0, msgElements: undefined, content,
89
+ attachments: readable.length ? readable : undefined } };
90
+ }
@@ -2,9 +2,10 @@ import { isQqVoiceAttachment } from './voice-attachment.mjs';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { detectedImageMediaType, fetchImageBuffer } from '../shared/image-prompt.mjs';
4
4
  import { QQ_IMAGE_HOSTS } from './qq-bridge.mjs';
5
+ import { QQ_READABLE_IMAGE_TYPES, qqAttachmentUrl, qqImageMediaType } from './external-attachments.mjs';
5
6
 
6
7
  export const QQ_EXTERNAL_IMAGE_LIMIT = 25 * 1024 * 1024;
7
- const imageTypes = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
8
+ const imageTypes = QQ_READABLE_IMAGE_TYPES;
8
9
  const refusal = (code, reason) => Object.assign(new Error(code), { code, ...(reason ? { reason } : {}) });
9
10
 
10
11
  /** Native caption and attachment order are separate; no native interleaving is inferred. */
@@ -16,12 +17,13 @@ export function qqSourceAttachments(message, event, { sourceImages = true, sourc
16
17
  const voice = sourceVoiceAudio && message.attachments.length === 1
17
18
  && isQqVoiceAttachment(native);
18
19
  const mediaType = voice ? 'audio/unknown' : native?.content_type === 'file' && sourceFiles
19
- ? 'application/octet-stream' : sourceImages && imageTypes.has(native?.content_type) ? native.content_type : null;
20
+ ? 'application/octet-stream' : sourceImages ? qqImageMediaType(native) ?? null : null;
20
21
  if (!mediaType) throw refusal('invalid-inbound', 'file-category-invalid');
21
- if (typeof native.url !== 'string' || native.url.length > 16384)
22
+ const nativeUrl = qqAttachmentUrl(native.url);
23
+ if (typeof nativeUrl !== 'string' || nativeUrl.length > 16384)
22
24
  throw refusal('invalid-inbound', 'file-url-invalid');
23
25
  let url;
24
- try { url = new URL(native.url); } catch { throw refusal('invalid-inbound', 'file-url-invalid'); }
26
+ try { url = new URL(nativeUrl); } catch { throw refusal('invalid-inbound', 'file-url-invalid'); }
25
27
  if (url.protocol !== 'https:' || url.username || url.password || (url.port && url.port !== '443')
26
28
  || !QQ_IMAGE_HOSTS.some(host => url.hostname === host.slice(1) || url.hostname.endsWith(host)))
27
29
  throw refusal('resource-unavailable');
@@ -36,7 +38,7 @@ export function qqSourceAttachments(message, event, { sourceImages = true, sourc
36
38
  && !/[\x00-\x1f\x7f/\\]/.test(native.filename) ? native.filename : native.content_type === 'file' ? 'file' : voice ? 'voice.bin' : 'image';
37
39
  const attachment = { id, messageId: event.messageId, resourceKey: id, name,
38
40
  mediaType, ...(native.size === undefined ? {} : { sizeBytes: native.size }) };
39
- return { attachment, url: native.url };
41
+ return { attachment, url: nativeUrl };
40
42
  });
41
43
  return { files, event: { ...event, attachments: files.map(file => file.attachment),
42
44
  contentParts: [
@@ -62,7 +64,8 @@ export async function readQqSourceAttachment(source, attachment, { signal, asser
62
64
  assertCurrent();
63
65
  await verifyAccount();
64
66
  assertCurrent();
65
- if ((attachment.mediaType.startsWith('image/') && detectedImageMediaType(bytes) !== attachment.mediaType)
67
+ // QQ's declared image type is not always the stored format; any readable image format is accepted.
68
+ if ((attachment.mediaType.startsWith('image/') && !imageTypes.has(detectedImageMediaType(bytes)))
66
69
  || (attachment.sizeBytes !== undefined && bytes.byteLength !== attachment.sizeBytes))
67
70
  throw refusal('resource-unavailable');
68
71
  return (async function* () {
@@ -376,11 +376,14 @@ function sendPlainText(bot, target, content, msgSeq) {
376
376
  * 以 markdown(msg_type=2)发送回复;单条被平台拒绝时回退纯文本(msg_type=0)。
377
377
  * 返回每条消息的平台响应,供调用方提取 provider message ids。
378
378
  */
379
- export async function sendMarkdownReply(bot, target, text, { logger } = {}) {
379
+ export async function sendMarkdownReply(bot, target, text, { logger, passiveRepliesUsed = 0 } = {}) {
380
380
  const chunks = chunkMarkdownParts(text);
381
381
  const results = [];
382
382
  const firstMsgSeq = nextMsgSeq();
383
- const passiveLimit = target?.msgId ? PASSIVE_REPLY_LIMIT[target.scope] : null;
383
+ // Earlier replies to the same msg_id (for example a timeout notice) spend
384
+ // part of QQ's passive budget; at least one slot is kept for this reply.
385
+ const passiveLimit = target?.msgId
386
+ ? Math.max(1, PASSIVE_REPLY_LIMIT[target.scope] - passiveRepliesUsed) : null;
384
387
  const overflow = passiveLimit !== null && chunks.length > passiveLimit;
385
388
  const passiveContentCount = overflow ? passiveLimit - 1 : chunks.length;
386
389
  const proactiveTarget = target?.msgId
@@ -67,6 +67,7 @@ import {
67
67
  COMMAND_PERMISSION_DENIED_MESSAGE,
68
68
  evaluateInboundAccess,
69
69
  } from '../shared/inbound-access.mjs';
70
+ import { ApiError } from '@tencent-connect/qqbot-nodejs';
70
71
  import { sendMarkdownReply } from './markdown-reply.mjs';
71
72
  import {
72
73
  isQqMenuCommand, parseQqMenuCommand, QqMenuStore,
@@ -253,6 +254,28 @@ export function qqInboundMessage(message, { fetchImpl = fetch } = {}) {
253
254
  };
254
255
  }
255
256
 
257
+ // QQ accepts passive replies to an inbound msg_id for a bounded window
258
+ // (C2C 60 min, group 5 min). Proactive C2C/group sends are quota-limited and
259
+ // are often refused, so a late result keeps the passive route while the
260
+ // window is still open and only falls back to proactive delivery after it.
261
+ const PASSIVE_REPLY_WINDOW_MS = Object.freeze({ c2c: 60 * 60_000, group: 5 * 60_000 });
262
+ const PASSIVE_REPLY_MARGIN_MS = 30_000;
263
+
264
+ function deferredQqTarget(message, target, acceptedAt) {
265
+ const route = { scope: target.scope, targetId: target.targetId };
266
+ const msgId = nonEmptyString(target.msgId);
267
+ if (!msgId || !PASSIVE_REPLY_WINDOW_MS[target.scope]) return route;
268
+ const sentAt = Date.parse(message?.timestamp ?? '');
269
+ return { ...route, msgId, receivedAt: Number.isFinite(sentAt) ? Math.min(sentAt, acceptedAt) : acceptedAt };
270
+ }
271
+
272
+ export function deferredDeliveryTarget(target, now = Date.now()) {
273
+ const route = { scope: target?.scope, targetId: target?.targetId };
274
+ const window = PASSIVE_REPLY_WINDOW_MS[target?.scope];
275
+ if (!nonEmptyString(target?.msgId) || !window || !Number.isFinite(target?.receivedAt)) return route;
276
+ return now - target.receivedAt < window - PASSIVE_REPLY_MARGIN_MS ? { ...route, msgId: target.msgId } : route;
277
+ }
278
+
256
279
  function nonEmptyString(value) {
257
280
  return typeof value === 'string' && value.trim() ? value.trim() : null;
258
281
  }
@@ -709,7 +732,22 @@ export class QqHarnessBridge {
709
732
  }
710
733
 
711
734
  async #deliverDeferredOutcome(entry, outcome) {
712
- await sendMarkdownReply(this.#bot, entry.target, deferredOutcomeText(outcome), { logger: this.#logger });
735
+ const text = deferredOutcomeText(outcome);
736
+ const target = deferredDeliveryTarget(entry.target);
737
+ if (!target.msgId) {
738
+ await sendMarkdownReply(this.#bot, target, text, { logger: this.#logger });
739
+ return true;
740
+ }
741
+ try {
742
+ // The timeout notice already answered this msg_id once.
743
+ await sendMarkdownReply(this.#bot, target, text, { logger: this.#logger, passiveRepliesUsed: 1 });
744
+ } catch (error) {
745
+ // Nothing was sent and QQ definitely refused the passive reply (window
746
+ // closed early or budget spent), so the proactive route cannot duplicate it.
747
+ if (!(error instanceof ApiError) || !(error.httpStatus >= 400 && error.httpStatus < 500)) throw error;
748
+ this.#logger.warn?.('[dsh-im:qq] passive deferred reply was refused; retrying proactively:', error);
749
+ await sendMarkdownReply(this.#bot, { scope: target.scope, targetId: target.targetId }, text, { logger: this.#logger });
750
+ }
713
751
  return true;
714
752
  }
715
753
 
@@ -964,6 +1002,7 @@ export class QqHarnessBridge {
964
1002
  batchSubmission = null,
965
1003
  } = {}) {
966
1004
  if (this.#signal?.aborted) return;
1005
+ const acceptedAt = Date.now();
967
1006
  const messageId = nonEmptyString(message?.messageId);
968
1007
  const sender = nonEmptyString(message?.senderId);
969
1008
  if (!messageId || !sender || message.senderIsBot === true) return;
@@ -1064,7 +1103,7 @@ export class QqHarnessBridge {
1064
1103
  // redelivery after a failed error notice must never execute it twice.
1065
1104
  await markMessageSeen();
1066
1105
  ({ answer, artifacts = [] } = await askInWorkspaceSession({
1067
- deferredDelivery: () => ({ coordinator: this.#deferred, target: { scope: target.scope, targetId: target.targetId } }),
1106
+ deferredDelivery: () => ({ coordinator: this.#deferred, target: deferredQqTarget(message, target, acceptedAt) }),
1068
1107
  harness: this.#harness,
1069
1108
  state: this.#state,
1070
1109
  key,
@@ -321,18 +321,18 @@ export class QqController {
321
321
  return this.#withBotTransition(botId, async () => ({
322
322
  version: 1, botId, channel: 'qq', account: await this.#deliveryAccount(botId), connected: true,
323
323
  capabilities: ['proactive-text-checked', 'proactive-receipt-checked', 'proactive-fence-checked',
324
- 'exclusive-text-consumer', 'ordinary-text-consumer', 'reply-text-checked', 'reply-context-checked',
324
+ 'exclusive-text-consumer', 'ordinary-text-consumer', 'direct-message-consumer', 'reply-text-checked', 'reply-context-checked',
325
325
  'reply-receipt-checked', 'reply-fence-checked', 'source-file-checked', 'source-image-checked',
326
326
  'reply-file-checked', 'reply-image-fence-checked', 'reply-file-receipt-checked',
327
327
  'source-generic-file-checked', 'reply-file-fence-checked', 'source-voice-transcript-checked', 'source-voice-audio-checked'],
328
328
  }));
329
329
  }
330
330
 
331
- async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceImages = false, sourceFiles = false, sourceVoiceTranscripts = false, sourceVoiceAudio = false, ordinaryText = false } = {}) {
331
+ async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceImages = false, sourceFiles = false, sourceVoiceTranscripts = false, sourceVoiceAudio = false, ordinaryText = false, directMessages = false } = {}) {
332
332
  return this.#withBotTransition(botId, async () => {
333
333
  const account = await this.#deliveryAccount(botId, signal);
334
334
  if (account.fingerprint !== expectedFingerprint) throw qqRefusal('account-changed');
335
- const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal, sourceImages, sourceFiles, sourceVoiceTranscripts, sourceVoiceAudio, ordinaryText });
335
+ const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal, sourceImages, sourceFiles, sourceVoiceTranscripts, sourceVoiceAudio, ordinaryText, directMessages });
336
336
  try {
337
337
  const saved = await this.#configStore.save({ ...this.#configStore.get(botId), consumerMode: 'external-consumer' });
338
338
  const secret = await this.#resolveSecret(saved.secretRef);
@@ -569,6 +569,7 @@ export class QqController {
569
569
  sourceVoiceTranscripts: () => this.#inboundConsumers.acceptsVoiceTranscripts(config.botId),
570
570
  sourceVoiceAudio: () => this.#inboundConsumers.acceptsVoiceAudio(config.botId),
571
571
  ordinaryText: () => this.#inboundConsumers.acceptsOrdinary(config.botId),
572
+ directMessages: () => this.#inboundConsumers.acceptsDirect(config.botId),
572
573
  } : {}),
573
574
  }));
574
575
  if (!runtime || typeof runtime.start !== 'function' || typeof runtime.stop !== 'function') {
@@ -58,6 +58,8 @@ export class QqRuntime {
58
58
  #sourceVoiceTranscripts;
59
59
  #sourceVoiceAudio;
60
60
  #ordinaryText;
61
+ #directMessages;
62
+ #rateLimitRetryDelaysMs;
61
63
  #externalBridge = null;
62
64
 
63
65
  constructor({
@@ -75,7 +77,8 @@ export class QqRuntime {
75
77
  externalConsumer,
76
78
  sourceImages = () => false,
77
79
  sourceFiles = () => false,
78
- sourceVoiceTranscripts = () => false, sourceVoiceAudio = () => false, ordinaryText = () => false,
80
+ sourceVoiceTranscripts = () => false, sourceVoiceAudio = () => false, ordinaryText = () => false, directMessages = () => false,
81
+ rateLimitRetryDelaysMs,
79
82
  }) {
80
83
  if (!config || !appSecret || !harness || !state) {
81
84
  throw new TypeError('QqRuntime requires config, app secret, Harness, and state');
@@ -97,6 +100,8 @@ export class QqRuntime {
97
100
  this.#sourceVoiceTranscripts = sourceVoiceTranscripts;
98
101
  this.#sourceVoiceAudio = sourceVoiceAudio;
99
102
  this.#ordinaryText = ordinaryText;
103
+ this.#directMessages = directMessages;
104
+ this.#rateLimitRetryDelaysMs = rateLimitRetryDelaysMs;
100
105
  }
101
106
 
102
107
  get status() {
@@ -340,6 +345,8 @@ export class QqRuntime {
340
345
  sourceVoiceTranscripts: this.#sourceVoiceTranscripts,
341
346
  sourceVoiceAudio: this.#sourceVoiceAudio,
342
347
  ordinaryText: this.#ordinaryText,
348
+ directMessages: this.#directMessages,
349
+ rateLimitRetryDelaysMs: this.#rateLimitRetryDelaysMs,
343
350
  reportNativeObservation: record => this.#logger.info?.('[dsh-im:qq] native reply observation', record),
344
351
  reportNativeFrame: record => this.#logger.info?.('[dsh-im:qq] native reply frame', record),
345
352
  });
@@ -12,14 +12,15 @@ export class ExclusiveInboundConsumers {
12
12
  acceptsVideos(botId) { return this.#entries.get(botId)?.sourceVideos === true; }
13
13
  acceptsVoiceAudio(botId) { return this.#entries.get(botId)?.sourceVoiceAudio === true; }
14
14
  acceptsOrdinary(botId) { return this.#entries.get(botId)?.ordinaryText === true; }
15
+ acceptsDirect(botId) { return this.#entries.get(botId)?.directMessages === true; }
15
16
 
16
- register(botId, { fingerprint, onEvent, signal, sourceFiles = false, sourceImages = false, sourceVoiceTranscripts = false, sourceVoiceAudio = false, sourceVideos = false, sourceQuotes = false, ordinaryText = false, onEcho, onAction }) {
17
+ register(botId, { fingerprint, onEvent, signal, sourceFiles = false, sourceImages = false, sourceVoiceTranscripts = false, sourceVoiceAudio = false, sourceVideos = false, sourceQuotes = false, ordinaryText = false, directMessages = false, onEcho, onAction }) {
17
18
  if (this.#entries.has(botId)) throw refusal('consumer-conflict');
18
- if (!/^[a-f0-9]{64}$/.test(fingerprint ?? '') || typeof onEvent !== 'function' || typeof sourceFiles !== 'boolean' || typeof sourceImages !== 'boolean' || typeof sourceVoiceTranscripts !== 'boolean' || typeof sourceVoiceAudio !== 'boolean' || typeof sourceVideos !== 'boolean' || typeof sourceQuotes !== 'boolean' || typeof ordinaryText !== 'boolean' || (onEcho !== undefined && typeof onEcho !== 'function') || (onAction !== undefined && typeof onAction !== 'function'))
19
+ if (!/^[a-f0-9]{64}$/.test(fingerprint ?? '') || typeof onEvent !== 'function' || typeof sourceFiles !== 'boolean' || typeof sourceImages !== 'boolean' || typeof sourceVoiceTranscripts !== 'boolean' || typeof sourceVoiceAudio !== 'boolean' || typeof sourceVideos !== 'boolean' || typeof sourceQuotes !== 'boolean' || typeof ordinaryText !== 'boolean' || typeof directMessages !== 'boolean' || (onEcho !== undefined && typeof onEcho !== 'function') || (onAction !== undefined && typeof onAction !== 'function'))
19
20
  throw refusal('bad-request');
20
21
  signal?.throwIfAborted();
21
22
  const controller = new AbortController();
22
- const entry = { fingerprint, onEvent, onEcho, onAction, sourceFiles, sourceImages, sourceVoiceTranscripts, sourceVoiceAudio, sourceVideos, sourceQuotes, ordinaryText, controller, dispose: undefined };
23
+ const entry = { fingerprint, onEvent, onEcho, onAction, sourceFiles, sourceImages, sourceVoiceTranscripts, sourceVoiceAudio, sourceVideos, sourceQuotes, ordinaryText, directMessages, controller, dispose: undefined };
23
24
  const dispose = () => {
24
25
  if (this.#entries.get(botId) === entry) this.#entries.delete(botId);
25
26
  controller.abort(refusal('consumer-unavailable'));
@@ -101,6 +101,15 @@ function providerFailureCode(error) {
101
101
  return PROVIDER_FAILURES[value.trim().toUpperCase()] ?? null;
102
102
  }
103
103
 
104
+ // Typert Gateway failures that mean dsh-im and the Host disagree on the call
105
+ // contract, as opposed to a business failure behind the Gateway.
106
+ const GATEWAY_CONTRACT_FAILURES = new Set([
107
+ 'gateway/ambiguous-endpoint', 'gateway/arguments-invalid', 'gateway/binding-invalid',
108
+ 'gateway/definition-unavailable', 'gateway/method-unavailable', 'gateway/peer-disposed',
109
+ 'gateway/protocol', 'gateway/provider-mismatch', 'gateway/result-invalid',
110
+ 'gateway/signature-invalid',
111
+ ]);
112
+
104
113
  function failureCode(error) {
105
114
  const code = typeof error?.code === 'string' ? error.code : '';
106
115
  const providerCode = providerFailureCode(error);
@@ -122,7 +131,8 @@ function failureCode(error) {
122
131
  'harness-loopback-forbidden', 'harness-host-untrusted',
123
132
  'harness-request-forbidden',
124
133
  ].includes(code)) return 'HARNESS_ACCESS';
125
- if (['harness-api-not-found', 'harness-response-invalid'].includes(code)) {
134
+ if (['harness-api-not-found', 'harness-response-invalid'].includes(code)
135
+ || GATEWAY_CONTRACT_FAILURES.has(code)) {
126
136
  return 'HARNESS_PROTOCOL';
127
137
  }
128
138
  if (code === 'harness-turn-failed') return 'INTERNAL_UNKNOWN';