@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
@@ -1,3 +1,4 @@
1
+ import { isQqVoiceAttachment } from './voice-attachment.mjs';
1
2
  import { extractConnectionEvidence, createConnectionDiagnostics, atConnectionStage } from '../shared/connection-error.mjs';
2
3
  import { QQBot, contentSanitizer, typingIndicator } from '@tencent-connect/qqbot-nodejs';
3
4
 
@@ -8,6 +9,10 @@ import {
8
9
  import { t } from '../shared/i18n.mjs';
9
10
  import { evaluateInboundAccess } from '../shared/inbound-access.mjs';
10
11
  import { createQqBridgeStatus, QqHarnessBridge } from './qq-bridge.mjs';
12
+ import { QqExternalConsumer, qqRefusal, verifiedQqAccount } from './external-consumer.mjs';
13
+ import { postQqText } from './external-post.mjs';
14
+ import { QqNativeGatewayDiagnostics } from './native-gateway-diagnostics.mjs';
15
+ import { QqNativeTransportDiagnostics } from './native-transport-diagnostics.mjs';
11
16
 
12
17
  function timeoutError() {
13
18
  const error = new Error('QQ WebSocket did not become ready in time');
@@ -47,6 +52,13 @@ export class QqRuntime {
47
52
  #abortController = null;
48
53
  #runTask = null;
49
54
  #starting = null;
55
+ #externalConsumer;
56
+ #sourceImages;
57
+ #sourceFiles;
58
+ #sourceVoiceTranscripts;
59
+ #sourceVoiceAudio;
60
+ #ordinaryText;
61
+ #externalBridge = null;
50
62
 
51
63
  constructor({
52
64
  config,
@@ -60,6 +72,10 @@ export class QqRuntime {
60
72
  connectTimeoutMs = 20_000,
61
73
  createBot = (options) => new QQBot(options),
62
74
  typingMiddleware = typingIndicator,
75
+ externalConsumer,
76
+ sourceImages = () => false,
77
+ sourceFiles = () => false,
78
+ sourceVoiceTranscripts = () => false, sourceVoiceAudio = () => false, ordinaryText = () => false,
63
79
  }) {
64
80
  if (!config || !appSecret || !harness || !state) {
65
81
  throw new TypeError('QqRuntime requires config, app secret, Harness, and state');
@@ -75,12 +91,78 @@ export class QqRuntime {
75
91
  this.#connectTimeoutMs = connectTimeoutMs;
76
92
  this.#createBot = createBot;
77
93
  this.#typingMiddleware = typingMiddleware;
94
+ this.#externalConsumer = externalConsumer;
95
+ this.#sourceImages = sourceImages;
96
+ this.#sourceFiles = sourceFiles;
97
+ this.#sourceVoiceTranscripts = sourceVoiceTranscripts;
98
+ this.#sourceVoiceAudio = sourceVoiceAudio;
99
+ this.#ordinaryText = ordinaryText;
78
100
  }
79
101
 
80
102
  get status() {
81
103
  return structuredClone(this.#status);
82
104
  }
83
105
 
106
+ async describeDeliveryAccount(signal) {
107
+ signal?.throwIfAborted();
108
+ if (!this.#status.ready || !this.#bot) throw qqRefusal('bot-not-connected');
109
+ const bot = this.#bot;
110
+ try {
111
+ const user = await bot.api.get('/users/@me');
112
+ signal?.throwIfAborted();
113
+ if (this.#bot !== bot || !this.#status.ready) throw qqRefusal('bot-not-connected');
114
+ const account = verifiedQqAccount(this.#config.appId, user);
115
+ if (this.#status.error?.details?.stage === 'credential.verify') {
116
+ this.#status.error = null;
117
+ this.#status.lastError = null;
118
+ }
119
+ return account;
120
+ } catch (error) {
121
+ if (!signal?.aborted && this.#bot === bot) {
122
+ const qualificationHints = {
123
+ 'application-id': t('QQ 应用标识无效。'),
124
+ 'native-user-id': t('QQ 账号响应未提供有效的原生用户标识。'),
125
+ 'native-bot-flag': t('QQ 账号响应返回了无效或矛盾的机器人标志。'),
126
+ };
127
+ this.#status.error = this.#diagnostics.report(error, { operation: 'connection.status',
128
+ stage: 'credential.verify', botId: this.#config.botId,
129
+ httpStatus: error?.httpStatus, providerCode: error?.bizCode,
130
+ ...(error?.code === 'account-unverified' ? { publicError: {
131
+ code: 'account-unverified', message: t('QQ 账号资格验证失败。'),
132
+ details: { reason: 'invalid-response', hint: qualificationHints[error.verificationFailure] },
133
+ } } : {}),
134
+ }).publicError;
135
+ this.#status.lastError = this.#status.error.message;
136
+ }
137
+ throw error;
138
+ }
139
+ }
140
+
141
+ qualifyReplyChecked(route, { signal } = {}) {
142
+ if (!this.#externalBridge) throw qqRefusal('consumer-unavailable');
143
+ return this.#externalBridge.qualify(route, signal);
144
+ }
145
+
146
+ replyChecked(route, text, options) {
147
+ if (!this.#externalBridge) throw qqRefusal('consumer-unavailable');
148
+ return this.#externalBridge.reply(route, text, options);
149
+ }
150
+
151
+ readSourceImage(route, attachment, options) {
152
+ if (!this.#externalBridge) throw qqRefusal('consumer-unavailable');
153
+ return this.#externalBridge.readImage(route, attachment, options);
154
+ }
155
+
156
+ readSourceFile(route, attachment, options) {
157
+ if (!this.#externalBridge) throw qqRefusal('consumer-unavailable');
158
+ return this.#externalBridge.readFile(route, attachment, options);
159
+ }
160
+
161
+ replyFileChecked(route, file, options) {
162
+ if (!this.#externalBridge) throw qqRefusal('consumer-unavailable');
163
+ return this.#externalBridge.replyFile(route, file, options);
164
+ }
165
+
84
166
  async sendConnectionTest(text) {
85
167
  if (!this.#status.ready || !this.#bot) {
86
168
  throw connectionTestTargetUnavailable(t('QQ机器人'));
@@ -103,7 +185,45 @@ export class QqRuntime {
103
185
  return { sent: true };
104
186
  }
105
187
 
106
- async sendProactiveText(target, text, { signal } = {}) {
188
+ async sendProactiveText(target, text, { signal, expectedFingerprint, beforeSend, verifyAccount } = {}) {
189
+ if (expectedFingerprint !== undefined) {
190
+ const bot = this.#bot;
191
+ const bridge = this.#externalBridge;
192
+ if (!bot || !this.#status.ready || !this.#abortController) throw qqRefusal('bot-not-connected');
193
+ const sendSignal = signal ? AbortSignal.any([signal, this.#abortController.signal]) : this.#abortController.signal;
194
+ const started = Date.now();
195
+ const report = (phase, reason, nativePost) => {
196
+ try {
197
+ this.#logger.info?.('[dsh-im:qq] checked post', { event: 'qq-external-post',
198
+ initiator: 'external-consumer', phase, durationMs: Math.max(0, Date.now() - started),
199
+ ...(reason ? { reason } : {}),
200
+ ...(nativePost ? { stage: 'native-post',
201
+ ...(Number.isInteger(nativePost.httpStatus) && nativePost.httpStatus >= 100 && nativePost.httpStatus <= 599
202
+ ? { httpStatus: nativePost.httpStatus } : {}),
203
+ ...(Number.isSafeInteger(nativePost.providerCode) && nativePost.providerCode >= 0
204
+ ? { providerCode: nativePost.providerCode } : {}),
205
+ } : {}) });
206
+ } catch {}
207
+ };
208
+ report('preparing');
209
+ let nativePostEvidence;
210
+ try {
211
+ const result = await postQqText({ bot, target, text, signal: sendSignal, beforeSend, verifyAccount,
212
+ onNativeFailure: evidence => { nativePostEvidence = evidence; },
213
+ assertCurrent: () => {
214
+ if (this.#bot !== bot || !this.#status.ready) throw qqRefusal('bot-not-connected');
215
+ } });
216
+ bridge?.recordNativeReceipt(result.receipt, sendSignal);
217
+ report('accepted', 'native-receipt');
218
+ return result;
219
+ } catch (error) {
220
+ const reason = ['invalid-target', 'bad-request', 'cancelled', 'provider-unavailable',
221
+ 'account-changed', 'consumer-unavailable', 'bot-not-connected', 'send-permission-denied',
222
+ 'send-rate-limited', 'send-result-unknown'].includes(error?.code) ? error.code : 'operation-failed';
223
+ report(reason === 'send-result-unknown' ? 'unknown' : 'refused', reason, nativePostEvidence);
224
+ throw error;
225
+ }
226
+ }
107
227
  const nativeId = target?.kind === 'user'
108
228
  ? (typeof target?.route?.userOpenId === 'string' ? target.route.userOpenId.trim() : '')
109
229
  : target?.kind === 'group'
@@ -140,14 +260,47 @@ export class QqRuntime {
140
260
  this.#status.startedAt = new Date().toISOString();
141
261
  this.#status.qqConnectionState = 'connecting';
142
262
  this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
143
- await atConnectionStage('harness.check', () => this.#harness.ensureRunning());
263
+ delete this.#status.transportObservation;
264
+ if (this.#config.consumerMode !== 'external-consumer')
265
+ await atConnectionStage('harness.check', () => this.#harness.ensureRunning());
144
266
  this.#status.harnessReachable = true;
145
267
 
268
+ const controller = new AbortController();
269
+ this.#abortController = controller;
270
+ const observeTransport = (message) => {
271
+ if (controller.signal.aborted || this.#abortController !== controller || typeof message !== 'string') return;
272
+ // SDK 1.0.4 exposes close through its public Logger, not a disconnect event.
273
+ if (message.startsWith(`[${this.#config.botId}] WebSocket closed:`)
274
+ || message.startsWith(`[${this.#config.botId}] Connection failed:`)
275
+ || message.startsWith(`[${this.#config.botId}] Connecting to `)) {
276
+ this.#status.ready = false;
277
+ this.#status.qqConnectionState = 'connecting';
278
+ } else if (message === `[${this.#config.botId}] Max reconnect attempts reached or aborted`) {
279
+ this.#status.ready = false;
280
+ this.#status.qqConnectionState = 'failed';
281
+ } else return false;
282
+ this.#logger.info?.(`[dsh-im:qq] ${JSON.stringify({ event: 'receiver-state',
283
+ botId: this.#config.botId, phase: this.#status.qqConnectionState })}`);
284
+ return true;
285
+ };
286
+ let gatewayDiagnostics;
287
+ let transportDiagnostics;
146
288
  const sdkLogger = {
147
- error: (...args) => this.#logger.error?.(...args),
289
+ error: (...args) => {
290
+ // Node's JSON error text can quote the payload. The maintained hook reports
291
+ // only the coded parse/processing disposition; never forward that raw text.
292
+ if (transportDiagnostics && typeof args[0] === 'string'
293
+ && args[0].startsWith(`[${this.#config.botId}] Message parse error:`)) return;
294
+ if (!observeTransport(args[0])) this.#logger.error?.(...args);
295
+ },
148
296
  warn: (...args) => this.#logger.warn?.(...args),
149
- info: (...args) => this.#logger.info?.(...args),
150
- debug: () => {},
297
+ info: (...args) => { if (!observeTransport(args[0])) this.#logger.info?.(...args); },
298
+ debug: message => {
299
+ try {
300
+ if (!controller.signal.aborted && this.#abortController === controller)
301
+ gatewayDiagnostics?.observe(message, controller.signal, transportDiagnostics?.context);
302
+ } catch {}
303
+ },
151
304
  };
152
305
  const bot = this.#createBot({
153
306
  appId: this.#config.appId,
@@ -156,6 +309,13 @@ export class QqRuntime {
156
309
  logger: sdkLogger,
157
310
  transport: 'websocket',
158
311
  tokenPrefetch: 'sync',
312
+ // Public option proposed by the maintained, hash-checked SDK build patch.
313
+ onGatewayObservation: value => {
314
+ if (!controller.signal.aborted && this.#abortController === controller) {
315
+ transportDiagnostics?.observe(value, controller.signal);
316
+ if (transportDiagnostics) this.#status.transportObservation = transportDiagnostics.snapshot;
317
+ }
318
+ },
159
319
  // sendText is reserved for literal notices/connection tests. Markdown
160
320
  // replies use the explicit msg_type=2 path in sendMarkdownReply().
161
321
  markdownSupport: false,
@@ -163,10 +323,32 @@ export class QqRuntime {
163
323
  if (!bot || typeof bot.start !== 'function' || typeof bot.stop !== 'function') {
164
324
  throw new TypeError('QQ bot factory returned an invalid client');
165
325
  }
166
- const controller = new AbortController();
167
- this.#abortController = controller;
168
326
  this.#bot = bot;
169
- this.#bridge = new QqHarnessBridge({
327
+ if (this.#config.consumerMode === 'external-consumer' && this.#externalConsumer) {
328
+ try {
329
+ const nativeUser = await bot.api.get('/users/@me');
330
+ const account = verifiedQqAccount(this.#config.appId, nativeUser);
331
+ controller.signal.throwIfAborted();
332
+ gatewayDiagnostics = new QqNativeGatewayDiagnostics({ botId: this.#config.botId, account,
333
+ report: record => this.#logger.info?.('[dsh-im:qq] native gateway diagnostic', record) });
334
+ transportDiagnostics = new QqNativeTransportDiagnostics({ account,
335
+ report: record => this.#logger.info?.('[dsh-im:qq] native transport diagnostic', record) });
336
+ this.#externalBridge = new QqExternalConsumer({ bot, account, nativeUser, botId: this.#config.botId,
337
+ accept: this.#externalConsumer,
338
+ sourceImages: this.#sourceImages,
339
+ sourceFiles: this.#sourceFiles,
340
+ sourceVoiceTranscripts: this.#sourceVoiceTranscripts,
341
+ sourceVoiceAudio: this.#sourceVoiceAudio,
342
+ ordinaryText: this.#ordinaryText,
343
+ reportNativeObservation: record => this.#logger.info?.('[dsh-im:qq] native reply observation', record),
344
+ reportNativeFrame: record => this.#logger.info?.('[dsh-im:qq] native reply frame', record),
345
+ });
346
+ } catch (error) {
347
+ await this.stop();
348
+ throw error;
349
+ }
350
+ }
351
+ this.#bridge = this.#config.consumerMode === 'external-consumer' ? null : new QqHarnessBridge({
170
352
  bot,
171
353
  ownerUserOpenid: this.#config.ownerUserOpenid,
172
354
  harness: this.#harness,
@@ -182,7 +364,7 @@ export class QqRuntime {
182
364
  // tags. Parse them into readable text so the Harness sees what the sender
183
365
  // actually meant instead of an unusable markup fragment.
184
366
  bot.use(contentSanitizer({ parseFaceTags: true }));
185
- bot.use?.(this.#typingMiddleware({
367
+ if (this.#config.consumerMode !== 'external-consumer') bot.use?.(this.#typingMiddleware({
186
368
  keepAlive: true,
187
369
  predicate: (ctx) => {
188
370
  const message = ctx?.message;
@@ -208,6 +390,7 @@ export class QqRuntime {
208
390
  readyReject = reject;
209
391
  });
210
392
  const onReady = () => {
393
+ if (controller.signal.aborted || this.#bot !== bot) return;
211
394
  const now = Date.now();
212
395
  this.#status.ready = true;
213
396
  this.#status.qqConnectionState = 'connected';
@@ -217,18 +400,81 @@ export class QqRuntime {
217
400
  readyResolve();
218
401
  };
219
402
  const onError = (error) => {
403
+ if (controller.signal.aborted || this.#bot !== bot) return;
220
404
  if (!this.#status.ready) readyReject(error);
221
405
  else {
222
406
  this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#config?.botId, automatic: true }).publicError;
223
407
  this.#status.lastError = this.#status.error.message;
224
408
  this.#logger.warn?.(`[dsh-im:qq] bot ${this.#config.botId} connection error:`, extractConnectionEvidence(error).details);
225
409
  }
410
+ this.#status.ready = false;
411
+ this.#status.qqConnectionState = 'connecting';
226
412
  };
227
- const onMessage = (_ctx, message) => {
228
- const task = this.#bridge?.accept(message);
413
+ const onMessage = async (_ctx, message) => {
414
+ if (controller.signal.aborted || this.#bot !== bot) return;
415
+ const elements = Array.isArray(message?.raw?.msg_elements) ? message.raw.msg_elements : [];
416
+ const quotedAttachments = elements.slice(0, 2).flatMap(element => Array.isArray(element?.attachments)
417
+ ? element.attachments.slice(0, 33) : []);
418
+ const quotedFiles = quotedAttachments.filter(file => file?.content_type === 'file');
419
+ const lastInbound = {
420
+ observedAt: new Date().toISOString(),
421
+ eventType: ['GROUP_AT_MESSAGE_CREATE', 'GROUP_MESSAGE_CREATE', 'C2C_MESSAGE_CREATE'].includes(message?.rawEventType)
422
+ ? message.rawEventType : 'other',
423
+ messageType: Number.isSafeInteger(message?.msgType) ? message.msgType : null,
424
+ mentionCount: Array.isArray(message?.mentions) ? Math.min(message.mentions.length, 128) : 0,
425
+ explicitSelfMention: Array.isArray(message?.mentions) && message.mentions.some(mention => mention?.is_you === true),
426
+ textPresent: typeof message?.content === 'string' && !!message.content.trim(),
427
+ directAttachments: Array.isArray(message?.attachments) ? Math.min(message.attachments.length, 33) : 0,
428
+ quotedElements: Math.min(elements.length, 2), quotedFiles: Math.min(quotedFiles.length, 33),
429
+ quoteIndexMatches: typeof message?.refMsgIdx === 'string' && message.refMsgIdx.length > 0
430
+ && elements.length === 1 && elements[0]?.msg_idx === message.refMsgIdx,
431
+ };
432
+ if (message?.msgType === 103) {
433
+ const attachmentShape = value => value === undefined ? 'absent' : value === null ? 'null'
434
+ : Array.isArray(value) ? value.length ? 'nonempty-array' : 'empty-array' : 'other';
435
+ lastInbound.quoteShape = {
436
+ directAttachments: attachmentShape(message.attachments),
437
+ rawDirectAttachments: attachmentShape(message.raw?.attachments),
438
+ elementFields: elements[0] && typeof elements[0] === 'object'
439
+ ? Object.keys(elements[0]).filter(key => /^[a-z_]{1,32}$/.test(key)).sort().slice(0, 16) : [],
440
+ elementMessageType: Number.isSafeInteger(elements[0]?.message_type) && elements[0].message_type >= 0
441
+ ? elements[0].message_type : null,
442
+ normalizedElementMatches: Array.isArray(message.msgElements) && message.msgElements.length === 1
443
+ && elements.length === 1 && message.msgElements[0]?.msg_idx === elements[0]?.msg_idx,
444
+ files: quotedFiles.slice(0, 2).map(file => ({
445
+ urlPresent: typeof file.url === 'string' && file.url.length > 0,
446
+ httpsUrl: typeof file.url === 'string' && file.url.startsWith('https://'),
447
+ sizeType: file.size === undefined ? 'absent' : file.size === null ? 'null'
448
+ : ['string', 'number'].includes(typeof file.size) ? typeof file.size : 'other',
449
+ sizeValid: file.size === undefined || (Number.isSafeInteger(file.size) && file.size > 0),
450
+ })),
451
+ };
452
+ }
453
+ const voices = [...(Array.isArray(message?.attachments) ? message.attachments.slice(0, 2) : []), ...quotedAttachments.slice(0, 2)]
454
+ .filter(isQqVoiceAttachment);
455
+ if (voices.length) lastInbound.voice = {
456
+ count: Math.min(voices.length, 2),
457
+ quotedAttachmentCount: Math.min(quotedAttachments.length, 8),
458
+ quotedCategories: quotedAttachments.slice(0, 4).map(file => {
459
+ const type = file?.content_type;
460
+ return typeof type === 'string' && /^(?:voice|file|image|audio\/[a-z0-9!#$&^_.+-]+|image\/[a-z0-9!#$&^_.+-]+)$/i.test(type)
461
+ ? type.slice(0, 64) : typeof type;
462
+ }),
463
+ platformTranscriptPresent: voices.some(file => typeof file.asr_refer_text === 'string' && !!file.asr_refer_text.trim()),
464
+ platformWavPresent: voices.some(file => typeof file.voice_wav_url === 'string' && !!file.voice_wav_url),
465
+ };
466
+ this.#status.lastInbound = lastInbound;
467
+ const task = this.#config.consumerMode === 'external-consumer'
468
+ ? this.#externalBridge?.accept(message, controller.signal)
469
+ : this.#bridge?.accept(message);
229
470
  if (!task) return;
230
- void task.catch((error) => {
471
+ return task.catch((error) => {
231
472
  if (controller.signal.aborted) return;
473
+ lastInbound.refusalCode = typeof error?.code === 'string' && /^[a-z-]{1,64}$/.test(error.code)
474
+ ? error.code : 'message-handling-failed';
475
+ if (['quote-envelope-invalid', 'quote-reference-invalid', 'quote-elements-invalid',
476
+ 'file-category-invalid', 'file-url-invalid', 'file-size-invalid'].includes(error?.reason))
477
+ lastInbound.refusalReason = error.reason;
232
478
  this.#logger.error?.(
233
479
  `[dsh-im:qq] bot ${this.#config.botId} message handling failed:`,
234
480
  extractConnectionEvidence(error).details,
@@ -285,6 +531,7 @@ export class QqRuntime {
285
531
  this.#abortController = null;
286
532
  this.#bot = null;
287
533
  this.#bridge = null;
534
+ this.#externalBridge = null;
288
535
  this.#runTask = null;
289
536
  try {
290
537
  bot?.stop();
@@ -0,0 +1,31 @@
1
+ // Proposed public constructor option, compiled into the hash-checked SDK 1.0.4.
2
+ // These values are the pinned SDK's protocol constants, never caller-supplied labels.
3
+ export const qqObservedOpcodes = Object.freeze([0, 1, 2, 6, 7, 9, 10, 11]);
4
+ export const qqObservedEventTypes = Object.freeze(['READY', 'RESUMED', 'GROUP_MESSAGE_CREATE', 'GROUP_AT_MESSAGE_CREATE',
5
+ 'C2C_MESSAGE_CREATE', 'AT_MESSAGE_CREATE', 'DIRECT_MESSAGE_CREATE', 'INTERACTION_CREATE', 'other']);
6
+
7
+ export function frameBytes(data) {
8
+ if (typeof data === 'string') return Buffer.byteLength(data, 'utf8');
9
+ if (Buffer.isBuffer(data)) return data.byteLength;
10
+ if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) return data.byteLength;
11
+ if (Array.isArray(data) && data.every(Buffer.isBuffer)) {
12
+ const total = data.reduce((size, chunk) => size + chunk.byteLength, 0);
13
+ return Number.isSafeInteger(total) ? total : null;
14
+ }
15
+ return null;
16
+ }
17
+
18
+ export function frameEnvelope(op, type, sequence) {
19
+ return { opcode: qqObservedOpcodes.includes(op) ? op : 'other',
20
+ eventType: qqObservedEventTypes.includes(type) ? type : 'other',
21
+ sequence: Number.isSafeInteger(sequence) && sequence >= 0 ? sequence : null };
22
+ }
23
+
24
+ export function observeFrame(observer, value) {
25
+ if (typeof observer !== 'function') return false;
26
+ try {
27
+ const result = observer(Object.freeze(value));
28
+ if (result && typeof result.then === 'function') void Promise.resolve(result).catch(() => {});
29
+ return true;
30
+ } catch { return false; }
31
+ }
@@ -0,0 +1,3 @@
1
+ export function isQqVoiceAttachment(native) {
2
+ return native?.content_type === 'voice' || /^audio\/[a-z0-9!#$&^_.+-]+$/i.test(native?.content_type ?? '');
3
+ }
@@ -1,5 +1,9 @@
1
1
  // English translations (qq area). Keys are exact Chinese literals passed to t().
2
2
  export default {
3
+ 'QQ 应用标识无效。': 'QQ application identifier is invalid.',
4
+ 'QQ 账号响应未提供有效的原生用户标识。': 'QQ account response did not contain a valid native user identifier.',
5
+ 'QQ 账号响应返回了无效或矛盾的机器人标志。': 'QQ account response returned an invalid or contradictory bot flag.',
6
+ 'QQ 账号资格验证失败。': 'QQ account qualification failed.',
3
7
  '无法读取 QQ 本地状态,请检查数据目录及访问权限。': 'Unable to read local QQ state. Check the data directory and access permissions.',
4
8
  'QQ 本地状态已损坏,但无法备份,原文件已保留。': 'Local QQ state is corrupt and could not be backed up. The original file has been preserved.',
5
9
  '无法保存 QQ 本地状态,请检查磁盘空间及目录写入权限。': 'Unable to save local QQ state. Check disk space and directory write permissions.',
@@ -2,6 +2,7 @@ import diagnostics from '../../weixin/connection-error.en.mjs';
2
2
  // English translations (weixin area). Keys are exact Chinese literals passed to t().
3
3
  export default {
4
4
  ...diagnostics,
5
+ '该微信账号已绑定,请选择已有应用。': 'This WeChat account is already paired. Choose the existing app.',
5
6
  // weixin-bridge.mjs
6
7
  '微信已连接 DeepSeek Harness。': 'WeChat is connected to DeepSeek Harness.',
7
8
  '结果文件「{name}」已生成,但微信机器人当前没有文件消息发送权限,请检查机器人文件消息能力。': 'The result file "{name}" was generated, but the WeChat bot currently has no permission to send file messages. Please check the bot\'s file messaging capability.',
@@ -316,6 +316,32 @@ export class TokenBotController {
316
316
  return { runtime, signal: signal ? AbortSignal.any([signal, lease]) : lease };
317
317
  }
318
318
 
319
+ async listReachableConversations(botId,options = {}) {
320
+ if(!this.#checkedDelivery?.capabilities?.includes('reachable-conversations-checked'))throw Object.assign(new Error('capability-unavailable'),{code:'capability-unavailable'});
321
+ return this.#withBotTransition(botId,async()=>{
322
+ const checked=await this.#checkedRuntime(botId,options.expectedFingerprint,options.signal);
323
+ const page=await checked.runtime.listReachableConversations({...options,signal:checked.signal});
324
+ checked.signal.throwIfAborted();
325
+ if(this.#closed)throw Object.assign(new Error('provider-unavailable'),{code:'provider-unavailable'});
326
+ return page;
327
+ });
328
+ }
329
+
330
+ async postConversationChecked(botId,id,text,options = {}) {
331
+ if(!this.#checkedDelivery?.capabilities?.includes('reachable-conversations-checked'))throw Object.assign(new Error('capability-unavailable'),{code:'capability-unavailable'});
332
+ return this.#withBotTransition(botId,async()=>{
333
+ const checked=await this.#checkedRuntime(botId,options.expectedFingerprint,options.signal);
334
+ return checked.runtime.postConversationChecked(id,text,{...options,signal:checked.signal,beforeSend:()=>{
335
+ if(this.#closed)throw Object.assign(new Error('provider-unavailable'),{code:'provider-unavailable'});
336
+ checked.signal.throwIfAborted();
337
+ const allowed=options.beforeSend?.()===true;
338
+ checked.signal.throwIfAborted();
339
+ if(this.#closed)throw Object.assign(new Error('provider-unavailable'),{code:'provider-unavailable'});
340
+ return allowed;
341
+ }});
342
+ });
343
+ }
344
+
319
345
  async qualifyReplyChecked(botId, route, options = {}) {
320
346
  return this.#withBotTransition(botId, async () => {
321
347
  const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
@@ -0,0 +1,136 @@
1
+ import { slackRefusal, slackTimestamp } from './external-consumer.mjs';
2
+
3
+ const channelId = (value) => typeof value === 'string' && /^[CG][A-Z0-9]{4,30}$/.test(value);
4
+ const denied = (error) =>
5
+ [
6
+ 'missing_scope',
7
+ 'not_in_channel',
8
+ 'channel_not_found',
9
+ 'is_archived',
10
+ 'no_permission',
11
+ 'restricted_action',
12
+ 'restricted_action_read_only_channel',
13
+ 'access_denied',
14
+ ].includes(error?.providerCode);
15
+
16
+ function preflightFailure(error, checked) {
17
+ if (checked.signal.aborted) return slackRefusal('cancelled');
18
+ if (
19
+ ['send-permission-denied', 'capability-unavailable', 'cancelled', 'bad-request'].includes(
20
+ error?.code,
21
+ )
22
+ )
23
+ return error;
24
+ return slackRefusal(denied(error) ? 'send-permission-denied' : 'send-preflight-unavailable');
25
+ }
26
+
27
+ function canSpeak(channel, account) {
28
+ if (
29
+ !channelId(channel?.id) ||
30
+ channel.is_member !== true ||
31
+ channel.is_archived === true ||
32
+ channel.is_im === true ||
33
+ channel.is_mpim === true ||
34
+ (channel.is_channel !== true && channel.is_group !== true)
35
+ )
36
+ return false;
37
+ const restriction = channel.properties?.posting_restricted_to;
38
+ if (restriction === undefined) return true;
39
+ if (!restriction || typeof restriction !== 'object') return false;
40
+ for (const field of ['user', 'subteam', 'type']) {
41
+ if (
42
+ restriction[field] !== undefined &&
43
+ (!Array.isArray(restriction[field]) ||
44
+ restriction[field].some((value) => typeof value !== 'string'))
45
+ )
46
+ return false;
47
+ }
48
+ if (restriction.user?.includes(account.userId)) return true;
49
+ return ['user', 'subteam', 'type'].every((field) => !restriction[field]?.length);
50
+ }
51
+
52
+ async function inspect(checked, id) {
53
+ checked.assertCurrent();
54
+ const channel = await checked.api.conversationInfo({ channelId: id, signal: checked.signal });
55
+ checked.assertCurrent();
56
+ const scopes = checked.api.postingScopes();
57
+ if (!(scopes instanceof Set)) throw slackRefusal('send-preflight-unavailable');
58
+ if (!scopes.has('chat:write') || channel?.id !== id || !canSpeak(channel, checked.account))
59
+ throw slackRefusal('send-permission-denied');
60
+ return channel;
61
+ }
62
+
63
+ export async function listSlackReachable(checked, { cursor } = {}) {
64
+ if (cursor !== undefined && (typeof cursor !== 'string' || !cursor || cursor.length > 2048))
65
+ throw slackRefusal('bad-request');
66
+ try {
67
+ checked.assertCurrent();
68
+ const page = await checked.api.userConversations({
69
+ signal: checked.signal,
70
+ ...(cursor ? { cursor } : {}),
71
+ });
72
+ checked.assertCurrent();
73
+ if (!Array.isArray(page?.channels) || page.channels.length > 100)
74
+ throw slackRefusal('send-preflight-unavailable');
75
+ const conversations = [];
76
+ for (const row of page.channels) {
77
+ if (!channelId(row?.id)) continue;
78
+ try {
79
+ const channel = await inspect(checked, row.id);
80
+ conversations.push({
81
+ id: channel.id,
82
+ kind: 'group',
83
+ name: typeof channel.name === 'string' && channel.name ? channel.name : channel.id,
84
+ });
85
+ } catch (error) {
86
+ if (error?.code !== 'send-permission-denied' && !denied(error)) throw error;
87
+ }
88
+ }
89
+ checked.assertCurrent();
90
+ const next = page.response_metadata?.next_cursor;
91
+ if (next !== undefined && (typeof next !== 'string' || next.length > 2048 || next === cursor))
92
+ throw slackRefusal('send-preflight-unavailable');
93
+ return { version: 1, conversations, hasMore: !!next, ...(next ? { cursor: next } : {}) };
94
+ } catch (error) {
95
+ throw preflightFailure(error, checked);
96
+ }
97
+ }
98
+
99
+ export async function postSlackConversation(checked, id, text, { beforeSend } = {}) {
100
+ if (
101
+ !channelId(id) ||
102
+ typeof text !== 'string' ||
103
+ !text.trim() ||
104
+ text.length > 4000 ||
105
+ typeof beforeSend !== 'function'
106
+ )
107
+ throw slackRefusal('bad-request');
108
+ try {
109
+ await inspect(checked, id);
110
+ } catch (error) {
111
+ throw preflightFailure(error, checked);
112
+ }
113
+ checked.assertCurrent();
114
+ if (beforeSend() !== true) throw slackRefusal('send-permission-denied');
115
+ checked.assertCurrent();
116
+ let sent;
117
+ try {
118
+ sent = await checked.api.postMessage({
119
+ channelId: id,
120
+ text,
121
+ signal: checked.signal,
122
+ retry: false,
123
+ });
124
+ } catch (error) {
125
+ throw slackRefusal(denied(error) ? 'send-permission-denied' : 'send-result-unknown');
126
+ }
127
+ if (
128
+ !slackTimestamp(sent?.ts) ||
129
+ sent.channel !== id ||
130
+ (sent.message?.user !== undefined && sent.message.user !== checked.account.userId) ||
131
+ (sent.message?.bot_id !== undefined && sent.message.bot_id !== checked.account.botId) ||
132
+ (sent.message?.app_id !== undefined && sent.message.app_id !== checked.account.appId)
133
+ )
134
+ throw slackRefusal('send-result-unknown');
135
+ return { sent: true, receipt: { version: 1, messageId: sent.ts, conversationId: id } };
136
+ }
@@ -249,6 +249,14 @@ export class SlackApi {
249
249
  return value.channel;
250
250
  }
251
251
 
252
+ userConversations({ cursor, signal } = {}) {
253
+ return this.#request('users.conversations', { tokenKind: 'bot', signal,
254
+ body: { types: 'public_channel,private_channel', exclude_archived: true, limit: 100,
255
+ ...(cursor ? { cursor } : {}) } });
256
+ }
257
+
258
+ postingScopes() { return this.#botScopes ? new Set(this.#botScopes) : null; }
259
+
252
260
  async threadMessage({ channelId, threadTs, messageTs, signal } = {}) {
253
261
  const value = await this.#request('conversations.replies', { tokenKind: 'bot', signal,
254
262
  body: { channel: slackId(channelId, 'channel id'), ts: requiredString(threadTs, 'thread timestamp'),
@@ -559,7 +567,7 @@ export class SlackApi {
559
567
  const token = tokenKind === 'app' ? this.#appToken : this.#botToken;
560
568
  if (!token) throw new TypeError(`Slack ${tokenKind} token is required for ${method}`);
561
569
  const formEncoded = ['files.getUploadURLExternal', 'files.info', 'bots.info', 'users.info',
562
- 'conversations.info', 'conversations.history', 'conversations.replies'].includes(method);
570
+ 'conversations.info', 'conversations.history', 'conversations.replies', 'users.conversations'].includes(method);
563
571
  let response;
564
572
  try {
565
573
  response = await this.#fetch(new URL(method, this.#baseUrl), {
@@ -240,8 +240,7 @@ export class SlackController {
240
240
  const account = await this.#deliveryAccount(config);
241
241
  return { version: 1, botId, channel: 'slack', account,
242
242
  connected: this.#runtimes.get(botId)?.status?.ready === true,
243
- capabilities: ['proactive-text-checked', 'proactive-receipt-checked', 'exclusive-text-consumer', 'ordinary-text-consumer', 'reply-text-checked',
244
- 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'reply-mention-checked',
243
+ capabilities: ['proactive-text-checked', 'proactive-receipt-checked', 'proactive-fence-checked', 'reachable-conversations-checked', 'exclusive-text-consumer', 'ordinary-text-consumer', 'reply-text-checked', 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'reply-mention-checked',
245
244
  'history-text-checked', 'thread-history-text-checked', 'source-file-checked', 'reply-file-checked'] };
246
245
  });
247
246
  }
@@ -283,6 +282,30 @@ export class SlackController {
283
282
  });
284
283
  }
285
284
 
285
+ async listReachableConversations(botId, options = {}) {
286
+ return this.#withBotTransition(botId, async () => {
287
+ const checked=await this.#checkedRuntime(botId,options.expectedFingerprint,options.signal);
288
+ const page=await checked.runtime.listReachableConversations({...options,signal:checked.signal});
289
+ checked.signal.throwIfAborted();
290
+ if(this.#closed) throw slackRefusal('provider-unavailable');
291
+ return page;
292
+ });
293
+ }
294
+
295
+ async postConversationChecked(botId,id,text,options = {}) {
296
+ return this.#withBotTransition(botId, async () => {
297
+ const checked=await this.#checkedRuntime(botId,options.expectedFingerprint,options.signal);
298
+ return checked.runtime.postConversationChecked(id,text,{...options,signal:checked.signal,beforeSend:()=>{
299
+ if(this.#closed) throw slackRefusal('provider-unavailable');
300
+ checked.signal.throwIfAborted();
301
+ const allowed=options.beforeSend?.()===true;
302
+ checked.signal.throwIfAborted();
303
+ if(this.#closed) throw slackRefusal('provider-unavailable');
304
+ return allowed;
305
+ }});
306
+ });
307
+ }
308
+
286
309
  async externalFileChecked(botId, route, file, options = {}) {
287
310
  return this.#withBotTransition(botId, async () => {
288
311
  const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);