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

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.
Files changed (45) hide show
  1. package/PROVENANCE.json +9 -9
  2. package/lib/client.js +8 -5
  3. package/lib/index.js +305 -308
  4. package/package.json +6 -5
  5. package/plugin-src/host/app-setup.mjs +244 -0
  6. package/plugin-src/host/build.mjs +3 -2
  7. package/plugin-src/host/channels/qq/production.mjs +7 -1
  8. package/plugin-src/host/channels/shared/startup.mjs +3 -0
  9. package/plugin-src/host/delivery-adapter.mjs +15 -0
  10. package/plugin-src/host/delivery-service.mjs +103 -3
  11. package/plugin-src/host/index.mjs +15 -2
  12. package/plugin-src/host/qq-sdk-observation-patch.mjs +53 -0
  13. package/src/channels/discord/discord-api.mjs +9 -0
  14. package/src/channels/discord/discord-controller.mjs +1 -2
  15. package/src/channels/discord/discord-runtime.mjs +13 -0
  16. package/src/channels/discord/reachable-conversations.mjs +211 -0
  17. package/src/channels/feishu/external-cards.mjs +63 -6
  18. package/src/channels/feishu/external-reactions.mjs +36 -0
  19. package/src/channels/feishu/feishu-runtime.mjs +95 -2
  20. package/src/channels/feishu/multi-bot-controller.mjs +78 -4
  21. package/src/channels/qq/config-store.mjs +1 -0
  22. package/src/channels/qq/external-addressing.mjs +6 -0
  23. package/src/channels/qq/external-consumer.mjs +214 -0
  24. package/src/channels/qq/external-files.mjs +50 -0
  25. package/src/channels/qq/external-images.mjs +109 -0
  26. package/src/channels/qq/external-mentions.mjs +32 -0
  27. package/src/channels/qq/external-post.mjs +51 -0
  28. package/src/channels/qq/external-voice.mjs +32 -0
  29. package/src/channels/qq/native-gateway-diagnostics.mjs +86 -0
  30. package/src/channels/qq/native-reply-observations.mjs +143 -0
  31. package/src/channels/qq/native-transport-diagnostics.mjs +42 -0
  32. package/src/channels/qq/qq-controller.mjs +105 -1
  33. package/src/channels/qq/qq-runtime.mjs +259 -12
  34. package/src/channels/qq/sdk-frame-observation.mjs +31 -0
  35. package/src/channels/qq/voice-attachment.mjs +3 -0
  36. package/src/channels/shared/i18n-en/qq.mjs +4 -0
  37. package/src/channels/shared/i18n-en/weixin.mjs +1 -0
  38. package/src/channels/shared/token-bot-controller.mjs +26 -0
  39. package/src/channels/slack/reachable-conversations.mjs +136 -0
  40. package/src/channels/slack/slack-api.mjs +9 -1
  41. package/src/channels/slack/slack-controller.mjs +25 -2
  42. package/src/channels/slack/slack-runtime.mjs +23 -0
  43. package/src/channels/weixin/connection-error.en.mjs +1 -0
  44. package/src/channels/weixin/connection-error.mjs +1 -0
  45. package/src/channels/weixin/weixin-controller.mjs +23 -2
@@ -434,7 +434,7 @@ export class MultiBotDshFeishuController {
434
434
  });
435
435
  }
436
436
 
437
- async bindCredentials({ appId, appSecret, domain = 'feishu' } = {}) {
437
+ async bindCredentials({ appId, appSecret, domain = 'feishu', consumerMode, signal } = {}) {
438
438
  this.#assertOpen();
439
439
  const normalizedAppId = typeof appId === 'string' ? appId.trim() : '';
440
440
  const normalizedSecret = typeof appSecret === 'string' ? appSecret.trim() : '';
@@ -445,15 +445,20 @@ export class MultiBotDshFeishuController {
445
445
 
446
446
  return this.#serializeConfig(async () => {
447
447
  this.#assertOpen();
448
+ signal?.throwIfAborted();
448
449
  const bot = await this.#verifyApp({
449
450
  appId: normalizedAppId,
450
451
  appSecret: normalizedSecret,
451
452
  domain: normalizedDomain,
452
453
  });
454
+ signal?.throwIfAborted();
453
455
  this.#assertOpen();
454
456
  const existing = this.#configStore.list().find(
455
457
  (candidate) => candidate.appId === normalizedAppId,
456
458
  );
459
+ if (consumerMode === 'external-consumer' && existing) {
460
+ throw Object.assign(new Error('setup-account-exists'), { code: 'setup-account-exists' });
461
+ }
457
462
  const botId = existing?.id ?? this.#createBotId();
