@xmanrui/dsh-im 5.3.0 → 5.4.0

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.
Files changed (49) hide show
  1. package/THIRD_PARTY_NOTICES.md +209 -0
  2. package/docs/client-integration.md +2 -2
  3. package/lib/client.js +1688 -233
  4. package/lib/index.js +322 -318
  5. package/package.json +1 -1
  6. package/plugin-src/client/channels/telegram/group-triggers-settings.js +393 -0
  7. package/plugin-src/client/delivery-settings.js +21 -1
  8. package/plugin-src/client/ds-bot-avatar-data.js +537 -0
  9. package/plugin-src/client/ds-bot-avatar.js +55 -0
  10. package/plugin-src/client/ds-bot-session-avatars.js +77 -0
  11. package/plugin-src/client/ds-bot-settings.js +194 -0
  12. package/plugin-src/client/i18n.js +59 -1
  13. package/plugin-src/client/index.js +12 -1
  14. package/plugin-src/client/plugin-page.js +3 -8
  15. package/plugin-src/client/styles.js +25 -5
  16. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  17. package/plugin-src/host/channels/feishu/production.mjs +13 -5
  18. package/plugin-src/host/channels/qq/production.mjs +2 -1
  19. package/plugin-src/host/channels/shared/group-triggers-rpc.mjs +110 -0
  20. package/plugin-src/host/channels/shared/production.mjs +7 -1
  21. package/plugin-src/host/channels/slack/production.mjs +2 -1
  22. package/plugin-src/host/channels/telegram/index.mjs +1 -0
  23. package/plugin-src/host/channels/telegram/production.mjs +2 -0
  24. package/plugin-src/host/channels/telegram/rpc.mjs +17 -2
  25. package/plugin-src/host/channels/wecom/production.mjs +4 -1
  26. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  27. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  28. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  29. package/plugin-src/host/delivery-adapter.mjs +89 -9
  30. package/plugin-src/host/delivery-rpc.mjs +33 -1
  31. package/plugin-src/host/delivery-service.mjs +70 -1
  32. package/plugin-src/host/delivery-suggestions.mjs +11 -0
  33. package/plugin-src/host/ds-bot-client.mjs +74 -0
  34. package/plugin-src/host/index.mjs +5 -1
  35. package/src/channels/feishu/feishu-cards.mjs +11 -7
  36. package/src/channels/shared/bot-workspace-store.mjs +136 -7
  37. package/src/channels/shared/group-history-store.mjs +26 -0
  38. package/src/channels/shared/i18n-en/feishu.mjs +1 -0
  39. package/src/channels/shared/i18n-en/wecom.mjs +4 -0
  40. package/src/channels/shared/session-binding-lock.mjs +2 -0
  41. package/src/channels/shared/workspace-session.mjs +5 -1
  42. package/src/channels/telegram/config-store.mjs +5 -1
  43. package/src/channels/telegram/group-triggers.mjs +229 -0
  44. package/src/channels/telegram/telegram-api.mjs +12 -0
  45. package/src/channels/telegram/telegram-controller.mjs +110 -1
  46. package/src/channels/telegram/telegram-runtime.mjs +15 -2
  47. package/src/channels/wecom/stream-supervisor.mjs +184 -0
  48. package/src/channels/wecom/wecom-bridge.mjs +25 -11
  49. package/src/channels/wecom/wecom-runtime.mjs +12 -1
