@xmanrui/dsh-im 5.7.0 → 5.9.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 (77) hide show
  1. package/README.en.md +42 -7
  2. package/README.md +53 -7
  3. package/docs/preset-workspaces.md +37 -0
  4. package/lib/client.js +375 -160
  5. package/lib/index.js +330 -325
  6. package/package.json +3 -1
  7. package/plugin-src/client/channels/feishu/api.js +5 -0
  8. package/plugin-src/client/channels/feishu/conversation-directory-settings.js +73 -0
  9. package/plugin-src/client/channels/feishu/index.js +1 -0
  10. package/plugin-src/client/connection-error.js +1 -1
  11. package/plugin-src/client/delivery-settings.js +4 -0
  12. package/plugin-src/client/i18n-ru.js +17 -0
  13. package/plugin-src/client/i18n.js +17 -0
  14. package/plugin-src/client/styles.js +6 -0
  15. package/plugin-src/client/workspace-editor.js +6 -5
  16. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  17. package/plugin-src/host/channels/feishu/production.mjs +2 -1
  18. package/plugin-src/host/channels/feishu/rpc.mjs +25 -0
  19. package/plugin-src/host/channels/matrix/production.mjs +2 -1
  20. package/plugin-src/host/channels/qq/production.mjs +2 -1
  21. package/plugin-src/host/channels/shared/binding-events.mjs +130 -0
  22. package/plugin-src/host/channels/shared/production.mjs +32 -3
  23. package/plugin-src/host/channels/shared/workspace-rpc.mjs +2 -0
  24. package/plugin-src/host/channels/slack/production.mjs +2 -1
  25. package/plugin-src/host/channels/wecom/production.mjs +2 -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 +122 -1
  30. package/plugin-src/host/delivery-service.mjs +40 -0
  31. package/plugin-src/host/ds-bot-client.mjs +28 -2
  32. package/plugin-src/host/index.mjs +24 -1
  33. package/plugin-src/host/modern-harness-api.mjs +3 -0
  34. package/scripts/telegram-menu-scopes.mjs +57 -0
  35. package/scripts/verify-interface-language.mjs +60 -15
  36. package/scripts/verify-package.mjs +17 -6
  37. package/src/channels/dingtalk/dingtalk-bridge.mjs +2 -3
  38. package/src/channels/dingtalk/dingtalk-menu.mjs +4 -5
  39. package/src/channels/email/transports/imap-smtp.mjs +21 -11
  40. package/src/channels/feishu/bridge.mjs +75 -22
  41. package/src/channels/feishu/feishu-cards.mjs +96 -25
  42. package/src/channels/feishu/message-utils.mjs +1 -0
  43. package/src/channels/qq/qq-menu.mjs +3 -4
  44. package/src/channels/shared/action-card.mjs +331 -0
  45. package/src/channels/shared/bot-workspace-store.mjs +369 -6
  46. package/src/channels/shared/command-catalog.mjs +20 -5
  47. package/src/channels/shared/conversation/describe.mjs +116 -0
  48. package/src/channels/shared/conversation-directory-ensure.mjs +46 -0
  49. package/src/channels/shared/conversation-directory.mjs +29 -0
  50. package/src/channels/shared/conversation-state-store.mjs +62 -0
  51. package/src/channels/shared/diagnostic-details.mjs +38 -0
  52. package/src/channels/shared/harness-approval.mjs +58 -13
  53. package/src/channels/shared/harness-client.mjs +85 -2
  54. package/src/channels/shared/harness-session-binding.mjs +13 -1
  55. package/src/channels/shared/i18n-en/diagnostics.mjs +2 -0
  56. package/src/channels/shared/i18n-en/feishu.mjs +6 -0
  57. package/src/channels/shared/i18n-en/shared-a.mjs +14 -0
  58. package/src/channels/shared/i18n-en/telegram.mjs +14 -0
  59. package/src/channels/shared/i18n-ru/diagnostics.mjs +2 -0
  60. package/src/channels/shared/i18n-ru/feishu.mjs +6 -0
  61. package/src/channels/shared/i18n-ru/shared-a.mjs +14 -0
  62. package/src/channels/shared/i18n-ru/telegram.mjs +14 -0
  63. package/src/channels/shared/message-failure.mjs +8 -0
  64. package/src/channels/shared/model-command.mjs +5 -0
  65. package/src/channels/shared/new-command.mjs +7 -0
  66. package/src/channels/shared/preset-workspaces.mjs +48 -0
  67. package/src/channels/shared/qr-encoding-error.mjs +8 -2
  68. package/src/channels/shared/semantic/reply-reference.mjs +25 -5
  69. package/src/channels/shared/status-command.mjs +159 -0
  70. package/src/channels/shared/text-harness-bridge.mjs +89 -6
  71. package/src/channels/shared/workspace-command.mjs +36 -15
  72. package/src/channels/shared/workspace-session.mjs +30 -5
  73. package/src/channels/telegram/approval-card.mjs +379 -0
  74. package/src/channels/telegram/telegram-api.mjs +10 -1
  75. package/src/channels/telegram/telegram-bridge.mjs +7 -0
  76. package/src/channels/telegram/telegram-runtime.mjs +125 -13
  77. package/src/channels/wecom/wecom-bridge.mjs +5 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xmanrui/dsh-im",
3
- "version": "5.7.0",
3
+ "version": "5.9.0",
4
4
  "icon": "./assets/logo-plugin-message-link-gradient.webp",
5
5
  "description": "把微信、飞书、企微、钉钉、QQ、Telegram、WhatsApp、Slack、Discord、Matrix接入DSH。 Connect Telegram, WhatsApp, Slack, Discord, Matrix, WeChat, Feishu, WeCom, DingTalk, and QQ to DSH.",
