@botharness/im-provider 4.32.0-botharness.24 → 4.32.0-botharness.27
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 +292 -290
- package/package.json +2 -2
- package/plugin-src/host/delivery-adapter.mjs +5 -0
- package/plugin-src/host/delivery-service.mjs +14 -0
- package/plugin-src/host/index.mjs +2 -0
- package/src/channels/discord/discord-runtime.mjs +15 -5
- package/src/channels/discord/external-consumer.mjs +12 -1
- package/src/channels/feishu/external-cards.mjs +13 -7
- package/src/channels/feishu/external-files.mjs +40 -9
- package/src/channels/feishu/external-questions.mjs +55 -0
- package/src/channels/feishu/feishu-runtime.mjs +15 -2
- package/src/channels/feishu/multi-bot-controller.mjs +21 -4
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.27",
|
|
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": "bb0c7956896f5f5845950a0707837cd7938a11b3"
|
|
182
182
|
}
|
|
183
183
|
}
|
|
@@ -255,6 +255,11 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
|
|
|
255
255
|
throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
|
|
256
256
|
return coreController.approvalCardChecked(botId, route, card, options);
|
|
257
257
|
},
|
|
258
|
+
questionCardChecked: (botId, route, card, options) => {
|
|
259
|
+
if (channel !== 'feishu' || typeof coreController.questionCardChecked !== 'function')
|
|
260
|
+
throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
|
|
261
|
+
return coreController.questionCardChecked(botId, route, card, options);
|
|
262
|
+
},
|
|
258
263
|
historyChecked: (botId, route, query, options) => {
|
|
259
264
|
if (typeof coreController.historyChecked !== 'function')
|
|
260
265
|
throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
|
|
@@ -483,6 +483,20 @@ export class DeliveryService {
|
|
|
483
483
|
} catch (error) { throw publicOperationError(error, 'send-result-unknown'); }
|
|
484
484
|
}
|
|
485
485
|
|
|
486
|
+
async questionCardChecked(botId, route, card, options = {}) {
|
|
487
|
+
const id = botIdOf(botId);
|
|
488
|
+
cancellation(options.signal);
|
|
489
|
+
if (!/^[a-f0-9]{64}$/.test(options.expectedFingerprint ?? '') || typeof options.beforeSend !== 'function') throw deliveryError('bad-request');
|
|
490
|
+
const registration = await this.#checkedRegistrationFor(id);
|
|
491
|
+
if (registration.adapter.channel !== 'feishu' || typeof registration.adapter.questionCardChecked !== 'function') throw deliveryError('capability-unavailable');
|
|
492
|
+
this.#assertRegistered(registration);
|
|
493
|
+
try {
|
|
494
|
+
return await registration.adapter.questionCardChecked(id, route, card, { ...options,
|
|
495
|
+
signal: options.signal ? AbortSignal.any([options.signal, registration.controller.signal]) : registration.controller.signal,
|
|
496
|
+
beforeSend: () => { this.#assertRegistered(registration); return options.beforeSend() === true; } });
|
|
497
|
+
} catch (error) { throw publicOperationError(error, 'send-result-unknown'); }
|
|
498
|
+
}
|
|
499
|
+
|
|
486
500
|
async historyChecked(botId, route, query, options = {}) {
|
|
487
501
|
const id = botIdOf(botId);
|
|
488
502
|
cancellation(options.signal);
|
|
@@ -103,6 +103,8 @@ export function createImHostPlugin(internals = {}) {
|
|
|
103
103
|
inboundVersion: 1,
|
|
104
104
|
fileVersion: 1,
|
|
105
105
|
approvalCardVersion: 1,
|
|
106
|
+
questionCardVersion: 1,
|
|
107
|
+
questionCardChecked: (botId, route, card, options) => deliveryService.questionCardChecked(botId, route, card, options),
|
|
106
108
|
approvalRuleCardVersion: 2,
|
|
107
109
|
pairingCardVersion: 1,
|
|
108
110
|
approvalCardChecked: (botId, route, card, options) => deliveryService.approvalCardChecked(botId, route, card, options),
|
|
@@ -10,7 +10,7 @@ import { DiscordApi } from './discord-api.mjs';
|
|
|
10
10
|
import { createDiscordReachable } from './reachable-conversations.mjs';
|
|
11
11
|
import { createDiscordHistoryReader } from './history-reader.mjs';
|
|
12
12
|
import { createDiscordBridgeStatus, DiscordHarnessBridge } from './discord-bridge.mjs';
|
|
13
|
-
import { discordRefusal, verifiedDiscordAccount, discordMessageContentAllowed, inspectDiscordSourceChannel, normalizeDiscordExternalText,
|
|
13
|
+
import { discordRefusal, discordSnowflake, verifiedDiscordAccount, discordMessageContentAllowed, discordMessageMentionsAccount, inspectDiscordSourceChannel, normalizeDiscordExternalText,
|
|
14
14
|
qualifyDiscordReply, sendDiscordReply, sendDiscordCheckedText } from './external-consumer.mjs';
|
|
15
15
|
|
|
16
16
|
const DISCORD_GATEWAY_INTENTS = (1 << 0) | (1 << 9) | (1 << 12) | (1 << 15);
|
|
@@ -939,19 +939,29 @@ export class DiscordRuntime {
|
|
|
939
939
|
if (!this.#account || !this.#status.ready || generation !== this.#generation
|
|
940
940
|
|| !message?.guild_id || message.webhook_id || message.author?.id === this.#account.userId
|
|
941
941
|
|| !Array.isArray(message.mentions)) return;
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
if (!mentioned &&
|
|
942
|
+
let mentioned = message.mentions.some(user => user.id === this.#account.userId);
|
|
943
|
+
const roleCandidate = Array.isArray(message.mention_roles) && message.mention_roles.some(discordSnowflake);
|
|
944
|
+
if (message.author?.bot === true && !mentioned && !roleCandidate) return;
|
|
945
|
+
if (!mentioned && !roleCandidate && (!this.#ordinaryAuthorized || this.#externalOrdinaryText() !== true
|
|
945
946
|
|| typeof message.content !== 'string' || !message.content.trim())) return;
|
|
946
947
|
const checked = this.#checkedLifetime();
|
|
948
|
+
let channel;
|
|
949
|
+
if (!mentioned && roleCandidate) {
|
|
950
|
+
channel = await inspectDiscordSourceChannel(checked.api, message.channel_id, checked.account, checked.signal);
|
|
951
|
+
checked.assertCurrent();
|
|
952
|
+
mentioned = discordMessageMentionsAccount(message, checked.account, channel);
|
|
953
|
+
}
|
|
947
954
|
if (!mentioned) {
|
|
955
|
+
if (message.author?.bot === true) return;
|
|
956
|
+
if (!this.#ordinaryAuthorized || this.#externalOrdinaryText() !== true
|
|
957
|
+
|| typeof message.content !== 'string' || !message.content.trim()) return;
|
|
948
958
|
const application = await checked.api.getCurrentApplication({ signal: checked.signal });
|
|
949
959
|
if (verifiedDiscordAccount({ id: checked.account.userId, bot: true }, application).fingerprint !== checked.account.fingerprint)
|
|
950
960
|
throw discordRefusal('account-changed');
|
|
951
961
|
checked.assertCurrent();
|
|
952
962
|
if (!discordMessageContentAllowed(application) || this.#externalOrdinaryText() !== true) return;
|
|
953
963
|
}
|
|
954
|
-
|
|
964
|
+
channel ??= await inspectDiscordSourceChannel(checked.api, message.channel_id, checked.account, checked.signal);
|
|
955
965
|
let event = normalizeDiscordExternalText(message, { botId: this.#config.botId, account: checked.account,
|
|
956
966
|
channel, eventId: `gateway:${this.#sessionId}:${sequence}`, ordinaryText: !mentioned });
|
|
957
967
|
checked.assertCurrent();
|
|
@@ -89,7 +89,11 @@ export async function inspectDiscordSourceChannel(api, channelId, account, signa
|
|
|
89
89
|
signal?.throwIfAborted();
|
|
90
90
|
const name = [guild.name, parent.name].every(value => typeof value === 'string' && value.trim())
|
|
91
91
|
? `${guild.name.trim()} #${parent.name.trim()}`.slice(0, 512) : undefined;
|
|
92
|
+
const ownManagedRoleIds = guild.roles.filter(role => discordSnowflake(role.id)
|
|
93
|
+
&& role.id !== guild.id && role.managed === true && role.tags?.bot_id === account.userId
|
|
94
|
+
&& member.roles.includes(role.id)).map(role => role.id);
|
|
92
95
|
return { guildId: guild.id, conversationId: parent.id, channelId: channel.id, ...(name ? { name } : {}),
|
|
96
|
+
...(ownManagedRoleIds.length ? { ownManagedRoleIds } : {}),
|
|
93
97
|
...(isThread ? { threadId: channel.id } : {}) };
|
|
94
98
|
} catch (error) { throw nativeFailure(error, 'source-not-found'); }
|
|
95
99
|
}
|
|
@@ -115,6 +119,13 @@ export function normalizeDiscordHistoryText(message, identity) {
|
|
|
115
119
|
return normalizeDiscordHumanText(message, identity, false);
|
|
116
120
|
}
|
|
117
121
|
|
|
122
|
+
/** Role ownership comes only from the checked current guild/member, never message text or names. */
|
|
123
|
+
export function discordMessageMentionsAccount(message, account, channel) {
|
|
124
|
+
return message.mentions.some(user => user.id === account.userId)
|
|
125
|
+
|| (Array.isArray(message.mention_roles) && message.mention_roles.some(roleId =>
|
|
126
|
+
discordSnowflake(roleId) && channel.ownManagedRoleIds?.includes(roleId)));
|
|
127
|
+
}
|
|
128
|
+
|
|
118
129
|
function normalizeDiscordHumanText(message, { botId, account, channel, eventId }, requireMention, allowBots = false) {
|
|
119
130
|
if (!discordSnowflake(message?.id) || !discordSnowflake(message?.author?.id)
|
|
120
131
|
|| (message.author.bot === true && !allowBots) || message.webhook_id || message.author.id === account.userId
|
|
@@ -122,7 +133,7 @@ function normalizeDiscordHumanText(message, { botId, account, channel, eventId }
|
|
|
122
133
|
|| message.content.length > 16000 || !Array.isArray(message.mentions)) return null;
|
|
123
134
|
if (message.guild_id !== channel.guildId || message.channel_id !== channel.channelId)
|
|
124
135
|
throw discordRefusal('stale-route');
|
|
125
|
-
const mentionedAccount = message
|
|
136
|
+
const mentionedAccount = discordMessageMentionsAccount(message, account, channel);
|
|
126
137
|
if ((requireMention || message.author.bot === true) && !mentionedAccount) return null;
|
|
127
138
|
const timestamp = Date.parse(message.timestamp);
|
|
128
139
|
if (!Number.isFinite(timestamp) || typeof eventId !== 'string' || !eventId || eventId.length > 512)
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { qualifyExternalReply } from './reply-context.mjs';
|
|
2
|
+
import { questionActionValues } from './external-questions.mjs';
|
|
2
3
|
|
|
3
4
|
const refuse = (code) => { throw Object.assign(new Error(code), { code }); };
|
|
4
5
|
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
@@ -62,7 +63,8 @@ export function normalizeExternalCardAction(event, identity) {
|
|
|
62
63
|
const appId = event?.header?.app_id ?? event?.app_id;
|
|
63
64
|
if (appId !== undefined && appId !== identity.appId) refuse('account-changed');
|
|
64
65
|
const value = event?.action?.value;
|
|
65
|
-
|
|
66
|
+
const question = value?.namespace === 'botharness/question-v1';
|
|
67
|
+
if (!question && !['botharness/approval-v1', 'botharness/pairing-v1', 'botharness/approval-rule-v1'].includes(value?.namespace)) return null;
|
|
66
68
|
const actorId = event?.operator?.open_id;
|
|
67
69
|
const messageId = event?.context?.open_message_id;
|
|
68
70
|
const conversationId = event?.context?.open_chat_id;
|
|
@@ -84,13 +86,13 @@ export function normalizeExternalCardAction(event, identity) {
|
|
|
84
86
|
return Object.freeze({ kind: 'pairing', version: 1, channel: 'feishu', botId: identity.botId, fingerprint: identity.fingerprint,
|
|
85
87
|
actorId, messageId, conversationId, requestId: value.requestId, action: value.action, ...(roleId ? { roleId } : {}) });
|
|
86
88
|
}
|
|
87
|
-
if (event.action.tag !== 'button' || !['allowed-once', 'rejected'].includes(value.action)) refuse('invalid-inbound');
|
|
89
|
+
if (event.action.tag !== 'button' || (!question && !['allowed-once', 'rejected'].includes(value.action))) refuse('invalid-inbound');
|
|
88
90
|
return Object.freeze({ version: 1, channel: 'feishu', botId: identity.botId, fingerprint: identity.fingerprint,
|
|
89
|
-
actorId, messageId, conversationId, requestId: value.requestId, action: value.action });
|
|
91
|
+
actorId, messageId, conversationId, requestId: value.requestId, ...(question ? { action: 'answer', values: questionActionValues(event) } : { action: value.action }) });
|
|
90
92
|
}
|
|
91
93
|
|
|
92
|
-
export async function replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend } = {}) {
|
|
93
|
-
const content =
|
|
94
|
+
export async function replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend, render = externalApprovalCard } = {}) {
|
|
95
|
+
const content = render(card);
|
|
94
96
|
assertCurrent?.();
|
|
95
97
|
const current = await qualifyExternalReply(client, route, signal);
|
|
96
98
|
if (current.actorId !== route.actorId) refuse('stale-route');
|
|
@@ -107,8 +109,8 @@ export async function replyExternalApprovalCard(client, route, card, { signal, a
|
|
|
107
109
|
return { sent: true, receipt: { version: 1, messageId: result.data.message_id, conversationId: result.data.chat_id } };
|
|
108
110
|
}
|
|
109
111
|
|
|
110
|
-
export async function updateExternalApprovalCard(client, identity, receipt, card, { signal, assertCurrent, beforeSend } = {}) {
|
|
111
|
-
const content =
|
|
112
|
+
export async function updateExternalApprovalCard(client, identity, receipt, card, { signal, assertCurrent, beforeSend, render = externalApprovalCard, privateOnly = false } = {}) {
|
|
113
|
+
const content = render(card);
|
|
112
114
|
if (!identifier(receipt?.messageId, 'om') || !identifier(receipt?.conversationId, 'oc')) refuse('bad-request');
|
|
113
115
|
assertCurrent?.();
|
|
114
116
|
const result = await client.im.v1.message.get({ path: { message_id: receipt.messageId } }, { signal });
|
|
@@ -117,6 +119,10 @@ export async function updateExternalApprovalCard(client, identity, receipt, card
|
|
|
117
119
|
((source.sender.id_type === 'app_id' && source.sender.id === identity.appId) ||
|
|
118
120
|
(source.sender.id_type === 'open_id' && source.sender.id === identity.botOpenId));
|
|
119
121
|
if (result?.code !== 0 || !ownSender || source.deleted || source.chat_id !== receipt.conversationId || source.msg_type !== 'interactive') refuse('stale-route');
|
|
122
|
+
if (privateOnly) {
|
|
123
|
+
const chat = await client.im.v1.chat.get({ path: { chat_id: receipt.conversationId } }, { signal });
|
|
124
|
+
if (chat?.code !== 0 || chat?.data?.chat_mode !== 'p2p') refuse('stale-route');
|
|
125
|
+
}
|
|
120
126
|
assertCurrent?.();
|
|
121
127
|
signal?.throwIfAborted();
|
|
122
128
|
if (typeof beforeSend !== 'function' || beforeSend() !== true) refuse('stale-route');
|
|
@@ -19,39 +19,70 @@ export async function checkedReplySource(client, route, signal) {
|
|
|
19
19
|
return source;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
async function
|
|
22
|
+
async function parentResources(client, route, signal, { sourceVideos = false, sourceImages = false, sourceVoiceAudio = false } = {}) {
|
|
23
23
|
if (!route.parentId || route.parentId === route.messageId) return undefined;
|
|
24
24
|
signal?.throwIfAborted();
|
|
25
25
|
const result = await client.im.v1.message.get({ path: { message_id: route.parentId } });
|
|
26
26
|
const file = result?.data?.items?.find(item => item.message_id === route.parentId);
|
|
27
27
|
if (result?.code || !file || file.deleted === true || file.chat_id !== route.conversationId)
|
|
28
28
|
throw failure('stale-route');
|
|
29
|
-
if (file.msg_type !== 'file'
|
|
29
|
+
if (file.msg_type !== 'file' && !(sourceVideos && file.msg_type === 'media')
|
|
30
|
+
&& !(sourceVoiceAudio && file.msg_type === 'audio')) return undefined;
|
|
30
31
|
if (file.thread_id && route.threadId && file.thread_id !== route.threadId) throw failure('stale-route');
|
|
31
32
|
let content;
|
|
32
33
|
try { content = JSON.parse(file.body?.content); } catch { throw failure('invalid-inbound'); }
|
|
34
|
+
if (file.msg_type === 'audio') return parentAudio(route, file, content, signal);
|
|
33
35
|
if (typeof content?.file_key !== 'string' || !content.file_key || content.file_key.length > 512
|
|
34
|
-
|| typeof content.file_name !== 'string' || !content.file_name || content.file_name.length > 512
|
|
36
|
+
|| typeof content.file_name !== 'string' || !content.file_name || content.file_name.length > 512
|
|
37
|
+
|| (content.duration !== undefined && (!Number.isSafeInteger(content.duration) || content.duration < 0))
|
|
38
|
+
|| (file.msg_type === 'media' && content.image_key !== undefined &&
|
|
39
|
+
(typeof content.image_key !== 'string' || !content.image_key || content.image_key.length > 512)))
|
|
35
40
|
throw failure('invalid-inbound');
|
|
36
41
|
signal?.throwIfAborted();
|
|
37
|
-
|
|
42
|
+
const attachment = Object.freeze({
|
|
38
43
|
id: createHash('sha256').update(JSON.stringify([route.conversationId, file.message_id, content.file_key])).digest('hex'),
|
|
39
44
|
messageId: file.message_id, resourceKey: content.file_key, name: content.file_name,
|
|
45
|
+
...(file.msg_type === 'media' ? { mediaType: 'video/unknown' } : {}),
|
|
40
46
|
});
|
|
47
|
+
const poster = file.msg_type === 'media' && sourceImages && content.image_key ? Object.freeze({
|
|
48
|
+
id: createHash('sha256').update(JSON.stringify([route.conversationId, file.message_id, content.image_key])).digest('hex'),
|
|
49
|
+
messageId: file.message_id, resourceKey: content.image_key, name: 'video-cover', mediaType: 'image/unknown',
|
|
50
|
+
}) : undefined;
|
|
51
|
+
return Object.freeze({ attachments: Object.freeze([attachment, ...(poster ? [poster] : [])]),
|
|
52
|
+
...(file.msg_type === 'media' ? { video: Object.freeze({ itemId: attachment.id,
|
|
53
|
+
...(content.duration === undefined ? {} : { durationMs: content.duration }),
|
|
54
|
+
...(poster ? { posterAttachmentId: poster.id } : {}),
|
|
55
|
+
}) } : {}),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function parentAudio(route, file, content, signal) {
|
|
60
|
+
if (typeof content?.file_key !== 'string' || !content.file_key || content.file_key.length > 512
|
|
61
|
+
|| (content.duration !== undefined && (!Number.isSafeInteger(content.duration) || content.duration < 0)))
|
|
62
|
+
throw failure('invalid-inbound');
|
|
63
|
+
signal?.throwIfAborted();
|
|
64
|
+
const attachment = Object.freeze({
|
|
65
|
+
id: createHash('sha256').update(JSON.stringify([route.conversationId, file.message_id, content.file_key])).digest('hex'),
|
|
66
|
+
messageId: file.message_id, resourceKey: content.file_key, name: 'voice.opus', mediaType: 'audio/unknown',
|
|
67
|
+
});
|
|
68
|
+
return Object.freeze({ attachments: Object.freeze([attachment]), voice: Object.freeze({
|
|
69
|
+
transcript: 'unavailable', itemId: attachment.id,
|
|
70
|
+
...(content.duration === undefined ? {} : { durationMs: content.duration }),
|
|
71
|
+
}) });
|
|
41
72
|
}
|
|
42
73
|
|
|
43
|
-
export async function externalAttachments(client, evidence, signal) {
|
|
74
|
+
export async function externalAttachments(client, evidence, signal, options) {
|
|
44
75
|
if (evidence.attachments?.length || !evidence.mentionedAccount || !evidence.reply.parentId) return evidence;
|
|
45
|
-
const
|
|
46
|
-
return
|
|
76
|
+
const resources = await parentResources(client, evidence.reply, signal, options);
|
|
77
|
+
return resources ? Object.freeze({ ...evidence, ...resources }) : evidence;
|
|
47
78
|
}
|
|
48
79
|
|
|
49
80
|
export async function readExternalFile(client, route, attachment, { signal, assertCurrent }) {
|
|
50
81
|
const source = await checkedReplySource(client, route, signal);
|
|
51
82
|
const ownImages = nativeImageContent(source, route.conversationId);
|
|
52
|
-
const current = attachment.mediaType === 'image/unknown'
|
|
83
|
+
const current = attachment.mediaType === 'image/unknown' && attachment.messageId === route.messageId
|
|
53
84
|
? ownImages?.attachments.find(item => item.id === attachment.id)
|
|
54
|
-
: await
|
|
85
|
+
: (await parentResources(client, route, signal, { sourceVideos: true, sourceImages: true, sourceVoiceAudio: true }))?.attachments.find(item => item.id === attachment.id);
|
|
55
86
|
if (!current || JSON.stringify(current) !== JSON.stringify(attachment)) throw failure('stale-route');
|
|
56
87
|
assertCurrent();
|
|
57
88
|
const resource = await client.im.v1.messageResource.get({
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
|
|
2
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
3
|
+
const text = (value, max) => typeof value === 'string' && value.length > 0 && value.length <= max;
|
|
4
|
+
const refuse = () => { throw Object.assign(new Error('bad-request'), { code: 'bad-request' }); };
|
|
5
|
+
const plain = (value) => String(value).replace(/[\\`*_{}[\]()<>#|!]/g, (character) => String.fromCharCode(92) + character);
|
|
6
|
+
export function externalQuestionCard(value) {
|
|
7
|
+
if (!value || !uuid.test(value.requestId ?? '') || !/^[A-F0-9]{12}$/.test(value.reference ?? '') ||
|
|
8
|
+
!text(value.detail, 16000) || !['pending', 'answered', 'cancelled', 'expired', 'web-required'].includes(value.status) ||
|
|
9
|
+
!Array.isArray(value.questions) || value.questions.length > 3 || JSON.stringify(value.questions).length > 16000) refuse();
|
|
10
|
+
const labels = { pending: 'Human question / Human 提问', answered: 'Answered / 已回答', cancelled: 'Cancelled / 已取消', expired: 'Expired / 已过期', 'web-required': 'Check in Web / 请在 Web 核对' };
|
|
11
|
+
const elements = [{ tag: 'markdown', content: plain(labels[value.status] + '\n' + value.detail) }];
|
|
12
|
+
if (value.status === 'pending') {
|
|
13
|
+
if (!value.questions.length) refuse();
|
|
14
|
+
const fields = value.questions.flatMap((question, index) => {
|
|
15
|
+
if (!text(question.id, 512) || !text(question.question, 16000) ||
|
|
16
|
+
question.options !== undefined && (!Array.isArray(question.options) || question.options.length > 100)) refuse();
|
|
17
|
+
if ([question.header, question.detail].some((value) => value !== undefined && typeof value !== 'string')) refuse();
|
|
18
|
+
const fields = [{ tag: 'markdown', content: plain([question.header, (index + 1) + '. ' + question.question, question.detail].filter(Boolean).join('\n')) }];
|
|
19
|
+
for (const option of question.options ?? []) {
|
|
20
|
+
if (option.description !== undefined && typeof option.description !== 'string') refuse();
|
|
21
|
+
if (option.description) fields.push({ tag: 'markdown', content: plain(option.label + ': ' + option.description) });
|
|
22
|
+
}
|
|
23
|
+
if (question.options?.length) fields.push({ tag: question.multiSelect === true ? 'multi_select_static' : 'select_static',
|
|
24
|
+
name: 'q' + index + '_choices', placeholder: { tag: 'plain_text', content: 'Choose / 选择' },
|
|
25
|
+
options: question.options.map((option, pick) => {
|
|
26
|
+
if (!text(option.label, 2000)) refuse();
|
|
27
|
+
return { text: { tag: 'plain_text', content: option.label }, value: String(pick) };
|
|
28
|
+
}) });
|
|
29
|
+
fields.push({ tag: 'input', name: 'q' + index + '_custom', input_type: 'multiline_text', max_length: 1000,
|
|
30
|
+
placeholder: { tag: 'plain_text', content: 'Or enter your answer / 或填写自己的答案' } });
|
|
31
|
+
return fields;
|
|
32
|
+
});
|
|
33
|
+
fields.push({ tag: 'button', name: 'answer_submit', type: 'primary_filled', form_action_type: 'submit',
|
|
34
|
+
text: { tag: 'plain_text', content: 'Submit answers / 提交答案' },
|
|
35
|
+
behaviors: [{ type: 'callback', value: { namespace: 'botharness/question-v1', requestId: value.requestId, count: value.questions.length } }] });
|
|
36
|
+
elements.push({ tag: 'form', name: 'questions', elements: fields });
|
|
37
|
+
}
|
|
38
|
+
return JSON.stringify({ schema: '2.0', config: { update_multi: true },
|
|
39
|
+
header: { title: { tag: 'plain_text', content: labels[value.status] + ' · ' + value.reference }, template: 'blue' }, body: { elements } });
|
|
40
|
+
}
|
|
41
|
+
export function questionActionValues(event) {
|
|
42
|
+
const count = event.action.value.count;
|
|
43
|
+
const form = event.action.form_value;
|
|
44
|
+
if (!Number.isInteger(count) || count < 1 || count > 3 || !form || typeof form !== 'object' || Array.isArray(form) || JSON.stringify(form).length > 16000) refuse();
|
|
45
|
+
const allowed = new Set(Array.from({ length: count }, (_, i) => ['q' + i + '_choices', 'q' + i + '_custom']).flat());
|
|
46
|
+
if (Object.keys(form).some((key) => !allowed.has(key))) refuse();
|
|
47
|
+
return Array.from({ length: count }, (_, i) => {
|
|
48
|
+
const selected = form['q' + i + '_choices'];
|
|
49
|
+
const values = selected === undefined || selected === null || selected === '' ? [] : Array.isArray(selected) ? selected : [selected];
|
|
50
|
+
if (values.length > 100 || values.some((value) => typeof value !== 'string' || !/^(0|[1-9][0-9]?)$/.test(value)) || new Set(values).size !== values.length) refuse();
|
|
51
|
+
const custom = form['q' + i + '_custom'];
|
|
52
|
+
if (custom !== undefined && (typeof custom !== 'string' || custom.length > 1000)) refuse();
|
|
53
|
+
return { selected: values.map(Number), ...(custom?.trim() ? { custom: custom.trim() } : {}) };
|
|
54
|
+
});
|
|
55
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { consumeExternalCardAction } from './external-cards.mjs';
|
|
2
2
|
import { reactExternalMessage } from './external-reactions.mjs';
|
|
3
3
|
import { createExternalNameCache, externalNames } from './external-names.mjs';
|
|
4
|
+
import { externalQuestionCard } from './external-questions.mjs';
|
|
4
5
|
import { qualifyExternalReply } from './reply-context.mjs';
|
|
5
6
|
import { readExternalHistory } from './history-reader.mjs';
|
|
6
7
|
import { externalAttachments, readExternalFile, replyExternalFile } from './external-files.mjs';
|
|
@@ -872,6 +873,18 @@ export class FeishuRuntime {
|
|
|
872
873
|
: replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend });
|
|
873
874
|
}
|
|
874
875
|
|
|
876
|
+
async questionCardChecked(identity, route, card, { signal, beforeSend, update = false } = {}) {
|
|
877
|
+
const client = this.#client;
|
|
878
|
+
const assertCurrent = () => {
|
|
879
|
+
signal?.throwIfAborted();
|
|
880
|
+
if (!client || this.#client !== client || this.#consumerMode !== 'external-consumer')
|
|
881
|
+
throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
|
|
882
|
+
};
|
|
883
|
+
assertCurrent();
|
|
884
|
+
return update ? updateExternalApprovalCard(client, identity, route, card, { signal, assertCurrent, beforeSend, render: externalQuestionCard, privateOnly: true })
|
|
885
|
+
: replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend, render: externalQuestionCard, privateOnly: true });
|
|
886
|
+
}
|
|
887
|
+
|
|
875
888
|
async historyChecked(identity, route, query, { signal } = {}) {
|
|
876
889
|
const client = this.#client;
|
|
877
890
|
if (!client || this.#consumerMode !== 'external-consumer')
|
|
@@ -891,10 +904,10 @@ export class FeishuRuntime {
|
|
|
891
904
|
return result;
|
|
892
905
|
}
|
|
893
906
|
|
|
894
|
-
async enrichExternal(evidence, { signal } = {}) {
|
|
907
|
+
async enrichExternal(evidence, { signal, sourceVideos = false, sourceImages = false, sourceVoiceAudio = false } = {}) {
|
|
895
908
|
const client = this.#client;
|
|
896
909
|
if (!client || this.#consumerMode !== 'external-consumer') throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
|
|
897
|
-
const result = await externalAttachments(client, evidence, signal);
|
|
910
|
+
const result = await externalAttachments(client, evidence, signal, { sourceVideos, sourceImages, sourceVoiceAudio });
|
|
898
911
|
signal?.throwIfAborted();
|
|
899
912
|
if (this.#client !== client) throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
|
|
900
913
|
return result;
|
|
@@ -602,11 +602,11 @@ export class MultiBotDshFeishuController {
|
|
|
602
602
|
const account = await this.#deliveryAccount(config);
|
|
603
603
|
return { version: 1, botId, channel: 'feishu', account,
|
|
604
604
|
connected: isConnected(connectionStatus(this.#runtimes.get(botId))),
|
|
605
|
-
capabilities: ['reachable-conversations-checked', 'proactive-fence-checked', 'proactive-text-checked', 'proactive-receipt-checked', 'own-text-echo', 'exclusive-text-consumer', 'reply-text-checked', 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'history-text-checked', 'thread-history-text-checked', 'source-file-checked', 'reply-file-checked', 'approval-card-checked', 'approval-card-update-checked', 'approval-action-consumer', 'reaction-write-checked', 'source-image-checked', 'approval-rule-card-checked', 'approval-rule-all-opaque-card-checked', 'pairing-card-checked'] };
|
|
605
|
+
capabilities: ['source-video-checked', 'source-voice-audio-checked', 'question-card-checked', 'question-card-update-checked', 'question-action-consumer', 'reachable-conversations-checked', 'proactive-fence-checked', 'proactive-text-checked', 'proactive-receipt-checked', 'own-text-echo', 'exclusive-text-consumer', 'reply-text-checked', 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'history-text-checked', 'thread-history-text-checked', 'source-file-checked', 'reply-file-checked', 'approval-card-checked', 'approval-card-update-checked', 'approval-action-consumer', 'reaction-write-checked', 'source-image-checked', 'approval-rule-card-checked', 'approval-rule-all-opaque-card-checked', 'pairing-card-checked'] };
|
|
606
606
|
});
|
|
607
607
|
}
|
|
608
608
|
|
|
609
|
-
async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceFiles = false, sourceImages = false, onEcho, onAction } = {}) {
|
|
609
|
+
async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceFiles = false, sourceImages = false, sourceVideos = false, sourceVoiceAudio = false, onEcho, onAction } = {}) {
|
|
610
610
|
this.#assertOpen();
|
|
611
611
|
return this.#withBotTransition(botId, async () => {
|
|
612
612
|
this.#assertOpen();
|
|
@@ -615,7 +615,7 @@ export class MultiBotDshFeishuController {
|
|
|
615
615
|
const account = await this.#deliveryAccount(config);
|
|
616
616
|
if (account.fingerprint !== expectedFingerprint)
|
|
617
617
|
throw Object.assign(new Error('account-changed'), { code: 'account-changed' });
|
|
618
|
-
const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal, sourceFiles, sourceImages, onEcho, onAction });
|
|
618
|
+
const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal, sourceFiles, sourceImages, sourceVideos, sourceVoiceAudio, onEcho, onAction });
|
|
619
619
|
try {
|
|
620
620
|
const saved = await this.#configStore.saveBot({ ...config, consumerMode: 'external-consumer' });
|
|
621
621
|
const resolved = await this.#credentials.resolve(saved.secretRef);
|
|
@@ -728,6 +728,23 @@ export class MultiBotDshFeishuController {
|
|
|
728
728
|
});
|
|
729
729
|
}
|
|
730
730
|
|
|
731
|
+
async questionCardChecked(botId, route, card, { expectedFingerprint, signal, beforeSend, update = false } = {}) {
|
|
732
|
+
this.#assertOpen();
|
|
733
|
+
return this.#withBotTransition(botId, async () => {
|
|
734
|
+
this.#assertOpen();
|
|
735
|
+
signal?.throwIfAborted();
|
|
736
|
+
const config = this.#requireBot(botId);
|
|
737
|
+
const account = await this.#deliveryAccount(config);
|
|
738
|
+
if (account.fingerprint !== expectedFingerprint) throw Object.assign(new Error('account-changed'), { code: 'account-changed' });
|
|
739
|
+
const runtime = this.#runtimes.get(botId);
|
|
740
|
+
if (config.consumerMode !== 'external-consumer' || !isConnected(connectionStatus(runtime))
|
|
741
|
+
|| typeof runtime.questionCardChecked !== 'function') throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
|
|
742
|
+
const lease = this.#inboundConsumers.signalFor(botId, expectedFingerprint);
|
|
743
|
+
return runtime.questionCardChecked({ appId: config.appId, botOpenId: config.botOpenId }, route, card,
|
|
744
|
+
{ signal: signal ? AbortSignal.any([signal, lease]) : lease, beforeSend, update });
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
|
|
731
748
|
async externalFileChecked(botId, route, value, { expectedFingerprint, signal, reply = false } = {}) {
|
|
732
749
|
this.#assertOpen();
|
|
733
750
|
return this.#withBotTransition(botId, async () => {
|
|
@@ -1571,7 +1588,7 @@ export class MultiBotDshFeishuController {
|
|
|
1571
1588
|
if (evidence === null) return { accepted: true, ignored: true };
|
|
1572
1589
|
if (evidence.attachments?.length && !this.#inboundConsumers.acceptsImages(config.id)) return { accepted: true, ignored: true };
|
|
1573
1590
|
const named = typeof runtime.enrichExternalNames === 'function' ? await runtime.enrichExternalNames(evidence, { signal }) : evidence;
|
|
1574
|
-
const enriched = this.#inboundConsumers.acceptsFiles(config.id) && typeof runtime.enrichExternal === 'function' ? await runtime.enrichExternal(named, { signal }) : named;
|
|
1591
|
+
const enriched = this.#inboundConsumers.acceptsFiles(config.id) && typeof runtime.enrichExternal === 'function' ? await runtime.enrichExternal(named, { signal, sourceVideos: this.#inboundConsumers.acceptsVideos(config.id), sourceImages: this.#inboundConsumers.acceptsImages(config.id), sourceVoiceAudio: this.#inboundConsumers.acceptsVoiceAudio(config.id) }) : named;
|
|
1575
1592
|
return this.#inboundConsumers.accept(config.id, enriched, signal);
|
|
1576
1593
|
}),
|
|
1577
1594
|
}));
|