@botharness/im-provider 4.32.0-botharness.24 → 4.32.0-botharness.28

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botharness/im-provider",
3
- "version": "4.32.0-botharness.24",
3
+ "version": "4.32.0-botharness.28",
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": "7505ce6fcda26c02810781fde9d4da81dab28a68"
181
+ "upstreamSource": "b79f94809af560313bda30398ae37f95fd9894c1"
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);
@@ -599,7 +613,8 @@ export class DeliveryService {
599
613
  throw deliveryError('capability-unavailable');
600
614
  }
601
615
  if (account.account?.fingerprint !== expectedFingerprint) throw deliveryError('account-changed');
602
- const receiptConversation = adapter.channel === 'feishu' && target.kind === 'group'
616
+ const receiptConversation = adapter.channel === 'feishu'
617
+ && (target.kind === 'group' || typeof target.route.chatId === 'string')
603
618
  ? target.route.chatId : adapter.channel === 'slack' && target.kind === 'conversation'
604
619
  ? target.route.channelId : adapter.channel === 'qq' && target.kind === 'group'
605
620
  ? target.route.groupOpenId : adapter.channel === 'weixin' && target.kind === 'user'
@@ -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),
@@ -13,7 +13,7 @@ export class DiscordController extends TokenBotController {
13
13
  deriveIdentity: deriveDiscordBotIdentity,
14
14
  maskPlatformId: maskDiscordBotId,
15
15
  checkedDelivery: {
16
- 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',
16
+ 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', 'reply-standalone-checked',
17
17
  'history-text-checked', 'thread-history-text-checked', 'source-file-checked', 'reply-file-checked'],
18
18
  inspectAccount: async (token, config, { signal }) => {
19
19
  const api = (options.createApi ?? (args => new DiscordApi(args)))({ token });
@@ -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);
@@ -817,7 +817,7 @@ export class DiscordRuntime {
817
817
  d: {
818
818
  token: this.#token,
819
819
  intents: this.#config.consumerMode === 'external-consumer'
820
- ? (1 << 0) | (1 << 9) | (this.#ordinaryAuthorized && this.#externalOrdinaryText() === true ? (1 << 15) : 0)
820
+ ? (1 << 0) | (1 << 9) | (1 << 12) | (this.#ordinaryAuthorized && this.#externalOrdinaryText() === true ? (1 << 15) : 0)
821
821
  : DISCORD_GATEWAY_INTENTS,
822
822
  properties: {
823
823
  os: process.platform,
@@ -937,21 +937,32 @@ 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.webhook_id || message.author?.id === this.#account.userId
941
- || !Array.isArray(message.mentions)) return;
942
- const mentioned = message.mentions.some(user => user.id === this.#account.userId);
943
- if (message.author?.bot === true && !mentioned) return;
944
- if (!mentioned && (!this.#ordinaryAuthorized || this.#externalOrdinaryText() !== true
940
+ || message?.webhook_id || message?.author?.id === this.#account.userId
941
+ || !Array.isArray(message?.mentions)) return;
942
+ if (!message.guild_id) return this.#acceptExternalDirectMessage(message, sequence);
943
+ let mentioned = message.mentions.some(user => user.id === this.#account.userId);
944
+ const roleCandidate = Array.isArray(message.mention_roles) && message.mention_roles.some(discordSnowflake);
945
+ if (message.author?.bot === true && !mentioned && !roleCandidate) return;
946
+ if (!mentioned && !roleCandidate && (!this.#ordinaryAuthorized || this.#externalOrdinaryText() !== true
945
947
  || typeof message.content !== 'string' || !message.content.trim())) return;
946
948
  const checked = this.#checkedLifetime();
949
+ let channel;
950
+ if (!mentioned && roleCandidate) {
951
+ channel = await inspectDiscordSourceChannel(checked.api, message.channel_id, checked.account, checked.signal);
952
+ checked.assertCurrent();
953
+ mentioned = discordMessageMentionsAccount(message, checked.account, channel);
954
+ }
947
955
  if (!mentioned) {
956
+ if (message.author?.bot === true) return;
957
+ if (!this.#ordinaryAuthorized || this.#externalOrdinaryText() !== true
958
+ || typeof message.content !== 'string' || !message.content.trim()) return;
948
959
  const application = await checked.api.getCurrentApplication({ signal: checked.signal });
949
960
  if (verifiedDiscordAccount({ id: checked.account.userId, bot: true }, application).fingerprint !== checked.account.fingerprint)
950
961
  throw discordRefusal('account-changed');
951
962
  checked.assertCurrent();
952
963
  if (!discordMessageContentAllowed(application) || this.#externalOrdinaryText() !== true) return;
953
964
  }
954
- const channel = await inspectDiscordSourceChannel(checked.api, message.channel_id, checked.account, checked.signal);
965
+ channel ??= await inspectDiscordSourceChannel(checked.api, message.channel_id, checked.account, checked.signal);
955
966
  let event = normalizeDiscordExternalText(message, { botId: this.#config.botId, account: checked.account,
956
967
  channel, eventId: `gateway:${this.#sessionId}:${sequence}`, ordinaryText: !mentioned });
957
968
  checked.assertCurrent();
@@ -965,6 +976,23 @@ export class DiscordRuntime {
965
976
  this.#status.messagesReceived++;
966
977
  }
967
978
 
979
+ async #acceptExternalDirectMessage(message, sequence) {
980
+ if (message.author?.bot === true || typeof message.content !== 'string' || !message.content.trim()) return;
981
+ const checked = this.#checkedLifetime();
982
+ const channel = await inspectDiscordSourceChannel(checked.api, message.channel_id, checked.account, checked.signal);
983
+ checked.assertCurrent();
984
+ if (!channel.direct) throw discordRefusal('stale-route');
985
+ let event = normalizeDiscordExternalText(message, { botId: this.#config.botId, account: checked.account,
986
+ channel, eventId: `gateway:${this.#sessionId}:${sequence}` });
987
+ if (!event) return;
988
+ if (this.#externalSourceFiles() === true) event = externalAttachments(event, message);
989
+ if (typeof this.#externalConsumer !== 'function') throw discordRefusal('consumer-unavailable');
990
+ const result = await this.#externalConsumer(event, checked.signal);
991
+ checked.assertCurrent();
992
+ if (result?.accepted !== true) throw discordRefusal('ingress-not-accepted');
993
+ this.#status.messagesReceived++;
994
+ }
995
+
968
996
  async #acceptMessage(message, bridge) {
969
997
  const messageId = String(message?.id ?? '');
970
998
  if (!messageId || this.#state.hasSeen(messageId)) return;
@@ -4,6 +4,7 @@ export function discordRefusal(code) { return Object.assign(new Error(code), { c
4
4
  export function discordSnowflake(value) { return typeof value === 'string' && /^[0-9]{5,30}$/.test(value); }
5
5
  const PUBLIC_THREAD = 11;
6
6
  const TEXT_CHANNEL = 0;
7
+ const DM_CHANNEL = 1;
7
8
  const VIEW = 1n << 10n;
8
9
  const SEND = 1n << 11n;
9
10
  const ATTACH = 1n << 15n;
@@ -68,6 +69,12 @@ export async function inspectDiscordSourceChannel(api, channelId, account, signa
68
69
  signal?.throwIfAborted();
69
70
  try {
70
71
  const channel = await api.getChannel({ channelId, signal });
72
+ if (channel?.id === channelId && channel.type === DM_CHANNEL && channel.guild_id === undefined) {
73
+ const recipient = Array.isArray(channel.recipients) && channel.recipients.length === 1 ? channel.recipients[0] : undefined;
74
+ if (!discordSnowflake(recipient?.id) || recipient.id === account.userId) throw discordRefusal('stale-route');
75
+ signal?.throwIfAborted();
76
+ return { conversationId: channel.id, channelId: channel.id, direct: true, recipientId: recipient.id };
77
+ }
71
78
  if (channel?.id !== channelId || !discordSnowflake(channel.guild_id)) throw discordRefusal('stale-route');
72
79
  const isThread = channel.type === PUBLIC_THREAD;
73
80
  if (channel.type !== TEXT_CHANNEL && !isThread) throw discordRefusal('reply-permission-denied');
@@ -89,7 +96,11 @@ export async function inspectDiscordSourceChannel(api, channelId, account, signa
89
96
  signal?.throwIfAborted();
90
97
  const name = [guild.name, parent.name].every(value => typeof value === 'string' && value.trim())
91
98
  ? `${guild.name.trim()} #${parent.name.trim()}`.slice(0, 512) : undefined;
99
+ const ownManagedRoleIds = guild.roles.filter(role => discordSnowflake(role.id)
100
+ && role.id !== guild.id && role.managed === true && role.tags?.bot_id === account.userId
101
+ && member.roles.includes(role.id)).map(role => role.id);
92
102
  return { guildId: guild.id, conversationId: parent.id, channelId: channel.id, ...(name ? { name } : {}),
103
+ ...(ownManagedRoleIds.length ? { ownManagedRoleIds } : {}),
93
104
  ...(isThread ? { threadId: channel.id } : {}) };
94
105
  } catch (error) { throw nativeFailure(error, 'source-not-found'); }
95
106
  }
@@ -115,6 +126,13 @@ export function normalizeDiscordHistoryText(message, identity) {
115
126
  return normalizeDiscordHumanText(message, identity, false);
116
127
  }
117
128
 
129
+ /** Role ownership comes only from the checked current guild/member, never message text or names. */
130
+ export function discordMessageMentionsAccount(message, account, channel) {
131
+ return message.mentions.some(user => user.id === account.userId)
132
+ || (Array.isArray(message.mention_roles) && message.mention_roles.some(roleId =>
133
+ discordSnowflake(roleId) && channel.ownManagedRoleIds?.includes(roleId)));
134
+ }
135
+
118
136
  function normalizeDiscordHumanText(message, { botId, account, channel, eventId }, requireMention, allowBots = false) {
119
137
  if (!discordSnowflake(message?.id) || !discordSnowflake(message?.author?.id)
120
138
  || (message.author.bot === true && !allowBots) || message.webhook_id || message.author.id === account.userId
@@ -122,8 +140,9 @@ function normalizeDiscordHumanText(message, { botId, account, channel, eventId }
122
140
  || message.content.length > 16000 || !Array.isArray(message.mentions)) return null;
123
141
  if (message.guild_id !== channel.guildId || message.channel_id !== channel.channelId)
124
142
  throw discordRefusal('stale-route');
125
- const mentionedAccount = message.mentions.some(user => user.id === account.userId);
126
- if ((requireMention || message.author.bot === true) && !mentionedAccount) return null;
143
+ if (channel.direct && (message.author.bot === true || message.author.id !== channel.recipientId)) return null;
144
+ const mentionedAccount = discordMessageMentionsAccount(message, account, channel);
145
+ if (!channel.direct && (requireMention || message.author.bot === true) && !mentionedAccount) return null;
127
146
  const timestamp = Date.parse(message.timestamp);
128
147
  if (!Number.isFinite(timestamp) || typeof eventId !== 'string' || !eventId || eventId.length > 512)
129
148
  throw discordRefusal('invalid-inbound');
@@ -134,7 +153,7 @@ function normalizeDiscordHumanText(message, { botId, account, channel, eventId }
134
153
  ...(user.id === account.userId ? { name: account.name } : {}) }));
135
154
  return { version: 1, channel: 'discord', botId, fingerprint: account.fingerprint,
136
155
  eventId, messageId: message.id, actor: { kind: message.author.bot === true ? 'bot' : 'user', id: message.author.id, ...(name ? { name: name.slice(0, 512) } : {}) },
137
- conversation: { kind: 'group', id: channel.conversationId, ...(channel.name ? { name: channel.name } : {}) }, mentions, mentionedAccount,
156
+ conversation: { kind: channel.direct ? 'dm' : 'group', id: channel.conversationId, ...(channel.name ? { name: channel.name } : {}) }, mentions, mentionedAccount,
138
157
  at: new Date(timestamp).toISOString(), text: message.content,
139
158
  reply: { messageId: message.id, conversationId: channel.conversationId, actorId: message.author.id,
140
159
  ...(channel.threadId ? { threadId: channel.threadId } : {}) },
@@ -169,7 +188,7 @@ export function discordReplyMentions(mentionUserIds, route, source) {
169
188
  return [...new Set(mentionUserIds)];
170
189
  }
171
190
 
172
- export async function sendDiscordReply(api, account, route, text, { signal, beforeSend, assertCurrent = () => {}, receipt = false, mentionUserIds } = {}) {
191
+ export async function sendDiscordReply(api, account, route, text, { signal, beforeSend, assertCurrent = () => {}, receipt = false, mentionUserIds, standalone = false } = {}) {
173
192
  if (typeof text !== 'string' || !text.trim() || text.length > 2000) throw discordRefusal('bad-request');
174
193
  const checked = await qualifyDiscordReply(api, account, route, signal);
175
194
  const mentions = discordReplyMentions(mentionUserIds, route, checked.source);
@@ -178,7 +197,8 @@ export async function sendDiscordReply(api, account, route, text, { signal, befo
178
197
  assertCurrent();
179
198
  if (beforeSend && beforeSend() !== true) throw discordRefusal('stale-route');
180
199
  signal?.throwIfAborted();
181
- return sendDiscordCheckedText(api, account, checked.channel, text, { signal, receipt, replyToMessageId: route.messageId,
200
+ return sendDiscordCheckedText(api, account, checked.channel, text, { signal, receipt,
201
+ replyToMessageId: standalone === true && checked.channel.direct ? undefined : route.messageId,
182
202
  ...(mentions.length ? { mentionUserIds: mentions } : {}) });
183
203
  }
184
204
 
@@ -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}$/;
@@ -12,6 +13,9 @@ export function externalApprovalCard(value) {
12
13
  const elements = [{ tag: 'div', text: { tag: 'plain_text', content: value.detail } }];
13
14
  if (value.rules !== undefined && (!Array.isArray(value.rules) || ![1, 2].includes(value.rules.length)
14
15
  || value.rules[0] !== 'exact' || (value.rules.length === 2 && value.rules[1] !== 'all-opaque'))) refuse('bad-request');
16
+ if (value.actions !== undefined && (!Array.isArray(value.actions) || value.actions.length < 1 || value.actions.length > 2
17
+ || value.actions.some(action => !['allowed-once', 'rejected'].includes(action)) || new Set(value.actions).size !== value.actions.length)) refuse('bad-request');
18
+ const offers = action => value.actions === undefined || value.actions.includes(action);
15
19
  if (value.ruleConfirmation !== undefined && (!uuid.test(value.ruleConfirmation.id ?? '') || !['exact', 'all-opaque'].includes(value.ruleConfirmation.kind))) refuse('bad-request');
16
20
  const ruleAction = (action, label, type = 'default') => ({ tag: 'button', type,
17
21
  text: { tag: 'plain_text', content: label }, value: { namespace: 'botharness/approval-rule-v1', requestId: value.requestId, action,
@@ -23,10 +27,10 @@ export function externalApprovalCard(value) {
23
27
  ruleAction('cancel-rule', 'Back / 返回'),
24
28
  ] });
25
29
  else if (value.status === 'pending') elements.push({ tag: 'action', actions: [
26
- { tag: 'button', type: 'primary', text: { tag: 'plain_text', content: 'Allow once / 允许一次' }, value: { namespace: 'botharness/approval-v1', requestId: value.requestId, action: 'allowed-once' } },
27
- { tag: 'button', type: 'danger', text: { tag: 'plain_text', content: 'Reject / 拒绝' }, value: { namespace: 'botharness/approval-v1', requestId: value.requestId, action: 'rejected' } },
28
- ...(value.rules ? [ruleAction('preview-exact', 'Allow matching operations… / 批准匹配操作…')] : []),
29
- ...(value.rules?.includes('all-opaque') ? [ruleAction('preview-all-opaque', 'All opaque tools in this scope… / 此范围内全部不透明工具…', 'danger')] : []),
30
+ ...(offers('allowed-once') ? [{ tag: 'button', type: 'primary', text: { tag: 'plain_text', content: 'Allow once / 允许一次' }, value: { namespace: 'botharness/approval-v1', requestId: value.requestId, action: 'allowed-once' } }] : []),
31
+ ...(offers('rejected') ? [{ tag: 'button', type: 'danger', text: { tag: 'plain_text', content: 'Reject / 拒绝' }, value: { namespace: 'botharness/approval-v1', requestId: value.requestId, action: 'rejected' } }] : []),
32
+ ...(value.rules && offers('allowed-once') ? [ruleAction('preview-exact', 'Allow matching operations… / 批准匹配操作…')] : []),
33
+ ...(value.rules?.includes('all-opaque') && offers('allowed-once') ? [ruleAction('preview-all-opaque', 'All opaque tools in this scope… / 此范围内全部不透明工具…', 'danger')] : []),
30
34
  ] });
31
35
  // Both the initial card and later PATCH need shared mode for receiver-visible updates.
32
36
  return JSON.stringify({ config: { wide_screen_mode: true, update_multi: true }, header: { title: { tag: 'plain_text', content: value.title }, template: 'blue' }, elements });
@@ -62,7 +66,8 @@ export function normalizeExternalCardAction(event, identity) {
62
66
  const appId = event?.header?.app_id ?? event?.app_id;
63
67
  if (appId !== undefined && appId !== identity.appId) refuse('account-changed');
64
68
  const value = event?.action?.value;
65
- if (!['botharness/approval-v1', 'botharness/pairing-v1', 'botharness/approval-rule-v1'].includes(value?.namespace)) return null;
69
+ const question = value?.namespace === 'botharness/question-v1';
70
+ if (!question && !['botharness/approval-v1', 'botharness/pairing-v1', 'botharness/approval-rule-v1'].includes(value?.namespace)) return null;
66
71
  const actorId = event?.operator?.open_id;
67
72
  const messageId = event?.context?.open_message_id;
68
73
  const conversationId = event?.context?.open_chat_id;
@@ -84,18 +89,18 @@ export function normalizeExternalCardAction(event, identity) {
84
89
  return Object.freeze({ kind: 'pairing', version: 1, channel: 'feishu', botId: identity.botId, fingerprint: identity.fingerprint,
85
90
  actorId, messageId, conversationId, requestId: value.requestId, action: value.action, ...(roleId ? { roleId } : {}) });
86
91
  }
87
- if (event.action.tag !== 'button' || !['allowed-once', 'rejected'].includes(value.action)) refuse('invalid-inbound');
92
+ if (event.action.tag !== 'button' || (!question && !['allowed-once', 'rejected'].includes(value.action))) refuse('invalid-inbound');
88
93
  return Object.freeze({ version: 1, channel: 'feishu', botId: identity.botId, fingerprint: identity.fingerprint,
89
- actorId, messageId, conversationId, requestId: value.requestId, action: value.action });
94
+ actorId, messageId, conversationId, requestId: value.requestId, ...(question ? { action: 'answer', values: questionActionValues(event) } : { action: value.action }) });
90
95
  }
91
96
 
92
- export async function replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend } = {}) {
93
- const content = externalApprovalCard(card);
97
+ export async function replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend, render = externalApprovalCard } = {}) {
98
+ const content = render(card);
94
99
  assertCurrent?.();
95
100
  const current = await qualifyExternalReply(client, route, signal);
96
101
  if (current.actorId !== route.actorId) refuse('stale-route');
97
102
  const chat = await client.im.v1.chat.get({ path: { chat_id: route.conversationId } }, { signal });
98
- if (chat?.code !== 0 || !(card.kind === 'pairing' ? ['p2p', 'group'] : ['p2p']).includes(chat?.data?.chat_mode)) refuse('stale-route');
103
+ if (chat?.code !== 0 || !['p2p', 'group'].includes(chat?.data?.chat_mode)) refuse('stale-route');
99
104
  assertCurrent?.();
100
105
  signal?.throwIfAborted();
101
106
  if (typeof beforeSend !== 'function' || beforeSend() !== true) refuse('stale-route');
@@ -107,8 +112,8 @@ export async function replyExternalApprovalCard(client, route, card, { signal, a
107
112
  return { sent: true, receipt: { version: 1, messageId: result.data.message_id, conversationId: result.data.chat_id } };
108
113
  }
109
114
 
110
- export async function updateExternalApprovalCard(client, identity, receipt, card, { signal, assertCurrent, beforeSend } = {}) {
111
- const content = externalApprovalCard(card);
115
+ export async function updateExternalApprovalCard(client, identity, receipt, card, { signal, assertCurrent, beforeSend, render = externalApprovalCard } = {}) {
116
+ const content = render(card);
112
117
  if (!identifier(receipt?.messageId, 'om') || !identifier(receipt?.conversationId, 'oc')) refuse('bad-request');
113
118
  assertCurrent?.();
114
119
  const result = await client.im.v1.message.get({ path: { message_id: receipt.messageId } }, { signal });
@@ -19,39 +19,70 @@ export async function checkedReplySource(client, route, signal) {
19
19
  return source;
20
20
  }
21
21
 
22
- async function parentFile(client, route, signal) {
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') return undefined;
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
- return Object.freeze({
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 file = await parentFile(client, evidence.reply, signal);
46
- return file ? Object.freeze({ ...evidence, attachments: Object.freeze([file]) }) : evidence;
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 parentFile(client, route, signal);
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';
@@ -817,7 +818,11 @@ export class FeishuRuntime {
817
818
  error.code = 'bad-request';
818
819
  throw error;
819
820
  }
820
- if (typeof receipt !== 'boolean' || (receipt && target.kind !== 'group'))
821
+ // A receipt proves the exact conversation: a group chat, or the private
822
+ // chat a saved user target names alongside its open_id.
823
+ const receiptConversation = target.kind === 'group' ? receiveId
824
+ : nonEmptyString(target?.route?.chatId);
825
+ if (typeof receipt !== 'boolean' || (receipt && !receiptConversation))
821
826
  throw Object.assign(new Error('capability-unavailable'), { code: 'capability-unavailable' });
822
827
  signal?.throwIfAborted();
823
828
  // Use the same native Markdown element as chat, without opening a stream
@@ -845,7 +850,7 @@ export class FeishuRuntime {
845
850
  if (!receipt) return { sent: true };
846
851
  const messageId = response?.data?.message_id;
847
852
  const conversationId = response?.data?.chat_id;
848
- if (typeof messageId !== 'string' || !messageId || messageId.length > 512 || conversationId !== receiveId)
853
+ if (typeof messageId !== 'string' || !messageId || messageId.length > 512 || conversationId !== receiptConversation)
849
854
  throw Object.assign(new Error('send-result-unknown'), { code: 'send-result-unknown' });
850
855
  return { sent: true, receipt: { version: 1, messageId, conversationId } };
851
856
  }
@@ -872,6 +877,18 @@ export class FeishuRuntime {
872
877
  : replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend });
873
878
  }
874
879
 
880
+ async questionCardChecked(identity, route, card, { signal, beforeSend, update = false } = {}) {
881
+ const client = this.#client;
882
+ const assertCurrent = () => {
883
+ signal?.throwIfAborted();
884
+ if (!client || this.#client !== client || this.#consumerMode !== 'external-consumer')
885
+ throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
886
+ };
887
+ assertCurrent();
888
+ return update ? updateExternalApprovalCard(client, identity, route, card, { signal, assertCurrent, beforeSend, render: externalQuestionCard })
889
+ : replyExternalApprovalCard(client, route, card, { signal, assertCurrent, beforeSend, render: externalQuestionCard });
890
+ }
891
+
875
892
  async historyChecked(identity, route, query, { signal } = {}) {
876
893
  const client = this.#client;
877
894
  if (!client || this.#consumerMode !== 'external-consumer')
@@ -891,10 +908,10 @@ export class FeishuRuntime {
891
908
  return result;
892
909
  }
893
910
 
894
- async enrichExternal(evidence, { signal } = {}) {
911
+ async enrichExternal(evidence, { signal, sourceVideos = false, sourceImages = false, sourceVoiceAudio = false } = {}) {
895
912
  const client = this.#client;
896
913
  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);
914
+ const result = await externalAttachments(client, evidence, signal, { sourceVideos, sourceImages, sourceVoiceAudio });
898
915
  signal?.throwIfAborted();
899
916
  if (this.#client !== client) throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
900
917
  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
  }));