@@ -0,0 +1,194 @@
1
+ import * as React from 'react';
2
+ import { h } from './i18n.js';
3
+ import { DsBotAvatar } from './ds-bot-avatar.js';
4
+
5
+ export const DS_BOT_MESSAGES = Object.freeze({
6
+ missing: '未安装 DS Bot,请先在 DSH 插件管理中安装 ds-bot,然后刷新。',
7
+ disabled: 'DS Bot 尚未启用,请在 DSH 插件管理中启用后刷新。',
8
+ unavailable: '暂时无法读取 DS Bot,请检查插件是否正常运行后重试。',
9
+ readonly: 'DS Bot 当前由其他 Host 管理,请在运行它的 Host 中绑定。',
10
+ remote: '绑定bot仅支持当前 Host 的会话,请先检查机器人的 Harness 连接设置。',
11
+ });
12
+
13
+ export function dsBotErrorMessage(error) {
14
+ return {
15
+ 'ds-bot-unavailable': DS_BOT_MESSAGES.unavailable,
16
+ 'ds-bot-not-found': '所选 DS Bot 已不存在,请刷新后重新选择。',
17
+ 'ds-bot-private-required': '仅支持已经建立会话的私聊,请先与机器人私聊后刷新。',
18
+ 'ds-bot-binding-conflict': '所选 DS Bot 或私聊对象已绑定,请刷新后重新选择。',
19
+ }[error?.code] ?? '绑定设置保存失败,请刷新后重试。';
20
+ }
21
+
22
+ export function DsBotPicker({ bots, value, onChange, disabled }) {
23
+ const [open, setOpen] = React.useState(false);
24
+ const [active, setActive] = React.useState(0);
25
+ const root = React.useRef(null);
26
+ const trigger = React.useRef(null);
27
+ const listId = React.useId();
28
+ const selected = bots.find((bot) => bot.id === value);
29
+ const isOpen = open && !disabled && bots.length > 0;
30
+ React.useEffect(() => {
31
+ const dismiss = (event) => { if (!root.current?.contains(event.target)) setOpen(false); };
32
+ if (open) globalThis.document?.addEventListener('pointerdown', dismiss);
33
+ return () => globalThis.document?.removeEventListener('pointerdown', dismiss);
34
+ }, [open]);
35
+ const choose = (bot) => { onChange(bot.id); setOpen(false); trigger.current?.focus(); };
36
+ const optionId = (index) => `${listId}-${index}`;
37
+ return h('div', { className: 'dim-dsBotPicker', ref: root },
38
+ h('button', {
39
+ type: 'button', role: 'combobox', ref: trigger, className: 'dim-dsBotPickerTrigger',
40
+ disabled: disabled || !bots.length, 'aria-label': 'DS Bot', 'aria-expanded': isOpen, 'aria-controls': listId,
41
+ 'aria-haspopup': 'listbox', 'aria-activedescendant': isOpen ? optionId(active) : undefined,
42
+ onClick: () => { setActive(Math.max(0, bots.findIndex((bot) => bot.id === value))); setOpen(!open); },
43
+ onKeyDown: (event) => {
44
+ if (disabled || !bots.length) return;
45
+ if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
46
+ event.preventDefault();
47
+ const index = event.key === 'Home' ? 0 : event.key === 'End' ? bots.length - 1
48
+ : open ? (active + (event.key === 'ArrowDown' ? 1 : -1) + bots.length) % bots.length
49
+ : Math.max(0, bots.findIndex((bot) => bot.id === value));
50
+ setActive(index); setOpen(true);
51
+ } else if (open && ['Enter', ' '].includes(event.key)) {
52
+ event.preventDefault(); if (bots[active]) choose(bots[active]);
53
+ } else if (event.key === 'Escape' || event.key === 'Tab') setOpen(false);
54
+ },
55
+ },
56
+ selected ? h(DsBotAvatar, { bot: selected }) : null,
57
+ selected ? React.createElement('span', { className: 'dim-dsBotPickerName' }, selected.name)
58
+ : h('span', { className: 'dim-dsBotPickerName' }, bots.length ? '选择 DS Bot' : '暂无可选 DS Bot'),
59
+ h('svg', { width: 14, height: 14, viewBox: '0 0 16 16', 'aria-hidden': true },
60
+ h('path', { d: 'm4 6 4 4 4-4', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round' }))),
61
+ isOpen ? h('div', { id: listId, role: 'listbox', 'aria-label': 'DS Bot', className: 'dim-dsBotOptions' },
62
+ bots.map((bot, index) => h('button', {
63
+ key: bot.id, id: optionId(index), type: 'button', role: 'option', tabIndex: -1,
64
+ 'aria-selected': value === bot.id, 'data-active': active === index,
65
+ onMouseDown: (event) => event.preventDefault(), onMouseEnter: () => setActive(index), onClick: () => choose(bot),
66
+ }, h(DsBotAvatar, { bot }),
67
+ React.createElement('span', { className: 'dim-dsBotPickerName' }, bot.name),
68
+ value === bot.id ? h('span', { 'aria-hidden': true }, '✓') : null))) : null);
69
+ }
70
+
71
+ function conversationLabel(conversation) {
72
+ if (conversation.name) return conversation.name;
73
+ const value = conversation.address;
74
+ return value.length > 24 ? `${value.slice(0, 10)}…${value.slice(-8)}` : value;
75
+ }
76
+
77
+ export function DsBotSettingsPage({ botId, rpcCall }) {
78
+ const [status, setStatus] = React.useState(null);
79
+ const [dsBotId, setDsBotId] = React.useState('');
80
+ const [conversationKey, setConversationKey] = React.useState('');
81
+ const [loading, setLoading] = React.useState(true);
82
+ const [busy, setBusy] = React.useState(false);
83
+ const [feedback, setFeedback] = React.useState(null);
84
+ const [feedbackTone, setFeedbackTone] = React.useState('success');
85
+ const requests = React.useRef({ revision: 0, busy: false, controller: null });
86
+ const refresh = React.useCallback(async (signal = requests.current.controller?.signal) => {
87
+ const state = requests.current;
88
+ if (signal?.aborted) return;
89
+ const revision = ++state.revision;
90
+ const current = () => !signal?.aborted && revision === state.revision;
91
+ setLoading(true);
92
+ try {
93
+ const value = await rpcCall('ds-bot.status', { botId }, signal);
94
+ if (current()) setStatus(value);
95
+ } catch {
96
+ if (current()) setStatus((previous) => ({ ...previous, state: 'unavailable' }));
97
+ } finally {
98
+ if (current()) setLoading(false);
99
+ }
100
+ }, [botId, rpcCall]);
101
+ React.useEffect(() => {
102
+ const controller = new AbortController();
103
+ requests.current.controller = controller;
104
+ void refresh(controller.signal);
105
+ return () => {
106
+ controller.abort();
107
+ requests.current.revision++;
108
+ };
109
+ }, [refresh]);
110
+ const conversations = status?.conversations ?? [];
111
+ const bots = status?.bots ?? [];
112
+ const bindings = conversations.filter((conversation) => conversation.dsBotId);
113
+ const usedBotIds = new Set(bindings.map((binding) => binding.dsBotId));
114
+ const availableBots = bots.filter((bot) => !usedBotIds.has(bot.id));
115
+ const availableConversations = conversations.filter((conversation) => !conversation.dsBotId);
116
+ const canSave = !busy && !loading && status?.state === 'ready'
117
+ && availableBots.some((bot) => bot.id === dsBotId)
118
+ && availableConversations.some((conversation) => conversation.conversationKey === conversationKey);
119
+ React.useEffect(() => {
120
+ setDsBotId((value) => availableBots.some((bot) => bot.id === value) ? value : '');
121
+ setConversationKey((value) => availableConversations.some((conversation) => conversation.conversationKey === value) ? value : '');
122
+ }, [status]);
123
+ const save = async (event) => {
124
+ event.preventDefault();
125
+ if (!canSave || requests.current.busy) return;
126
+ requests.current.busy = true;
127
+ requests.current.revision++;
128
+ setBusy(true); setFeedback(null);
129
+ try {
130
+ await rpcCall('ds-bot.bind', { botId, conversationKey, dsBotId });
131
+ setDsBotId(''); setConversationKey('');
132
+ await refresh();
133
+ setFeedbackTone('success'); setFeedback('绑定已保存。');
134
+ } catch (error) {
135
+ if (error?.code === 'ds-bot-binding-conflict') await refresh();
136
+ setFeedbackTone('error'); setFeedback(dsBotErrorMessage(error));
137
+ } finally { requests.current.busy = false; setBusy(false); }
138
+ };
139
+ const unbind = async (key) => {
140
+ if (requests.current.busy) return;
141
+ requests.current.busy = true;
142
+ requests.current.revision++;
143
+ setBusy(true); setFeedback(null);
144
+ try {
145
+ await rpcCall('ds-bot.unbind', { botId, conversationKey: key });
146
+ await refresh();
147
+ setFeedbackTone('success'); setFeedback('已解除绑定,聊天记录保留。');
148
+ } catch (error) {
149
+ setFeedbackTone('error'); setFeedback(dsBotErrorMessage(error));
150
+ } finally { requests.current.busy = false; setBusy(false); }
151
+ };
152
+ return h('section', { className: 'dim-deliveryTargets dim-dsBotSettings', 'aria-label': '绑定bot' },
153
+ h('div', { className: 'dim-deliverySectionHeading' },
154
+ h('div', null, h('h3', null, '绑定bot'), h('p', null, '选择 DS Bot 和私聊对象,直接使用 Bot 的会话。')),
155
+ h('button', { className: 'dim-deliveryButton', type: 'button', disabled: busy || loading, onClick: () => void refresh() }, '刷新')),
156
+ !status ? h('p', { className: 'dim-dsBotNotice', role: 'status' }, '正在检测 DS Bot…')
157
+ : status.state !== 'ready' ? h('p', { className: 'dim-dsBotNotice', role: 'status' }, DS_BOT_MESSAGES[status.state] ?? DS_BOT_MESSAGES.unavailable)
158
+ : !bots.length ? h('p', { className: 'dim-dsBotNotice' }, '还没有 DS Bot,请先在 DS Bot 中创建机器人后刷新。')
159
+ : !conversations.length ? h('p', { className: 'dim-dsBotNotice' }, '还没有可绑定的私聊。先给这个机器人发一条私聊消息,再点击刷新。')
160
+ : h('form', { className: 'dim-dsBotForm', onSubmit: save },
161
+ h('div', { className: 'dim-targetFormGrid' },
162
+ h('div', { className: 'dim-targetField' }, h('span', null, 'DS Bot'),
163
+ h(DsBotPicker, { bots: availableBots, value: dsBotId, onChange: setDsBotId, disabled: busy || loading })),
164
+ h('label', { className: 'dim-targetField' }, h('span', null, '私聊对象'),
165
+ h('select', {
166
+ value: conversationKey, required: true, disabled: busy || loading || !availableConversations.length,
167
+ onChange: (event) => setConversationKey(event.target.value),
168
+ }, h('option', { value: '' }, availableConversations.length ? '选择私聊对象' : '暂无可选私聊对象'),
169
+ availableConversations.map((conversation) => React.createElement('option', {
170
+ key: conversation.conversationKey, value: conversation.conversationKey,
171
+ }, conversationLabel(conversation)))))),
172
+ !availableBots.length || !availableConversations.length
173
+ ? h('p', { className: 'dim-dsBotNotice' }, '已绑定的 DS Bot 和私聊对象不可重复选择,解除绑定后可重新选择。')
174
+ : null,
175
+ h('div', { className: 'dim-targetFormActions' },
176
+ h('button', { type: 'submit', className: 'dim-deliveryButton', 'data-kind': 'primary',
177
+ disabled: !canSave,
178
+ }, busy ? '正在保存…' : '保存绑定'))),
179
+ bindings.length ? h('ul', { className: 'dim-targetList' }, bindings.map((conversation) => {
180
+ const bot = bots.find((entry) => entry.id === conversation.dsBotId);
181
+ return h('li', { className: 'dim-targetRow dim-dsBotBinding', key: conversation.conversationKey },
182
+ h('div', { className: 'dim-dsBotBoundIdentity' },
183
+ h(DsBotAvatar, { bot: bot ?? { id: conversation.dsBotId }, size: 32 }),
184
+ h('div', { className: 'dim-targetSummary' },
185
+ h('div', { className: 'dim-targetTitle' },
186
+ bot ? React.createElement('strong', null, bot.name) : h('strong', null, 'DS Bot 暂不可用'),
187
+ h('span', null, '已绑定')),
188
+ React.createElement('p', { className: 'dim-dsBotDestination' }, conversationLabel(conversation)))),
189
+ h('button', { type: 'button', className: 'dim-deliveryButton', 'data-kind': 'danger', disabled: busy || loading,
190
+ onClick: () => void unbind(conversation.conversationKey),
191
+ }, '解除绑定'));
192
+ })) : null,
193
+ feedback ? h('p', { role: 'status', className: 'dim-targetFeedback', 'data-tone': feedbackTone }, feedback) : null);
194
+ }
@@ -6,6 +6,33 @@ import * as React from 'react';
6
6
  export const IM_LOCALE_NAMESPACE = 'dsh-im';
7
7
 
8
8
  const EN = Object.freeze({
9
+ "私聊对象": "Private chat",
10
+ "选择私聊对象": "Select a private chat",
11
+ "仅支持已经建立会话的私聊,请先与机器人私聊后刷新。": "Only established private chats are supported. Message the bot privately, then refresh.",
12
+ "选择 DS Bot 和私聊对象,直接使用 Bot 的会话。": "Choose a DS Bot and a private chat to use the Bot’s session.",
13
+ "还没有可绑定的私聊。先给这个机器人发一条私聊消息,再点击刷新。": "No private chats yet. Send this bot a private message, then refresh.",
14
+
15
+ "绑定bot": "Bind bot",
16
+ "正在检测 DS Bot…": "Checking DS Bot…",
17
+ "选择 DS Bot": "Select DS Bot",
18
+ "暂无可选 DS Bot": "No available DS Bots",
19
+ "暂无可选私聊对象": "No available private chats",
20
+ "已绑定的 DS Bot 和私聊对象不可重复选择,解除绑定后可重新选择。": "Bound DS Bots and private chats cannot be selected again. Unbind them to make them available.",
21
+ "所选 DS Bot 或私聊对象已绑定,请刷新后重新选择。": "The selected DS Bot or private chat is already bound. Refresh and choose again.",
22
+ "解除绑定": "Unbind",
23
+ "已绑定": "Bound",
24
+ "未安装 DS Bot,请先在 DSH 插件管理中安装 ds-bot,然后刷新。": "DS Bot is not installed. Install ds-bot in DSH plugin management, then refresh.",
25
+ "DS Bot 尚未启用,请在 DSH 插件管理中启用后刷新。": "DS Bot is disabled. Enable it in DSH plugin management, then refresh.",
26
+ "暂时无法读取 DS Bot,请检查插件是否正常运行后重试。": "Unable to read DS Bot. Check that the plugin is running, then retry.",
27
+ "DS Bot 当前由其他 Host 管理,请在运行它的 Host 中绑定。": "DS Bot is managed by another Host. Bind it on that Host.",
28
+ "绑定bot仅支持当前 Host 的会话,请先检查机器人的 Harness 连接设置。": "Bot binding requires the current Host. Check the bot’s Harness connection settings.",
29
+ "所选 DS Bot 已不存在,请刷新后重新选择。": "The selected DS Bot no longer exists. Refresh and select another.",
30
+ "绑定设置保存失败,请刷新后重试。": "Could not save the binding. Refresh and retry.",
31
+ "绑定已保存。": "Binding saved.",
32
+ "已解除绑定,聊天记录保留。": "Binding removed. Chat history is preserved.",
33
+ "还没有 DS Bot,请先在 DS Bot 中创建机器人后刷新。": "No bots yet. Create a bot in DS Bot, then refresh.",
34
+ "DS Bot 暂不可用": "DS Bot unavailable",
35
+
9
36
  ...weixinDiagnostics,
10
37
  ...diagnostics,
11
38
  ...imageInput,
@@ -67,7 +94,6 @@ const EN = Object.freeze({
67
94
  'macOS Messages 权限': 'macOS Messages permissions',
68
95
  'IM机器人': 'IM bots',
69
96
  '打开 IM机器人': 'Open IM bots',
70
- '返回插件详情': 'Back to plugin details',
71
97
  'IM机器人设置': 'IM bot settings',
72
98
  'IM 面板加载失败': 'Could not load the IM panel',
73
99
  '更多机器人设置': 'More bot settings',
@@ -78,6 +104,38 @@ const EN = Object.freeze({
78
104
  '机器人设置': 'Bot settings',
79
105
  '机器人设置页签': 'Bot settings tabs',
80
106
  '投递设置': 'Delivery settings',
107
+ '机器人群聊行为': 'Bot in groups',
108
+ '新群聊默认设置': 'Default for new groups',
109
+ '响应条件': 'React to',
110
+ '不响应': 'Do not react',
111
+ '被 @ 或回复时(任何人)': 'Mention or reply, anyone',
112
+ '被 @ 或回复时(仅名单成员)': 'Mention or reply, listed members only',
113
+ '所有消息(任何人)': 'All messages, anyone',
114
+ '所有消息(仅名单成员)': 'All messages, listed members only',
115
+ '成员名单': 'Members list',
116
+ '名单为空:该模式不会响应任何成员。': 'The list is empty, so nobody can trigger the bot in this mode.',
117
+ '当前模式不使用名单。': 'This mode does not use the list.',
118
+ '群 ID': 'Group',
119
+ '标题': 'Title',
120
+ '最近活动': 'Last activity',
121
+ '(默认)': ' (default)',
122
+ '× 移除': '× Remove',
123
+ '自定义': 'Customize',
124
+ '添加群聊': 'Add group',
125
+ '群 ID、@用户名或消息链接': 'Group ID, @username or message link',
126
+ '支持数字 ID、@用户名、t.me/<name> 或 t.me/c/<id>/<msg>;真实 ID 通过 getChat 解析。': 'Accepts a numeric ID, @username, t.me/<name> or t.me/c/<id>/<msg>; the real ID is resolved through getChat.',
127
+ '+ 添加': '+ Add',
128
+ '保存群聊设置': 'Save group settings',
129
+ '已从列表移除,保存后生效。': 'Removed from the list. Save to apply.',
130
+ '已添加,保存后生效。': 'Added. Save to apply.',
131
+ '已添加。Telegram 未确认该群(机器人可能还不在群里),保存后生效。': 'Added without Telegram confirmation (the bot may not be in that group yet). Save to apply.',
132
+ '群聊设置已保存。': 'Group settings saved.',
133
+ '正在读取群聊设置…': 'Loading group settings…',
134
+ '无法读取群聊设置,请稍后重试。': 'Unable to read group settings. Try again.',
135
+ '无法保存群聊设置,请稍后重试。': 'Unable to save group settings. Try again.',
136
+ '无法读取或保存群聊设置,请稍后重试。': 'Unable to read or save group settings. Try again.',
137
+ '无法解析该群聊,请重试或填写数字群 ID。': 'Could not resolve this group. Try again or enter the numeric group ID.',
138
+ '该群已在列表中,请编辑上方的卡片。': 'This group is already in the list. Edit its card above instead.',
81
139
  '访问设置': 'Access settings',
82
140
  '查看访问权限说明': 'View access permission details',
83
141
  '允许所有用户': 'Allow all users',
@@ -80,6 +80,7 @@ import {
80
80
  } from './loopback-recovery.js';
81
81
  import { installImStyles } from './styles.js';
82
82
  import { installSessionChannelLogos } from './session-channel-logos.js';
83
+ import { installDsBotSessionAvatars } from './ds-bot-session-avatars.js';
83
84
  import { UpdatePanel, UPDATE_RPC_CHANNEL } from './update-panel.js';
84
85
  import { WorkspaceDirectoryPickerContext } from './workspace-editor.js';
85
86
  import { IMPanelErrorBoundary } from './panel-error-boundary.js';
@@ -470,6 +471,14 @@ export function apply(ctx) {
470
471
  );
471
472
 
472
473
  ctx.effect(() => installSessionChannelLogos(), 'im-settings: Session channel logos');
474
+ let dsBotAvatars;
475
+ ctx.effect(() => {
476
+ dsBotAvatars = installDsBotSessionAvatars(ctx, {
477
+ rpcCall: (endpoint, payload, signal) =>
478
+ callManagementRpc(ctx.connection, DELIVERY_RPC_CHANNEL, endpoint, payload, signal),
479
+ });
480
+ return () => { dsBotAvatars.dispose(); dsBotAvatars = null; };
481
+ }, 'im-settings: bound DS Bot session avatars');
473
482
 
474
483
  ctx.effect(() => {
475
484
  const disposers = [
@@ -497,8 +506,10 @@ export function apply(ctx) {
497
506
  const managementRpc = async (connection, channel, endpoint, payload, signal) => {
498
507
  const result = await callManagementRpc(connection, channel, endpoint, payload, signal);
499
508
  if (result?.ok === true) {
509
+ const dsBotRead = channel === DELIVERY_RPC_CHANNEL && endpoint === 'ds-bot.status';
510
+ if (channel === DELIVERY_RPC_CHANNEL && ['ds-bot.bind', 'ds-bot.unbind'].includes(endpoint)) dsBotAvatars?.refresh();
500
511
  if (endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set) sidebarSync?.apply(result);
501
- else if (endpoint !== SIDEBAR_SETTINGS_ENDPOINTS.get) sidebarSync?.refresh();
512
+ else if (!dsBotRead && endpoint !== SIDEBAR_SETTINGS_ENDPOINTS.get) sidebarSync?.refresh();
502
513
  }
503
514
  return result;
504
515
  };
@@ -13,11 +13,9 @@ function OpenImAction({ subject, packageName, onOpen, t }) {
13
13
  }, t('打开 IM机器人'));
14
14
  }
15
15
 
16
- function ImPluginPage({ renderPanel, onBack, t }) {
16
+ function ImPluginPage({ renderPanel }) {
17
17
  return h('div', { className: 'dim-pluginPage' },
18
18
  h('div', { className: 'dim-pluginPageContent' },
19
- h('button', { type: 'button', className: 'dim-pluginBack', onClick: onBack },
20
- h('span', { 'aria-hidden': true }, '‹'), t('返回插件详情')),
21
19
  renderPanel()));
22
20
  }
23
21
 
@@ -47,14 +45,11 @@ export function installImPluginPage(ctx, { packageName, renderPanel, sidebarVisi
47
45
  },
48
46
  };
49
47
  if (typeof ctx.inject !== 'function') return controller;
50
- ctx.inject(['layout', 'pluginNavigation'], (pageCtx) =>
48
+ ctx.inject(['layout'], (pageCtx) =>
51
49
  pageCtx.slots.inject('main', () => {
52
50
  const unregisterPage = pageCtx.slots.register({
53
51
  name: 'main', key: IM_MAIN_PANEL_ID, locale: IM_LOCALE_NAMESPACE,
54
- inject: () => ({
55
- renderPanel,
56
- onBack: () => pageCtx.pluginNavigation.openBundle(packageName),
57
- }),
52
+ inject: () => ({ renderPanel }),
58
53
  }, ImPluginPage);
59
54
  let stopSidebar = null;
60
55
  const update = () => {
@@ -4,13 +4,10 @@ const CSS = String.raw`
4
4
  .dim-sidebarIcon { display: block; flex: none; }
5
5
  .dim-pluginOpen { display: inline-flex; align-items: center; justify-content: center; min-height: 36px; padding: 7px 14px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 8px; color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-bg-layer-1, #fff); font: inherit; font-size: 13px; line-height: 20px; cursor: pointer; }
6
6
  .dim-pluginOpen:hover { background: var(--dsw-alias-interactive-bg-hover, #f7f8fa); }
7
- .dim-pluginOpen:focus-visible, .dim-pluginBack:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary, #3370ff); outline-offset: 3px; }
7
+ .dim-pluginOpen:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary, #3370ff); outline-offset: 3px; }
8
8
  .dim-pluginPage { height: 100%; min-height: 0; overflow: auto; box-sizing: border-box; padding: 24px clamp(16px, 4vw, 48px) 32px; color: var(--dsw-alias-label-primary, #1f2329); }
9
9
  .dim-pluginPageContent { max-width: 1080px; margin: 0 auto; }
10
- .dim-pluginBack { display: inline-flex; align-items: center; gap: 8px; min-height: 36px; margin: 0 0 24px; padding: 6px 8px; border: 0; border-radius: 8px; color: var(--dsw-alias-label-secondary, #646a73); background: transparent; font: inherit; font-size: 13px; line-height: 20px; cursor: pointer; }
11
- .dim-pluginBack:hover { color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-interactive-bg-hover, #f7f8fa); }
12
- .dim-pluginBack > span { font-size: 22px; line-height: 20px; }
13
- @media (pointer: coarse) { .dim-pluginOpen, .dim-pluginBack { min-height: 44px; } }
10
+ @media (pointer: coarse) { .dim-pluginOpen { min-height: 44px; } }
14
11
  .dim-connectionDiagnostic { min-width: 0; width: 100%; color: var(--dsw-alias-label-secondary, #646a73); overflow-wrap: anywhere; font-size: 13px; line-height: 1.6; }
15
12
  .dim-connectionDiagnostic[data-warning="true"] { color: var(--dsw-alias-state-warn-primary, #d97706); }
16
13
  .dim-connectionDiagnostic p { margin: 4px 0; }
@@ -602,6 +599,25 @@ const CSS = String.raw`
602
599
  .dim-targetField input[readonly] { color: var(--dsw-alias-label-secondary, #646a73); background: var(--dsw-alias-bg-module-platform, #f7f8fa); }
603
600
  .dim-targetFormError { margin: 10px 0 0; font-size: 12px; line-height: 18px; }
604
601
  .dim-targetFormActions { display: flex; justify-content: flex-end; gap: 7px; margin-top: 12px; }
602
+ .dim-dsBotForm { margin-top: 20px; }
603
+ .dim-dsBotForm .dim-targetFormGrid { grid-template-columns: repeat(auto-fit, minmax(min(220px, 100%), 1fr)); margin-top: 0; gap: 16px; }
604
+ .dim-dsBotForm .dim-targetFormActions { margin-top: 16px; }
605
+ .dim-targetRow.dim-dsBotBinding { grid-template-columns: minmax(0, 1fr) max-content; align-items: center; }
606
+ .dim-dsBotDestination { margin: 3px 0 0; color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; line-height: 18px; overflow-wrap: anywhere; }
607
+ .dim-dsBotNotice { margin: 20px 0 0; color: var(--dsw-alias-label-secondary, #646a73); font-size: 12px; line-height: 20px; }
608
+ .dim-dsBotNotice p { margin: 0 0 10px; }
609
+ .dim-dsBotSettings > .dim-targetFeedback { margin-top: 12px; }
610
+ .dim-dsBotAvatar { display: block; flex: none; object-fit: cover; border-radius: 5px; }
611
+ .dim-dsBotBoundIdentity { display: flex; align-items: center; gap: 10px; min-width: 0; }
612
+ .dim-dsBotPicker { position: relative; min-width: 0; }
613
+ .dim-dsBotPickerTrigger { display: flex; align-items: center; gap: 8px; width: 100%; height: 34px; padding: 0 9px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 7px; color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-bg-layer-1, #fff); font: inherit; font-size: 12px; text-align: left; cursor: pointer; }
614
+ .dim-dsBotPickerName { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
615
+ .dim-dsBotPickerTrigger:focus-visible { outline: 2px solid color-mix(in srgb, var(--dsw-alias-state-business-primary, #3370ff) 28%, transparent); border-color: var(--dsw-alias-state-business-primary, #3370ff); }
616
+ .dim-dsBotPickerTrigger:disabled { opacity: .5; cursor: not-allowed; }
617
+ .dim-dsBotOptions { position: absolute; z-index: 20; inset: calc(100% + 5px) 0 auto; max-height: 240px; overflow-y: auto; padding: 4px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 9px; background: var(--dsw-alias-bg-layer-1, #fff); box-shadow: 0 5px 18px rgb(0 0 0 / 10%); }
618
+ .dim-dsBotOptions > button { display: flex; align-items: center; gap: 8px; width: 100%; min-height: 36px; padding: 5px 8px; border: 0; border-radius: 6px; background: transparent; color: var(--dsw-alias-label-primary, #1f2329); font: inherit; font-size: 12px; text-align: left; cursor: pointer; }
619
+ .dim-dsBotOptions > button[data-active="true"] { background: var(--dsw-alias-interactive-bg-hover, #eef0f3); }
620
+ .dim-dsBotOptions > button[aria-selected="true"] { color: var(--dsw-alias-state-business-primary, #3370ff); }
605
621
  .dim-accessPage { min-width: 0; display: grid; gap: 14px; }
606
622
  .dim-accessScene { position: relative; min-width: 0; margin: 0; padding: 16px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 12px; background: var(--dsw-alias-bg-layer-3, #fff); }
607
623
  .dim-accessScene > legend { padding: 0 6px; color: var(--dsw-alias-label-primary, #1f2329); font-size: 15px; line-height: 22px; font-weight: 650; }
@@ -612,6 +628,10 @@ const CSS = String.raw`
612
628
  .dim-accessControls[data-mode="allowlist"] { grid-template-columns: minmax(0, 1fr); }
613
629
  .dim-accessField { min-width: 0; display: grid; align-content: start; gap: 5px; color: var(--dsw-alias-label-secondary, #646a73); font-size: 11px; line-height: 16px; }
614
630
  .dim-accessField input, .dim-accessField select { width: 100%; min-width: 0; height: 36px; padding: 0 9px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 7px; color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-bg-layer-1, #fff); font: inherit; font-size: 12px; }
631
+ .dim-accessField textarea { width: 100%; min-width: 0; padding: 7px 9px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 7px; color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-bg-layer-1, #fff); font: inherit; font-size: 12px; line-height: 18px; resize: vertical; }
632
+ .dim-accessField textarea:focus { outline: 2px solid color-mix(in srgb, var(--dsw-alias-state-business-primary, #3370ff) 28%, transparent); border-color: var(--dsw-alias-state-business-primary, #3370ff); }
633
+ .dim-accessField textarea:disabled { opacity: .6; }
634
+ .dim-groupTriggerValue { color: var(--dsw-alias-label-primary, #1f2329); font-size: 12px; line-height: 18px; overflow-wrap: anywhere; }
615
635
  .dim-accessField input:focus, .dim-accessField select:focus { outline: 2px solid color-mix(in srgb, var(--dsw-alias-state-business-primary, #3370ff) 28%, transparent); border-color: var(--dsw-alias-state-business-primary, #3370ff); }
616
636
  .dim-accessUsers { min-width: 0; margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--dsw-alias-border-l1, #eef0f3); }
617
637
  .dim-accessUsersHeading { position: relative; min-width: 0; display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
@@ -129,6 +129,7 @@ export async function createProductionController(ctx, config = {}, internals = {
129
129
  initialAccessPolicy: initialAccessPolicyFor('dingtalk', botConfig),
130
130
  });
131
131
  const workspaceScope = createBotWorkspaceScope(harness, {
132
+ dsBot: config.deliveryService?.dsBot,
132
133
  botId, workspaces, state, agentPresetCatalog,
133
134
  });
134
135
  return new Runtime({
@@ -180,7 +181,7 @@ export async function createProductionController(ctx, config = {}, internals = {
180
181
  }).start();
181
182
  return {
182
183
  controller,
183
- deliveryAdapter: createDeliveryAdapter({
184
+ deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
184
185
  channel: 'dingtalk', workspaces, coreController, stateFor,
185
186
  }),
186
187
  ready: supervisor.ready,
@@ -32,7 +32,7 @@ import {
32
32
  import { prepareBotWorkspace } from '../../../../src/channels/shared/default-workspace.mjs';
33
33
  import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-preset.mjs';
34
34
  import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
35
- import { createDeliveryAdapter } from '../../delivery-adapter.mjs';
35
+ import { createDeliveryAdapter, configuredSessionSyncTargets, sessionSyncTarget } from '../../delivery-adapter.mjs';
36
36
  import {
37
37
  accessPolicyProvider,
38
38
  initialAccessPolicyFor,
@@ -173,16 +173,23 @@ export async function createProductionController(ctx, config = {}, internals = {
173
173
  const sessionSyncTargetsFor = async (sessionId) => {
174
174
  if (typeof workspaces.listSessionSyncTargets !== 'function') return [];
175
175
  const matches = [];
176
- for (const entry of workspaces.listSessionSyncTargets()) {
176
+ for (const entry of configuredSessionSyncTargets(workspaces)) {
177
177
  let state;
178
178
  try {
179
179
  state = await stateForBotId(entry.botId);
180
180
  } catch {
181
181
  continue;
182
182
  }
183
- const bound = state?.snapshot?.().sessions?.[entry.conversationKey];
183
+ let bound;
184
+ try {
185
+ bound = entry.dsBotId
186
+ ? (await config.deliveryService?.dsBot?.resolve(entry.dsBotId))?.sessionId
187
+ : state?.snapshot?.().sessions?.[entry.conversationKey];
188
+ } catch {
189
+ continue;
190
+ }
184
191
  if (bound !== sessionId) continue;
185
- const target = workspaces.deliveryTargetFor(entry.botId, entry.targetId);
192
+ const target = sessionSyncTarget('feishu', workspaces, entry);
186
193
  const openId = target?.route?.openId;
187
194
  if (openId) matches.push({ openId, botId: entry.botId, targetId: entry.targetId });
188
195
  }
@@ -235,6 +242,7 @@ export async function createProductionController(ctx, config = {}, internals = {
235
242
  initialAccessPolicy: newBotAccessPolicyFor('feishu', botConfig),
236
243
  });
237
244
  const workspaceScope = createBotWorkspaceScope(harness, {
245
+ dsBot: config.deliveryService?.dsBot,
238
246
  botId: id, workspaces, state, agentPresetCatalog,
239
247
  });
240
248
  // 语音是可选渠道能力:凭据读取失败时静默禁用,不阻断机器人连接。
@@ -319,7 +327,7 @@ export async function createProductionController(ctx, config = {}, internals = {
319
327
  }).start();
320
328
  return {
321
329
  controller,
322
- deliveryAdapter: createDeliveryAdapter({
330
+ deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
323
331
  channel: 'feishu', workspaces, coreController, stateFor: stateForBotId,
324
332
  }),
325
333
  ready: supervisor.ready,
@@ -122,6 +122,7 @@ export async function createProductionController(ctx, config = {}, internals = {
122
122
  initialAccessPolicy: newBotAccessPolicyFor('qq', botConfig),
123
123
  });
124
124
  const workspaceScope = createBotWorkspaceScope(harness, {
125
+ dsBot: config.deliveryService?.dsBot,
125
126
  botId, workspaces, state, agentPresetCatalog,
126
127
  });
127
128
  return new Runtime({
@@ -173,7 +174,7 @@ export async function createProductionController(ctx, config = {}, internals = {
173
174
  }).start();
174
175
  return {
175
176
  controller,
176
- deliveryAdapter: createDeliveryAdapter({ channel: 'qq', workspaces, coreController, stateFor }),
177
+ deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot, channel: 'qq', workspaces, coreController, stateFor }),
177
178
  ready: supervisor.ready,
178
179
  async close() {
179
180
  await supervisor.close();
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Management RPC for Telegram's per-group reply rules.
3
+ *
4
+ * Kept out of `TOKEN_BOT_ENDPOINTS`: those are shared by every token channel,
5
+ * and per-group triggers only exist for Telegram.
6
+ */
7
+ import { normalizeGroupTriggers } from '../../../../src/channels/telegram/group-triggers.mjs';
8
+
9
+ export const GROUP_TRIGGERS_ENDPOINTS = Object.freeze({
10
+ get: 'bot.group-triggers.get',
11
+ set: 'bot.group-triggers.set',
12
+ resolve: 'bot.group-triggers.resolve',
13
+ });
14
+
15
+ const ENDPOINTS = Object.freeze(Object.values(GROUP_TRIGGERS_ENDPOINTS));
16
+ const BOT_ID = /^[A-Za-z0-9_-]{1,128}$/;
17
+ const MAX_REFERENCE_LENGTH = 2_048;
18
+
19
+ function isRecord(value) {
20
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
21
+ }
22
+
23
+ function exactKeys(value, allowed) {
24
+ return isRecord(value) && Object.keys(value).every((key) => allowed.includes(key));
25
+ }
26
+
27
+ function validBotId(value) {
28
+ return typeof value === 'string' && BOT_ID.test(value);
29
+ }
30
+
31
+ function validRemoved(value) {
32
+ return value === undefined || (Array.isArray(value)
33
+ && value.every((entry) => typeof entry === 'string' && entry.trim().length > 0 && entry.length <= 64));
34
+ }
35
+
36
+ /** Normalized rules, or null when the payload cannot be saved. */
37
+ export function validGroupTriggersConfig(value) {
38
+ try {
39
+ return normalizeGroupTriggers(value);
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ export function validGroupTriggersPayload(endpoint, payload) {
46
+ if (!isRecord(payload)) return false;
47
+ if (endpoint === GROUP_TRIGGERS_ENDPOINTS.get) {
48
+ return exactKeys(payload, ['botId']) && validBotId(payload.botId);
49
+ }
50
+ if (endpoint === GROUP_TRIGGERS_ENDPOINTS.set) {
51
+ return exactKeys(payload, ['botId', 'config', 'removed'])
52
+ && validBotId(payload.botId)
53
+ && validGroupTriggersConfig(payload.config) !== null
54
+ && validRemoved(payload.removed);
55
+ }
56
+ return exactKeys(payload, ['botId', 'input'])
57
+ && validBotId(payload.botId)
58
+ && typeof payload.input === 'string'
59
+ && payload.input.trim().length > 0
60
+ && payload.input.length <= MAX_REFERENCE_LENGTH;
61
+ }
62
+
63
+ function operationError(error) {
64
+ if (error?.code === 'group-triggers-invalid') {
65
+ return { code: 'group-triggers-invalid', message: error.message };
66
+ }
67
+ return {
68
+ code: 'group-triggers-failed',
69
+ message: typeof error?.message === 'string' && error.message
70
+ ? error.message : 'Group trigger settings are unavailable.',
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Handle one of the group-trigger endpoints.
76
+ *
77
+ * Returns null for any other endpoint so the caller can fall through to the
78
+ * regular token-bot handler.
79
+ */
80
+ export function createGroupTriggersRpcHandler(controller) {
81
+ return async (endpoint, payload, signal) => {
82
+ if (!ENDPOINTS.includes(endpoint)) return null;
83
+ if (signal?.aborted) {
84
+ return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
85
+ }
86
+ if (!validGroupTriggersPayload(endpoint, payload)) {
87
+ return { ok: false, error: { code: 'bad-request', message: 'Invalid group trigger request.' } };
88
+ }
89
+ try {
90
+ if (endpoint === GROUP_TRIGGERS_ENDPOINTS.get) {
91
+ if (typeof controller.groupTriggersPanel !== 'function') throw new Error('Group trigger settings are unavailable.');
92
+ return { ok: true, value: await controller.groupTriggersPanel(payload.botId) };
93
+ }
94
+ if (endpoint === GROUP_TRIGGERS_ENDPOINTS.set) {
95
+ if (typeof controller.updateGroupTriggers !== 'function') throw new Error('Group trigger settings are unavailable.');
96
+ return {
97
+ ok: true,
98
+ value: await controller.updateGroupTriggers(payload.botId, {
99
+ config: payload.config,
100
+ removed: payload.removed ?? [],
101
+ }),
102
+ };
103
+ }
104
+ if (typeof controller.resolveGroupTrigger !== 'function') throw new Error('Group lookup is unavailable.');
105
+ return { ok: true, value: await controller.resolveGroupTrigger(payload.botId, payload.input) };
106
+ } catch (error) {
107
+ return { ok: false, error: operationError(error) };
108
+ }
109
+ };
110
+ }
@@ -135,6 +135,11 @@ export async function createTokenProductionController(ctx, config, internals, de
135
135
  const coreController = new ResolvedController({
136
136
  credentials: ctx.credentials,
137
137
  configStore: observedConfigStore,
138
+ // Channel settings scoped per chat need the archived group list (titles and
139
+ // real chat IDs) to offer something better than a blank form.
140
+ ...(definitions.controllerGroupHistory ? {
141
+ groupHistory: internals.groupHistory ?? getGroupHistoryStore(ctx, config),
142
+ } : {}),
138
143
  logger,
139
144
  ...(internals.inspectToken ? { inspectToken: internals.inspectToken } : {}),
140
145
  // Optional per-channel hook: a channel whose own settings also express an
@@ -162,6 +167,7 @@ export async function createTokenProductionController(ctx, config, internals, de
162
167
  const state = await stateFor(botId);
163
168
  await ensureWorkspace(botId, botConfig);
164
169
  const workspaceScope = createBotWorkspaceScope(harness, {
170
+ dsBot: config.deliveryService?.dsBot,
165
171
  botId, workspaces, state, agentPresetCatalog,
166
172
  });
167
173
  const persistTokens = typeof definitions.persistBotCredential === 'function'
@@ -227,7 +233,7 @@ export async function createTokenProductionController(ctx, config, internals, de
227
233
  return {
228
234
  controller,
229
235
  ...(supportsDeliveryChannel(channel) ? {
230
- deliveryAdapter: createDeliveryAdapter({ channel, workspaces, coreController, stateFor }),
236
+ deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot, channel, workspaces, coreController, stateFor }),
231
237
  } : {}),
232
238
  ready: supervisor.ready,
233
239
  async close() {
@@ -109,6 +109,7 @@ export async function createProductionController(ctx, config = {}, internals = {
109
109
  initialAccessPolicy: initialAccessPolicyFor('slack', botConfig),
110
110
  });
111
111
  const workspaceScope = createBotWorkspaceScope(harness, {
112
+ dsBot: config.deliveryService?.dsBot,
112
113
  botId, workspaces, state, agentPresetCatalog,
113
114
  });
114
115
  return new ResolvedRuntime({
@@ -162,7 +163,7 @@ export async function createProductionController(ctx, config = {}, internals = {
162
163
  }).start();
163
164
  return {
164
165
  controller,
165
- deliveryAdapter: createDeliveryAdapter({
166
+ deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
166
167
  channel: 'slack', workspaces, coreController, stateFor,
167
168
  }),
168
169
  ready: supervisor.ready,