458
463
  if (typeof botId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(botId)
459
464
  || (!existing && this.#configStore.getBot(botId))) {
@@ -461,8 +466,10 @@ export class MultiBotDshFeishuController {
461
466
  }
462
467
  const secretRef = existing?.secretRef ?? secretRefFor(botId);
463
468
  const previousSecret = await atConnectionStage('credential.read', () => this.#credentials.resolve(secretRef), 'credential-store').catch(() => undefined);
469
+ signal?.throwIfAborted();
464
470
  const config = {
465
471
  ...existing,
472
+ ...(consumerMode === 'external-consumer' ? { consumerMode } : {}),
466
473
  id: botId,
467
474
  appId: normalizedAppId,
468
475
  secretRef,
@@ -483,6 +490,7 @@ export class MultiBotDshFeishuController {
483
490
  await atConnectionStage('credential.save', () => this.#credentials.set(secretRef, normalizedSecret), 'credential-store');
484
491
  let saved;
485
492
  try {
493
+ signal?.throwIfAborted();
486
494
  saved = await this.#configStore.saveBot(config);
487
495
  } catch (error) {
488
496
  await this.#restoreCredential(secretRef, previousSecret);
@@ -501,7 +509,7 @@ export class MultiBotDshFeishuController {
501
509
  }
502
510
  });
503
511
  this.#touch();
504
- return this.status(botId);
512
+ return consumerMode === 'external-consumer' ? { accountRef: botId } : this.status(botId);
505
513
  });
506
514
  }
507
515
 
@@ -594,7 +602,7 @@ export class MultiBotDshFeishuController {
594
602
  const account = await this.#deliveryAccount(config);
595
603
  return { version: 1, botId, channel: 'feishu', account,
596
604
  connected: isConnected(connectionStatus(this.#runtimes.get(botId))),
597
- capabilities: ['proactive-text-checked', 'proactive-receipt-checked', 'own-text-echo', 'exclusive-text-consumer', 'reply-text-checked', 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'history-text-checked', 'thread-history-text-checked', 'source-file-checked', 'source-image-checked', 'reply-file-checked', 'approval-card-checked', 'approval-card-update-checked', 'approval-action-consumer'] };
605
+ capabilities: ['reachable-conversations-checked', 'proactive-fence-checked', 'proactive-text-checked', 'proactive-receipt-checked', 'own-text-echo', 'exclusive-text-consumer', 'reply-text-checked', 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'history-text-checked', 'thread-history-text-checked', 'source-file-checked', 'reply-file-checked', 'approval-card-checked', 'approval-card-update-checked', 'approval-action-consumer', 'reaction-write-checked', 'source-image-checked', 'approval-rule-card-checked', 'approval-rule-all-opaque-card-checked', 'pairing-card-checked'] };
598
606
  });
599
607
  }
600
608
 
@@ -682,6 +690,27 @@ export class MultiBotDshFeishuController {
682
690
  });
683
691
  }
684
692
 
693
+ async reactionChecked(botId, route, reaction, { expectedFingerprint, signal, beforeSend } = {}) {
694
+ this.#assertOpen();
695
+ const prepared = await this.#withBotTransition(botId, async () => {
696
+ this.#assertOpen();
697
+ signal?.throwIfAborted();
698
+ const config = this.#requireBot(botId);
699
+ const account = await this.#deliveryAccount(config);
700
+ if (account.fingerprint !== expectedFingerprint)
701
+ throw Object.assign(new Error('account-changed'), { code: 'account-changed' });
702
+ const runtime = this.#runtimes.get(botId);
703
+ if (config.consumerMode !== 'external-consumer' || !isConnected(connectionStatus(runtime)) ||
704
+ typeof runtime.reactionChecked !== 'function')
705
+ throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
706
+ const lease = this.#inboundConsumers.signalFor(botId, expectedFingerprint);
707
+ return { runtime, appId: config.appId, signal: signal ? AbortSignal.any([signal, lease]) : lease };
708
+ });
709
+ // Platform feedback must not occupy the Bot transition queue while writing.
710
+ return prepared.runtime.reactionChecked({ appId: prepared.appId }, route, reaction,
711
+ { signal: prepared.signal, beforeSend });
712
+ }
713
+
685
714
  async approvalCardChecked(botId, route, card, { expectedFingerprint, signal, beforeSend, update = false } = {}) {
686
715
  this.#assertOpen();
687
716
  return this.#withBotTransition(botId, async () => {
@@ -715,6 +744,42 @@ export class MultiBotDshFeishuController {
715
744
  });
716
745
  }
717
746
 
