@botharness/im-provider 4.32.0-botharness.21 → 4.32.0-botharness.23
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 +283 -279
- package/package.json +2 -2
- package/plugin-src/host/channels/qq/production.mjs +2 -1
- package/plugin-src/host/harness-command-executor.mjs +3 -0
- package/plugin-src/host/host-owner-peer.mjs +29 -0
- package/plugin-src/host/modern-harness-api.mjs +10 -3
- package/src/channels/discord/discord-runtime.mjs +2 -1
- package/src/channels/discord/external-consumer.mjs +6 -6
- package/src/channels/discord/history-reader.mjs +1 -1
- package/src/channels/feishu/external-consumer.mjs +8 -4
- package/src/channels/feishu/external-files.mjs +2 -2
- package/src/channels/feishu/external-names.mjs +3 -2
- package/src/channels/feishu/external-sender.mjs +8 -0
- package/src/channels/feishu/feishu-runtime.mjs +23 -9
- package/src/channels/feishu/reply-context.mjs +6 -3
- package/src/channels/qq/external-addressing.mjs +9 -0
- package/src/channels/qq/external-attachments.mjs +63 -0
- package/src/channels/qq/external-consumer.mjs +127 -47
- package/src/channels/qq/external-files.mjs +53 -13
- package/src/channels/qq/external-images.mjs +9 -6
- package/src/channels/qq/markdown-reply.mjs +5 -2
- package/src/channels/qq/qq-bridge.mjs +41 -2
- package/src/channels/qq/qq-controller.mjs +4 -3
- package/src/channels/qq/qq-runtime.mjs +8 -1
- package/src/channels/shared/exclusive-inbound-consumers.mjs +4 -3
- package/src/channels/shared/message-failure.mjs +11 -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.23",
|
|
4
4
|
"icon": "./assets/logo-plugin-message-link-gradient.webp",
|
|
5
5
|
"description": "BotHarness-qualified IM Provider, maintained from dsh-im",
|
|
6
6
|
"keywords": [
|
|
@@ -178,6 +178,6 @@
|
|
|
178
178
|
"peerDependencies": {},
|
|
179
179
|
"botharness": {
|
|
180
180
|
"managedByProduct": true,
|
|
181
|
-
"upstreamSource": "
|
|
181
|
+
"upstreamSource": "7505ce6fcda26c02810781fde9d4da81dab28a68"
|
|
182
182
|
}
|
|
183
183
|
}
|
|
@@ -113,7 +113,7 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
113
113
|
credentials: ctx.credentials,
|
|
114
114
|
configStore: observedConfigStore,
|
|
115
115
|
logger,
|
|
116
|
-
createRuntime: async ({ botId, config: botConfig, appSecret, externalConsumer, sourceImages, sourceFiles, sourceVoiceTranscripts, sourceVoiceAudio, ordinaryText }) => {
|
|
116
|
+
createRuntime: async ({ botId, config: botConfig, appSecret, externalConsumer, sourceImages, sourceFiles, sourceVoiceTranscripts, sourceVoiceAudio, ordinaryText, directMessages }) => {
|
|
117
117
|
const state = await stateFor(botId);
|
|
118
118
|
await workspaces.ensure(botId, {
|
|
119
119
|
defaultAgentPreset: config.agentPreset,
|
|
@@ -131,6 +131,7 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
131
131
|
sourceVoiceTranscripts,
|
|
132
132
|
sourceVoiceAudio,
|
|
133
133
|
ordinaryText,
|
|
134
|
+
directMessages,
|
|
134
135
|
harness: workspaceScope.harness,
|
|
135
136
|
state: workspaceScope.state,
|
|
136
137
|
contextEnhancement: { botId, getSettings: () => workspaces.contextEnhancementFor(botId) },
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { hostOwnerPeer } from './host-owner-peer.mjs';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Adapt the Host's Typert command gateway to the channel Harness client.
|
|
3
5
|
* Programmatic production fixtures may omit the gateway and exercise other assembly paths.
|
|
@@ -17,6 +19,7 @@ export function createHarnessCommandExecutor(ctx, provided) {
|
|
|
17
19
|
namespace: 'commands',
|
|
18
20
|
method: 'execute',
|
|
19
21
|
args: { agentId: sessionId, line, images: [] },
|
|
22
|
+
peer: hostOwnerPeer(ctx),
|
|
20
23
|
signal: options.signal,
|
|
21
24
|
};
|
|
22
25
|
try {
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const peers = new WeakMap();
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* DSH 0.2.1 Gateways require every in-process caller to name the Peer it
|
|
7
|
+
* speaks for. dsh-im runs inside the Host on behalf of its local owner, so
|
|
8
|
+
* every dsh-im caller under one Host root shares one owner Peer. Gateways
|
|
9
|
+
* before 0.2.1 ignore the field.
|
|
10
|
+
*/
|
|
11
|
+
export function hostOwnerPeer(ctx) {
|
|
12
|
+
const scope = ctx?.root ?? ctx;
|
|
13
|
+
const current = peers.get(scope);
|
|
14
|
+
if (current && !current.signal.aborted) return current;
|
|
15
|
+
const controller = new AbortController();
|
|
16
|
+
const peer = Object.freeze({
|
|
17
|
+
id: `dsh-im:${randomUUID()}`,
|
|
18
|
+
ctx,
|
|
19
|
+
principal: Object.freeze({ kind: 'owner' }),
|
|
20
|
+
signal: controller.signal,
|
|
21
|
+
interactions: 'none',
|
|
22
|
+
async dispose() {
|
|
23
|
+
controller.abort();
|
|
24
|
+
if (peers.get(scope) === peer) peers.delete(scope);
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
peers.set(scope, peer);
|
|
28
|
+
return peer;
|
|
29
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
|
|
3
3
|
import { hasActiveHarnessInteractionOwner } from '../../src/channels/shared/harness-client.mjs';
|
|
4
|
+
import { hostOwnerPeer } from './host-owner-peer.mjs';
|
|
4
5
|
|
|
5
6
|
const modernApis = new WeakMap();
|
|
6
7
|
|
|
@@ -36,15 +37,17 @@ function rpcResult(request, operation) {
|
|
|
36
37
|
);
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
function remoteRequest(namespace, method, args, signal) {
|
|
40
|
+
function remoteRequest(namespace, method, args, signal, peer) {
|
|
40
41
|
return {
|
|
41
42
|
namespace,
|
|
42
43
|
method,
|
|
43
44
|
args,
|
|
45
|
+
peer,
|
|
44
46
|
...(signal === undefined ? {} : { signal }),
|
|
45
47
|
};
|
|
46
48
|
}
|
|
47
49
|
|
|
50
|
+
|
|
48
51
|
function questionError(message, code) {
|
|
49
52
|
const error = new Error(message);
|
|
50
53
|
error.name = 'UserQuestionError';
|
|
@@ -196,6 +199,7 @@ class MuxSubscription {
|
|
|
196
199
|
class ModernHarnessApi {
|
|
197
200
|
#gateway;
|
|
198
201
|
#scope;
|
|
202
|
+
#ctx;
|
|
199
203
|
#mux = new Set();
|
|
200
204
|
#pendingQuestions = new Map();
|
|
201
205
|
#pendingApprovals = new Map();
|
|
@@ -207,6 +211,7 @@ class ModernHarnessApi {
|
|
|
207
211
|
constructor(ctx, gateway, scope) {
|
|
208
212
|
this.#gateway = gateway;
|
|
209
213
|
this.#scope = scope;
|
|
214
|
+
this.#ctx = ctx;
|
|
210
215
|
|
|
211
216
|
this.host = Object.freeze({
|
|
212
217
|
describe: (request) => rpcResult(request, () => ({ ready: true, transport: 'typert' })),
|
|
@@ -283,7 +288,7 @@ class ModernHarnessApi {
|
|
|
283
288
|
}
|
|
284
289
|
|
|
285
290
|
async #invoke(namespace, method, args, signal) {
|
|
286
|
-
return this.#gateway.invoke(remoteRequest(namespace, method, args, signal));
|
|
291
|
+
return this.#gateway.invoke(remoteRequest(namespace, method, args, signal, hostOwnerPeer(this.#ctx)));
|
|
287
292
|
}
|
|
288
293
|
|
|
289
294
|
async #streamFirst(namespace, method, args, signal) {
|
|
@@ -294,7 +299,7 @@ class ModernHarnessApi {
|
|
|
294
299
|
let iterator;
|
|
295
300
|
try {
|
|
296
301
|
const source = await this.#gateway.stream(remoteRequest(
|
|
297
|
-
namespace, method, args, streamSignal,
|
|
302
|
+
namespace, method, args, streamSignal, hostOwnerPeer(this.#ctx),
|
|
298
303
|
));
|
|
299
304
|
iterator = source[Symbol.asyncIterator]();
|
|
300
305
|
const first = await iterator.next();
|
|
@@ -711,6 +716,8 @@ class ModernHarnessApi {
|
|
|
711
716
|
questionError('dsh-im interaction adapter was disposed', 'ASK_ABORTED'),
|
|
712
717
|
);
|
|
713
718
|
for (const dispose of this.#disposers.splice(0).reverse()) dispose?.();
|
|
719
|
+
// The adapter ends with its Host root; so does the Peer it spoke for.
|
|
720
|
+
void hostOwnerPeer(this.#ctx).dispose();
|
|
714
721
|
}
|
|
715
722
|
}
|
|
716
723
|
|
|
@@ -937,9 +937,10 @@ export class DiscordRuntime {
|
|
|
937
937
|
|
|
938
938
|
async #acceptExternalMessage(message, sequence, generation) {
|
|
939
939
|
if (!this.#account || !this.#status.ready || generation !== this.#generation
|
|
940
|
-
|| !message?.guild_id || message.author?.
|
|
940
|
+
|| !message?.guild_id || message.webhook_id || message.author?.id === this.#account.userId
|
|
941
941
|
|| !Array.isArray(message.mentions)) return;
|
|
942
942
|
const mentioned = message.mentions.some(user => user.id === this.#account.userId);
|
|
943
|
+
if (message.author?.bot === true && !mentioned) return;
|
|
943
944
|
if (!mentioned && (!this.#ordinaryAuthorized || this.#externalOrdinaryText() !== true
|
|
944
945
|
|| typeof message.content !== 'string' || !message.content.trim())) return;
|
|
945
946
|
const checked = this.#checkedLifetime();
|
|
@@ -107,7 +107,7 @@ export function discordMessageContentAllowed(application) {
|
|
|
107
107
|
}
|
|
108
108
|
|
|
109
109
|
export function normalizeDiscordExternalText(message, { botId, account, channel, eventId, ordinaryText = false }) {
|
|
110
|
-
return normalizeDiscordHumanText(message, { botId, account, channel, eventId }, ordinaryText !== true);
|
|
110
|
+
return normalizeDiscordHumanText(message, { botId, account, channel, eventId }, ordinaryText !== true, true);
|
|
111
111
|
}
|
|
112
112
|
|
|
113
113
|
/** History visibility never relaxes the mention-only live admission predicate. */
|
|
@@ -115,15 +115,15 @@ export function normalizeDiscordHistoryText(message, identity) {
|
|
|
115
115
|
return normalizeDiscordHumanText(message, identity, false);
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
-
function normalizeDiscordHumanText(message, { botId, account, channel, eventId }, requireMention) {
|
|
118
|
+
function normalizeDiscordHumanText(message, { botId, account, channel, eventId }, requireMention, allowBots = false) {
|
|
119
119
|
if (!discordSnowflake(message?.id) || !discordSnowflake(message?.author?.id)
|
|
120
|
-
|| message.author.bot === true || message.webhook_id || message.author.id === account.userId
|
|
120
|
+
|| (message.author.bot === true && !allowBots) || message.webhook_id || message.author.id === account.userId
|
|
121
121
|
|| ![0, 19].includes(message.type) || typeof message.content !== 'string' || !message.content.trim()
|
|
122
122
|
|| message.content.length > 16000 || !Array.isArray(message.mentions)) return null;
|
|
123
123
|
if (message.guild_id !== channel.guildId || message.channel_id !== channel.channelId)
|
|
124
124
|
throw discordRefusal('stale-route');
|
|
125
125
|
const mentionedAccount = message.mentions.some(user => user.id === account.userId);
|
|
126
|
-
if (requireMention && !mentionedAccount) return null;
|
|
126
|
+
if ((requireMention || message.author.bot === true) && !mentionedAccount) return null;
|
|
127
127
|
const timestamp = Date.parse(message.timestamp);
|
|
128
128
|
if (!Number.isFinite(timestamp) || typeof eventId !== 'string' || !eventId || eventId.length > 512)
|
|
129
129
|
throw discordRefusal('invalid-inbound');
|
|
@@ -133,7 +133,7 @@ function normalizeDiscordHumanText(message, { botId, account, channel, eventId }
|
|
|
133
133
|
.map(user => ({ id: user.id, key: `<@${user.id}>`,
|
|
134
134
|
...(user.id === account.userId ? { name: account.name } : {}) }));
|
|
135
135
|
return { version: 1, channel: 'discord', botId, fingerprint: account.fingerprint,
|
|
136
|
-
eventId, messageId: message.id, actor: { kind: 'user', id: message.author.id, ...(name ? { name: name.slice(0, 512) } : {}) },
|
|
136
|
+
eventId, messageId: message.id, actor: { kind: message.author.bot === true ? 'bot' : 'user', id: message.author.id, ...(name ? { name: name.slice(0, 512) } : {}) },
|
|
137
137
|
conversation: { kind: 'group', id: channel.conversationId, ...(channel.name ? { name: channel.name } : {}) }, mentions, mentionedAccount,
|
|
138
138
|
at: new Date(timestamp).toISOString(), text: message.content,
|
|
139
139
|
reply: { messageId: message.id, conversationId: channel.conversationId, actorId: message.author.id,
|
|
@@ -153,7 +153,7 @@ export async function qualifyDiscordReply(api, account, route, signal, permissio
|
|
|
153
153
|
try { source = await api.getMessage({ channelId: channel.channelId, messageId: route.messageId, signal }); }
|
|
154
154
|
catch (error) { throw nativeFailure(error, 'source-not-found'); }
|
|
155
155
|
if (source?.id !== route.messageId || source.channel_id !== channel.channelId
|
|
156
|
-
|| source.author?.id !== route.actorId || source.author.
|
|
156
|
+
|| source.author?.id !== route.actorId || source.author.id === account.userId || source.webhook_id
|
|
157
157
|
|| ![0, 19].includes(source.type)) throw discordRefusal('stale-route');
|
|
158
158
|
signal?.throwIfAborted();
|
|
159
159
|
return { channel, route: { ...route }, source };
|
|
@@ -75,7 +75,7 @@ export function createDiscordHistoryReader({ now = Date.now } = {}) {
|
|
|
75
75
|
messageId: route.messageId, signal }));
|
|
76
76
|
if (source?.id !== route.messageId || source.channel_id !== sourceChannel.channelId
|
|
77
77
|
|| (source.guild_id !== undefined && source.guild_id !== sourceChannel.guildId)
|
|
78
|
-
|| source.author?.id !== route.actorId || source.author.
|
|
78
|
+
|| source.author?.id !== route.actorId || source.author.id === current.userId || source.webhook_id
|
|
79
79
|
|| ![0, 19].includes(source.type)) throw discordRefusal('stale-route');
|
|
80
80
|
const channel = query.scope === 'thread' || query.scope === 'nearby' ? sourceChannel : await checked(() =>
|
|
81
81
|
inspectDiscordSourceChannel(api, route.conversationId, current, signal, { forHistory: true }));
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { nativeImageContent } from './external-images.mjs';
|
|
2
|
+
import { isBotSenderType } from './external-sender.mjs';
|
|
2
3
|
function refusal(code) {
|
|
3
4
|
const error = new Error(code);
|
|
4
5
|
error.code = code;
|
|
@@ -17,8 +18,10 @@ export function normalizeExternalText(event, { botId, appId, botOpenId, fingerpr
|
|
|
17
18
|
const eventId = identifier(event?.event_id ?? event?.header?.event_id);
|
|
18
19
|
const eventApp = event?.app_id ?? event?.header?.app_id;
|
|
19
20
|
if (eventApp !== undefined && eventApp !== appId) throw refusal('account-changed');
|
|
20
|
-
|
|
21
|
-
if (
|
|
21
|
+
const botSender = isBotSenderType(event?.sender);
|
|
22
|
+
if (botSender && (message?.chat_type !== 'group' || !identifier(botOpenId) || !actorId || actorId === botOpenId
|
|
23
|
+
|| event?.sender?.sender_id?.app_id === appId)) return null;
|
|
24
|
+
if ((!botSender && event?.sender?.sender_type !== 'user')
|
|
22
25
|
|| !['p2p', 'group'].includes(message?.chat_type) || message?.message_type !== 'text') return null;
|
|
23
26
|
if (message.chat_type === 'group' && !identifier(botOpenId)) throw refusal('account-unverified');
|
|
24
27
|
if (message.mentions !== undefined && (!Array.isArray(message.mentions) || message.mentions.length > 100))
|
|
@@ -30,6 +33,7 @@ export function normalizeExternalText(event, { botId, appId, botOpenId, fingerpr
|
|
|
30
33
|
const name = identifier(mention?.name);
|
|
31
34
|
return Object.freeze({ id, key, ...(name ? { name } : {}) });
|
|
32
35
|
}));
|
|
36
|
+
if (botSender && !mentions.some(mention => mention.id === botOpenId)) return null;
|
|
33
37
|
if (!actorId || !messageId || !conversationId || !eventId
|
|
34
38
|
|| !/^[a-f0-9]{64}$/.test(fingerprint ?? '')) throw refusal('invalid-inbound');
|
|
35
39
|
let text;
|
|
@@ -47,7 +51,7 @@ export function normalizeExternalText(event, { botId, appId, botOpenId, fingerpr
|
|
|
47
51
|
});
|
|
48
52
|
return Object.freeze({
|
|
49
53
|
version: 1, channel: 'feishu', botId, fingerprint, eventId, messageId,
|
|
50
|
-
actor: Object.freeze({ kind: 'user', id: actorId,
|
|
54
|
+
actor: Object.freeze({ kind: botSender ? 'bot' : 'user', id: actorId,
|
|
51
55
|
...(identifier(event.sender.sender_name) ? { name: event.sender.sender_name } : {}) }),
|
|
52
56
|
conversation: Object.freeze({ kind: message.chat_type === 'group' ? 'group' : 'dm', id: conversationId }),
|
|
53
57
|
mentions, mentionedAccount: mentions.some(mention => mention.id === botOpenId),
|
|
@@ -59,7 +63,7 @@ export function normalizeExternalText(event, { botId, appId, botOpenId, fingerpr
|
|
|
59
63
|
export function normalizeExternalMedia(event, identity) {
|
|
60
64
|
const message = event?.message;
|
|
61
65
|
if (!['image', 'post'].includes(message?.message_type)) return normalizeExternalText(event, identity);
|
|
62
|
-
if (event?.sender?.sender_type !== 'user') return null;
|
|
66
|
+
if (event?.sender?.sender_type !== 'user' && !isBotSenderType(event?.sender)) return null;
|
|
63
67
|
const media = nativeImageContent(message, message.chat_id);
|
|
64
68
|
if (!media) return null;
|
|
65
69
|
const base = normalizeExternalText({ ...event, message: { ...message, message_type: 'text', content: JSON.stringify({ text: media.text }) } }, identity);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { nativeImageContent } from './external-images.mjs';
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
3
|
import { VerifiedFeishuChannel } from './feishu-channel.mjs';
|
|
4
|
+
import { sourceSenderMatches } from './external-sender.mjs';
|
|
4
5
|
|
|
5
6
|
const MAX_BYTES = 25 * 1024 * 1024;
|
|
6
7
|
const failure = (code) => Object.assign(new Error(code), { code });
|
|
@@ -11,8 +12,7 @@ export async function checkedReplySource(client, route, signal) {
|
|
|
11
12
|
const current = await client.im.v1.message.get({ path: { message_id: route.messageId } });
|
|
12
13
|
const source = current?.data?.items?.find(item => item.message_id === route.messageId);
|
|
13
14
|
if (current?.code || !source || source.deleted === true || source.chat_id !== route.conversationId
|
|
14
|
-
|| source.sender
|
|
15
|
-
|| source.sender?.id !== route.actorId || (source.thread_id || undefined) !== route.threadId
|
|
15
|
+
|| !sourceSenderMatches(source.sender, route.actorId) || (source.thread_id || undefined) !== route.threadId
|
|
16
16
|
|| (source.root_id || undefined) !== route.rootId || (source.parent_id || undefined) !== route.parentId)
|
|
17
17
|
throw failure('stale-route');
|
|
18
18
|
signal?.throwIfAborted();
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { sourceSenderMatches } from './external-sender.mjs';
|
|
2
|
+
|
|
1
3
|
const NAME_TTL_MS = 60 * 60 * 1000;
|
|
2
4
|
const MISS_TTL_MS = 60 * 1000;
|
|
3
5
|
const CACHE_LIMIT = 1000;
|
|
@@ -64,8 +66,7 @@ export async function externalSenderName(client, evidence, { signal, timeoutMs =
|
|
|
64
66
|
const source = response?.data?.items?.find(item => item.message_id === evidence.messageId);
|
|
65
67
|
if (response?.code || !source || source.deleted === true || source.msg_type !== 'text'
|
|
66
68
|
|| source.chat_id !== route.conversationId
|
|
67
|
-
|| source.sender
|
|
68
|
-
|| source.sender?.id !== evidence.actor.id
|
|
69
|
+
|| !sourceSenderMatches(source.sender, evidence.actor.id)
|
|
69
70
|
|| (source.thread_id || undefined) !== route.threadId
|
|
70
71
|
|| (source.root_id || undefined) !== route.rootId
|
|
71
72
|
|| (source.parent_id || undefined) !== route.parentId) return undefined;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function isBotSenderType(sender) {
|
|
2
|
+
return sender?.sender_type === 'app' || sender?.sender_type === 'bot';
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function sourceSenderMatches(sender, actorId) {
|
|
6
|
+
if (sender?.sender_type === 'user') return sender.id_type === 'open_id' && sender.id === actorId;
|
|
7
|
+
return isBotSenderType(sender) && typeof sender.id === 'string' && sender.id.length > 0;
|
|
8
|
+
}
|
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
sendRememberedConnectionTest,
|
|
24
24
|
} from '../shared/connection-test.mjs';
|
|
25
25
|
import { t } from '../shared/i18n.mjs';
|
|
26
|
+
import { sourceSenderMatches } from './external-sender.mjs';
|
|
26
27
|
|
|
27
28
|
const DEFAULT_REQUEST_TIMEOUT_MS = 15_000;
|
|
28
29
|
const CALLBACK_PROBE_SUCCESS_NOTICE = '✅ 修复完成:已实测收到 card.action.trigger,菜单按钮现在可用。';
|
|
@@ -31,6 +32,23 @@ const CALLBACK_PROBE_SEND_FAILURE_NOTICE = '⚠️ 修复验证失败:无法
|
|
|
31
32
|
const CALLBACK_PROBE_ABORT_NOTICE = '⚠️ 修复验证中断:Runtime 已停止,未完成 card.action.trigger 实测,不能确认修复成功。请不要重复授权;先等待机器人恢复连接。';
|
|
32
33
|
const REUSABLE_WS_STATES = new Set(['connected', 'connecting', 'reconnecting']);
|
|
33
34
|
|
|
35
|
+
// Checked Bot replies arrive as Markdown. Lark shows it only inside a card, so
|
|
36
|
+
// a reply that uses Markdown goes out as the same native Markdown element as
|
|
37
|
+
// chat. Plain replies and replies carrying a text-message <at user_id> stay
|
|
38
|
+
// text: cards do not render that mention syntax, and other Bots and own echoes
|
|
39
|
+
// are read from text messages only.
|
|
40
|
+
const MARKDOWN_SYNTAX = /(^|\n)[ \t]{0,3}(#{1,6}[ \t]|[-*+][ \t]|\d{1,9}[.)][ \t]|>|```|\|.*\|)|\*\*\S|__\S|~~\S|`[^`\n]+`|\[[^\]\n]+\]\([^)\s]+\)/;
|
|
41
|
+
|
|
42
|
+
export function checkedTextFormat(text) {
|
|
43
|
+
return !text.includes('<at ') && MARKDOWN_SYNTAX.test(text) ? 'markdown' : 'plain';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function textMessage(text, format) {
|
|
47
|
+
return format === 'markdown'
|
|
48
|
+
? { msg_type: 'interactive', content: JSON.stringify({ schema: '2.0', body: { elements: [{ tag: 'markdown', content: text }] } }) }
|
|
49
|
+
: { msg_type: 'text', content: JSON.stringify({ text }) };
|
|
50
|
+
}
|
|
51
|
+
|
|
34
52
|
function nonEmptyString(value) {
|
|
35
53
|
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
36
54
|
}
|
|
@@ -773,7 +791,7 @@ export class FeishuRuntime {
|
|
|
773
791
|
if (!allowed)
|
|
774
792
|
throw Object.assign(new Error('send-permission-denied'), { code: 'send-permission-denied' });
|
|
775
793
|
return this.sendProactiveText({kind: 'group', route: {chatId: conversationId}}, text,
|
|
776
|
-
{...options, receipt: true});
|
|
794
|
+
{...options, format: checkedTextFormat(text), receipt: true});
|
|
777
795
|
}
|
|
778
796
|
|
|
779
797
|
async sendProactiveText(target, text, { signal, format = 'plain', receipt = false, beforeSend } = {}) {
|
|
@@ -804,9 +822,7 @@ export class FeishuRuntime {
|
|
|
804
822
|
signal?.throwIfAborted();
|
|
805
823
|
// Use the same native Markdown element as chat, without opening a stream
|
|
806
824
|
// or retrying as plain text after a possibly accepted delivery.
|
|
807
|
-
const
|
|
808
|
-
? { schema: '2.0', body: { elements: [{ tag: 'markdown', content: text }] } }
|
|
809
|
-
: { text };
|
|
825
|
+
const message = textMessage(text, format);
|
|
810
826
|
const client = this.#client;
|
|
811
827
|
const allowed = beforeSend === undefined || (typeof beforeSend === 'function' && beforeSend() === true);
|
|
812
828
|
signal?.throwIfAborted();
|
|
@@ -818,8 +834,7 @@ export class FeishuRuntime {
|
|
|
818
834
|
params: { receive_id_type: receiveIdType },
|
|
819
835
|
data: {
|
|
820
836
|
receive_id: receiveId,
|
|
821
|
-
|
|
822
|
-
content: JSON.stringify(content),
|
|
837
|
+
...message,
|
|
823
838
|
},
|
|
824
839
|
});
|
|
825
840
|
if (response?.code && response.code !== 0) {
|
|
@@ -918,8 +933,7 @@ export class FeishuRuntime {
|
|
|
918
933
|
const current = await client.im.v1.message.get({ path: { message_id: route.messageId } });
|
|
919
934
|
const source = current?.data?.items?.find(item => item.message_id === route.messageId);
|
|
920
935
|
if (current?.code || !source || source.deleted === true || source.chat_id !== route.conversationId
|
|
921
|
-
|| source.sender
|
|
922
|
-
|| source.sender?.id !== route.actorId || (source.thread_id || undefined) !== route.threadId
|
|
936
|
+
|| !sourceSenderMatches(source.sender, route.actorId) || (source.thread_id || undefined) !== route.threadId
|
|
923
937
|
|| (source.root_id || undefined) !== route.rootId || (source.parent_id || undefined) !== route.parentId)
|
|
924
938
|
throw Object.assign(new Error('stale-route'), { code: 'stale-route' });
|
|
925
939
|
signal?.throwIfAborted();
|
|
@@ -929,7 +943,7 @@ export class FeishuRuntime {
|
|
|
929
943
|
signal?.throwIfAborted();
|
|
930
944
|
const response = await client.im.v1.message.reply({
|
|
931
945
|
path: { message_id: route.messageId },
|
|
932
|
-
data: {
|
|
946
|
+
data: { ...textMessage(text, checkedTextFormat(text)), reply_in_thread: Boolean(route.threadId) },
|
|
933
947
|
});
|
|
934
948
|
const messageId = response?.data?.message_id;
|
|
935
949
|
if (response?.code || typeof messageId !== 'string' || !messageId)
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { isBotSenderType, sourceSenderMatches } from './external-sender.mjs';
|
|
2
|
+
|
|
1
3
|
function refuse(code) { throw Object.assign(new Error(code), { code }); }
|
|
2
4
|
const fields = ['messageId', 'conversationId', 'actorId'];
|
|
3
5
|
const optional = ['threadId', 'rootId', 'parentId'];
|
|
@@ -13,10 +15,11 @@ export async function qualifyExternalReply(client, route, signal) {
|
|
|
13
15
|
if (current?.code !== 0 || !Array.isArray(current?.data?.items)) refuse('source-unavailable');
|
|
14
16
|
const source = current?.data?.items?.find(item => item.message_id === route.messageId);
|
|
15
17
|
if (!source || source.deleted) refuse('source-not-found');
|
|
16
|
-
if (source.chat_id !== route.conversationId
|
|
17
|
-
|| source.sender
|
|
18
|
+
if (source.chat_id !== route.conversationId
|
|
19
|
+
|| !sourceSenderMatches(source.sender, source.sender?.id)
|
|
20
|
+
|| typeof source.sender.id !== 'string' || !source.sender.id
|
|
18
21
|
|| optional.some(key => (source[{threadId:'thread_id',rootId:'root_id',parentId:'parent_id'}[key]] || undefined) !== route[key]))
|
|
19
22
|
refuse('stale-route');
|
|
20
23
|
return Object.freeze({ messageId: route.messageId, conversationId: route.conversationId,
|
|
21
|
-
actorId: source.sender.id, ...Object.fromEntries(optional.filter(key => route[key] !== undefined).map(key => [key, route[key]])) });
|
|
24
|
+
actorId: isBotSenderType(source.sender) ? route.actorId : source.sender.id, ...Object.fromEntries(optional.filter(key => route[key] !== undefined).map(key => [key, route[key]])) });
|
|
22
25
|
}
|
|
@@ -4,3 +4,12 @@ export function isQqAddressedGroupMessage(message) {
|
|
|
4
4
|
|| (message.rawEventType === 'GROUP_MESSAGE_CREATE' && Array.isArray(message.mentions)
|
|
5
5
|
&& message.mentions.some(mention => mention?.is_you === true)));
|
|
6
6
|
}
|
|
7
|
+
|
|
8
|
+
/** A private (C2C) message is always addressed to the receiving application. */
|
|
9
|
+
export function isQqDirectMessage(message) {
|
|
10
|
+
return message?.kind === 'c2c' && message.rawEventType === 'C2C_MESSAGE_CREATE';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function isQqAddressedMessage(message) {
|
|
14
|
+
return isQqAddressedGroupMessage(message) || isQqDirectMessage(message);
|
|
15
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { isQqVoiceAttachment } from './voice-attachment.mjs';
|
|
2
|
+
|
|
3
|
+
export const QQ_READABLE_IMAGE_TYPES = Object.freeze(new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']));
|
|
4
|
+
const IMAGE_ALIASES = Object.freeze({ 'image/jpg': 'image/jpeg', 'image/pjpeg': 'image/jpeg', 'image/x-png': 'image/png' });
|
|
5
|
+
const IMAGE_EXTENSIONS = Object.freeze({ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp' });
|
|
6
|
+
const LABELS = Object.freeze({ image: 'image', file: 'file', voice: 'voice message', video: 'video', other: 'attachment' });
|
|
7
|
+
|
|
8
|
+
function contentType(native) {
|
|
9
|
+
return typeof native?.content_type === 'string' ? native.content_type.split(';', 1)[0].trim().toLowerCase() : '';
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** QQ labels images loosely, so the declared type, its common aliases and the file name all count. */
|
|
13
|
+
export function qqImageMediaType(native) {
|
|
14
|
+
const type = contentType(native);
|
|
15
|
+
const declared = IMAGE_ALIASES[type] ?? type;
|
|
16
|
+
if (QQ_READABLE_IMAGE_TYPES.has(declared)) return declared;
|
|
17
|
+
if (type && type !== 'image' && type !== 'application/octet-stream') return undefined;
|
|
18
|
+
const extension = typeof native?.filename === 'string' ? /\.([a-z0-9]{1,8})$/i.exec(native.filename)?.[1] : undefined;
|
|
19
|
+
return extension ? IMAGE_EXTENSIONS[extension.toLowerCase()] : undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function qqAttachmentCategory(native) {
|
|
23
|
+
if (isQqVoiceAttachment(native)) return 'voice';
|
|
24
|
+
if (qqImageMediaType(native)) return 'image';
|
|
25
|
+
const type = contentType(native);
|
|
26
|
+
if (type === 'file') return 'file';
|
|
27
|
+
if (type === 'video' || type.startsWith('video/')) return 'video';
|
|
28
|
+
if (type === 'image' || type.startsWith('image/')) return 'image-unsupported';
|
|
29
|
+
return 'other';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** QQ sometimes omits the scheme or sends plain HTTP for its own media hosts. */
|
|
33
|
+
export function qqAttachmentUrl(value) {
|
|
34
|
+
if (typeof value !== 'string') return value;
|
|
35
|
+
if (value.startsWith('//')) return `https:${value}`;
|
|
36
|
+
if (/^http:\/\//i.test(value)) return `https://${value.slice(7)}`;
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Splits native attachments into what this consumer can read and what it can only mention. */
|
|
41
|
+
export function qqReadableAttachments(attachments, { sourceImages = false, sourceFiles = false } = {}) {
|
|
42
|
+
const readable = [];
|
|
43
|
+
const skipped = [];
|
|
44
|
+
for (const native of Array.isArray(attachments) ? attachments : []) {
|
|
45
|
+
const category = qqAttachmentCategory(native);
|
|
46
|
+
if ((category === 'image' && sourceImages) || (category === 'file' && sourceFiles))
|
|
47
|
+
readable.push({ ...native, url: qqAttachmentUrl(native.url) });
|
|
48
|
+
else skipped.push(category);
|
|
49
|
+
}
|
|
50
|
+
return { readable, skipped };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function qqAttachmentLabel(native) {
|
|
54
|
+
return LABELS[qqAttachmentCategory(native)] ?? LABELS.other;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function qqSkippedAttachmentNotes(skipped, { quoted = false } = {}) {
|
|
58
|
+
return skipped.map(category => {
|
|
59
|
+
const label = category === 'image-unsupported' ? 'image in an unsupported format' : LABELS[category] ?? LABELS.other;
|
|
60
|
+
return quoted ? `[Quoted ${label} not readable by the Bot]`
|
|
61
|
+
: `[${label[0].toUpperCase()}${label.slice(1)} not readable by the Bot]`;
|
|
62
|
+
});
|
|
63
|
+
}
|