@botharness/im-provider 4.32.0-botharness.3 → 4.32.0-botharness.4
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 +6 -6
- package/lib/client.js +2 -2
- package/lib/index.js +285 -285
- package/package.json +2 -2
- package/plugin-src/host/channels/weixin/production.mjs +2 -1
- package/plugin-src/host/delivery-adapter.mjs +7 -1
- package/src/channels/weixin/config-store.mjs +2 -0
- package/src/channels/weixin/external-consumer.mjs +51 -0
- package/src/channels/weixin/state-store.mjs +14 -1
- package/src/channels/weixin/weixin-api.mjs +15 -1
- package/src/channels/weixin/weixin-controller.mjs +84 -1
- package/src/channels/weixin/weixin-runtime.mjs +31 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botharness/im-provider",
|
|
3
|
-
"version": "4.32.0-botharness.
|
|
3
|
+
"version": "4.32.0-botharness.4",
|
|
4
4
|
"icon": "./assets/logo-plugin-message-link-gradient.webp",
|
|
5
5
|
"description": "BotHarness-qualified IM Provider, maintained from dsh-im",
|
|
6
6
|
"keywords": [
|
|
@@ -176,6 +176,6 @@
|
|
|
176
176
|
},
|
|
177
177
|
"botharness": {
|
|
178
178
|
"managedByProduct": true,
|
|
179
|
-
"upstreamSource": "
|
|
179
|
+
"upstreamSource": "589e5507d47ab21de5b39c776a598452744a5368"
|
|
180
180
|
}
|
|
181
181
|
}
|
|
@@ -157,7 +157,7 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
157
157
|
configStore: observedConfigStore,
|
|
158
158
|
logger,
|
|
159
159
|
diagnostics,
|
|
160
|
-
createRuntime: async ({ botId, config: accountConfig, token }) => {
|
|
160
|
+
createRuntime: async ({ botId, config: accountConfig, token, externalConsumer }) => {
|
|
161
161
|
const state = await stateFor(botId);
|
|
162
162
|
await workspaces.ensure(botId, {
|
|
163
163
|
defaultAgentPreset: config.agentPreset,
|
|
@@ -171,6 +171,7 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
171
171
|
api,
|
|
172
172
|
config: accountConfig,
|
|
173
173
|
token,
|
|
174
|
+
externalConsumer: (message, signal) => externalConsumer(message, state, signal),
|
|
174
175
|
harness: workspaceScope.harness,
|
|
175
176
|
state: workspaceScope.state,
|
|
176
177
|
contextEnhancement: { botId, getSettings: () => workspaces.contextEnhancementFor(botId) },
|
|
@@ -269,7 +269,13 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
|
|
|
269
269
|
ownsBot: (botId) => workspaces.has(botId),
|
|
270
270
|
listBots: () => workspaces.listBotIds(),
|
|
271
271
|
async listTargets(botId) {
|
|
272
|
-
|
|
272
|
+
let targets = [...workspaces.listDeliveryTargets(botId)];
|
|
273
|
+
if (channel === 'weixin' && typeof coreController.describeDeliveryAccount === 'function') {
|
|
274
|
+
const paired = await coreController.describeDeliveryAccount(botId);
|
|
275
|
+
targets = targets.filter(target => target.kind === 'user' && target.route?.toUserId === paired?.account?.ownerUserId);
|
|
276
|
+
if (paired?.account?.ownerUserId && !targets.some(target => target.kind === 'user' && target.route?.toUserId === paired.account.ownerUserId))
|
|
277
|
+
targets.push({ targetId: 'paired-owner', name: '扫码绑定者私聊', kind: 'user', route: { toUserId: paired.account.ownerUserId } });
|
|
278
|
+
}
|
|
273
279
|
const configured = new Map(
|
|
274
280
|
sessionSyncConfigs(workspaces, botId).map((target) => [target.targetId, target]),
|
|
275
281
|
);
|
|
@@ -57,6 +57,7 @@ function normalizeAccount(value, invalid = () => null) {
|
|
|
57
57
|
} catch (error) {
|
|
58
58
|
return invalid('.baseUrl', error?.code === 'untrusted-base-url' ? 'untrusted-api-url' : 'invalid-api-url');
|
|
59
59
|
}
|
|
60
|
+
if (value.consumerMode != null && value.consumerMode !== 'external-consumer') return invalid('.consumerMode', 'invalid-mode');
|
|
60
61
|
return Object.freeze({
|
|
61
62
|
botId,
|
|
62
63
|
accountId,
|
|
@@ -65,6 +66,7 @@ function normalizeAccount(value, invalid = () => null) {
|
|
|
65
66
|
baseUrl,
|
|
66
67
|
createdAt: cleanString(value.createdAt) ?? new Date().toISOString(),
|
|
67
68
|
connectedAt: cleanString(value.connectedAt),
|
|
69
|
+
...(value.consumerMode == null ? {} : { consumerMode: value.consumerMode }),
|
|
68
70
|
});
|
|
69
71
|
}
|
|
70
72
|
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { deriveWeixinBotIdentity, maskWeixinAccountId } from './config-store.mjs';
|
|
3
|
+
import { extractWeixinText, weixinMessageId } from './weixin-api.mjs';
|
|
4
|
+
|
|
5
|
+
export function weixinRefusal(code) { return Object.assign(new Error(code), { code }); }
|
|
6
|
+
const continuation = value => typeof value === 'string' && value.length > 0 && value.length <= 16384;
|
|
7
|
+
const id = value => typeof value === 'string' && value.length > 0 && value.length <= 512 && value.trim() === value;
|
|
8
|
+
|
|
9
|
+
/** Identity comes from the stored server-confirmed QR pairing, not a fabricated auth.test API.
|
|
10
|
+
* A different credential invalidates all grants even if its local reference is unchanged. */
|
|
11
|
+
export function pairedWeixinAccount(config, token) {
|
|
12
|
+
if (!id(config?.accountId) || !id(config?.ownerUserId) || !config.connectedAt || typeof token !== 'string' || !token.trim()
|
|
13
|
+
|| deriveWeixinBotIdentity(config.accountId).botId !== config.botId) throw weixinRefusal('account-unverified');
|
|
14
|
+
const credentialHash = createHash('sha256').update(token).digest('hex');
|
|
15
|
+
const identity = { provider: 'weixin', accountId: config.accountId, ownerUserId: config.ownerUserId,
|
|
16
|
+
baseUrl: config.baseUrl, credentialHash };
|
|
17
|
+
return Object.freeze({ accountId: config.accountId, ownerUserId: config.ownerUserId,
|
|
18
|
+
name: `微信 · ${maskWeixinAccountId(config.accountId)}`,
|
|
19
|
+
fingerprint: createHash('sha256').update(JSON.stringify(identity)).digest('hex') });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** First tracer is paired-owner plain text only. No group, mention, or thread is invented. */
|
|
23
|
+
export function normalizeWeixinExternalText(message, { botId, account }) {
|
|
24
|
+
if (message?.message_type !== 1 || message.from_user_id !== account.ownerUserId) return null;
|
|
25
|
+
if (message.to_user_id !== account.accountId) throw weixinRefusal('account-changed');
|
|
26
|
+
if (!Array.isArray(message.item_list) || !message.item_list.length
|
|
27
|
+
|| message.item_list.some(item => item?.type !== 1)) return null;
|
|
28
|
+
const messageId = weixinMessageId(message);
|
|
29
|
+
const text = extractWeixinText(message);
|
|
30
|
+
const time = typeof message.create_time_ms === 'string' ? Number(message.create_time_ms) : message.create_time_ms;
|
|
31
|
+
if (!messageId || !/^\d+$/.test(messageId) || !text?.trim() || text.length > 16000
|
|
32
|
+
|| !Number.isSafeInteger(time) || time <= 0 || !continuation(message.context_token)) throw weixinRefusal('invalid-inbound');
|
|
33
|
+
const at = new Date(time);
|
|
34
|
+
if (!Number.isFinite(at.getTime())) throw weixinRefusal('invalid-inbound');
|
|
35
|
+
const conversationId = account.ownerUserId;
|
|
36
|
+
return Object.freeze({ version: 1, channel: 'weixin', botId, fingerprint: account.fingerprint,
|
|
37
|
+
eventId: messageId, messageId, actor: Object.freeze({ kind: 'user', id: account.ownerUserId }),
|
|
38
|
+
conversation: Object.freeze({ kind: 'dm', id: conversationId }), mentions: Object.freeze([]),
|
|
39
|
+
mentionedAccount: false, at: at.toISOString(), text,
|
|
40
|
+
reply: Object.freeze({ messageId, conversationId, actorId: account.ownerUserId }),
|
|
41
|
+
replay: Object.freeze({ kind: 'provider-redelivery', resumeCursor: false, gapPossible: true }) });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function checkedWeixinRoute(route, account, source) {
|
|
45
|
+
if (!route || Object.keys(route).some(key => !['messageId', 'conversationId', 'actorId'].includes(key))
|
|
46
|
+
|| route.conversationId !== account.ownerUserId || route.actorId !== account.ownerUserId
|
|
47
|
+
|| !id(route.messageId) || !source || source.fingerprint !== account.fingerprint
|
|
48
|
+
|| source.actorId !== route.actorId || source.messageId !== route.messageId
|
|
49
|
+
|| source.expiresAt <= Date.now() || !continuation(source.contextToken)) throw weixinRefusal('stale-route');
|
|
50
|
+
return { messageId: route.messageId, conversationId: route.conversationId, actorId: route.actorId };
|
|
51
|
+
}
|
|
@@ -100,6 +100,7 @@ function normalizeState(value) {
|
|
|
100
100
|
return {
|
|
101
101
|
version: 1,
|
|
102
102
|
sessions,
|
|
103
|
+
externalReplySources: Object.fromEntries(Object.entries(value.externalReplySources ?? {}).filter(([key, entry]) => /^\d+$/.test(key) && entry?.messageId === key && entry.expiresAt > Date.now()).slice(-1000)),
|
|
103
104
|
...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}),
|
|
104
105
|
seenMessageIds: Array.isArray(value.seenMessageIds)
|
|
105
106
|
? value.seenMessageIds.filter((id) => typeof id === 'string').slice(-1_000)
|
|
@@ -166,6 +167,18 @@ export class WeixinStateStore {
|
|
|
166
167
|
await this.#persist();
|
|
167
168
|
}
|
|
168
169
|
|
|
170
|
+
externalReplySource(messageId) {
|
|
171
|
+
return structuredClone(this.#state.externalReplySources?.[messageId]);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async rememberExternalReplySource(source) {
|
|
175
|
+
const entries = Object.entries(this.#state.externalReplySources ?? {})
|
|
176
|
+
.filter(([key, value]) => key !== source.messageId && value.expiresAt > Date.now()).slice(-999);
|
|
177
|
+
entries.push([source.messageId, structuredClone(source)]);
|
|
178
|
+
this.#state.externalReplySources = Object.fromEntries(entries);
|
|
179
|
+
await this.#persist();
|
|
180
|
+
}
|
|
181
|
+
|
|
169
182
|
sessionFor(key) {
|
|
170
183
|
return this.#state.sessions[key] ?? null;
|
|
171
184
|
}
|
|
@@ -264,7 +277,7 @@ export class WeixinStateStore {
|
|
|
264
277
|
}
|
|
265
278
|
|
|
266
279
|
snapshot() {
|
|
267
|
-
const { contextTokens, ...state } = this.#state;
|
|
280
|
+
const { contextTokens, externalReplySources, ...state } = this.#state;
|
|
268
281
|
return structuredClone(state);
|
|
269
282
|
}
|
|
270
283
|
|
|
@@ -475,7 +475,18 @@ async function requestJson(fetchImpl, {
|
|
|
475
475
|
);
|
|
476
476
|
}
|
|
477
477
|
try {
|
|
478
|
-
|
|
478
|
+
// Native IDs may exceed Number.MAX_SAFE_INTEGER. Read their original JSON
|
|
479
|
+
// lexemes before numeric precision is lost; other protocol values keep
|
|
480
|
+
// their original types (ret/errcode and timestamps are not message IDs).
|
|
481
|
+
return JSON.parse(await response.text(), (key, value, context) => {
|
|
482
|
+
if ((key === 'message_id' || key === 'msg_id') && typeof value === 'number') {
|
|
483
|
+
if (!context?.source || !/^\d+$/.test(context.source)) {
|
|
484
|
+
throw new TypeError('Invalid native Weixin message ID');
|
|
485
|
+
}
|
|
486
|
+
return context.source;
|
|
487
|
+
}
|
|
488
|
+
return value;
|
|
489
|
+
});
|
|
479
490
|
} catch (error) {
|
|
480
491
|
throw new WeixinApiError('invalid-response', '微信服务返回了无法解析的响应。', { cause: error });
|
|
481
492
|
}
|
|
@@ -929,6 +940,9 @@ export function weixinMessageTimestampMs(messageId, { now = Date.now() } = {}) {
|
|
|
929
940
|
|
|
930
941
|
export function weixinMessageId(message) {
|
|
931
942
|
if (message?.message_id !== undefined && message.message_id !== null) {
|
|
943
|
+
if (typeof message.message_id === 'number' && !Number.isSafeInteger(message.message_id)) {
|
|
944
|
+
return null;
|
|
945
|
+
}
|
|
932
946
|
return String(message.message_id);
|
|
933
947
|
}
|
|
934
948
|
return nonEmptyString(message?.client_id);
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { ExclusiveInboundConsumers } from '../shared/exclusive-inbound-consumers.mjs';
|
|
2
|
+
import { pairedWeixinAccount, normalizeWeixinExternalText, weixinRefusal } from './external-consumer.mjs';
|
|
1
3
|
import { randomUUID } from 'node:crypto';
|
|
2
4
|
import { createWeixinDiagnostics, knownWeixinErrorCode, weixinStageError } from './connection-error.mjs';
|
|
3
5
|
|
|
@@ -61,6 +63,7 @@ function preserveActivationError(error, fallbackCode) {
|
|
|
61
63
|
}
|
|
62
64
|
|
|
63
65
|
export class WeixinController {
|
|
66
|
+
#inboundConsumers = new ExclusiveInboundConsumers();
|
|
64
67
|
#api;
|
|
65
68
|
#credentials;
|
|
66
69
|
#configStore;
|
|
@@ -145,6 +148,66 @@ export class WeixinController {
|
|
|
145
148
|
this.#touch();
|
|
146
149
|
}
|
|
147
150
|
|
|
151
|
+
async #deliveryAccount(config, signal) {
|
|
152
|
+
signal?.throwIfAborted();
|
|
153
|
+
if (this.#closed) throw weixinRefusal('provider-unavailable');
|
|
154
|
+
return pairedWeixinAccount(config, await this.#resolveToken(config.tokenRef));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async describeDeliveryAccount(botId) {
|
|
158
|
+
return this.#withBotTransition(botId, async () => {
|
|
159
|
+
const config = this.#configStore.get(botId);
|
|
160
|
+
if (!config) throw weixinRefusal('unknown-bot');
|
|
161
|
+
const account = await this.#deliveryAccount(config);
|
|
162
|
+
return { version: 1, botId, channel: 'weixin', account,
|
|
163
|
+
connected: this.#runtimes.get(botId)?.status?.ready === true,
|
|
164
|
+
capabilities: ['proactive-text-checked', 'exclusive-text-consumer', 'reply-text-checked',
|
|
165
|
+
'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked'] };
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceFiles = false } = {}) {
|
|
170
|
+
return this.#withBotTransition(botId, async () => {
|
|
171
|
+
if (sourceFiles) throw weixinRefusal('capability-unavailable');
|
|
172
|
+
const config = this.#configStore.get(botId);
|
|
173
|
+
if (!config) throw weixinRefusal('unknown-bot');
|
|
174
|
+
const account = await this.#deliveryAccount(config, signal);
|
|
175
|
+
if (account.fingerprint !== expectedFingerprint) throw weixinRefusal('account-changed');
|
|
176
|
+
const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal });
|
|
177
|
+
try {
|
|
178
|
+
const saved = await this.#configStore.save({ ...config, consumerMode: 'external-consumer' });
|
|
179
|
+
await this.#startRuntime(saved, await this.#resolveToken(saved.tokenRef));
|
|
180
|
+
signal?.throwIfAborted();
|
|
181
|
+
return dispose;
|
|
182
|
+
} catch (error) { dispose(); throw error; }
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async #checkedRuntime(botId, expectedFingerprint, signal) {
|
|
187
|
+
const config = this.#configStore.get(botId);
|
|
188
|
+
if (!config) throw weixinRefusal('unknown-bot');
|
|
189
|
+
const account = await this.#deliveryAccount(config, signal);
|
|
190
|
+
if (account.fingerprint !== expectedFingerprint) throw weixinRefusal('account-changed');
|
|
191
|
+
const runtime = this.#runtimes.get(botId);
|
|
192
|
+
if (config.consumerMode !== 'external-consumer' || !runtime?.status?.ready) throw weixinRefusal('capability-unavailable');
|
|
193
|
+
const lease = this.#inboundConsumers.signalFor(botId, expectedFingerprint);
|
|
194
|
+
return { runtime, account, signal: signal ? AbortSignal.any([signal, lease]) : lease };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async qualifyReplyChecked(botId, route, options = {}) {
|
|
198
|
+
return this.#withBotTransition(botId, async () => {
|
|
199
|
+
const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
|
|
200
|
+
return checked.runtime.qualifyReplyChecked(route, checked);
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async replyChecked(botId, route, text, options = {}) {
|
|
205
|
+
return this.#withBotTransition(botId, async () => {
|
|
206
|
+
const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
|
|
207
|
+
return checked.runtime.replyChecked(route, text, { ...options, ...checked });
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
148
211
|
async startProvisioning() {
|
|
149
212
|
if (this.#closed) throw new Error('dsh-weixin controller is closed');
|
|
150
213
|
if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
|
|
@@ -285,11 +348,17 @@ export class WeixinController {
|
|
|
285
348
|
error.code = 'bot-not-connected';
|
|
286
349
|
throw error;
|
|
287
350
|
}
|
|
351
|
+
if (options.expectedFingerprint !== undefined) {
|
|
352
|
+
const account = await this.#deliveryAccount(config, options.signal);
|
|
353
|
+
if (account.fingerprint !== options.expectedFingerprint) throw weixinRefusal('account-changed');
|
|
354
|
+
if (target?.kind !== 'user' || target.route?.toUserId !== account.ownerUserId) throw weixinRefusal('invalid-target');
|
|
355
|
+
}
|
|
288
356
|
return runtime.sendProactiveText(target, text, options);
|
|
289
357
|
});
|
|
290
358
|
}
|
|
291
359
|
|
|
292
360
|
async deleteBot(botId) {
|
|
361
|
+
this.#inboundConsumers.remove(botId);
|
|
293
362
|
const config = this.#configStore.get(botId);
|
|
294
363
|
if (!config) throw weixinStageError('workspace-bot-not-found', undefined, 'account.remove');
|
|
295
364
|
const warnings = [];
|
|
@@ -405,6 +474,7 @@ export class WeixinController {
|
|
|
405
474
|
}
|
|
406
475
|
|
|
407
476
|
async close() {
|
|
477
|
+
this.#inboundConsumers.close();
|
|
408
478
|
if (this.#closed) return;
|
|
409
479
|
this.#closed = true;
|
|
410
480
|
if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
|
|
@@ -523,6 +593,7 @@ export class WeixinController {
|
|
|
523
593
|
baseUrl,
|
|
524
594
|
createdAt: previousConfig?.createdAt ?? new Date().toISOString(),
|
|
525
595
|
connectedAt: new Date().toISOString(),
|
|
596
|
+
...(previousConfig?.consumerMode ? { consumerMode: previousConfig.consumerMode } : {}),
|
|
526
597
|
};
|
|
527
598
|
let previousToken;
|
|
528
599
|
try {
|
|
@@ -589,7 +660,19 @@ export class WeixinController {
|
|
|
589
660
|
await this.#stopRuntime(config.botId);
|
|
590
661
|
let runtime;
|
|
591
662
|
try {
|
|
592
|
-
|
|
663
|
+
const account = config.consumerMode === 'external-consumer' ? pairedWeixinAccount(config, token) : undefined;
|
|
664
|
+
runtime = await this.#createRuntime({ botId: config.botId, config, token,
|
|
665
|
+
externalConsumer: async (message, state, signal) => {
|
|
666
|
+
const current = await this.#deliveryAccount(this.#configStore.get(config.botId), signal);
|
|
667
|
+
if (current.fingerprint !== account.fingerprint) throw weixinRefusal('account-changed');
|
|
668
|
+
this.#inboundConsumers.signalFor(config.botId, account.fingerprint).throwIfAborted();
|
|
669
|
+
const event = normalizeWeixinExternalText(message, { botId: config.botId, account });
|
|
670
|
+
if (!event) return { accepted: true, ignored: true };
|
|
671
|
+
await state.rememberExternalReplySource({ messageId: event.messageId, actorId: event.actor.id,
|
|
672
|
+
fingerprint: account.fingerprint, contextToken: message.context_token,
|
|
673
|
+
expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000 });
|
|
674
|
+
return this.#inboundConsumers.accept(config.botId, event, signal);
|
|
675
|
+
} });
|
|
593
676
|
} catch (error) {
|
|
594
677
|
throw preserveActivationError(error, 'runtime-prepare-failed');
|
|
595
678
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { checkedWeixinRoute, weixinRefusal } from './external-consumer.mjs';
|
|
1
2
|
import { createWeixinDiagnostics } from './connection-error.mjs';
|
|
2
3
|
import { DEFAULT_WEIXIN_MAX_MESSAGE_CHARS, WeixinApiError, rejectedProviderResponse } from './weixin-api.mjs';
|
|
3
4
|
import {
|
|
@@ -116,6 +117,7 @@ export class WeixinRuntime {
|
|
|
116
117
|
#token;
|
|
117
118
|
#harness;
|
|
118
119
|
#state;
|
|
120
|
+
#externalConsumer;
|
|
119
121
|
#contextEnhancement;
|
|
120
122
|
#accessPolicy;
|
|
121
123
|
#logger;
|
|
@@ -137,6 +139,7 @@ export class WeixinRuntime {
|
|
|
137
139
|
harness,
|
|
138
140
|
state,
|
|
139
141
|
contextEnhancement,
|
|
142
|
+
externalConsumer,
|
|
140
143
|
accessPolicy,
|
|
141
144
|
logger = console,
|
|
142
145
|
diagnostics,
|
|
@@ -153,6 +156,7 @@ export class WeixinRuntime {
|
|
|
153
156
|
this.#harness = harness;
|
|
154
157
|
this.#state = state;
|
|
155
158
|
this.#contextEnhancement = contextEnhancement;
|
|
159
|
+
this.#externalConsumer = externalConsumer;
|
|
156
160
|
this.#accessPolicy = accessPolicy;
|
|
157
161
|
this.#logger = logger;
|
|
158
162
|
this.#diagnostics = diagnostics ?? createWeixinDiagnostics({ logger });
|
|
@@ -192,7 +196,7 @@ export class WeixinRuntime {
|
|
|
192
196
|
await this.#notifyStart();
|
|
193
197
|
this.#abortController = new AbortController();
|
|
194
198
|
const signal = this.#abortController.signal;
|
|
195
|
-
this.#bridge = new WeixinHarnessBridge({
|
|
199
|
+
this.#bridge = this.#config.consumerMode === 'external-consumer' ? null : new WeixinHarnessBridge({
|
|
196
200
|
api: this.#api,
|
|
197
201
|
baseUrl: this.#config.baseUrl,
|
|
198
202
|
token: this.#token,
|
|
@@ -276,6 +280,11 @@ export class WeixinRuntime {
|
|
|
276
280
|
this.#status.connectionError = null;
|
|
277
281
|
|
|
278
282
|
for (const message of orderWeixinMessages(response?.msgs)) {
|
|
283
|
+
if (this.#config.consumerMode === 'external-consumer') {
|
|
284
|
+
if (!this.#externalConsumer) throw weixinRefusal('consumer-unavailable');
|
|
285
|
+
await this.#externalConsumer(message, signal);
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
279
288
|
void this.#bridge.accept(message).catch((error) => {
|
|
280
289
|
if (signal.aborted) return;
|
|
281
290
|
this.#logger.error?.(
|
|
@@ -301,6 +310,27 @@ export class WeixinRuntime {
|
|
|
301
310
|
}
|
|
302
311
|
}
|
|
303
312
|
|
|
313
|
+
async qualifyReplyChecked(route, { account, signal } = {}) {
|
|
314
|
+
signal?.throwIfAborted();
|
|
315
|
+
return checkedWeixinRoute(route, account, this.#state.externalReplySource(route?.messageId));
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async replyChecked(route, text, { account, signal, receipt = false, beforeSend } = {}) {
|
|
319
|
+
const checked = await this.qualifyReplyChecked(route, { account, signal });
|
|
320
|
+
if (typeof text !== 'string' || !text.trim() || [...text].length > this.#maxMessageChars)
|
|
321
|
+
throw weixinRefusal('bad-request');
|
|
322
|
+
const source = this.#state.externalReplySource(checked.messageId);
|
|
323
|
+
signal?.throwIfAborted();
|
|
324
|
+
if (beforeSend && beforeSend() !== true) throw weixinRefusal('stale-route');
|
|
325
|
+
const result = await this.#api.sendText({ baseUrl: this.#config.baseUrl, token: this.#token,
|
|
326
|
+
toUserId: checked.actorId, contextToken: source.contextToken, text, signal });
|
|
327
|
+
const clientId = result?.providerMessageIds?.[0];
|
|
328
|
+
if (typeof clientId !== 'string' || !clientId.startsWith('dsh-weixin-'))
|
|
329
|
+
throw weixinRefusal('provider-result-unknown');
|
|
330
|
+
return { sent: true, ...(receipt ? { receipt: { version: 1, messageId: clientId,
|
|
331
|
+
conversationId: checked.conversationId, identityKind: 'client-acknowledgement' } } : {}) };
|
|
332
|
+
}
|
|
333
|
+
|
|
304
334
|
async stop() {
|
|
305
335
|
const warnings = [];
|
|
306
336
|
const monitor = this.#monitor;
|