747
+ async #withReachableRuntime(botId, options, operation) {
748
+ this.#assertOpen();
749
+ return this.#withBotTransition(botId, async () => {
750
+ this.#assertOpen();
751
+ options.signal?.throwIfAborted();
752
+ const config = this.#requireBot(botId);
753
+ const account = await this.#deliveryAccount(config);
754
+ if (account.fingerprint !== options.expectedFingerprint)
755
+ throw Object.assign(new Error('account-changed'), { code: 'account-changed' });
756
+ const runtime = this.#runtimes.get(botId);
757
+ if (!isConnected(connectionStatus(runtime)))
758
+ throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
759
+ options.signal?.throwIfAborted();
760
+ const result = await operation(runtime);
761
+ return result;
762
+ });
763
+ }
764
+
765
+ async listReachableConversations(botId, options = {}) {
766
+ const result = await this.#withReachableRuntime(botId, options, runtime => runtime.listReachableConversations(options));
767
+ this.#assertOpen('capability-unavailable');
768
+ return result;
769
+ }
770
+
771
+ async postConversationChecked(botId, conversationId, text, options = {}) {
772
+ return this.#withReachableRuntime(botId, options,
773
+ runtime => runtime.postConversationChecked(conversationId, text, { ...options, beforeSend: () => {
774
+ this.#assertOpen('provider-unavailable');
775
+ options.signal?.throwIfAborted();
776
+ const allowed = options.beforeSend?.() === true;
777
+ this.#assertOpen('provider-unavailable');
778
+ options.signal?.throwIfAborted();
779
+ return allowed;
780
+ } }));
781
+ }
782
+
718
783
  async sendProactiveText(botId, target, text, options = {}) {
719
784
  this.#assertOpen();
720
785
  return this.#withBotTransition(botId, async () => {
@@ -736,7 +801,16 @@ export class MultiBotDshFeishuController {
736
801
  error.code = 'bot-not-connected';
737
802
  throw error;
738
803
  }
739
- return runtime.sendProactiveText(target, text, options);
804
+ return runtime.sendProactiveText(target, text, { ...options,
805
+ ...(options.beforeSend === undefined ? {} : { beforeSend: () => {
806
+ this.#assertOpen('provider-unavailable');
807
+ options.signal?.throwIfAborted();
808
+ const allowed = options.beforeSend() === true;
809
+ this.#assertOpen('provider-unavailable');
810
+ options.signal?.throwIfAborted();
811
+ return allowed;
812
+ } }),
813
+ });
740
814
  });
741
815
  }
742
816
 
@@ -50,6 +50,7 @@ function normalizeBot(value) {
50
50
  appId,
51
51
  secretRef,
52
52
  ownerUserOpenid,
53
+ ...(value.consumerMode === 'external-consumer' ? { consumerMode: value.consumerMode } : {}),
53
54
  createdAt: cleanString(value.createdAt) ?? new Date().toISOString(),
54
55
  connectedAt: cleanString(value.connectedAt),
55
56
  });