6
6
  "keywords": [
@@ -56,6 +56,7 @@
56
56
  "lib",
57
57
  "locale/*.json",
58
58
  "plugin-src",
59
+ "scripts/telegram-menu-scopes.mjs",
59
60
  "scripts/verify-interface-language.mjs",
60
61
  "scripts/verify-injected-context.mjs",
61
62
  "scripts/verify-lan-management.mjs",
@@ -67,6 +68,7 @@
67
68
  "PROACTIVE_DELIVERY.md",
68
69
  "PROACTIVE_DELIVERY.en.md",
69
70
  "docs/client-integration.md",
71
+ "docs/preset-workspaces.md",
70
72
  "LICENSE",
71
73
  "README.md",
72
74
  "README.en.md",
@@ -17,6 +17,7 @@ import { normalizeContextEnhancementConfig } from "../../../../src/channels/shar
17
17
  import { normalizeFeishuStepPushMode, normalizeFeishuStepCardPanels } from "../../../../src/channels/feishu/step-push-mode.mjs";
18
18
  import { normalizeFeishuVoiceConfig } from "../../../../src/channels/feishu/voice-config.mjs";
19
19
  import { normalizeSlashPanelConfig } from "../../../../src/channels/feishu/slash-command-panel.mjs";
20
+ import { normalizeConversationDirectory } from "../../../../src/channels/shared/conversation-directory.mjs";
20
21
 
21
22
  export const FEISHU_RPC_CHANNEL = "/feishu";
22
23
 
@@ -32,6 +33,8 @@ export const FEISHU_ENDPOINTS = Object.freeze({
32
33
  disconnectBot: "bot.disconnect",
33
34
  deleteBot: "bot.delete",
34
35
  setWorkspace: "bot.workspace.set",
36
+ setConversationDirectory: "bot.conversation-directory.set",
37
+ setConversationDirectoryDefault: "bot.conversation-directory.default.set",
35
38
  setModel: SET_MODEL_ENDPOINT,
36
39
  setAgentPreset: "bot.preset.set",
37
40
  setContextEnhancement: "bot.context-enhancement.set",
@@ -224,6 +227,8 @@ export function normalizeBotConnection(value, fallbackBotId) {
224
227
  connected,
225
228
  configured: value.configured !== false,
226
229
  workspace: optionalString(value.workspace)?.slice(0, 4_096) ?? "",
230
+ conversationDirectory: normalizeConversationDirectory(value.conversationDirectory),
231
+ conversationDirectoryOverride: normalizeConversationDirectory(value.conversationDirectoryOverride),
227
232
  model: normalizeModelSelection(value.model),
228
233
  agentPreset: normalizeAgentPresetId(value.agentPreset),
229
234
  busyMessageMode: normalizeBusyMessageMode(value.busyMessageMode), contextEnhancement: normalizeContextEnhancementConfig(value.contextEnhancement),
@@ -0,0 +1,73 @@
1
+ import * as React from 'react';
2
+ import { h } from '../../i18n.js';
3
+ import { FEISHU_ENDPOINTS } from './api.js';
4
+ import { normalizeConversationDirectory, validateConversationDirectory } from '../../../../src/channels/shared/conversation-directory.mjs';
5
+
6
+ function ConfigForm({ title, value, inherited, busy, onSave, onClear }) {
7
+ const id = React.useId();
8
+ const [draft, setDraft] = React.useState(() => normalizeConversationDirectory(value) ?? { enabled: false, strategy: 'per-conversation', prefix: 'conv-' });
9
+ const [error, setError] = React.useState(null);
10
+ React.useEffect(() => {
11
+ setDraft(normalizeConversationDirectory(value) ?? { enabled: false, strategy: 'per-conversation', prefix: 'conv-' });
12
+ setError(null);
13
+ }, [value]);
14
+ const update = (key, next) => { setDraft((current) => ({ ...current, [key]: next })); setError(null); };
15
+ const save = async (event) => {
16
+ event.preventDefault();
17
+ try { setError(null); await onSave(validateConversationDirectory(draft)); }
18
+ catch (cause) { setError(cause.message); }
19
+ };
20
+ return h('form', { className: 'dim-conversationDirectoryForm', onSubmit: save, 'aria-label': title },
21
+ h('h3', null, title),
22
+ inherited ? h('p', { className: 'dim-botGeneralHelp' }, '继承渠道默认;保存后仅覆盖当前机器人。') : null,
23
+ h('label', { className: 'dim-botGeneralRow', htmlFor: `${id}-enabled` },
24
+ h('span', { className: 'dim-botGeneralTitle' }, '启用会话目录隔离'),
25
+ h('input', { id: `${id}-enabled`, type: 'checkbox', role: 'switch', className: 'dim-contextSwitch', checked: draft.enabled, disabled: busy, onChange: (event) => update('enabled', event.target.checked) })),
26
+ h('label', { className: 'dim-conversationDirectoryField', htmlFor: `${id}-strategy` },
27
+ h('span', null, '目录策略'),
28
+ h('select', { id: `${id}-strategy`, value: draft.strategy, disabled: busy, onChange: (event) => update('strategy', event.target.value) },
29
+ h('option', { value: 'per-conversation' }, '每个对话固定一个目录'),
30
+ h('option', { value: 'per-session' }, '每次新建会话使用新目录'))),
31
+ h('label', { className: 'dim-conversationDirectoryField', htmlFor: `${id}-prefix` },
32
+ h('span', null, '目录前缀'),
33
+ h('input', { id: `${id}-prefix`, value: draft.prefix, maxLength: 32, pattern: '[A-Za-z0-9_-]{1,32}', disabled: busy, onChange: (event) => update('prefix', event.target.value) })),
34
+ h('p', { className: 'dim-botGeneralHelp' }, '1–32 位字母、数字、下划线或连字符,默认为 conv-。'),
35
+ error ? h('p', { role: 'alert', className: 'dim-accessFeedback', 'data-tone': 'error' }, error) : null,
36
+ h('div', { className: 'dim-targetFormActions' },
37
+ h('button', { type: 'submit', className: 'dim-deliveryButton', disabled: busy }, '保存设置'),
38
+ onClear ? h('button', { type: 'button', className: 'dim-deliveryButton', disabled: busy, onClick: () => void onClear() }, title === '当前机器人' ? '恢复继承渠道默认' : '清除渠道默认') : null));
39
+ }
40
+
41
+ export function FeishuConversationDirectorySettingsPage({ account, rpcCall }) {
42
+ const [snapshot, setSnapshot] = React.useState(null);
43
+ const [busy, setBusy] = React.useState(false);
44
+ const [error, setError] = React.useState(null);
45
+ const load = React.useCallback(async () => {
46
+ setBusy(true); setError(null);
47
+ try {
48
+ const result = await rpcCall(FEISHU_ENDPOINTS.status, {});
49
+ if (result?.ok !== true) throw new Error(result?.error?.message ?? '无法读取会话目录设置。');
50
+ setSnapshot(result.value);
51
+ } catch (cause) { setError(cause.message); }
52
+ finally { setBusy(false); }
53
+ }, [rpcCall]);
54
+ React.useEffect(() => { void load(); }, [load]);
55
+ const save = async (endpoint, config) => {
56
+ setBusy(true); setError(null);
57
+ try {
58
+ const payload = endpoint === FEISHU_ENDPOINTS.setConversationDirectoryDefault ? { config } : { botId: account.botId, config };
59
+ const result = await rpcCall(endpoint, payload);
60
+ if (result?.ok !== true) throw new Error(result?.error?.message ?? '保存会话目录设置失败。');
61
+ setSnapshot(result.value);
62
+ } catch (cause) { setError(cause.message); }
63
+ finally { setBusy(false); }
64
+ };
65
+ const bot = snapshot?.bots?.find((item) => item.botId === account.botId);
66
+ return h('section', { className: 'dim-conversationDirectorySettings', 'aria-label': '会话目录隔离', 'aria-busy': busy },
67
+ h('p', { className: 'dim-botGeneralHelp' }, '让每个对话在自己的目录里工作,避免多人使用同一机器人时互相覆盖文件。默认关闭。'),
68
+ h('p', { className: 'dim-botGeneralHelp' }, '设置保存后对新会话生效。发送 /new 使用新设置;已有会话和旧目录中的文件保留。开启后无法手动修改工作区。'),
69
+ error ? h('p', { role: 'alert' }, error) : null,
70
+ bot ? h(React.Fragment, null,
71
+ h(ConfigForm, { key: `bot-${account.botId}`, title: '当前机器人', value: bot.conversationDirectoryOverride ?? bot.conversationDirectory, inherited: bot.conversationDirectoryOverride == null, busy, onSave: (config) => save(FEISHU_ENDPOINTS.setConversationDirectory, config), onClear: () => save(FEISHU_ENDPOINTS.setConversationDirectory, null) }),
72
+ h(ConfigForm, { key: `default-${JSON.stringify(snapshot.conversationDirectory)}`, title: '当前类型全部机器人会话目录隔离', value: snapshot.conversationDirectory, busy, onSave: (config) => save(FEISHU_ENDPOINTS.setConversationDirectoryDefault, config), onClear: () => save(FEISHU_ENDPOINTS.setConversationDirectoryDefault, null) })) : null);
73
+ }
@@ -649,6 +649,7 @@ export function BotCard({
649
649
  },
650
650
  h(WorkspaceEditor, {
651
651
  workspace: connection.workspace,
652
+ locked: connection.conversationDirectory?.enabled === true,
652
653
  disabled: Boolean(busy),
653
654
  onSave: onWorkspaceSave,
654
655
  }),
@@ -37,7 +37,7 @@ export function formatConnectionDiagnostic(value) {
37
37
  return [
38
38
  localizeText(error.message), details.hint ? localizeText(details.hint) : null,
39
39
  localizeText('错误码') + ': ' + error.code,
40
- ...['channel', 'operation', 'stage', 'method', 'transport', 'submissionState', 'attempts', 'lastFailureReason', 'reason', 'reasons', 'errorTypes', 'qrEncoder', 'qrRenderer', 'host', 'durationMs', 'timeoutMs', 'nodeVersion', 'dshVersion', 'platform', 'dependencies', 'proxyConfigured', 'truncated', 'httpStatus', 'providerCode', 'resource', 'file', 'field', 'issue', 'referenceId', 'occurredAt', 'rollback', 'pluginVersion']
40
+ ...['channel', 'operation', 'stage', 'method', 'transport', 'submissionState', 'attempts', 'lastFailureReason', 'reason', 'reasons', 'errorTypes', 'causeMessage', 'qrEncoder', 'qrRenderer', 'host', 'durationMs', 'timeoutMs', 'nodeVersion', 'dshVersion', 'platform', 'dependencies', 'proxyConfigured', 'truncated', 'httpStatus', 'providerCode', 'resource', 'file', 'field', 'issue', 'referenceId', 'occurredAt', 'rollback', 'pluginVersion']
41
41
  .filter(field => details[field] !== undefined)
42
42
  .map(field => `${field}: ${typeof details[field] === 'object' ? JSON.stringify(details[field]) : details[field]}`),
43
43
  ].filter(Boolean).join('\n');
@@ -7,6 +7,7 @@ import { DsBotSettingsPage } from './ds-bot-settings.js';
7
7
  import { FeishuGroupSettingsPage } from './channels/feishu/group-settings.js';
8
8
  import { FeishuVoiceSettingsPage } from './channels/feishu/voice-settings.js';
9
9
  import { FeishuSlashPanelSettingsPage } from './channels/feishu/slash-panel-settings.js';
10
+ import { FeishuConversationDirectorySettingsPage } from './channels/feishu/conversation-directory-settings.js';
10
11
  import { TelegramGroupTriggersSettings } from './channels/telegram/group-triggers-settings.js';
11
12
  import { h, imLocale, localizeTemplate, localizeText } from './i18n.js';
12
13
 
@@ -36,6 +37,7 @@ export const BOT_SETTINGS_TABS = Object.freeze([
36
37
 
37
38
  export const FEISHU_BOT_SETTINGS_TABS = Object.freeze([
38
39
  ...BOT_SETTINGS_TABS,
40
+ Object.freeze({ id: 'conversation-directory', label: '会话目录' }),
39
41
  Object.freeze({ id: 'group', label: '群聊' }),
40
42
  Object.freeze({ id: 'slash', label: '指令面板' }),
41
43
  Object.freeze({ id: 'voice', label: '语音交互' }),
@@ -812,6 +814,8 @@ export function DeliveryTargetSettingsPage({
812
814
  rpcCall: accessRpcCall,
813
815
  onSaved: setAccessPolicy,
814
816
  })
817
+ : activeTab.id === 'conversation-directory' && channel === 'feishu'
818
+ ? h(FeishuConversationDirectorySettingsPage, { account, rpcCall: accessRpcCall })
815
819
  : activeTab.id === 'groups' && channel === 'telegram'
816
820
  ? h(TelegramGroupTriggersSettings, {
817
821
  key: `${channel}:${account.botId}:groups`,
@@ -25,6 +25,23 @@ import weixinDiagnostics from '../../src/channels/shared/i18n-ru/weixin.mjs';
25
25
  // Sentences the settings UI composes itself, as `{name}` templates: the key is the
26
26
  // Chinese template and the value keeps the placeholders of the English one.
27
27
  const COMPOSED = Object.freeze({
28
+ '会话目录': 'Каталоги бесед',
29
+ '会话目录隔离': 'Изоляция каталогов бесед',
30
+ '会话目录隔离已开启,工作区由对话自动分配。': 'Изоляция каталогов бесед включена. Рабочая область назначается автоматически для каждой беседы.',
31
+ '无法读取会话目录设置。': 'Не удалось загрузить настройки каталогов бесед.',
32
+ '保存会话目录设置失败。': 'Не удалось сохранить настройки каталогов бесед.',
33
+ '让每个对话在自己的目录里工作,避免多人使用同一机器人时互相覆盖文件。默认关闭。': 'Каждая беседа работает в собственном каталоге, чтобы пользователи одного бота не перезаписывали файлы друг друга. По умолчанию отключено.',
34
+ '设置保存后对新会话生效。发送 /new 使用新设置;已有会话和旧目录中的文件保留。开启后无法手动修改工作区。': 'Сохранённые настройки применяются к новым сеансам. Отправьте /new, чтобы использовать их. Существующие сеансы и файлы в прежних каталогах сохраняются. При включённой изоляции нельзя менять рабочую область вручную.',
35
+ '当前类型全部机器人会话目录隔离': 'Изоляция каталогов бесед по умолчанию для всех ботов этого канала',
36
+ '继承渠道默认;保存后仅覆盖当前机器人。': 'Наследуются настройки канала. Сохранение переопределит их только для текущего бота.',
37
+ '启用会话目录隔离': 'Включить изоляцию каталогов бесед',
38
+ '目录策略': 'Правило создания каталогов',
39
+ '每个对话固定一个目录': 'Один постоянный каталог для каждой беседы',
40
+ '每次新建会话使用新目录': 'Новый каталог для каждого нового сеанса',
41
+ '目录前缀': 'Префикс каталога',
42
+ '恢复继承渠道默认': 'Восстановить настройки канала по умолчанию',
43
+ '清除渠道默认': 'Сбросить настройки канала по умолчанию',
44
+ '1–32 位字母、数字、下划线或连字符,默认为 conv-。': 'От 1 до 32 латинских букв, цифр, знаков подчёркивания или дефисов. По умолчанию: conv-.',
28
45
  '使用 Bot Token 接入 {channel} 机器人': 'Подключить бота {channel} по Bot Token',
29
46
  '已接入的 {channel} 机器人': 'Подключённые боты {channel}',
30
47
  '正在读取 {channel} 机器人状态…': 'Читаю состояние ботов {channel}…',
@@ -154,6 +154,23 @@ const EN = Object.freeze({
154
154
  'IM 面板加载失败': 'Could not load the IM panel',
155
155
  '更多机器人设置': 'More bot settings',
156
156
  '更多设置': 'More settings',
157
+ '会话目录': 'Conversation directories',
158
+ '会话目录隔离': 'Conversation directory isolation',
159
+ '会话目录隔离已开启,工作区由对话自动分配。': 'Conversation directory isolation is enabled. Workspaces are assigned automatically.',
160
+ '无法读取会话目录设置。': 'Could not load conversation directory settings.',
161
+ '保存会话目录设置失败。': 'Could not save conversation directory settings.',
162
+ '让每个对话在自己的目录里工作,避免多人使用同一机器人时互相覆盖文件。默认关闭。': 'Give each conversation its own directory to prevent users sharing a bot from overwriting files. Off by default.',
163
+ '设置保存后对新会话生效。发送 /new 使用新设置;已有会话和旧目录中的文件保留。开启后无法手动修改工作区。': 'New settings apply to new sessions. Send /new to use them. Existing sessions and files remain. Workspaces cannot be changed manually while isolation is enabled.',
164
+ '当前类型全部机器人会话目录隔离': 'Channel default · Conversation directory isolation',
165
+ '继承渠道默认;保存后仅覆盖当前机器人。': 'Inherits the channel default. Saving overrides it for this bot only.',
166
+ '启用会话目录隔离': 'Enable conversation directory isolation',
167
+ '目录策略': 'Directory strategy',
168
+ '每个对话固定一个目录': 'One directory per conversation',
169
+ '每次新建会话使用新目录': 'A new directory for every session',
170
+ '目录前缀': 'Directory prefix',
171
+ '恢复继承渠道默认': 'Restore channel default',
172
+ '清除渠道默认': 'Clear channel default',
173
+ '1–32 位字母、数字、下划线或连字符,默认为 conv-。': '1–32 letters, digits, underscores or hyphens. Default: conv-.',
157
174
  '向左滚动设置页签': 'Scroll settings tabs left',
158
175
  '向右滚动设置页签': 'Scroll settings tabs right',
159
176
  '常用配置': 'Common settings',
@@ -1,6 +1,12 @@
1
1
  export const IM_STYLE_ID = 'xmanrui-dsh-im-settings';
2
2
 
3
3
  const CSS = String.raw`
4
+ .dim-conversationDirectorySettings { max-width: 720px; }
5
+ .dim-conversationDirectoryForm { margin: 18px 0; padding: 16px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 8px; }
6
+ .dim-conversationDirectoryForm h3 { margin: 0 0 12px; font-size: 15px; }
7
+ .dim-conversationDirectoryField { display: flex; align-items: center; gap: 12px; margin: 12px 0; font-size: 13px; }
8
+ .dim-conversationDirectoryField > span { min-width: 72px; }
9
+ .dim-conversationDirectoryField input, .dim-conversationDirectoryField select { max-width: 100%; min-width: 0; padding: 7px 9px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 6px; font: inherit; color: inherit; background: var(--dsw-alias-bg-layer-1, #fff); }
4
10
  .dim-sidebarIcon { display: block; flex: none; }
5
11
  .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
12
  .dim-pluginOpen:hover { background: var(--dsw-alias-interactive-bg-hover, #f7f8fa); }
@@ -5,7 +5,7 @@ import { WorkspaceDirectoryPicker } from './workspace-directory-picker.js';
5
5
 
6
6
  export const WorkspaceDirectoryPickerContext = React.createContext(null);
7
7
 
8
- export function WorkspaceEditor({ workspace, directoryPicker, disabled = false, onSave }) {
8
+ export function WorkspaceEditor({ workspace, directoryPicker, disabled = false, locked = false, onSave }) {
9
9
  const sharedDirectoryPicker = React.useContext(WorkspaceDirectoryPickerContext);
10
10
  const activeDirectoryPicker = directoryPicker ?? sharedDirectoryPicker;
11
11
  const [open, setOpen] = React.useState(false);
@@ -21,7 +21,7 @@ export function WorkspaceEditor({ workspace, directoryPicker, disabled = false,
21
21
  }, []);
22
22
 
23
23
  const pick = React.useCallback(async (value) => {
24
- if (!value || savingRef.current || disabled) return;
24
+ if (!value || savingRef.current || disabled || locked) return;
25
25
  if (value === workspace) {
26
26
  close();
27
27
  return;
@@ -38,7 +38,7 @@ export function WorkspaceEditor({ workspace, directoryPicker, disabled = false,
38
38
  savingRef.current = false;
39
39
  setSaving(false);
40
40
  }
41
- }, [close, disabled, onSave, workspace]);
41
+ }, [close, disabled, locked, onSave, workspace]);
42
42
 
43
43
  return h('div', { className: 'dim-workspace' },
44
44
  h('div', { className: 'dim-workspaceHeader' },
@@ -48,7 +48,8 @@ export function WorkspaceEditor({ workspace, directoryPicker, disabled = false,
48
48
  ref: editButtonRef,
49
49
  className: 'dim-workspaceEdit',
50
50
  onClick: () => { setOpen(true); setError(null); },
51
- disabled: disabled || !activeDirectoryPicker,
51
+ disabled: disabled || locked || !activeDirectoryPicker,
52
+ title: locked ? '会话目录隔离已开启,工作区由对话自动分配。' : undefined,
52
53
  }, '选择目录')),
53
54
  workspace
54
55
  ? React.createElement('code', {
@@ -60,7 +61,7 @@ export function WorkspaceEditor({ workspace, directoryPicker, disabled = false,
60
61
  open,
61
62
  startPath: workspace,
62
63
  picker: activeDirectoryPicker,
63
- busy: saving || disabled,
64
+ busy: saving || disabled || locked,
64
65
  saveError: error,
65
66
  onPicked: pick,
66
67
  onCancel: close,
@@ -63,7 +63,7 @@ export async function createProductionController(ctx, config = {}, internals = {
63
63
  const { defaultWorkspace, ungroupedWorkspace } = await prepareBotWorkspace(config);
64
64
  const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
65
65
  const workspaces = internals.workspaces
66
- ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace }).load();
66
+ ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace, groupByAgentPreset: config.groupByAgentPreset }).load();
67
67
  const canListConfiguredBots = typeof configStore.list === 'function';
68
68
  const configuredBots = canListConfiguredBots ? configStore.list() : [];
69
69
  if (canListConfiguredBots) {
@@ -167,6 +167,7 @@ export async function createProductionController(ctx, config = {}, internals = {
167
167
  },
168
168
  });
169
169
  const controller = createWorkspaceAwareController(coreController, {
170
+ harness,
170
171
  workspaces,
171
172
  stateFor,
172
173
  agentPresetCatalog,
@@ -125,7 +125,7 @@ export async function createProductionController(ctx, config = {}, internals = {
125
125
  const { defaultWorkspace, ungroupedWorkspace } = await prepareBotWorkspace(config);
126
126
  const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
127
127
  const workspaces = internals.workspaces
128
- ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace }).load();
128
+ ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace, groupByAgentPreset: config.groupByAgentPreset }).load();
129
129
  const canListConfiguredBots = typeof configStore.list === 'function';
130
130
  const listConfiguredBots = () => canListConfiguredBots ? configStore.list() : [];
131
131
  const configuredBots = listConfiguredBots();
@@ -302,6 +302,7 @@ export async function createProductionController(ctx, config = {}, internals = {
302
302
  },
303
303
  });
304
304
  const controller = createWorkspaceAwareController(coreController, {
305
+ harness,
305
306
  workspaces,
306
307
  stateFor: stateForBotId,
307
308
  agentPresetCatalog,
@@ -17,6 +17,7 @@ import {
17
17
  normalizeModelSelection,
18
18
  } from '../../../../src/channels/shared/model-setting.mjs';
19
19
  import { normalizeAccessPolicy } from '../../../../src/channels/shared/access-policy.mjs';
20
+ import { normalizeConversationDirectory, validateConversationDirectory } from '../../../../src/channels/shared/conversation-directory.mjs';
20
21
  import { resolveRpcAuthority } from '../../rpc-authority.mjs';
21
22
  import { publicWorkspaceError, validWorkspacePayload } from '../shared/workspace-rpc.mjs';
22
23
  import { validAgentPresetPayload } from '../shared/agent-preset-rpc.mjs';
@@ -49,6 +50,8 @@ export const FEISHU_ENDPOINTS = Object.freeze({
49
50
  setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
50
51
  setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
51
52
  setAlias: SET_ALIAS_ENDPOINT,
53
+ setConversationDirectory: FEISHU_CLIENT_ENDPOINTS.setConversationDirectory,
54
+ setConversationDirectoryDefault: FEISHU_CLIENT_ENDPOINTS.setConversationDirectoryDefault,
52
55
  });
53
56
  export { FEISHU_RPC_CHANNEL };
54
57
  export const FEISHU_MULTI_ENDPOINTS = Object.freeze({
@@ -315,6 +318,8 @@ function publicBotEntry(entry) {
315
318
  contextEnhancement: normalizeContextEnhancementConfig(source.contextEnhancement),
316
319
  busyMessageMode: normalizeBusyMessageMode(source.busyMessageMode),
317
320
  accessPolicy: normalizeAccessPolicy(source.accessPolicy),
321
+ conversationDirectory: normalizeConversationDirectory(source.conversationDirectory),
322
+ conversationDirectoryOverride: normalizeConversationDirectory(source.conversationDirectoryOverride),
318
323
  groupResponseMode: normalizeFeishuGroupResponseMode(source.groupResponseMode),
319
324
  mentionTopicReply: source.mentionTopicReply !== false,
320
325
  stepPush: source.stepPush === true,
@@ -366,6 +371,7 @@ export async function toPublicFeishuStatus(status, { encodeQr = qrCodeDataUrl }
366
371
  bot: publicBot(source.bot),
367
372
  health: publicHealth(source, connected),
368
373
  bots,
374
+ conversationDirectory: normalizeConversationDirectory(source.conversationDirectory),
369
375
  agentPresetCatalog: normalizeAgentPresetCatalog(source.agentPresetCatalog),
370
376
  modelCatalog: normalizeModelCatalog(source.modelCatalog),
371
377
  totals: {
@@ -458,6 +464,18 @@ function validPayload(endpoint, payload) {
458
464
  return validWorkspacePayload(payload)
459
465
  ? null : '请输入工作区绝对路径。';
460
466
  }
467
+ if (endpoint === FEISHU_ENDPOINTS.setConversationDirectory
468
+ || endpoint === FEISHU_ENDPOINTS.setConversationDirectoryDefault) {
469
+ const isDefault = endpoint === FEISHU_ENDPOINTS.setConversationDirectoryDefault;
470
+ const allowed = isDefault ? new Set(['config']) : new Set(['botId', 'config']);
471
+ if (!hasOnlyKeys(payload, allowed) || (!isDefault && !safeOpaqueId(payload.botId))) {
472
+ return '请提交有效的会话目录设置。';
473
+ }
474
+ if (payload.config !== null) {
475
+ try { validateConversationDirectory(payload.config); } catch (error) { return error.message; }
476
+ }
477
+ return null;
478
+ }
461
479
  if (endpoint === FEISHU_ENDPOINTS.setModel) {
462
480
  return validModelPayload(payload) ? null : '请选择有效模型。';
463
481
  }
@@ -776,6 +794,13 @@ export function createFeishuRpcHandler(controller, { encodeQr = qrCodeDataUrl }
776
794
  } else if (endpoint === FEISHU_MULTI_ENDPOINTS.disconnectBot) {
777
795
  if (typeof controller.disconnectBot !== 'function') throw new Error('Multi-bot disconnect is unavailable');
778
796
  value = await toPublicFeishuStatus(await controller.disconnectBot(payload.botId), { encodeQr: cachedEncodeQr });
797
+ } else if (endpoint === FEISHU_ENDPOINTS.setConversationDirectory
798
+ || endpoint === FEISHU_ENDPOINTS.setConversationDirectoryDefault) {
799
+ if (typeof controller.updateConversationDirectory !== 'function') throw new Error('Conversation directory update is unavailable');
800
+ value = await toPublicFeishuStatus(await controller.updateConversationDirectory(
801
+ endpoint === FEISHU_ENDPOINTS.setConversationDirectoryDefault ? null : payload.botId,
802
+ payload.config,
803
+ ), { encodeQr: cachedEncodeQr });
779
804
  } else if (endpoint === FEISHU_ENDPOINTS.setWorkspace) {
780
805
  if (typeof controller.updateWorkspace !== 'function') throw new Error('Workspace update is unavailable');
781
806
  value = await toPublicFeishuStatus(
@@ -51,7 +51,7 @@ export async function createProductionController(ctx, config = {}, internals = {
51
51
  const defaultWorkspace = resolve(config.workspace ?? process.cwd());
52
52
  const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
53
53
  const workspaces = internals.workspaces
54
- ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace }).load();
54
+ ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, groupByAgentPreset: config.groupByAgentPreset }).load();
55
55
  const configuredBots = configStore.list();
56
56
  await workspaces.reconcile(configuredBots.map((bot) => bot.botId));
57
57
  await Promise.all(configuredBots.map((bot) => workspaces.ensure(bot.botId, {
@@ -213,6 +213,7 @@ export async function createProductionController(ctx, config = {}, internals = {
213
213
  },
214
214
  });
215
215
  const controller = createWorkspaceAwareController(coreController, {
216
+ harness,
216
217
  workspaces,
217
218
  stateFor,
218
219
  agentPresetCatalog,
@@ -62,7 +62,7 @@ export async function createProductionController(ctx, config = {}, internals = {
62
62
  const { defaultWorkspace, ungroupedWorkspace } = await prepareBotWorkspace(config);
63
63
  const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
64
64
  const workspaces = internals.workspaces
65
- ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace }).load();
65
+ ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace, groupByAgentPreset: config.groupByAgentPreset }).load();
66
66
  const configuredBots = configStore.list();
67
67
  await workspaces.reconcile(configuredBots.map((bot) => bot.botId));
68
68
  await Promise.all(configuredBots.map((bot) => workspaces.ensure(bot.botId, {
@@ -160,6 +160,7 @@ export async function createProductionController(ctx, config = {}, internals = {
160
160
  },
161
161
  });
162
162
  const controller = createWorkspaceAwareController(coreController, {
163
+ harness,
163
164
  workspaces,
164
165
  stateFor,
165
166
  agentPresetCatalog,
@@ -0,0 +1,130 @@
1
+ import { parseConversationKey } from '../../../../src/channels/shared/conversation/describe.mjs';
2
+
3
+ /**
4
+ * Identity events for conversation bindings.
5
+ *
6
+ * `dsh-im/session-pre-bind` is announced the moment a conversation points at a
7
+ * session. It runs synchronously and before the Session exists, so a subscriber
8
+ * holds the identity while the first system prompt is assembled.
9
+ *
10
+ * `dsh-im/session-unbind` is announced when a conversation stops pointing at a
11
+ * session: it was switched to another one, or the binding was cleared. Without
12
+ * it a subscriber can only notice that *some* session was bound later, and its
13
+ * own session->identity state keeps claiming a conversation it no longer owns.
14
+ *
15
+ * Both events carry the same conversation fields, so a subscriber handles them
16
+ * symmetrically.
17
+ */
18
+ export function createBindingAnnouncer({
19
+ channel,
20
+ emit,
21
+ authorsOf = () => null,
22
+ parse = parseConversationKey,
23
+ } = {}) {
24
+ if (typeof emit !== 'function') throw new TypeError('emit is required');
25
+
26
+ const conversationFields = (conversationKey) => {
27
+ const parsed = parse(conversationKey, { channel });
28
+ return {
29
+ channel,
30
+ conversationKey,
31
+ chatType: parsed?.chatType ?? null,
32
+ chatId: parsed?.chatId ?? null,
33
+ threadId: parsed?.threadId ?? null,
34
+ senderId: parsed?.senderId ?? null,
35
+ };
36
+ };
37
+
38
+ // A subscriber that throws must not break the message being handled, so every
39
+ // announce swallows its own failure.
40
+ const announce = (event, payload) => {
41
+ try {
42
+ emit(event, Object.freeze(payload));
43
+ } catch {
44
+ // ignore a subscriber's failure
45
+ }
46
+ };
47
+
48
+ const bind = (botId, conversationKey, sessionId) => {
49
+ try {
50
+ const authors = authorsOf(botId);
51
+ const author = authors?.[conversationKey] ?? null;
52
+ const fields = conversationFields(conversationKey);
53
+ announce('dsh-im/session-pre-bind', {
54
+ ...fields,
55
+ botId,
56
+ sessionId,
57
+ senderId: author?.senderId ?? fields.senderId,
58
+ senderName: author?.senderName ?? null,
59
+ });
60
+ } catch {
61
+ // ignore a malformed conversation key or author snapshot
62
+ }
63
+ };
64
+
65
+ const unbind = (botId, conversationKey, sessionId) => {
66
+ if (typeof sessionId !== 'string' || sessionId === '') return;
67
+ try {
68
+ announce('dsh-im/session-unbind', {
69
+ ...conversationFields(conversationKey),
70
+ botId,
71
+ sessionId,
72
+ });
73
+ } catch {
74
+ // ignore a malformed conversation key
75
+ }
76
+ };
77
+
78
+ const previousSession = (state, key) => (typeof state.sessionFor === 'function'
79
+ ? state.sessionFor(key)
80
+ : null);
81
+
82
+ /**
83
+ * Wrap one bot's state store so every committed binding change is announced.
84
+ * A refused write (`false`) announces nothing, and a write that repeats the
85
+ * current session is not an unbind: the conversation never left it.
86
+ */
87
+ const wrap = (botId, state) => {
88
+ if (state === null || typeof state !== 'object' || state.__announces === true) return state;
89
+ const setSession = state.setSession;
90
+ if (typeof setSession !== 'function') return state;
91
+
92
+ state.setSession = async (key, sessionId) => {
93
+ const previous = previousSession(state, key);
94
+ const result = await setSession.call(state, key, sessionId);
95
+ if (result === false) return result;
96
+ if (previous !== null && previous !== sessionId) unbind(botId, key, previous);
97
+ bind(botId, key, sessionId);
98
+ return result;
99
+ };
100
+
101
+ if (typeof state.clearSession === 'function') {
102
+ const clearSession = state.clearSession;
103
+ state.clearSession = async (key) => {
104
+ const previous = previousSession(state, key);
105
+ const result = await clearSession.call(state, key);
106
+ unbind(botId, key, previous);
107
+ return result;
108
+ };
109
+ }
110
+
111
+ if (typeof state.clearSessions === 'function') {
112
+ const clearSessions = state.clearSessions;
113
+ state.clearSessions = async () => {
114
+ const bindings = typeof state.snapshot === 'function'
115
+ ? state.snapshot()?.sessions ?? null
116
+ : null;
117
+ const result = await clearSessions.call(state);
118
+ for (const [key, sessionId] of Object.entries(bindings ?? {})) {
119
+ unbind(botId, key, sessionId);
120
+ }
121
+ return result;
122
+ };
123
+ }
124
+
125
+ state.__announces = true;
126
+ return state;
127
+ };
128
+
129
+ return { bind, unbind, wrap };
130
+ }
@@ -4,6 +4,7 @@ import { unlink } from 'node:fs/promises';
4
4
  import { homedir } from 'node:os';
5
5
  import { join, resolve } from 'node:path';
6
6
 
7
+ import { createBindingAnnouncer } from './binding-events.mjs';
7
8
  import { createTokenConnectionSupervisor } from './connection-supervisor.mjs';
8
9
  import { createHarnessCommandExecutor } from '../../harness-command-executor.mjs';
9
10
  import { harnessConnection } from '../../harness-connection.mjs';
@@ -71,7 +72,7 @@ export async function createTokenProductionController(ctx, config, internals, de
71
72
  const { defaultWorkspace, ungroupedWorkspace } = await prepareBotWorkspace(config);
72
73
  const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
73
74
  const workspaces = internals.workspaces
74
- ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace }).load();
75
+ ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace, groupByAgentPreset: config.groupByAgentPreset }).load();
75
76
  const configuredBots = configStore.list();
76
77
  await workspaces.reconcile(configuredBots.map((bot) => bot.botId));
77
78
  await Promise.all(configuredBots.map((bot) => workspaces.ensure(bot.botId, {
@@ -93,14 +94,33 @@ export async function createTokenProductionController(ctx, config, internals, de
93
94
  });
94
95
  const stateStores = new Map();
95
96
  const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
97
+
98
+ /**
99
+ * Every binding change is announced the moment it is written: a bind before the
100
+ * Session exists, an unbind when the conversation moves to another session or
101
+ * its binding is cleared. Listeners run synchronously.
102
+ */
103
+ const announcer = createBindingAnnouncer({
104
+ channel,
105
+ emit: (event, payload) => ctx.emit(event, payload),
106
+ authorsOf: (botId) => (typeof stateStores.get(botId)?.snapshot === 'function'
107
+ ? stateStores.get(botId).snapshot()?.authors ?? null
108
+ : null),
109
+ });
110
+
111
+ /** Every loaded store reports its own bindings, once. */
96
112
  const stateFor = async (botId) => {
97
113
  let state = stateStores.get(botId);
98
114
  if (!state) {
99
- state = await new ResolvedStateStore(statePath(botId)).load();
115
+ state = announcer.wrap(botId, await new ResolvedStateStore(statePath(botId)).load());
100
116
  stateStores.set(botId, state);
101
117
  }
102
118
  return state;
103
119
  };
120
+ // Warm the per-bot state memo now: the synchronous identity lookup can only
121
+ // answer from state that is already loaded in this process, and the first prompt
122
+ // of a session arrives long before any delivery call would load it.
123
+ await Promise.all(configuredBots.map((bot) => stateFor(bot.botId).catch(() => null)));
104
124
  const commandExecutor = createHarnessCommandExecutor(ctx, internals.commandExecutor);
105
125
  const inboundTtl = internals.inboundTtl ?? getInboundTtlRuntime(ctx, config);
106
126
  const inboundTtlService = inboundTtl?.service ?? inboundTtl;
@@ -222,6 +242,7 @@ export async function createTokenProductionController(ctx, config, internals, de
222
242
  });
223
243
  controllerRef = coreController;
224
244
  const controller = createWorkspaceAwareController(coreController, {
245
+ harness,
225
246
  workspaces,
226
247
  stateFor,
227
248
  agentPresetCatalog,
@@ -238,7 +259,15 @@ export async function createTokenProductionController(ctx, config, internals, de
238
259
  return {
239
260
  controller,
240
261
  ...(supportsDeliveryChannel(channel) ? {
241
- deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot, channel, workspaces, coreController, stateFor }),
262
+ deliveryAdapter: createDeliveryAdapter({
263
+ dsBot: config.deliveryService?.dsBot,
264
+ channel,
265
+ workspaces,
266
+ coreController,
267
+ stateFor,
268
+ // The same store, without the await: it is a memo of already loaded bots.
269
+ stateForSync: (botId) => stateStores.get(botId) ?? null,
270
+ }),
242
271
  } : {}),
243
272
  ready: supervisor.ready,
244
273
  async close() {
@@ -16,6 +16,8 @@ export function validWorkspacePayload(payload) {
16
16
 
17
17
  export function publicWorkspaceError(error) {
18
18
  if (![
19
+ 'workspace-manual-edit-disabled',
20
+ 'conversation-directory-invalid',
19
21
  'workspace-not-absolute',
20
22
  'workspace-not-found',
21
23
  'workspace-not-directory',