@botharness/im-provider 4.32.0-botharness.15 → 4.32.0-botharness.20
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.
- package/PROVENANCE.json +8 -8
- package/lib/client.js +9 -5
- package/lib/index.js +305 -308
- package/package.json +7 -5
- package/plugin-src/host/app-setup.mjs +244 -0
- package/plugin-src/host/build.mjs +3 -2
- package/plugin-src/host/channels/qq/production.mjs +6 -1
- package/plugin-src/host/channels/shared/startup.mjs +3 -0
- package/plugin-src/host/delivery-adapter.mjs +15 -0
- package/plugin-src/host/delivery-service.mjs +103 -3
- package/plugin-src/host/index.mjs +15 -2
- package/plugin-src/host/qq-sdk-observation-patch.mjs +53 -0
- package/src/channels/discord/discord-api.mjs +9 -0
- package/src/channels/discord/discord-controller.mjs +1 -2
- package/src/channels/discord/discord-runtime.mjs +13 -0
- package/src/channels/discord/reachable-conversations.mjs +211 -0
- package/src/channels/feishu/external-cards.mjs +63 -6
- package/src/channels/feishu/external-reactions.mjs +36 -0
- package/src/channels/feishu/feishu-runtime.mjs +95 -2
- package/src/channels/feishu/multi-bot-controller.mjs +78 -4
- package/src/channels/qq/config-store.mjs +1 -0
- package/src/channels/qq/external-addressing.mjs +6 -0
- package/src/channels/qq/external-consumer.mjs +207 -0
- package/src/channels/qq/external-files.mjs +50 -0
- package/src/channels/qq/external-images.mjs +109 -0
- package/src/channels/qq/external-mentions.mjs +32 -0
- package/src/channels/qq/external-post.mjs +51 -0
- package/src/channels/qq/external-voice.mjs +32 -0
- package/src/channels/qq/native-gateway-diagnostics.mjs +86 -0
- package/src/channels/qq/native-reply-observations.mjs +143 -0
- package/src/channels/qq/native-transport-diagnostics.mjs +42 -0
- package/src/channels/qq/qq-controller.mjs +104 -1
- package/src/channels/qq/qq-runtime.mjs +256 -12
- package/src/channels/qq/sdk-frame-observation.mjs +31 -0
- package/src/channels/qq/voice-attachment.mjs +3 -0
- package/src/channels/shared/i18n-en/qq.mjs +4 -0
- package/src/channels/shared/i18n-en/weixin.mjs +1 -0
- package/src/channels/shared/token-bot-controller.mjs +26 -0
- package/src/channels/slack/reachable-conversations.mjs +136 -0
- package/src/channels/slack/slack-api.mjs +9 -1
- package/src/channels/slack/slack-controller.mjs +25 -2
- package/src/channels/slack/slack-runtime.mjs +23 -0
- package/src/channels/weixin/connection-error.en.mjs +1 -0
- package/src/channels/weixin/connection-error.mjs +1 -0
- 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,12 @@ 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
|
+
#externalBridge = null;
|
|
50
61
|
|
|
51
62
|
constructor({
|
|
52
63
|
config,
|
|
@@ -60,6 +71,10 @@ export class QqRuntime {
|
|
|
60
71
|
connectTimeoutMs = 20_000,
|
|
61
72
|
createBot = (options) => new QQBot(options),
|
|
62
73
|
typingMiddleware = typingIndicator,
|
|
74
|
+
externalConsumer,
|
|
75
|
+
sourceImages = () => false,
|
|
76
|
+
sourceFiles = () => false,
|
|
77
|
+
sourceVoiceTranscripts = () => false, sourceVoiceAudio = () => false,
|
|
63
78
|
}) {
|
|
64
79
|
if (!config || !appSecret || !harness || !state) {
|
|
65
80
|
throw new TypeError('QqRuntime requires config, app secret, Harness, and state');
|
|
@@ -75,12 +90,77 @@ export class QqRuntime {
|
|
|
75
90
|
this.#connectTimeoutMs = connectTimeoutMs;
|
|
76
91
|
this.#createBot = createBot;
|
|
77
92
|
this.#typingMiddleware = typingMiddleware;
|
|
93
|
+
this.#externalConsumer = externalConsumer;
|
|
94
|
+
this.#sourceImages = sourceImages;
|
|
95
|
+
this.#sourceFiles = sourceFiles;
|
|
96
|
+
this.#sourceVoiceTranscripts = sourceVoiceTranscripts;
|
|
97
|
+
this.#sourceVoiceAudio = sourceVoiceAudio;
|
|
78
98
|
}
|
|
79
99
|
|
|
80
100
|
get status() {
|
|
81
101
|
return structuredClone(this.#status);
|
|
82
102
|
}
|
|
83
103
|
|
|
104
|
+
async describeDeliveryAccount(signal) {
|
|
105
|
+
signal?.throwIfAborted();
|
|
106
|
+
if (!this.#status.ready || !this.#bot) throw qqRefusal('bot-not-connected');
|
|
107
|
+
const bot = this.#bot;
|
|
108
|
+
try {
|
|
109
|
+
const user = await bot.api.get('/users/@me');
|
|
110
|
+
signal?.throwIfAborted();
|
|
111
|
+
if (this.#bot !== bot || !this.#status.ready) throw qqRefusal('bot-not-connected');
|
|
112
|
+
const account = verifiedQqAccount(this.#config.appId, user);
|
|
113
|
+
if (this.#status.error?.details?.stage === 'credential.verify') {
|
|
114
|
+
this.#status.error = null;
|
|
115
|
+
this.#status.lastError = null;
|
|
116
|
+
}
|
|
117
|
+
return account;
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (!signal?.aborted && this.#bot === bot) {
|
|
120
|
+
const qualificationHints = {
|
|
121
|
+
'application-id': t('QQ 应用标识无效。'),
|
|
122
|
+
'native-user-id': t('QQ 账号响应未提供有效的原生用户标识。'),
|
|
123
|
+
'native-bot-flag': t('QQ 账号响应返回了无效或矛盾的机器人标志。'),
|
|
124
|
+
};
|
|
125
|
+
this.#status.error = this.#diagnostics.report(error, { operation: 'connection.status',
|
|
126
|
+
stage: 'credential.verify', botId: this.#config.botId,
|
|
127
|
+
httpStatus: error?.httpStatus, providerCode: error?.bizCode,
|
|
128
|
+
...(error?.code === 'account-unverified' ? { publicError: {
|
|
129
|
+
code: 'account-unverified', message: t('QQ 账号资格验证失败。'),
|
|
130
|
+
details: { reason: 'invalid-response', hint: qualificationHints[error.verificationFailure] },
|
|
131
|
+
} } : {}),
|
|
132
|
+
}).publicError;
|
|
133
|
+
this.#status.lastError = this.#status.error.message;
|
|
134
|
+
}
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
qualifyReplyChecked(route, { signal } = {}) {
|
|
140
|
+
if (!this.#externalBridge) throw qqRefusal('consumer-unavailable');
|
|
141
|
+
return this.#externalBridge.qualify(route, signal);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
replyChecked(route, text, options) {
|
|
145
|
+
if (!this.#externalBridge) throw qqRefusal('consumer-unavailable');
|
|
146
|
+
return this.#externalBridge.reply(route, text, options);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
readSourceImage(route, attachment, options) {
|
|
150
|
+
if (!this.#externalBridge) throw qqRefusal('consumer-unavailable');
|
|
151
|
+
return this.#externalBridge.readImage(route, attachment, options);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
readSourceFile(route, attachment, options) {
|
|
155
|
+
if (!this.#externalBridge) throw qqRefusal('consumer-unavailable');
|
|
156
|
+
return this.#externalBridge.readFile(route, attachment, options);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
replyFileChecked(route, file, options) {
|
|
160
|
+
if (!this.#externalBridge) throw qqRefusal('consumer-unavailable');
|
|
161
|
+
return this.#externalBridge.replyFile(route, file, options);
|
|
162
|
+
}
|
|
163
|
+
|
|
84
164
|
async sendConnectionTest(text) {
|
|
85
165
|
if (!this.#status.ready || !this.#bot) {
|
|
86
166
|
throw connectionTestTargetUnavailable(t('QQ机器人'));
|
|
@@ -103,7 +183,45 @@ export class QqRuntime {
|
|
|
103
183
|
return { sent: true };
|
|
104
184
|
}
|
|
105
185
|
|
|
106
|
-
async sendProactiveText(target, text, { signal } = {}) {
|
|
186
|
+
async sendProactiveText(target, text, { signal, expectedFingerprint, beforeSend, verifyAccount } = {}) {
|
|
187
|
+
if (expectedFingerprint !== undefined) {
|
|
188
|
+
const bot = this.#bot;
|
|
189
|
+
const bridge = this.#externalBridge;
|
|
190
|
+
if (!bot || !this.#status.ready || !this.#abortController) throw qqRefusal('bot-not-connected');
|
|
191
|
+
const sendSignal = signal ? AbortSignal.any([signal, this.#abortController.signal]) : this.#abortController.signal;
|
|
192
|
+
const started = Date.now();
|
|
193
|
+
const report = (phase, reason, nativePost) => {
|
|
194
|
+
try {
|
|
195
|
+
this.#logger.info?.('[dsh-im:qq] checked post', { event: 'qq-external-post',
|
|
196
|
+
initiator: 'external-consumer', phase, durationMs: Math.max(0, Date.now() - started),
|
|
197
|
+
...(reason ? { reason } : {}),
|
|
198
|
+
...(nativePost ? { stage: 'native-post',
|
|
199
|
+
...(Number.isInteger(nativePost.httpStatus) && nativePost.httpStatus >= 100 && nativePost.httpStatus <= 599
|
|
200
|
+
? { httpStatus: nativePost.httpStatus } : {}),
|
|
201
|
+
...(Number.isSafeInteger(nativePost.providerCode) && nativePost.providerCode >= 0
|
|
202
|
+
? { providerCode: nativePost.providerCode } : {}),
|
|
203
|
+
} : {}) });
|
|
204
|
+
} catch {}
|
|
205
|
+
};
|
|
206
|
+
report('preparing');
|
|
207
|
+
let nativePostEvidence;
|
|
208
|
+
try {
|
|
209
|
+
const result = await postQqText({ bot, target, text, signal: sendSignal, beforeSend, verifyAccount,
|
|
210
|
+
onNativeFailure: evidence => { nativePostEvidence = evidence; },
|
|
211
|
+
assertCurrent: () => {
|
|
212
|
+
if (this.#bot !== bot || !this.#status.ready) throw qqRefusal('bot-not-connected');
|
|
213
|
+
} });
|
|
214
|
+
bridge?.recordNativeReceipt(result.receipt, sendSignal);
|
|
215
|
+
report('accepted', 'native-receipt');
|
|
216
|
+
return result;
|
|
217
|
+
} catch (error) {
|
|
218
|
+
const reason = ['invalid-target', 'bad-request', 'cancelled', 'provider-unavailable',
|
|
219
|
+
'account-changed', 'consumer-unavailable', 'bot-not-connected', 'send-permission-denied',
|
|
220
|
+
'send-rate-limited', 'send-result-unknown'].includes(error?.code) ? error.code : 'operation-failed';
|
|
221
|
+
report(reason === 'send-result-unknown' ? 'unknown' : 'refused', reason, nativePostEvidence);
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
107
225
|
const nativeId = target?.kind === 'user'
|
|
108
226
|
? (typeof target?.route?.userOpenId === 'string' ? target.route.userOpenId.trim() : '')
|
|
109
227
|
: target?.kind === 'group'
|
|
@@ -140,14 +258,47 @@ export class QqRuntime {
|
|
|
140
258
|
this.#status.startedAt = new Date().toISOString();
|
|
141
259
|
this.#status.qqConnectionState = 'connecting';
|
|
142
260
|
this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
|
|
143
|
-
|
|
261
|
+
delete this.#status.transportObservation;
|
|
262
|
+
if (this.#config.consumerMode !== 'external-consumer')
|
|
263
|
+
await atConnectionStage('harness.check', () => this.#harness.ensureRunning());
|
|
144
264
|
this.#status.harnessReachable = true;
|
|
145
265
|
|
|
266
|
+
const controller = new AbortController();
|
|
267
|
+
this.#abortController = controller;
|
|
268
|
+
const observeTransport = (message) => {
|
|
269
|
+
if (controller.signal.aborted || this.#abortController !== controller || typeof message !== 'string') return;
|
|
270
|
+
// SDK 1.0.4 exposes close through its public Logger, not a disconnect event.
|
|
271
|
+
if (message.startsWith(`[${this.#config.botId}] WebSocket closed:`)
|
|
272
|
+
|| message.startsWith(`[${this.#config.botId}] Connection failed:`)
|
|
273
|
+
|| message.startsWith(`[${this.#config.botId}] Connecting to `)) {
|
|
274
|
+
this.#status.ready = false;
|
|
275
|
+
this.#status.qqConnectionState = 'connecting';
|
|
276
|
+
} else if (message === `[${this.#config.botId}] Max reconnect attempts reached or aborted`) {
|
|
277
|
+
this.#status.ready = false;
|
|
278
|
+
this.#status.qqConnectionState = 'failed';
|
|
279
|
+
} else return false;
|
|
280
|
+
this.#logger.info?.(`[dsh-im:qq] ${JSON.stringify({ event: 'receiver-state',
|
|
281
|
+
botId: this.#config.botId, phase: this.#status.qqConnectionState })}`);
|
|
282
|
+
return true;
|
|
283
|
+
};
|
|
284
|
+
let gatewayDiagnostics;
|
|
285
|
+
let transportDiagnostics;
|
|
146
286
|
const sdkLogger = {
|
|
147
|
-
error: (...args) =>
|
|
287
|
+
error: (...args) => {
|
|
288
|
+
// Node's JSON error text can quote the payload. The maintained hook reports
|
|
289
|
+
// only the coded parse/processing disposition; never forward that raw text.
|
|
290
|
+
if (transportDiagnostics && typeof args[0] === 'string'
|
|
291
|
+
&& args[0].startsWith(`[${this.#config.botId}] Message parse error:`)) return;
|
|
292
|
+
if (!observeTransport(args[0])) this.#logger.error?.(...args);
|
|
293
|
+
},
|
|
148
294
|
warn: (...args) => this.#logger.warn?.(...args),
|
|
149
|
-
info: (...args) => this.#logger.info?.(...args),
|
|
150
|
-
debug:
|
|
295
|
+
info: (...args) => { if (!observeTransport(args[0])) this.#logger.info?.(...args); },
|
|
296
|
+
debug: message => {
|
|
297
|
+
try {
|
|
298
|
+
if (!controller.signal.aborted && this.#abortController === controller)
|
|
299
|
+
gatewayDiagnostics?.observe(message, controller.signal, transportDiagnostics?.context);
|
|
300
|
+
} catch {}
|
|
301
|
+
},
|
|
151
302
|
};
|
|
152
303
|
const bot = this.#createBot({
|
|
153
304
|
appId: this.#config.appId,
|
|
@@ -156,6 +307,13 @@ export class QqRuntime {
|
|
|
156
307
|
logger: sdkLogger,
|
|
157
308
|
transport: 'websocket',
|
|
158
309
|
tokenPrefetch: 'sync',
|
|
310
|
+
// Public option proposed by the maintained, hash-checked SDK build patch.
|
|
311
|
+
onGatewayObservation: value => {
|
|
312
|
+
if (!controller.signal.aborted && this.#abortController === controller) {
|
|
313
|
+
transportDiagnostics?.observe(value, controller.signal);
|
|
314
|
+
if (transportDiagnostics) this.#status.transportObservation = transportDiagnostics.snapshot;
|
|
315
|
+
}
|
|
316
|
+
},
|
|
159
317
|
// sendText is reserved for literal notices/connection tests. Markdown
|
|
160
318
|
// replies use the explicit msg_type=2 path in sendMarkdownReply().
|
|
161
319
|
markdownSupport: false,
|
|
@@ -163,10 +321,31 @@ export class QqRuntime {
|
|
|
163
321
|
if (!bot || typeof bot.start !== 'function' || typeof bot.stop !== 'function') {
|
|
164
322
|
throw new TypeError('QQ bot factory returned an invalid client');
|
|
165
323
|
}
|
|
166
|
-
const controller = new AbortController();
|
|
167
|
-
this.#abortController = controller;
|
|
168
324
|
this.#bot = bot;
|
|
169
|
-
this.#
|
|
325
|
+
if (this.#config.consumerMode === 'external-consumer' && this.#externalConsumer) {
|
|
326
|
+
try {
|
|
327
|
+
const nativeUser = await bot.api.get('/users/@me');
|
|
328
|
+
const account = verifiedQqAccount(this.#config.appId, nativeUser);
|
|
329
|
+
controller.signal.throwIfAborted();
|
|
330
|
+
gatewayDiagnostics = new QqNativeGatewayDiagnostics({ botId: this.#config.botId, account,
|
|
331
|
+
report: record => this.#logger.info?.('[dsh-im:qq] native gateway diagnostic', record) });
|
|
332
|
+
transportDiagnostics = new QqNativeTransportDiagnostics({ account,
|
|
333
|
+
report: record => this.#logger.info?.('[dsh-im:qq] native transport diagnostic', record) });
|
|
334
|
+
this.#externalBridge = new QqExternalConsumer({ bot, account, nativeUser, botId: this.#config.botId,
|
|
335
|
+
accept: this.#externalConsumer,
|
|
336
|
+
sourceImages: this.#sourceImages,
|
|
337
|
+
sourceFiles: this.#sourceFiles,
|
|
338
|
+
sourceVoiceTranscripts: this.#sourceVoiceTranscripts,
|
|
339
|
+
sourceVoiceAudio: this.#sourceVoiceAudio,
|
|
340
|
+
reportNativeObservation: record => this.#logger.info?.('[dsh-im:qq] native reply observation', record),
|
|
341
|
+
reportNativeFrame: record => this.#logger.info?.('[dsh-im:qq] native reply frame', record),
|
|
342
|
+
});
|
|
343
|
+
} catch (error) {
|
|
344
|
+
await this.stop();
|
|
345
|
+
throw error;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
this.#bridge = this.#config.consumerMode === 'external-consumer' ? null : new QqHarnessBridge({
|
|
170
349
|
bot,
|
|
171
350
|
ownerUserOpenid: this.#config.ownerUserOpenid,
|
|
172
351
|
harness: this.#harness,
|
|
@@ -182,7 +361,7 @@ export class QqRuntime {
|
|
|
182
361
|
// tags. Parse them into readable text so the Harness sees what the sender
|
|
183
362
|
// actually meant instead of an unusable markup fragment.
|
|
184
363
|
bot.use(contentSanitizer({ parseFaceTags: true }));
|
|
185
|
-
bot.use?.(this.#typingMiddleware({
|
|
364
|
+
if (this.#config.consumerMode !== 'external-consumer') bot.use?.(this.#typingMiddleware({
|
|
186
365
|
keepAlive: true,
|
|
187
366
|
predicate: (ctx) => {
|
|
188
367
|
const message = ctx?.message;
|
|
@@ -208,6 +387,7 @@ export class QqRuntime {
|
|
|
208
387
|
readyReject = reject;
|
|
209
388
|
});
|
|
210
389
|
const onReady = () => {
|
|
390
|
+
if (controller.signal.aborted || this.#bot !== bot) return;
|
|
211
391
|
const now = Date.now();
|
|
212
392
|
this.#status.ready = true;
|
|
213
393
|
this.#status.qqConnectionState = 'connected';
|
|
@@ -217,18 +397,81 @@ export class QqRuntime {
|
|
|
217
397
|
readyResolve();
|
|
218
398
|
};
|
|
219
399
|
const onError = (error) => {
|
|
400
|
+
if (controller.signal.aborted || this.#bot !== bot) return;
|
|
220
401
|
if (!this.#status.ready) readyReject(error);
|
|
221
402
|
else {
|
|
222
403
|
this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#config?.botId, automatic: true }).publicError;
|
|
223
404
|
this.#status.lastError = this.#status.error.message;
|
|
224
405
|
this.#logger.warn?.(`[dsh-im:qq] bot ${this.#config.botId} connection error:`, extractConnectionEvidence(error).details);
|
|
225
406
|
}
|
|
407
|
+
this.#status.ready = false;
|
|
408
|
+
this.#status.qqConnectionState = 'connecting';
|
|
226
409
|
};
|
|
227
|
-
const onMessage = (_ctx, message) => {
|
|
228
|
-
|
|
410
|
+
const onMessage = async (_ctx, message) => {
|
|
411
|
+
if (controller.signal.aborted || this.#bot !== bot) return;
|
|
412
|
+
const elements = Array.isArray(message?.raw?.msg_elements) ? message.raw.msg_elements : [];
|
|
413
|
+
const quotedAttachments = elements.slice(0, 2).flatMap(element => Array.isArray(element?.attachments)
|
|
414
|
+
? element.attachments.slice(0, 33) : []);
|
|
415
|
+
const quotedFiles = quotedAttachments.filter(file => file?.content_type === 'file');
|
|
416
|
+
const lastInbound = {
|
|
417
|
+
observedAt: new Date().toISOString(),
|
|
418
|
+
eventType: ['GROUP_AT_MESSAGE_CREATE', 'GROUP_MESSAGE_CREATE', 'C2C_MESSAGE_CREATE'].includes(message?.rawEventType)
|
|
419
|
+
? message.rawEventType : 'other',
|
|
420
|
+
messageType: Number.isSafeInteger(message?.msgType) ? message.msgType : null,
|
|
421
|
+
mentionCount: Array.isArray(message?.mentions) ? Math.min(message.mentions.length, 128) : 0,
|
|
422
|
+
explicitSelfMention: Array.isArray(message?.mentions) && message.mentions.some(mention => mention?.is_you === true),
|
|
423
|
+
textPresent: typeof message?.content === 'string' && !!message.content.trim(),
|
|
424
|
+
directAttachments: Array.isArray(message?.attachments) ? Math.min(message.attachments.length, 33) : 0,
|
|
425
|
+
quotedElements: Math.min(elements.length, 2), quotedFiles: Math.min(quotedFiles.length, 33),
|
|
426
|
+
quoteIndexMatches: typeof message?.refMsgIdx === 'string' && message.refMsgIdx.length > 0
|
|
427
|
+
&& elements.length === 1 && elements[0]?.msg_idx === message.refMsgIdx,
|
|
428
|
+
};
|
|
429
|
+
if (message?.msgType === 103) {
|
|
430
|
+
const attachmentShape = value => value === undefined ? 'absent' : value === null ? 'null'
|
|
431
|
+
: Array.isArray(value) ? value.length ? 'nonempty-array' : 'empty-array' : 'other';
|
|
432
|
+
lastInbound.quoteShape = {
|
|
433
|
+
directAttachments: attachmentShape(message.attachments),
|
|
434
|
+
rawDirectAttachments: attachmentShape(message.raw?.attachments),
|
|
435
|
+
elementFields: elements[0] && typeof elements[0] === 'object'
|
|
436
|
+
? Object.keys(elements[0]).filter(key => /^[a-z_]{1,32}$/.test(key)).sort().slice(0, 16) : [],
|
|
437
|
+
elementMessageType: Number.isSafeInteger(elements[0]?.message_type) && elements[0].message_type >= 0
|
|
438
|
+
? elements[0].message_type : null,
|
|
439
|
+
normalizedElementMatches: Array.isArray(message.msgElements) && message.msgElements.length === 1
|
|
440
|
+
&& elements.length === 1 && message.msgElements[0]?.msg_idx === elements[0]?.msg_idx,
|
|
441
|
+
files: quotedFiles.slice(0, 2).map(file => ({
|
|
442
|
+
urlPresent: typeof file.url === 'string' && file.url.length > 0,
|
|
443
|
+
httpsUrl: typeof file.url === 'string' && file.url.startsWith('https://'),
|
|
444
|
+
sizeType: file.size === undefined ? 'absent' : file.size === null ? 'null'
|
|
445
|
+
: ['string', 'number'].includes(typeof file.size) ? typeof file.size : 'other',
|
|
446
|
+
sizeValid: file.size === undefined || (Number.isSafeInteger(file.size) && file.size > 0),
|
|
447
|
+
})),
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
const voices = [...(Array.isArray(message?.attachments) ? message.attachments.slice(0, 2) : []), ...quotedAttachments.slice(0, 2)]
|
|
451
|
+
.filter(isQqVoiceAttachment);
|
|
452
|
+
if (voices.length) lastInbound.voice = {
|
|
453
|
+
count: Math.min(voices.length, 2),
|
|
454
|
+
quotedAttachmentCount: Math.min(quotedAttachments.length, 8),
|
|
455
|
+
quotedCategories: quotedAttachments.slice(0, 4).map(file => {
|
|
456
|
+
const type = file?.content_type;
|
|
457
|
+
return typeof type === 'string' && /^(?:voice|file|image|audio\/[a-z0-9!#$&^_.+-]+|image\/[a-z0-9!#$&^_.+-]+)$/i.test(type)
|
|
458
|
+
? type.slice(0, 64) : typeof type;
|
|
459
|
+
}),
|
|
460
|
+
platformTranscriptPresent: voices.some(file => typeof file.asr_refer_text === 'string' && !!file.asr_refer_text.trim()),
|
|
461
|
+
platformWavPresent: voices.some(file => typeof file.voice_wav_url === 'string' && !!file.voice_wav_url),
|
|
462
|
+
};
|
|
463
|
+
this.#status.lastInbound = lastInbound;
|
|
464
|
+
const task = this.#config.consumerMode === 'external-consumer'
|
|
465
|
+
? this.#externalBridge?.accept(message, controller.signal)
|
|
466
|
+
: this.#bridge?.accept(message);
|
|
229
467
|
if (!task) return;
|
|
230
|
-
|
|
468
|
+
return task.catch((error) => {
|
|
231
469
|
if (controller.signal.aborted) return;
|
|
470
|
+
lastInbound.refusalCode = typeof error?.code === 'string' && /^[a-z-]{1,64}$/.test(error.code)
|
|
471
|
+
? error.code : 'message-handling-failed';
|
|
472
|
+
if (['quote-envelope-invalid', 'quote-reference-invalid', 'quote-elements-invalid',
|
|
473
|
+
'file-category-invalid', 'file-url-invalid', 'file-size-invalid'].includes(error?.reason))
|
|
474
|
+
lastInbound.refusalReason = error.reason;
|
|
232
475
|
this.#logger.error?.(
|
|
233
476
|
`[dsh-im:qq] bot ${this.#config.botId} message handling failed:`,
|
|
234
477
|
extractConnectionEvidence(error).details,
|
|
@@ -285,6 +528,7 @@ export class QqRuntime {
|
|
|
285
528
|
this.#abortController = null;
|
|
286
529
|
this.#bot = null;
|
|
287
530
|
this.#bridge = null;
|
|
531
|
+
this.#externalBridge = null;
|
|
288
532
|
this.#runTask = null;
|
|
289
533
|
try {
|
|
290
534
|
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
|
+
}
|
|
@@ -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);
|