@@ -0,0 +1,6 @@
1
+ /** A full-reception callback is addressed only by its normalized top-level self mention. */
2
+ export function isQqAddressedGroupMessage(message) {
3
+ return message?.kind === 'group' && (message.rawEventType === 'GROUP_AT_MESSAGE_CREATE'
4
+ || (message.rawEventType === 'GROUP_MESSAGE_CREATE' && Array.isArray(message.mentions)
5
+ && message.mentions.some(mention => mention?.is_you === true)));
6
+ }
@@ -0,0 +1,214 @@
1
+ import { isQqAddressedGroupMessage } from './external-addressing.mjs';
2
+ import { createHash } from 'node:crypto';
3
+ import { ApiError, getNextMsgSeq, messagePath } from '@tencent-connect/qqbot-nodejs/protocol';
4
+ import { QqNativeReplyObservations, qqNativeIdentifier as identifier } from './native-reply-observations.mjs';
5
+ import { qqSourceAttachments, readQqSourceAttachment, checkedQqImageFile, uploadQqCheckedMedia } from './external-images.mjs';
6
+ import { checkedQqGenericFile, qqQuotedFileMessage } from './external-files.mjs';
7
+ import { qqVoiceMessage } from './external-voice.mjs';
8
+ import { qqExternalMentions } from './external-mentions.mjs';
9
+
10
+ export function qqRefusal(code) { return Object.assign(new Error(code), { code }); }
11
+
12
+ function nativeReplyFailure(error) {
13
+ if (!(error instanceof ApiError)) return qqRefusal('reply-result-unknown');
14
+ const code = Number(error.bizCode);
15
+ if ([304103, 40034005].includes(code)) return qqRefusal('reply-window-expired');
16
+ if (code === 40034128) return qqRefusal('reply-limit-exceeded');
17
+ if (error.httpStatus === 429 || code === 40034100) return qqRefusal('reply-rate-limited');
18
+ if ([40034101, 40034105, 40054002, 40054003, 40054016].includes(code))
19
+ return qqRefusal('reply-permission-denied');
20
+ if ([22006, 304061, 40034006, 40054007, 40054010].includes(code)) return qqRefusal('bad-request');
21
+ if (code === 40034024) return qqRefusal('stale-route');
22
+ return qqRefusal('reply-result-unknown');
23
+ }
24
+
25
+ export function verifiedQqAccount(appId, user) {
26
+ // Authenticated GET /users/@me identifies the current robot. Live group apps
27
+ // can omit the example's bot flag; an explicit contradictory flag still fails.
28
+ const robot = user && (user.bot === true || !Object.hasOwn(user, 'bot'));
29
+ if (!identifier(appId) || !identifier(user?.id) || !robot) {
30
+ const error = qqRefusal('account-unverified');
31
+ error.verificationFailure = !identifier(appId) ? 'application-id'
32
+ : !identifier(user?.id) ? 'native-user-id' : 'native-bot-flag';
33
+ throw error;
34
+ }
35
+ const identity = { provider: 'qq', appId, userId: user.id };
36
+ return Object.freeze({ appId, userId: user.id,
37
+ fingerprint: createHash('sha256').update(JSON.stringify(identity)).digest('hex'),
38
+ ...(typeof user.username === 'string' && user.username.trim()
39
+ ? { name: user.username.slice(0, 512) } : {}),
40
+ });
41
+ }
42
+
43
+ /** QQ group and member OpenIDs belong to this authenticated application. */
44
+ export function normalizeQqExternalText(message, { botId, account, ordinaryText = false }) {
45
+ const addressed = isQqAddressedGroupMessage(message);
46
+ const ordinary = ordinaryText === true && message?.kind === 'group'
47
+ && message.rawEventType === 'GROUP_MESSAGE_CREATE';
48
+ if (!(addressed || ordinary)
49
+ || message.senderIsBot || message.senderId === account.userId
50
+ || message.attachments?.length || message.msgElements?.length
51
+ || (message.msgType !== undefined && message.msgType !== 0)) return null;
52
+ if (!identifier(message.messageId) || !identifier(message.senderId)
53
+ || !identifier(message.groupOpenid) || typeof message.content !== 'string'
54
+ || !message.content.trim() || message.content.length > 16000
55
+ || message.replyTarget?.scope !== 'group'
56
+ || message.replyTarget.targetId !== message.groupOpenid
57
+ || message.replyTarget.msgId !== message.messageId)
58
+ throw qqRefusal('invalid-inbound');
59
+ const at = new Date(message.timestamp);
60
+ if (!Number.isFinite(at.getTime())) throw qqRefusal('invalid-inbound');
61
+ return Object.freeze({ version: 1, channel: 'qq', botId, fingerprint: account.fingerprint,
62
+ eventId: message.messageId, messageId: message.messageId,
63
+ actor: { kind: 'user', id: message.senderId,
64
+ ...(typeof message.senderName === 'string' && message.senderName.trim()
65
+ ? { 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 },
69
+ replay: { kind: 'provider-redelivery', resumeCursor: false, gapPossible: true },
70
+ });
71
+ }
72
+
73
+ /** Bounded, process-local source proof, never a second durable Inbox or history. */
74
+ export class QqExternalConsumer {
75
+ #bot;
76
+ #account;
77
+ #botId;
78
+ #accept;
79
+ #observations;
80
+ #sourceImages;
81
+ #sourceFiles;
82
+ #sourceVoiceTranscripts;
83
+ #sourceVoiceAudio;
84
+ #ordinaryText;
85
+ #sources = new Map();
86
+ constructor({ bot, account, botId, accept, sourceImages = () => false, sourceFiles = () => false, sourceVoiceTranscripts = () => false, sourceVoiceAudio = () => false, ordinaryText = () => false, reportNativeObservation = () => {}, reportNativeFrame, nativeUser }) {
87
+ this.#bot = bot; this.#account = account; this.#botId = botId; this.#accept = accept;
88
+ this.#observations = new QqNativeReplyObservations({ account, report: reportNativeObservation,
89
+ reportFrame: reportNativeFrame, nativeUser });
90
+ this.#sourceImages = sourceImages;
91
+ this.#sourceFiles = sourceFiles;
92
+ this.#sourceVoiceTranscripts = sourceVoiceTranscripts;
93
+ this.#sourceVoiceAudio = sourceVoiceAudio;
94
+ this.#ordinaryText = ordinaryText;
95
+ }
96
+ recordNativeReceipt(receipt, signal) {
97
+ this.#observations.sent(receipt.conversationId, receipt.messageId, signal);
98
+ }
99
+ async accept(message, signal) {
100
+ this.#observations.receive(message, signal);
101
+ const addressed = isQqAddressedGroupMessage(message);
102
+ const voice = addressed && (this.#sourceVoiceTranscripts() === true || this.#sourceVoiceAudio() === true)
103
+ ? qqVoiceMessage(message, { sourceVoiceTranscripts: this.#sourceVoiceTranscripts() === true }) : undefined;
104
+ const quoted = addressed && !voice && this.#sourceFiles() === true ? qqQuotedFileMessage(message) : undefined;
105
+ message = quoted?.message ?? message;
106
+ message = voice?.message ?? message;
107
+ const mediaEnabled = addressed && (this.#sourceImages() === true || this.#sourceFiles() === true) && message?.attachments?.length;
108
+ const base = normalizeQqExternalText(mediaEnabled ? { ...message, attachments: undefined,
109
+ content: typeof message.content === 'string' && !message.content.trim()
110
+ ? message.attachments.every(file => file?.content_type === 'file') ? '[File]' : '[Image]' : message.content } : message,
111
+ { botId: this.#botId, account: this.#account, ordinaryText: this.#ordinaryText() === true });
112
+ const media = base && voice && this.#sourceVoiceAudio() === true
113
+ ? qqSourceAttachments(voice.nativeMessage, base, { sourceImages: false, sourceVoiceAudio: true, referenceKey: voice.referenceKey })
114
+ : base && mediaEnabled ? qqSourceAttachments(message, base,
115
+ { sourceImages: this.#sourceImages() === true, sourceFiles: this.#sourceFiles() === true,
116
+ referenceKey: quoted?.referenceKey }) : undefined;
117
+ const event = base && voice ? { ...(media?.event ?? base), voice: voice.voice } : media?.event ?? base;
118
+ if (!event) return;
119
+ signal.throwIfAborted();
120
+ const prior = this.#sources.get(event.messageId);
121
+ if (prior && JSON.stringify(prior.event) !== JSON.stringify(event)) throw qqRefusal('stale-route');
122
+ // Consumer-owned objects never become the Provider's source authority.
123
+ if (!prior) this.#sources.set(event.messageId, { event: structuredClone(event),
124
+ ...(media ? { files: structuredClone(media.files) } : {}), attempts: 0 });
125
+ while (this.#sources.size > 2000) this.#sources.delete(this.#sources.keys().next().value);
126
+ // The external consumer acknowledges only after canonical ingestion commits.
127
+ return this.#accept(event, signal);
128
+ }
129
+ #source(route, signal) {
130
+ if (signal?.aborted) throw qqRefusal('cancelled');
131
+ const source = this.#sources.get(route?.messageId);
132
+ if (!source) throw qqRefusal('source-not-found');
133
+ if (Object.keys(route).some(key => !['messageId', 'conversationId', 'actorId'].includes(key))
134
+ || ['messageId', 'conversationId', 'actorId'].some(key => source.event.reply[key] !== route[key]))
135
+ throw qqRefusal('stale-route');
136
+ return source;
137
+ }
138
+ qualify(route, signal) {
139
+ 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');
143
+ return structuredClone(source.event.reply);
144
+ }
145
+ async readImage(route, attachment, options = {}) {
146
+ const source = this.#source(route, options.signal);
147
+ return readQqSourceAttachment(source, attachment, { ...options,
148
+ assertCurrent: () => {
149
+ if (this.#source(route, options.signal) !== source || this.#sourceImages() !== true)
150
+ throw qqRefusal('source-unavailable');
151
+ } });
152
+ }
153
+ async readFile(route, attachment, options = {}) {
154
+ const source = this.#source(route, options.signal);
155
+ return readQqSourceAttachment(source, attachment, { ...options,
156
+ assertCurrent: () => {
157
+ if (this.#source(route, options.signal) !== source || (source.event.voice ? this.#sourceVoiceAudio() !== true : this.#sourceFiles() !== true))
158
+ throw qqRefusal('source-unavailable');
159
+ } });
160
+ }
161
+ async replyFile(route, file, { signal, beforeSend, verifyAccount } = {}) {
162
+ const qualified = this.qualify(route, signal);
163
+ if (typeof beforeSend !== 'function' || typeof verifyAccount !== 'function') throw qqRefusal('bad-request');
164
+ const image = typeof file?.mediaType === 'string' && file.mediaType.startsWith('image/');
165
+ const bytes = image ? checkedQqImageFile(file) : checkedQqGenericFile(file);
166
+ if (beforeSend() !== true) throw qqRefusal('stale-route');
167
+ if (signal?.aborted) throw qqRefusal('cancelled');
168
+ const target = { scope: 'group', targetId: qualified.conversationId, msgId: qualified.messageId };
169
+ const fileInfo = await uploadQqCheckedMedia(this.#bot, target, file, bytes, signal, image ? 1 : 4);
170
+ 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); }
185
+ if (signal?.aborted || !identifier(response?.id)) throw qqRefusal('reply-result-unknown');
186
+ this.#observations.sent(qualified.conversationId, response.id, signal, response);
187
+ return { sent: true, receipt: { version: 1, messageId: response.id, conversationId: qualified.conversationId } };
188
+ }
189
+ async reply(route, text, { signal, receipt = false, beforeSend, mentionUserIds } = {}) {
190
+ const qualified = this.qualify(route, signal);
191
+ if (typeof text !== 'string' || !text.trim() || text.length > 4000 || mentionUserIds?.length)
192
+ 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); }
208
+ // Once dispatch begins, cancellation or a missing response cannot prove non-delivery.
209
+ if (signal?.aborted || !identifier(response?.id)) throw qqRefusal('reply-result-unknown');
210
+ this.#observations.sent(qualified.conversationId, response.id, signal, response);
211
+ return { sent: true, ...(receipt ? { receipt: { version: 1, messageId: response.id,
212
+ conversationId: qualified.conversationId } } : { messageId: response.id }) };
213
+ }
214
+ }
@@ -0,0 +1,50 @@
1
+ import { isQqAddressedGroupMessage } from './external-addressing.mjs';
2
+ import { QQ_EXTERNAL_IMAGE_LIMIT } from './external-images.mjs';
3
+ import { qqNativeIdentifier } from './native-reply-observations.mjs';
4
+
5
+ const refusal = (code, reason) => Object.assign(new Error(code), { code, ...(reason ? { reason } : {}) });
6
+
7
+ export function checkedQqGenericFile(file) {
8
+ if (typeof file?.id !== 'string' || !file.id || file.id.length > 512
9
+ || typeof file.name !== 'string' || !file.name.trim() || file.name.length > 512
10
+ || /[\x00-\x1f\x7f/\\]/.test(file.name) || !(file.bytes instanceof Uint8Array)
11
+ || !file.bytes.byteLength || typeof file.mediaType !== 'string'
12
+ || !/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(file.mediaType)
13
+ || /^(image|audio|video)\//i.test(file.mediaType)) throw refusal('bad-request');
14
+ if (file.bytes.byteLength > QQ_EXTERNAL_IMAGE_LIMIT) throw refusal('artifact-too-large');
15
+ return Buffer.from(file.bytes);
16
+ }
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;
24
+ const raw = message.raw;
25
+ const elements = raw?.msg_elements;
26
+ const element = Array.isArray(elements) && elements.length === 1 ? elements[0] : undefined;
27
+ const key = element?.msg_idx;
28
+ const refs = Array.isArray(raw?.message_scene?.ext)
29
+ ? raw.message_scene.ext.filter(value => typeof value === 'string' && value.split('=', 1)[0].trim() === 'ref_msg_idx')
30
+ .map(value => value.slice(value.indexOf('=') + 1).trim()) : [];
31
+ if (!isQqAddressedGroupMessage(message)
32
+ || raw?.message_type !== 103 || raw.id !== message.messageId || raw.group_openid !== message.groupOpenid
33
+ || raw.author?.member_openid !== message.senderId || raw.author?.bot === true)
34
+ throw refusal('invalid-inbound', 'quote-envelope-invalid');
35
+ if (!qqNativeIdentifier(key) || message.refMsgIdx !== key || refs.some(value => value !== key))
36
+ throw refusal('invalid-inbound', 'quote-reference-invalid');
37
+ if ((message.attachments !== undefined && (!Array.isArray(message.attachments) || message.attachments.length))
38
+ || (raw.attachments !== undefined && (!Array.isArray(raw.attachments) || raw.attachments.length))
39
+ || !Array.isArray(message.msgElements) || message.msgElements.length !== 1
40
+ || message.msgElements[0]?.msg_idx !== key
41
+ || Object.keys(element).some(field => !['msg_idx', 'content', 'message_type', 'attachments'].includes(field))
42
+ || (element.message_type !== undefined && (!Number.isSafeInteger(element.message_type)
43
+ || 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()))
47
+ throw refusal('invalid-inbound', 'quote-elements-invalid');
48
+ return { referenceKey: key, message: { ...message, msgType: 0, msgElements: undefined,
49
+ content: `${message.content}\n[Quoted ${label}]`, attachments: element.attachments } };
50
+ }
@@ -0,0 +1,109 @@
1
+ import { isQqVoiceAttachment } from './voice-attachment.mjs';
2
+ import { createHash } from 'node:crypto';
3
+ import { detectedImageMediaType, fetchImageBuffer } from '../shared/image-prompt.mjs';
4
+ import { QQ_IMAGE_HOSTS } from './qq-bridge.mjs';
5
+
6
+ export const QQ_EXTERNAL_IMAGE_LIMIT = 25 * 1024 * 1024;
7
+ const imageTypes = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
8
+ const refusal = (code, reason) => Object.assign(new Error(code), { code, ...(reason ? { reason } : {}) });
9
+
10
+ /** Native caption and attachment order are separate; no native interleaving is inferred. */
11
+ export function qqSourceAttachments(message, event, { sourceImages = true, sourceFiles = false, sourceVoiceAudio = false, referenceKey } = {}) {
12
+ if (!Array.isArray(message.attachments) || !message.attachments.length || message.attachments.length > 32)
13
+ throw refusal('invalid-inbound');
14
+ const files = message.attachments.map((native, index) => {
15
+ // Tencent's native `file` label is a category, not a MIME declaration.
16
+ const voice = sourceVoiceAudio && message.attachments.length === 1
17
+ && isQqVoiceAttachment(native);
18
+ 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
+ if (!mediaType) throw refusal('invalid-inbound', 'file-category-invalid');
21
+ if (typeof native.url !== 'string' || native.url.length > 16384)
22
+ throw refusal('invalid-inbound', 'file-url-invalid');
23
+ let url;
24
+ try { url = new URL(native.url); } catch { throw refusal('invalid-inbound', 'file-url-invalid'); }
25
+ if (url.protocol !== 'https:' || url.username || url.password || (url.port && url.port !== '443')
26
+ || !QQ_IMAGE_HOSTS.some(host => url.hostname === host.slice(1) || url.hostname.endsWith(host)))
27
+ throw refusal('resource-unavailable');
28
+ if (native.size !== undefined && (!Number.isSafeInteger(native.size) || native.size <= 0))
29
+ throw refusal('invalid-inbound', 'file-size-invalid');
30
+ if (native.size > (voice ? 1024 * 1024 : QQ_EXTERNAL_IMAGE_LIMIT)) throw refusal('artifact-too-large');
31
+ const id = createHash('sha256').update(JSON.stringify([
32
+ event.fingerprint, event.conversation.id, event.messageId, index,
33
+ ...(referenceKey === undefined ? [] : ['quote', referenceKey]),
34
+ ])).digest('hex');
35
+ const name = typeof native.filename === 'string' && native.filename.trim() && native.filename.length <= 512
36
+ && !/[\x00-\x1f\x7f/\\]/.test(native.filename) ? native.filename : native.content_type === 'file' ? 'file' : voice ? 'voice.bin' : 'image';
37
+ const attachment = { id, messageId: event.messageId, resourceKey: id, name,
38
+ mediaType, ...(native.size === undefined ? {} : { sizeBytes: native.size }) };
39
+ return { attachment, url: native.url };
40
+ });
41
+ return { files, event: { ...event, attachments: files.map(file => file.attachment),
42
+ contentParts: [
43
+ ...(message.content.trim() ? [{ kind: 'text', text: message.content }] : []),
44
+ ...files.map(({ attachment }) => ({ kind: 'attachment', id: attachment.id })),
45
+ ] } };
46
+ }
47
+
48
+ export async function readQqSourceAttachment(source, attachment, { signal, assertCurrent, verifyAccount }) {
49
+ assertCurrent();
50
+ const file = source.files?.find(file => file.attachment.id === attachment?.id);
51
+ if (!file || Object.keys(attachment).some(key => !Object.hasOwn(file.attachment, key))
52
+ || Object.keys(file.attachment).some(key => file.attachment[key] !== attachment[key]))
53
+ throw refusal('stale-route');
54
+ let bytes;
55
+ try {
56
+ bytes = await fetchImageBuffer(file.url, { signal, allowedHosts: QQ_IMAGE_HOSTS,
57
+ maxBytes: attachment.mediaType.startsWith('audio/') ? 1024 * 1024 : QQ_EXTERNAL_IMAGE_LIMIT, timeoutMs: 15000 });
58
+ } catch (error) {
59
+ assertCurrent();
60
+ throw refusal(error?.code === 'image-too-large' ? 'artifact-too-large' : 'resource-unavailable');
61
+ }
62
+ assertCurrent();
63
+ await verifyAccount();
64
+ assertCurrent();
65
+ if ((attachment.mediaType.startsWith('image/') && detectedImageMediaType(bytes) !== attachment.mediaType)
66
+ || (attachment.sizeBytes !== undefined && bytes.byteLength !== attachment.sizeBytes))
67
+ throw refusal('resource-unavailable');
68
+ return (async function* () {
69
+ await verifyAccount();
70
+ assertCurrent();
71
+ yield new Uint8Array(bytes);
72
+ assertCurrent();
73
+ })();
74
+ }
75
+
76
+ export function checkedQqImageFile(file) {
77
+ if (typeof file?.id !== 'string' || !file.id || file.id.length > 512
78
+ || typeof file.name !== 'string' || !file.name.trim() || file.name.length > 512
79
+ || /[\x00-\x1f\x7f/\\]/.test(file.name) || !(file.bytes instanceof Uint8Array)
80
+ || !file.bytes.byteLength || !imageTypes.has(file.mediaType)) throw refusal('bad-request');
81
+ if (file.bytes.byteLength > QQ_EXTERNAL_IMAGE_LIMIT) throw refusal('artifact-too-large');
82
+ const bytes = Buffer.from(file.bytes);
83
+ if (detectedImageMediaType(bytes) !== file.mediaType) throw refusal('bad-request');
84
+ return bytes;
85
+ }
86
+
87
+ /** Upload cancellation prevents the later send; the SDK upload itself has no AbortSignal. */
88
+ export async function uploadQqCheckedMedia(bot, target, file, bytes, signal, fileType = 1) {
89
+ let timer;
90
+ let aborted;
91
+ const interrupted = new Promise((_, reject) => {
92
+ aborted = () => reject(refusal('cancelled'));
93
+ signal?.addEventListener('abort', aborted, { once: true });
94
+ if (signal?.aborted) aborted();
95
+ timer = setTimeout(() => reject(refusal('file-upload-failed')), 120000);
96
+ });
97
+ try {
98
+ const uploaded = await Promise.race([interrupted,
99
+ bot.uploadMedia({ target, fileType, buffer: bytes, fileName: file.name, srvSendMsg: false })]);
100
+ if (typeof uploaded?.file_info !== 'string' || !uploaded.file_info || uploaded.file_info.length > 16384)
101
+ throw refusal('file-upload-failed');
102
+ return uploaded.file_info;
103
+ } catch (error) {
104
+ throw refusal(signal?.aborted || error?.code === 'cancelled' ? 'cancelled' : 'file-upload-failed');
105
+ } finally {
106
+ clearTimeout(timer);
107
+ signal?.removeEventListener('abort', aborted);
108
+ }
109
+ }
@@ -0,0 +1,32 @@
1
+ import { qqNativeIdentifier } from './native-reply-observations.mjs';
2
+
3
+ function displayName(value) {
4
+ return typeof value === 'string' && value.trim() && value.length <= 512
5
+ && !/[\u0000-\u001f]/u.test(value) ? value.trim() : undefined;
6
+ }
7
+
8
+ export function qqExternalMentions(message, account) {
9
+ if (!Array.isArray(message.mentions) || message.mentions.length > 100) return [];
10
+ const entries = new Map();
11
+ const ambiguous = new Set();
12
+ for (const mention of message.mentions) {
13
+ if (!mention || typeof mention !== 'object' || mention.scope === 'all') continue;
14
+ const ids = [...new Set([mention.id, mention.user_openid, mention.member_openid]
15
+ .filter(qqNativeIdentifier))];
16
+ if (ids.length !== 1) continue;
17
+ const id = ids[0];
18
+ const name = displayName(mention.username) ?? displayName(mention.nickname)
19
+ ?? (mention.is_you === true ? displayName(account.name) : undefined);
20
+ for (const key of [`<@${id}>`, `<@!${id}>`]) {
21
+ if (key.length > 512) continue;
22
+ if (!message.content.includes(key) || ambiguous.has(key)) continue;
23
+ const prior = entries.get(key);
24
+ if (prior && (prior.id !== id || prior.name !== name)) {
25
+ entries.delete(key); ambiguous.add(key); continue;
26
+ }
27
+ entries.set(key, Object.freeze({ id, key, ...(name ? { name } : {}) }));
28
+ if (entries.size > 100) return [];
29
+ }
30
+ }
31
+ return Object.freeze([...entries.values()]);
32
+ }
@@ -0,0 +1,51 @@
1
+ import { ApiError, messagePath } from '@tencent-connect/qqbot-nodejs/protocol';
2
+ import { qqNativeIdentifier } from './native-reply-observations.mjs';
3
+ import { qqRefusal } from './external-consumer.mjs';
4
+
5
+ function nativePostFailure(error) {
6
+ let reason = 'send-result-unknown';
7
+ const nativePost = {};
8
+ if (error instanceof ApiError) {
9
+ const rawCode = error.bizCode;
10
+ const code = typeof rawCode === 'number' ? rawCode
11
+ : typeof rawCode === 'string' && /^\d+$/.test(rawCode) ? Number(rawCode) : undefined;
12
+ if (Number.isInteger(error.httpStatus) && error.httpStatus >= 100 && error.httpStatus <= 599)
13
+ nativePost.httpStatus = error.httpStatus;
14
+ if (Number.isSafeInteger(code) && code >= 0) nativePost.providerCode = code;
15
+ if (error.httpStatus === 429 || code === 40034100) reason = 'send-rate-limited';
16
+ else if ([40034101, 40034105, 40054002, 40054003, 40054016].includes(code))
17
+ reason = 'send-permission-denied';
18
+ else if ([22006, 304061, 40034006, 40054007, 40054010].includes(code)) reason = 'bad-request';
19
+ }
20
+ return { refusal: qqRefusal(reason), evidence: Object.freeze(nativePost) };
21
+ }
22
+
23
+ export async function postQqText({ bot, target, text, signal, beforeSend, verifyAccount, assertCurrent, onNativeFailure }) {
24
+ const groupId = target?.route?.groupOpenId;
25
+ if (target?.kind !== 'group' || !qqNativeIdentifier(groupId)) throw qqRefusal('invalid-target');
26
+ if (typeof text !== 'string' || !text.trim() || text.length > 4000
27
+ || typeof beforeSend !== 'function' || typeof verifyAccount !== 'function') throw qqRefusal('bad-request');
28
+ const fence = () => {
29
+ if (signal?.aborted) throw qqRefusal('cancelled');
30
+ assertCurrent();
31
+ if (beforeSend() !== true) throw qqRefusal('send-permission-denied');
32
+ if (signal?.aborted) throw qqRefusal('cancelled');
33
+ };
34
+ fence();
35
+ let token;
36
+ try { token = await bot.api.getToken(); }
37
+ catch { throw qqRefusal(signal?.aborted ? 'cancelled' : 'provider-unavailable'); }
38
+ await verifyAccount();
39
+ fence();
40
+ let response;
41
+ try {
42
+ response = await bot.apiClient.request(token, 'POST', messagePath('group', groupId),
43
+ { msg_type: 0, content: text });
44
+ } catch (error) {
45
+ const { refusal, evidence } = nativePostFailure(error);
46
+ onNativeFailure?.(evidence);
47
+ throw refusal;
48
+ }
49
+ if (signal?.aborted || !qqNativeIdentifier(response?.id)) throw qqRefusal('send-result-unknown');
50
+ return { sent: true, receipt: { version: 1, messageId: response.id, conversationId: groupId } };
51
+ }