@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
@@ -0,0 +1,32 @@
1
+ import { isQqVoiceAttachment } from './voice-attachment.mjs';
2
+ import { qqQuotedMediaMessage } from './external-files.mjs';
3
+
4
+ const refusal = code => Object.assign(new Error(code), { code });
5
+
6
+ /** ASR provenance comes exclusively from the native voice attachment, never its caption. */
7
+
8
+ export function qqVoiceMessage(message, { sourceVoiceTranscripts = false } = {}) {
9
+ const candidate = message?.msgType === 103 ? message.raw?.msg_elements?.[0]?.attachments?.[0] : message?.attachments?.[0];
10
+ if (!isQqVoiceAttachment(candidate)) return undefined;
11
+ const quoted = message?.msgType === 103 ? qqQuotedMediaMessage(message, {
12
+ accepts: files => files.length === 1 && isQqVoiceAttachment(files[0]), label: 'voice', requireCaption: false,
13
+ }) : undefined;
14
+ message = quoted?.message ?? message;
15
+ const attachments = message?.attachments;
16
+ if (!Array.isArray(attachments) || attachments.length !== 1) return undefined;
17
+ const native = attachments[0];
18
+ if (!isQqVoiceAttachment(native)) return undefined;
19
+ if (native.asr_refer_text !== undefined && (typeof native.asr_refer_text !== 'string' || native.asr_refer_text.length > 12000))
20
+ throw refusal('invalid-inbound');
21
+ if (typeof message.content !== 'string') throw refusal('invalid-inbound');
22
+ const transcript = sourceVoiceTranscripts ? native.asr_refer_text?.trim() : undefined;
23
+ const caption = typeof message.content === 'string' ? message.content.trim() : '';
24
+ const body = transcript || (sourceVoiceTranscripts
25
+ ? '[QQ voice message: platform did not provide a transcript]'
26
+ : '[QQ voice message: transcription was not enabled for this consumer]');
27
+ const text = caption ? `${caption}\n[QQ voice]\n${body}` : body;
28
+ if (text.length > 16000) throw refusal('invalid-inbound');
29
+ return { nativeMessage: { ...message, content: text }, referenceKey: quoted?.referenceKey,
30
+ voice: { transcript: transcript ? 'platform' : 'unavailable' },
31
+ message: { ...message, attachments: undefined, content: text } };
32
+ }
@@ -0,0 +1,86 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { qqNativeIdentifier } from './native-reply-observations.mjs';
3
+ import { observeFrame } from './sdk-frame-observation.mjs';
4
+
5
+ const hash = value => createHash('sha256').update(value).digest('hex');
6
+ const evidence = value => qqNativeIdentifier(value) ? { hash: hash(value), length: value.length } : undefined;
7
+ const fields = (value, names) => value && typeof value === 'object' && !Array.isArray(value)
8
+ ? Object.fromEntries(names.flatMap(name => {
9
+ const item = evidence(Object.getOwnPropertyDescriptor(value, name)?.value);
10
+ return item ? [[name, item]] : [];
11
+ })) : {};
12
+
13
+ /** Metadata from the pinned SDK's public pre-dispatch Logger; never intake or Echo authority. */
14
+ export class QqNativeGatewayDiagnostics {
15
+ #prefix;
16
+ #fingerprint;
17
+ #report;
18
+ #seen = new Map();
19
+ #windowAt = 0;
20
+ #reported = 0;
21
+ #suppressed = 0;
22
+ constructor({ botId, account, report }) {
23
+ this.#prefix = `[${botId}] Dispatch event: t=`;
24
+ this.#fingerprint = account.fingerprint;
25
+ this.#report = report;
26
+ }
27
+ observe(message, signal, transport) {
28
+ if (signal?.aborted || typeof this.#report !== 'function' || typeof message !== 'string'
29
+ || !message.startsWith(this.#prefix)) return;
30
+ const now = Date.now();
31
+ if (now - this.#windowAt >= 60_000) { this.#windowAt = now; this.#reported = 0; }
32
+ if (this.#reported >= 64) { this.#suppressed++; return; }
33
+ this.#reported++;
34
+ const emit = record => {
35
+ try {
36
+ const context = Number.isSafeInteger(transport?.connection) && transport.connection > 0
37
+ && Number.isSafeInteger(transport?.frame) && transport.frame > 0
38
+ ? { transport: { connection: transport.connection, frame: transport.frame } } : {};
39
+ if (observeFrame(this.#report, { ...record, ...context, accountFingerprint: this.#fingerprint, suppressed: this.#suppressed }))
40
+ this.#suppressed = 0;
41
+ } catch {}
42
+ };
43
+ const refuse = reason => emit({ event: 'qq.native-gateway.refusal', reason });
44
+ if (message.length > 262_144 || Buffer.byteLength(message, 'utf8') > 262_144) { refuse('oversized'); return; }
45
+ const separator = message.indexOf(' payload=', this.#prefix.length);
46
+ if (separator < 0) { refuse('format'); return; }
47
+ const type = message.slice(this.#prefix.length, separator);
48
+ if (!/^[A-Z][A-Z0-9_]{0,79}$/.test(type)) { refuse('format'); return; }
49
+ if (type === 'READY' || type === 'RESUMED') {
50
+ emit({ event: 'qq.native-gateway.lifecycle', phase: type === 'READY' ? 'ready' : 'resumed' });
51
+ return;
52
+ }
53
+ let raw;
54
+ try { raw = JSON.parse(message.slice(separator + 9)); }
55
+ catch { refuse('malformed'); return; }
56
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)
57
+ || !qqNativeIdentifier(raw.group_openid) || !qqNativeIdentifier(raw.id)) {
58
+ refuse(['GROUP_AT_MESSAGE_CREATE', 'GROUP_MESSAGE_CREATE'].includes(type) ? 'invalid-group-frame' : 'non-group');
59
+ return;
60
+ }
61
+ for (const [key, at] of this.#seen) if (now - at > 300_000) this.#seen.delete(key);
62
+ const key = JSON.stringify([type, raw.group_openid, raw.id]);
63
+ if (this.#seen.has(key)) return;
64
+ this.#seen.set(key, now);
65
+ while (this.#seen.size > 128) this.#seen.delete(this.#seen.keys().next().value);
66
+ const flag = raw.author?.bot;
67
+ const indexes = Array.isArray(raw.message_scene?.ext) ? raw.message_scene.ext.slice(0, 64) : [];
68
+ const index = indexes.find(value => typeof value === 'string' && value.startsWith('msg_idx='));
69
+ emit({ event: 'qq.native-gateway.frame',
70
+ eventType: ['GROUP_AT_MESSAGE_CREATE', 'GROUP_MESSAGE_CREATE'].includes(type) ? type : 'other',
71
+ conversationHash: hash(raw.group_openid), messageHash: hash(raw.id),
72
+ senderBotFlag: flag === true ? 'true' : flag === false ? 'false' : flag === undefined ? 'absent' : 'other',
73
+ authorIdentifiers: fields(raw.author, ['member_openid', 'id', 'user_openid', 'union_openid', 'openid']),
74
+ messageIdentifiers: fields(raw, ['id', 'message_id', 'msg_id', 'msg_idx']),
75
+ messageIndexIdentifier: evidence(index?.slice(8)),
76
+ indexEvidenceTruncated: Array.isArray(raw.message_scene?.ext) && raw.message_scene.ext.length > 64,
77
+ mentionIdentifiers: Array.isArray(raw.mentions) ? raw.mentions.slice(0, 8).map(mention => ({
78
+ self: mention?.is_you === true,
79
+ selfFlag: mention?.is_you === true ? 'true' : mention?.is_you === false ? 'false'
80
+ : mention?.is_you === undefined ? 'absent' : 'other',
81
+ identifiers: fields(mention, ['id', 'user_openid', 'member_openid']),
82
+ })) : [],
83
+ mentionsTruncated: Array.isArray(raw.mentions) && raw.mentions.length > 8,
84
+ });
85
+ }
86
+ }
@@ -0,0 +1,143 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export function qqNativeIdentifier(value) {
4
+ return typeof value === 'string' && value.length > 0 && value.length <= 512
5
+ && value.trim() === value && !/[\s\u0000-\u001f]/u.test(value);
6
+ }
7
+
8
+ function hash(value) { return createHash('sha256').update(value).digest('hex'); }
9
+
10
+ function identifierEvidence(value) {
11
+ return qqNativeIdentifier(value) ? { hash: hash(value), length: value.length } : undefined;
12
+ }
13
+
14
+ function identifierFields(value, fields) {
15
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
16
+ return Object.fromEntries(fields.flatMap(field => {
17
+ const evidence = identifierEvidence(Object.getOwnPropertyDescriptor(value, field)?.value);
18
+ return evidence ? [[field, evidence]] : [];
19
+ }));
20
+ }
21
+
22
+ const AUTHOR_IDENTIFIERS = ['member_openid', 'id', 'user_openid', 'union_openid', 'openid'];
23
+ const MESSAGE_IDENTIFIERS = ['id', 'message_id', 'msg_id', 'msg_idx'];
24
+
25
+ export class QqNativeReplyObservations {
26
+ #account;
27
+ #report;
28
+ #entries = new Map();
29
+ #windowAt = 0;
30
+ #reported = 0;
31
+ #suppressed = 0;
32
+ #reportFrame;
33
+ #nativeUserIdentifiers = {};
34
+ #frameSeen = new Map();
35
+ #frameWindowAt = 0;
36
+ #framesReported = 0;
37
+ #framesSuppressed = 0;
38
+ constructor({ account, report, reportFrame, nativeUser }) {
39
+ this.#account = account;
40
+ this.#report = report;
41
+ this.#reportFrame = reportFrame;
42
+ if (typeof reportFrame === 'function') {
43
+ try { this.#nativeUserIdentifiers = identifierFields(nativeUser ?? { id: account.userId }, AUTHOR_IDENTIFIERS); }
44
+ catch {}
45
+ }
46
+ }
47
+ // Process evidence only. Unknown authors never enter the candidate/receipt cache.
48
+ #frame(phase, conversationId, messageId, metadata = () => ({})) {
49
+ if (typeof this.#reportFrame !== 'function') return;
50
+ const now = Date.now();
51
+ for (const [key, at] of this.#frameSeen)
52
+ if (now - at > 300_000) this.#frameSeen.delete(key);
53
+ const key = JSON.stringify([phase, conversationId, messageId]);
54
+ if (this.#frameSeen.has(key)) return;
55
+ this.#frameSeen.set(key, now);
56
+ while (this.#frameSeen.size > 128) this.#frameSeen.delete(this.#frameSeen.keys().next().value);
57
+ if (now - this.#frameWindowAt >= 60_000) {
58
+ this.#frameWindowAt = now;
59
+ this.#framesReported = 0;
60
+ }
61
+ if (this.#framesReported >= 64) { this.#framesSuppressed++; return; }
62
+ this.#framesReported++;
63
+ try {
64
+ const record = Object.freeze({ event: 'qq.native-reply.frame', phase,
65
+ accountFingerprint: this.#account.fingerprint,
66
+ authenticatedUser: identifierEvidence(this.#account.userId),
67
+ authenticatedUserIdentifiers: this.#nativeUserIdentifiers,
68
+ conversationHash: hash(conversationId), messageHash: hash(messageId),
69
+ ...metadata(), suppressed: this.#framesSuppressed });
70
+ this.#framesSuppressed = 0;
71
+ this.#reportFrame(record);
72
+ } catch {}
73
+ }
74
+ #entry(conversationId, messageId) {
75
+ const now = Date.now();
76
+ for (const [key, entry] of this.#entries)
77
+ if (now - entry.at > 300_000) this.#entries.delete(key);
78
+ const key = JSON.stringify([conversationId, messageId]);
79
+ let entry = this.#entries.get(key);
80
+ if (!entry) {
81
+ entry = { at: now, conversationHash: hash(conversationId), messageHash: hash(messageId),
82
+ receipt: false, native: undefined };
83
+ this.#entries.set(key, entry);
84
+ }
85
+ while (this.#entries.size > 128) this.#entries.delete(this.#entries.keys().next().value);
86
+ return entry;
87
+ }
88
+ #emit(entry) {
89
+ const now = Date.now();
90
+ if (now - this.#windowAt >= 60_000) {
91
+ this.#windowAt = now;
92
+ this.#reported = 0;
93
+ }
94
+ if (this.#reported >= 64) { this.#suppressed++; return; }
95
+ this.#reported++;
96
+ const record = Object.freeze({
97
+ event: 'qq.native-reply.observation', accountFingerprint: this.#account.fingerprint,
98
+ conversationHash: entry.conversationHash, messageHash: entry.messageHash,
99
+ ...entry.native, receiptMatched: entry.receipt, suppressed: this.#suppressed,
100
+ });
101
+ this.#suppressed = 0;
102
+ try { this.#report(record); } catch {}
103
+ }
104
+ receive(message, signal) {
105
+ if (signal?.aborted || message?.kind !== 'group'
106
+ || !['GROUP_AT_MESSAGE_CREATE', 'GROUP_MESSAGE_CREATE'].includes(message.rawEventType)
107
+ || !qqNativeIdentifier(message.messageId) || !qqNativeIdentifier(message.groupOpenid)) return;
108
+ this.#frame('callback', message.groupOpenid, message.messageId, () => ({
109
+ eventType: message.rawEventType,
110
+ senderBotFlag: message.senderIsBot === true ? 'true' : message.senderIsBot === false ? 'false'
111
+ : message.senderIsBot === undefined ? 'absent' : 'other',
112
+ senderMatchesAuthenticatedBot: message.senderId === this.#account.userId,
113
+ senderIdentifier: identifierEvidence(message.senderId),
114
+ authorIdentifiers: identifierFields(message.raw?.author, AUTHOR_IDENTIFIERS),
115
+ messageIdentifiers: identifierFields(message.raw, MESSAGE_IDENTIFIERS),
116
+ messageIndexIdentifier: identifierEvidence(message.msgIdx),
117
+ mentionIdentifiers: Array.isArray(message.mentions) ? message.mentions.slice(0, 8).map(mention => ({
118
+ self: mention?.is_you === true,
119
+ selfFlag: mention?.is_you === true ? 'true' : mention?.is_you === false ? 'false'
120
+ : mention?.is_you === undefined ? 'absent' : 'other',
121
+ identifiers: identifierFields(mention, ['id', 'user_openid', 'member_openid']),
122
+ })) : [],
123
+ mentionsTruncated: Array.isArray(message.mentions) && message.mentions.length > 8,
124
+ }));
125
+ if (!(message.senderIsBot === true || message.senderId === this.#account.userId)) return;
126
+ const entry = this.#entry(message.groupOpenid, message.messageId);
127
+ if (entry.native) return;
128
+ entry.native = { eventType: message.rawEventType, senderIsBot: message.senderIsBot === true,
129
+ senderMatchesAuthenticatedBot: message.senderId === this.#account.userId };
130
+ this.#emit(entry);
131
+ }
132
+ sent(conversationId, messageId, signal, nativeResponse) {
133
+ if (signal?.aborted || !qqNativeIdentifier(conversationId) || !qqNativeIdentifier(messageId)) return;
134
+ this.#frame('receipt', conversationId, messageId, () => ({
135
+ messageIdentifiers: identifierFields(nativeResponse ?? { id: messageId }, MESSAGE_IDENTIFIERS),
136
+ messageIndexIdentifier: identifierEvidence(nativeResponse?.ext_info?.ref_idx),
137
+ }));
138
+ const entry = this.#entry(conversationId, messageId);
139
+ if (entry.receipt) return;
140
+ entry.receipt = true;
141
+ if (entry.native) this.#emit(entry);
142
+ }
143
+ }
@@ -0,0 +1,42 @@
1
+ import { observeFrame, qqObservedOpcodes, qqObservedEventTypes } from './sdk-frame-observation.mjs';
2
+
3
+ const phases = ['received', 'decoded', 'parse-refused', 'processing-refused'];
4
+
5
+ /** Bounded process evidence for the maintained SDK option; never delivery authority. */
6
+ export class QqNativeTransportDiagnostics {
7
+ #fingerprint;
8
+ #report;
9
+ #windowAt = 0;
10
+ #reported = 0;
11
+ #suppressed = 0;
12
+ #context;
13
+ #counts = { received: 0, decoded: 0, parseRefused: 0, processingRefused: 0, reportAttempts: 0, suppressed: 0 };
14
+ #last;
15
+ constructor({ account, report }) { this.#fingerprint = account.fingerprint; this.#report = report; }
16
+ get context() { return this.#context && { ...this.#context }; }
17
+ get snapshot() { return { version: 1, ...this.#counts, ...(this.#last ? { last: { ...this.#last } } : {}) }; }
18
+ observe(value, signal) {
19
+ if (signal?.aborted || !value || !phases.includes(value.phase)
20
+ || !Number.isSafeInteger(value.connection) || value.connection < 1
21
+ || !Number.isSafeInteger(value.frame) || value.frame < 1
22
+ || !(value.bytes === null || Number.isSafeInteger(value.bytes) && value.bytes >= 0)) return;
23
+ const context = { connection: value.connection, frame: value.frame };
24
+ this.#context = value.phase === 'decoded' ? context : undefined;
25
+ this.#last = { ...context, phase: value.phase };
26
+ const count = { received: 'received', decoded: 'decoded', 'parse-refused': 'parseRefused', 'processing-refused': 'processingRefused' }[value.phase];
27
+ this.#counts[count]++;
28
+ const now = Date.now();
29
+ if (now - this.#windowAt >= 60_000) { this.#windowAt = now; this.#reported = 0; }
30
+ if (this.#reported >= 128) { this.#suppressed++; this.#counts.suppressed++; return; }
31
+ this.#reported++;
32
+ this.#counts.reportAttempts++;
33
+ const record = { event: 'qq.native-transport.frame', accountFingerprint: this.#fingerprint,
34
+ ...context, phase: value.phase, bytes: value.bytes, suppressed: this.#suppressed };
35
+ if (value.phase === 'decoded') {
36
+ record.opcode = qqObservedOpcodes.includes(value.opcode) ? value.opcode : 'other';
37
+ record.eventType = qqObservedEventTypes.includes(value.eventType) ? value.eventType : 'other';
38
+ record.sequence = Number.isSafeInteger(value.sequence) && value.sequence >= 0 ? value.sequence : null;
39
+ }
40
+ if (observeFrame(this.#report, record)) this.#suppressed = 0;
41
+ }
42
+ }
@@ -6,6 +6,8 @@ import { t } from '../shared/i18n.mjs';
6
6
  import { publicMessageFailure } from '../shared/message-failure.mjs';
7
7
  import { deriveQqBotIdentity, maskQqAppId } from './config-store.mjs';
8
8
  import { publicQqStateError } from './state-error.mjs';
9
+ import { ExclusiveInboundConsumers } from '../shared/exclusive-inbound-consumers.mjs';
10
+ import { qqRefusal } from './external-consumer.mjs';
9
11
 
10
12
  const ACTIVE_ATTEMPT_STATES = new Set(['starting', 'pending', 'refreshing', 'connecting']);
11
13
  const TERMINAL_ATTEMPT_STATES = new Set(['connected', 'failed', 'cancelled']);
@@ -52,6 +54,7 @@ export class QqController {
52
54
  #transitions = new Map();
53
55
  #revision = 0;
54
56
  #closed = false;
57
+ #inboundConsumers = new ExclusiveInboundConsumers();
55
58
 
56
59
  constructor({
57
60
  qrAuth,
@@ -210,6 +213,7 @@ export class QqController {
210
213
  appId: normalizedAppId,
211
214
  secretRef: identity.secretRef,
212
215
  ownerUserOpenid: previousConfig?.ownerUserOpenid ?? '*',
216
+ ...(previousConfig?.consumerMode === 'external-consumer' ? { consumerMode: 'external-consumer' } : {}),
213
217
  createdAt: previousConfig?.createdAt ?? new Date().toISOString(),
214
218
  connectedAt: new Date().toISOString(),
215
219
  };
@@ -287,6 +291,14 @@ export class QqController {
287
291
  const config = this.#configStore.get(botId);
288
292
  if (!config) throw new Error('Unknown QQ bot');
289
293
  return this.#withBotTransition(botId, async () => {
294
+ if (options.expectedFingerprint !== undefined) {
295
+ const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
296
+ const verifyAccount = async () => {
297
+ const current = await this.#checkedRuntime(botId, options.expectedFingerprint, checked.signal);
298
+ if (current.runtime !== checked.runtime) throw qqRefusal('account-changed');
299
+ };
300
+ return checked.runtime.sendProactiveText(target, text, { ...options, signal: checked.signal, verifyAccount });
301
+ }
290
302
  const runtime = this.#runtimes.get(botId);
291
303
  if (!runtime?.status?.ready || typeof runtime.sendProactiveText !== 'function') {
292
304
  const error = new Error(t('QQ机器人尚未连接'));
@@ -297,12 +309,91 @@ export class QqController {
297
309
  });
298
310
  }
299
311
 
312
+ async #deliveryAccount(botId, signal) {
313
+ if (this.#closed) throw qqRefusal('provider-unavailable');
314
+ if (!this.#configStore.get(botId)) throw qqRefusal('unknown-bot');
315
+ const runtime = this.#runtimes.get(botId);
316
+ if (!runtime?.status?.ready) throw qqRefusal('bot-not-connected');
317
+ return runtime.describeDeliveryAccount(signal);
318
+ }
319
+
320
+ async describeDeliveryAccount(botId) {
321
+ return this.#withBotTransition(botId, async () => ({
322
+ version: 1, botId, channel: 'qq', account: await this.#deliveryAccount(botId), connected: true,
323
+ capabilities: ['proactive-text-checked', 'proactive-receipt-checked', 'proactive-fence-checked',
324
+ 'exclusive-text-consumer', 'ordinary-text-consumer', 'reply-text-checked', 'reply-context-checked',
325
+ 'reply-receipt-checked', 'reply-fence-checked', 'source-file-checked', 'source-image-checked',
326
+ 'reply-file-checked', 'reply-image-fence-checked', 'reply-file-receipt-checked',
327
+ 'source-generic-file-checked', 'reply-file-fence-checked', 'source-voice-transcript-checked', 'source-voice-audio-checked'],
328
+ }));
329
+ }
330
+
331
+ async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceImages = false, sourceFiles = false, sourceVoiceTranscripts = false, sourceVoiceAudio = false, ordinaryText = false } = {}) {
332
+ return this.#withBotTransition(botId, async () => {
333
+ const account = await this.#deliveryAccount(botId, signal);
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 });
336
+ try {
337
+ const saved = await this.#configStore.save({ ...this.#configStore.get(botId), consumerMode: 'external-consumer' });
338
+ const secret = await this.#resolveSecret(saved.secretRef);
339
+ if (!secret) throw qqRefusal('account-unverified');
340
+ await this.#startRuntime(saved, secret);
341
+ signal?.throwIfAborted();
342
+ return dispose;
343
+ } catch (error) { dispose(); throw error; }
344
+ });
345
+ }
346
+
347
+ async #checkedRuntime(botId, expectedFingerprint, signal) {
348
+ let account;
349
+ try { account = await this.#deliveryAccount(botId, signal); }
350
+ catch (error) {
351
+ if (signal?.aborted || error?.name === 'AbortError') throw qqRefusal('cancelled');
352
+ throw error;
353
+ }
354
+ if (account.fingerprint !== expectedFingerprint) throw qqRefusal('account-changed');
355
+ const runtime = this.#runtimes.get(botId);
356
+ if (this.#configStore.get(botId)?.consumerMode !== 'external-consumer') throw qqRefusal('capability-unavailable');
357
+ const lease = this.#inboundConsumers.signalFor(botId, expectedFingerprint);
358
+ return { runtime, signal: signal ? AbortSignal.any([signal, lease]) : lease };
359
+ }
360
+
361
+ async qualifyReplyChecked(botId, route, options = {}) {
362
+ return this.#withBotTransition(botId, async () => {
363
+ const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
364
+ return checked.runtime.qualifyReplyChecked(route, { signal: checked.signal });
365
+ });
366
+ }
367
+
368
+ async replyChecked(botId, route, text, options = {}) {
369
+ return this.#withBotTransition(botId, async () => {
370
+ const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
371
+ return checked.runtime.replyChecked(route, text, { ...options, signal: checked.signal });
372
+ });
373
+ }
374
+
375
+ async externalFileChecked(botId, route, value, options = {}) {
376
+ return this.#withBotTransition(botId, async () => {
377
+ const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
378
+ const verifyAccount = async () => {
379
+ const current = await this.#checkedRuntime(botId, options.expectedFingerprint, checked.signal);
380
+ if (current.runtime !== checked.runtime) throw qqRefusal('account-changed');
381
+ };
382
+ if (options.reply) return checked.runtime.replyFileChecked(route, value, { ...options,
383
+ signal: checked.signal, verifyAccount });
384
+ return value?.mediaType === 'application/octet-stream' || value?.mediaType === 'audio/unknown'
385
+ ? checked.runtime.readSourceFile(route, value, { ...options, signal: checked.signal, verifyAccount })
386
+ : checked.runtime.readSourceImage(route, value, { ...options, signal: checked.signal, verifyAccount });
387
+ });
388
+ }
389
+
300
390
  async deleteBot(botId) {
301
391
  const warnings = [];
302
392
  const config = this.#configStore.get(botId);
303
393
  if (!config) throw new Error('Unknown QQ bot');
304
394
  await this.#withBotTransition(botId, async () => {
305
395
  const previous = await atConnectionStage('credential.read', () => this.#credentials.resolve(config.secretRef), 'credential-store');
396
+ this.#inboundConsumers.remove(botId);
306
397
  await this.#stopRuntime(botId);
307
398
  try {
308
399
  await atConnectionStage('credential.remove', () => this.#credentials.unset(config.secretRef), 'credential-store');
@@ -349,6 +440,8 @@ export class QqController {
349
440
  ?? (state === 'error' ? t('QQ 连接未就绪,插件会自动重试') : t('QQ 连接当前离线')),
350
441
  lastCheckedAt: runtimeStatus?.lastCheckedAt ?? null,
351
442
  lastConnectedAt: runtimeStatus?.lastConnectedAt ?? null,
443
+ ...(runtimeStatus?.lastInbound ? { lastInbound: structuredClone(runtimeStatus.lastInbound) } : {}),
444
+ ...(runtimeStatus?.transportObservation ? { transportObservation: structuredClone(runtimeStatus.transportObservation) } : {}),
352
445
  },
353
446
  stats: {
354
447
  messagesReceived: runtimeStatus?.messagesReceived ?? 0,
@@ -377,6 +470,7 @@ export class QqController {
377
470
  async close() {
378
471
  if (this.#closed) return;
379
472
  this.#closed = true;
473
+ this.#inboundConsumers.close();
380
474
  if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
381
475
  await Promise.allSettled([...this.#transitions.values()]);
382
476
  await Promise.allSettled([...this.#runtimes.keys()].map((botId) => this.#stopRuntime(botId)));
@@ -423,6 +517,7 @@ export class QqController {
423
517
  appId,
424
518
  secretRef: identity.secretRef,
425
519
  ownerUserOpenid,
520
+ ...(previousConfig?.consumerMode === 'external-consumer' ? { consumerMode: 'external-consumer' } : {}),
426
521
  createdAt: previousConfig?.createdAt ?? new Date().toISOString(),
427
522
  connectedAt: new Date().toISOString(),
428
523
  };
@@ -466,7 +561,16 @@ export class QqController {
466
561
  if (this.#closed) throw new Error('QQ controller is closed');
467
562
  await this.#stopRuntime(config.botId);
468
563
  if (this.#closed) throw new Error('QQ controller is closed');
469
- const runtime = await atConnectionStage('runtime.prepare', () => this.#createRuntime({ botId: config.botId, config, appSecret }));
564
+ const runtime = await atConnectionStage('runtime.prepare', () => this.#createRuntime({ botId: config.botId, config, appSecret,
565
+ ...(config.consumerMode === 'external-consumer' ? {
566
+ externalConsumer: (event, signal) => this.#inboundConsumers.accept(config.botId, event, signal),
567
+ sourceImages: () => this.#inboundConsumers.acceptsImages(config.botId),
568
+ sourceFiles: () => this.#inboundConsumers.acceptsFiles(config.botId),
569
+ sourceVoiceTranscripts: () => this.#inboundConsumers.acceptsVoiceTranscripts(config.botId),
570
+ sourceVoiceAudio: () => this.#inboundConsumers.acceptsVoiceAudio(config.botId),
571
+ ordinaryText: () => this.#inboundConsumers.acceptsOrdinary(config.botId),
572
+ } : {}),
573
+ }));
470
574
  if (!runtime || typeof runtime.start !== 'function' || typeof runtime.stop !== 'function') {
471
575
  throw new TypeError('createRuntime returned an invalid QQ runtime');
472
576
  }