@xmanrui/dsh-im 5.3.0 → 5.5.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 (112) hide show
  1. package/PROACTIVE_DELIVERY.en.md +15 -0
  2. package/PROACTIVE_DELIVERY.md +15 -0
  3. package/README.en.md +44 -3
  4. package/README.md +44 -3
  5. package/THIRD_PARTY_NOTICES.md +209 -0
  6. package/docs/client-integration.md +2 -2
  7. package/lib/client.js +3737 -433
  8. package/lib/index.js +415 -344
  9. package/package.json +1 -1
  10. package/plugin-src/client/channel-card-meta.js +6 -2
  11. package/plugin-src/client/channels/shared/token-api.js +13 -0
  12. package/plugin-src/client/channels/telegram/group-triggers-settings.js +393 -0
  13. package/plugin-src/client/channels/telegram/styles.js +4 -0
  14. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  15. package/plugin-src/client/delivery-settings.js +23 -3
  16. package/plugin-src/client/ds-bot-avatar-data.js +537 -0
  17. package/plugin-src/client/ds-bot-avatar.js +55 -0
  18. package/plugin-src/client/ds-bot-session-avatars.js +77 -0
  19. package/plugin-src/client/ds-bot-settings.js +194 -0
  20. package/plugin-src/client/i18n-ru.js +1615 -0
  21. package/plugin-src/client/i18n.js +130 -1
  22. package/plugin-src/client/index.js +20 -2
  23. package/plugin-src/client/plugin-page.js +3 -8
  24. package/plugin-src/client/styles.js +25 -5
  25. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  26. package/plugin-src/host/channels/feishu/production.mjs +13 -5
  27. package/plugin-src/host/channels/qq/production.mjs +2 -1
  28. package/plugin-src/host/channels/shared/group-triggers-rpc.mjs +110 -0
  29. package/plugin-src/host/channels/shared/production.mjs +12 -1
  30. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  31. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  32. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  33. package/plugin-src/host/channels/slack/production.mjs +2 -1
  34. package/plugin-src/host/channels/telegram/index.mjs +1 -0
  35. package/plugin-src/host/channels/telegram/production.mjs +9 -0
  36. package/plugin-src/host/channels/telegram/rpc.mjs +17 -2
  37. package/plugin-src/host/channels/wecom/production.mjs +4 -1
  38. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  39. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  40. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  41. package/plugin-src/host/delivery-adapter.mjs +129 -41
  42. package/plugin-src/host/delivery-rpc.mjs +33 -1
  43. package/plugin-src/host/delivery-service.mjs +112 -1
  44. package/plugin-src/host/delivery-suggestions.mjs +11 -0
  45. package/plugin-src/host/ds-bot-client.mjs +87 -0
  46. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  47. package/plugin-src/host/index.mjs +8 -1
  48. package/plugin-src/host/modern-harness-api.mjs +53 -8
  49. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  50. package/scripts/verify-package.mjs +17 -5
  51. package/src/channels/feishu/bridge.mjs +83 -5
  52. package/src/channels/feishu/feishu-cards.mjs +11 -7
  53. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  54. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  55. package/src/channels/shared/AGENTS.md +19 -0
  56. package/src/channels/shared/bot-workspace-store.mjs +136 -7
  57. package/src/channels/shared/clear-command.mjs +2 -1
  58. package/src/channels/shared/compact-command.mjs +2 -1
  59. package/src/channels/shared/conversation-queue.mjs +49 -0
  60. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  61. package/src/channels/shared/group-history-store.mjs +26 -0
  62. package/src/channels/shared/harness-client.mjs +5 -4
  63. package/src/channels/shared/history-command.mjs +2 -1
  64. package/src/channels/shared/i18n-en/feishu.mjs +1 -0
  65. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  66. package/src/channels/shared/i18n-en/shared-b.mjs +2 -2
  67. package/src/channels/shared/i18n-en/shared-c.mjs +3 -2
  68. package/src/channels/shared/i18n-en/wecom.mjs +4 -0
  69. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  70. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  71. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  72. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  73. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  74. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  75. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  76. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  77. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  78. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  79. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  80. package/src/channels/shared/i18n-ru/shared-b.mjs +257 -0
  81. package/src/channels/shared/i18n-ru/shared-c.mjs +173 -0
  82. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  83. package/src/channels/shared/i18n-ru/telegram.mjs +25 -0
  84. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  85. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  86. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  87. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  88. package/src/channels/shared/i18n-ru.mjs +48 -0
  89. package/src/channels/shared/i18n.mjs +47 -12
  90. package/src/channels/shared/inbound-access.mjs +1 -1
  91. package/src/channels/shared/interface-language.mjs +3 -3
  92. package/src/channels/shared/message-failure.mjs +3 -2
  93. package/src/channels/shared/model-command.mjs +2 -1
  94. package/src/channels/shared/permission-command.mjs +2 -1
  95. package/src/channels/shared/send-limit.mjs +38 -0
  96. package/src/channels/shared/session-binding-lock.mjs +2 -0
  97. package/src/channels/shared/session-error.mjs +3 -0
  98. package/src/channels/shared/status-reaction.mjs +2 -0
  99. package/src/channels/shared/text-harness-bridge.mjs +4 -0
  100. package/src/channels/shared/thinking-cadence.mjs +36 -0
  101. package/src/channels/shared/workspace-command.mjs +2 -1
  102. package/src/channels/shared/workspace-session.mjs +5 -1
  103. package/src/channels/telegram/config-store.mjs +38 -1
  104. package/src/channels/telegram/group-triggers.mjs +229 -0
  105. package/src/channels/telegram/telegram-api.mjs +223 -32
  106. package/src/channels/telegram/telegram-bridge.mjs +4 -1
  107. package/src/channels/telegram/telegram-controller.mjs +139 -1
  108. package/src/channels/telegram/telegram-runtime.mjs +522 -178
  109. package/src/channels/telegram/voice.mjs +250 -0
  110. package/src/channels/wecom/stream-supervisor.mjs +184 -0
  111. package/src/channels/wecom/wecom-bridge.mjs +25 -11
  112. package/src/channels/wecom/wecom-runtime.mjs +12 -1
@@ -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,
@@ -23,6 +23,7 @@ export function createTelegramHostPlugin(config) {
23
23
 
24
24
  export { createProductionController } from './production.mjs';
25
25
  export {
26
+ GROUP_TRIGGERS_ENDPOINTS,
26
27
  TELEGRAM_ENDPOINTS,
27
28
  TELEGRAM_RPC_CHANNEL,
28
29
  TELEGRAM_RPC_ENDPOINTS,
@@ -3,6 +3,7 @@ import { TelegramHarnessClient } from '../../../../src/channels/telegram/harness
3
3
  import { TelegramController } from '../../../../src/channels/telegram/telegram-controller.mjs';
4
4
  import { TelegramRuntime } from '../../../../src/channels/telegram/telegram-runtime.mjs';
5
5
  import { TelegramStateStore } from '../../../../src/channels/telegram/state-store.mjs';
6
+ import { createTelegramVoiceTranscriber } from '../../../../src/channels/telegram/voice.mjs';
6
7
  import { createTokenProductionController } from '../shared/production.mjs';
7
8
 
8
9
  export { normalizeTelegramAllowedUsers } from '../../../../src/channels/telegram/config-store.mjs';
@@ -15,5 +16,13 @@ export function createProductionController(ctx, config = {}, internals = {}) {
15
16
  HarnessClient: TelegramHarnessClient,
16
17
  Controller: TelegramController,
17
18
  Runtime: TelegramRuntime,
19
+ // The per-group reply rules list chats from the shared group archive.
20
+ controllerGroupHistory: true,
21
+ // Speech recognition is a Host service (@deepseek-ai/dsh-experimental-speech-to-text);
22
+ // the channel only converts the attachment and forwards the transcript.
23
+ createVoiceTranscriber: (ctx) => createTelegramVoiceTranscriber({
24
+ speechToText: typeof ctx?.get === 'function' ? ctx.get('speechToText') : ctx?.speechToText,
25
+ logger: typeof ctx?.logger === 'function' ? ctx.logger('dsh-im:telegram-voice') : ctx?.logger,
26
+ }),
18
27
  });
19
28
  }
@@ -3,14 +3,29 @@ import {
3
3
  TOKEN_BOT_ENDPOINTS,
4
4
  createTokenBotRpcHandler,
5
5
  } from '../shared/rpc.mjs';
6
+ import {
7
+ GROUP_TRIGGERS_ENDPOINTS,
8
+ createGroupTriggersRpcHandler,
9
+ } from '../shared/group-triggers-rpc.mjs';
6
10
  import { resolveRpcAuthority } from '../../rpc-authority.mjs';
7
11
 
8
12
  export const TELEGRAM_RPC_CHANNEL = '/telegram';
9
- export const TELEGRAM_ENDPOINTS = TOKEN_BOT_ENDPOINTS;
13
+ export { GROUP_TRIGGERS_ENDPOINTS } from '../shared/group-triggers-rpc.mjs';
14
+ export const TELEGRAM_ENDPOINTS = Object.freeze({
15
+ ...TOKEN_BOT_ENDPOINTS,
16
+ ...GROUP_TRIGGERS_ENDPOINTS,
17
+ });
10
18
  export const TELEGRAM_RPC_ENDPOINTS = Object.freeze(Object.values(TELEGRAM_ENDPOINTS));
11
19
 
12
20
  export function createTelegramRpcHandler(controller) {
13
- return createTokenBotRpcHandler(controller, { channel: 'Telegram' });
21
+ const handler = createTokenBotRpcHandler(controller, { channel: 'Telegram' });
22
+ // Per-group reply rules are Telegram-only, so they are layered on top of the
23
+ // shared token-bot endpoints instead of widening them for every channel.
24
+ const groupTriggers = createGroupTriggersRpcHandler(controller);
25
+ return async (endpoint, payload, signal) => {
26
+ const handled = await groupTriggers(endpoint, payload, signal);
27
+ return handled ?? handler(endpoint, payload, signal);
28
+ };
14
29
  }
15
30
 
16
31
  export function installTelegramRpc(ctx, controller, authority) {
@@ -123,6 +123,7 @@ export async function createProductionController(ctx, config = {}, internals = {
123
123
  initialAccessPolicy: initialAccessPolicyFor('wecom', botConfig),
124
124
  });
125
125
  const workspaceScope = createBotWorkspaceScope(harness, {
126
+ dsBot: config.deliveryService?.dsBot,
126
127
  botId, workspaces, state, agentPresetCatalog,
127
128
  });
128
129
  return new Runtime({
@@ -135,6 +136,8 @@ export async function createProductionController(ctx, config = {}, internals = {
135
136
  channel: 'wecom', config: botConfig,
136
137
  }),
137
138
  replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
139
+ streamRotateAfterMs: config.streamRotateAfterMs ?? 510_000,
140
+ streamSilentProbeMs: config.streamSilentProbeMs ?? 120_000,
138
141
  connectTimeoutMs: config.connectTimeoutMs ?? 20_000,
139
142
  maxReconnectAttempts: config.maxReconnectAttempts ?? 10,
140
143
  logger: {
@@ -174,7 +177,7 @@ export async function createProductionController(ctx, config = {}, internals = {
174
177
  }).start();
175
178
  return {
176
179
  controller,
177
- deliveryAdapter: createDeliveryAdapter({
180
+ deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
178
181
  channel: 'wecom', workspaces, coreController, stateFor,
179
182
  }),
180
183
  ready: supervisor.ready,
@@ -157,6 +157,7 @@ export async function createProductionController(ctx, config = {}, internals = {
157
157
  initialAccessPolicy: initialAccessPolicyFor('wecom-app', botConfig),
158
158
  });
159
159
  const workspaceScope = createBotWorkspaceScope(harness, {
160
+ dsBot: config.deliveryService?.dsBot,
160
161
  botId, workspaces, state, agentPresetCatalog,
161
162
  });
162
163
  return new Runtime({
@@ -207,7 +208,7 @@ export async function createProductionController(ctx, config = {}, internals = {
207
208
  }).start();
208
209
  return {
209
210
  controller,
210
- deliveryAdapter: createDeliveryAdapter({
211
+ deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
211
212
  channel: 'wecom-app', workspaces, coreController, stateFor,
212
213
  }),
213
214
  ready: supervisor.ready,
@@ -164,6 +164,7 @@ export async function createProductionController(ctx, config = {}, internals = {
164
164
  initialAccessPolicy: initialAccessPolicyFor('weixin', accountConfig),
165
165
  });
166
166
  const workspaceScope = createBotWorkspaceScope(harness, {
167
+ dsBot: config.deliveryService?.dsBot,
167
168
  botId, workspaces, state, agentPresetCatalog,
168
169
  });
169
170
  return new Runtime({
@@ -235,7 +236,7 @@ export async function createProductionController(ctx, config = {}, internals = {
235
236
  }).start();
236
237
  return {
237
238
  controller,
238
- deliveryAdapter: createDeliveryAdapter({
239
+ deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
239
240
  channel: 'weixin', workspaces, coreController, stateFor,
240
241
  }),
241
242
  ready: supervisor.ready,
@@ -130,6 +130,7 @@ export async function createProductionController(ctx, config = {}, internals = {
130
130
  initialAccessPolicy: initialAccessPolicyFor('whatsapp', botConfig),
131
131
  });
132
132
  const workspaceScope = createBotWorkspaceScope(harness, {
133
+ dsBot: config.deliveryService?.dsBot,
133
134
  botId, workspaces, state, agentPresetCatalog,
134
135
  });
135
136
  return new Runtime({
@@ -187,7 +188,7 @@ export async function createProductionController(ctx, config = {}, internals = {
187
188
  }).start();
188
189
  return {
189
190
  controller,
190
- deliveryAdapter: createDeliveryAdapter({
191
+ deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
191
192
  channel: 'whatsapp', workspaces, coreController, stateFor,
192
193
  }),
193
194
  ready: supervisor.ready,
@@ -1,8 +1,12 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import {
2
3
  deliverySuggestionsFromSessions,
3
4
  privateConversationKeyMatchesTarget,
5
+ privateDeliverySuggestionFromConversationKey,
4
6
  resolvePrivateConversationKey,
5
7
  } from './delivery-suggestions.mjs';
8
+ import { withSessionBindingLock } from '../../src/channels/shared/session-binding-lock.mjs';
9
+ import { dsBotError } from './ds-bot-client.mjs';
6
10
 
7
11
  const CHANNELS = new Set([
8
12
  'weixin',
@@ -191,6 +195,28 @@ function sessionSyncConfigs(workspaces, botId) {
191
195
  return botId === undefined ? targets : targets.filter((target) => target.botId === botId);
192
196
  }
193
197
 
198
+ /** Bindings own their private-chat sync while active. Ordinary delivery
199
+ * settings remain saved and resume after unbinding, without duplicate mirrors. */
200
+ export function configuredSessionSyncTargets(workspaces, botId) {
201
+ const bindings = (workspaces.listDsBotBindings?.(botId) ?? []).map((binding) => ({
202
+ ...binding,
203
+ targetId: `__dsbot_${createHash('sha256').update(binding.conversationKey).digest('hex').slice(0, 32)}`,
204
+ }));
205
+ return [
206
+ ...bindings,
207
+ ...sessionSyncConfigs(workspaces, botId).filter((target) => !bindings.some((binding) => (
208
+ binding.botId === target.botId && binding.conversationKey === target.conversationKey
209
+ ))),
210
+ ];
211
+ }
212
+
213
+ export function sessionSyncTarget(channel, workspaces, configured) {
214
+ if (!configured) return null;
215
+ if (!configured.dsBotId) return workspaces.deliveryTargetFor(configured.botId, configured.targetId);
216
+ const target = privateDeliverySuggestionFromConversationKey(channel, configured.conversationKey);
217
+ return target ? { ...target, targetId: configured.targetId } : null;
218
+ }
219
+
194
220
  function stateSessions(state) {
195
221
  if (!state || typeof state.snapshot !== 'function') return null;
196
222
  const sessions = state.snapshot()?.sessions;
@@ -220,7 +246,7 @@ function sessionSyncView(channel, target, sessions, configured) {
220
246
  }
221
247
 
222
248
  /** Bind one channel's existing workspace store and unwrapped controller to DeliveryService. */
223
- export function createDeliveryAdapter({ channel, workspaces, coreController, stateFor }) {
249
+ export function createDeliveryAdapter({ channel, workspaces, coreController, stateFor, dsBot }) {
224
250
  if (!supportsDeliveryChannel(channel)) throw new TypeError(`Unsupported delivery channel: ${channel}`);
225
251
  if (!workspaces || typeof workspaces !== 'object') {
226
252
  throw new TypeError('delivery adapter requires a workspace store');
@@ -231,17 +257,53 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
231
257
  if (typeof stateFor !== 'function') {
232
258
  throw new TypeError('delivery adapter requires a bot state getter');
233
259
  }
234
- const syncTarget = async (botId, targetId, sessionId) => {
235
- const configured = sessionSyncConfigs(workspaces, botId).find((entry) => entry.targetId === targetId);
236
- const target = workspaces.deliveryTargetFor(botId, targetId);
260
+ const syncTarget = async (botId, targetId, sessionId, { allowParts = true } = {}) => {
261
+ const configured = configuredSessionSyncTargets(workspaces, botId).find((entry) => entry.targetId === targetId);
262
+ const target = sessionSyncTarget(channel, workspaces, configured);
237
263
  if (!configured || !target || !privateConversationKeyMatchesTarget(channel, configured.conversationKey, target)) {
238
264
  throw sessionSyncUnavailable('Session sync target is no longer enabled');
239
265
  }
240
266
  const sessions = stateSessions(await stateFor(botId));
241
- if (sessions?.[configured.conversationKey] !== sessionId) {
267
+ const bot = configured.dsBotId ? await dsBot?.resolve(configured.dsBotId) : null;
268
+ const matches = configured.dsBotId
269
+ ? bot && (bot.sessionId === sessionId || (allowParts && bot.parts?.includes(sessionId)))
270
+ : sessions?.[configured.conversationKey] === sessionId;
271
+ if (!matches) {
242
272
  throw sessionSyncUnavailable('Session sync target is no longer bound to this Session');
243
273
  }
244
- return { target, conversationKey: configured.conversationKey };
274
+ return { target, conversationKey: configured.conversationKey, dsBotId: configured.dsBotId };
275
+ };
276
+ const describeSyncTarget = async (botId, targetId, sessionId) => {
277
+ const { conversationKey } = await syncTarget(botId, targetId, sessionId);
278
+ return { conversationKey };
279
+ };
280
+ const presentSyncInteraction = async (method, botId, targetId, sessionId, interaction, options = {}) => {
281
+ // Text from an old part may finish delivery, but a new question answer must
282
+ // still belong to the Bot's current session.
283
+ const routeOptions = { allowParts: method !== 'presentSessionSyncQuestion' };
284
+ const original = await syncTarget(botId, targetId, sessionId, routeOptions);
285
+ if (typeof coreController[method] !== 'function') return false;
286
+ const validate = async () => {
287
+ const current = await syncTarget(botId, targetId, sessionId, routeOptions);
288
+ if (current.conversationKey !== original.conversationKey || current.dsBotId !== original.dsBotId
289
+ || options.signal?.aborted) throw sessionSyncUnavailable('The interaction route changed or ended');
290
+ };
291
+ const guarded = {
292
+ ...interaction,
293
+ respond: async (result, responseOptions) => {
294
+ try { await validate(); }
295
+ catch (error) {
296
+ await interaction.withdraw?.();
297
+ throw Object.assign(new Error('Interaction route is no longer available', { cause: error }), {
298
+ code: 'interaction-not-pending',
299
+ });
300
+ }
301
+ return interaction.respond(result, responseOptions);
302
+ },
303
+ };
304
+ return coreController[method](botId, original.target, guarded, {
305
+ ...options, key: original.conversationKey, validate,
306
+ });
245
307
  };
246
308
  return Object.freeze({
247
309
  channel,
@@ -270,6 +332,9 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
270
332
  },
271
333
  ownsBot: (botId) => workspaces.has(botId),
272
334
  listBots: () => workspaces.listBotIds(),
335
+ listDsBotBindings: () => workspaces.listDsBotBindings().filter(({ conversationKey }) => (
336
+ privateDeliverySuggestionFromConversationKey(channel, conversationKey)
337
+ )),
273
338
  async listTargets(botId) {
274
339
  const targets = workspaces.listDeliveryTargets(botId);
275
340
  const configured = new Map(
@@ -286,6 +351,51 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
286
351
  sessionSync: sessionSyncView(channel, target, sessions, configured.get(target.targetId)),
287
352
  }));
288
353
  },
354
+ async listDsBotConversations(botId) {
355
+ const sessions = stateSessions(await stateFor(botId)) ?? {};
356
+ const keys = new Set([...Object.keys(sessions), ...workspaces.dsBotConversationKeys(botId)]);
357
+ return [...keys].flatMap((conversationKey) => {
358
+ const route = privateDeliverySuggestionFromConversationKey(channel, conversationKey);
359
+ if (!route) return [];
360
+ const binding = workspaces.dsBotBindingFor(botId, conversationKey);
361
+ const address = String(Object.values(route.route)[0]);
362
+ return [{ conversationKey, address, ...(binding ? { dsBotId: binding.dsBotId } : {}) }];
363
+ });
364
+ },
365
+ async bindDsBot(botId, conversationKey, dsBotId) {
366
+ if (!dsBot) throw dsBotError();
367
+ if (!privateDeliverySuggestionFromConversationKey(channel, conversationKey)) {
368
+ throw dsBotError('ds-bot-private-required');
369
+ }
370
+ const state = await stateFor(botId);
371
+ return withSessionBindingLock(state, conversationKey, async () => {
372
+ if (workspaces.listDsBotBindings(botId).some((binding) => (
373
+ binding.conversationKey === conversationKey || binding.dsBotId === dsBotId
374
+ ))) throw dsBotError('ds-bot-binding-conflict');
375
+ if (!state.sessionFor(conversationKey) && !workspaces.dsBotConversationKeys(botId).includes(conversationKey)) {
376
+ throw dsBotError('ds-bot-private-required');
377
+ }
378
+ const bot = await dsBot.resolve(dsBotId);
379
+ const previousSession = state.sessionFor(conversationKey);
380
+ await state.setSession(conversationKey, bot.sessionId);
381
+ try {
382
+ return await workspaces.setDsBotBinding(botId, conversationKey, dsBotId);
383
+ } catch (error) {
384
+ if (previousSession) await state.setSession(conversationKey, previousSession);
385
+ else await state.clearSession(conversationKey);
386
+ throw error;
387
+ }
388
+ });
389
+ },
390
+ async unbindDsBot(botId, conversationKey) {
391
+ const state = await stateFor(botId);
392
+ return withSessionBindingLock(state, conversationKey, async () => {
393
+ if (!workspaces.dsBotBindingFor(botId, conversationKey)) return false;
394
+ await state.clearSession(conversationKey);
395
+ await workspaces.setDsBotBinding(botId, conversationKey, null);
396
+ return true;
397
+ });
398
+ },
289
399
  async listSuggestions(botId) {
290
400
  const state = await stateFor(botId);
291
401
  if (!state || typeof state.snapshot !== 'function') {
@@ -347,56 +457,34 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
347
457
  throw new TypeError('sessionId is required');
348
458
  }
349
459
  const matches = [];
350
- for (const configured of sessionSyncConfigs(workspaces)) {
351
- const target = workspaces.deliveryTargetFor(configured.botId, configured.targetId);
460
+ for (const configured of configuredSessionSyncTargets(workspaces)) {
461
+ const target = sessionSyncTarget(channel, workspaces, configured);
352
462
  if (!target || !privateConversationKeyMatchesTarget(
353
463
  channel,
354
464
  configured.conversationKey,
355
465
  target,
356
466
  )) continue;
357
- let sessions;
467
+ let currentId;
358
468
  try {
359
- sessions = stateSessions(await stateFor(configured.botId));
469
+ currentId = configured.dsBotId
470
+ ? (await dsBot?.resolve(configured.dsBotId))?.sessionId
471
+ : stateSessions(await stateFor(configured.botId))?.[configured.conversationKey];
360
472
  } catch {
361
473
  continue;
362
474
  }
363
- if (sessions?.[configured.conversationKey] === sessionId) {
475
+ if (currentId === sessionId) {
364
476
  matches.push({ botId: configured.botId, targetId: configured.targetId });
365
477
  }
366
478
  }
367
479
  return matches;
368
480
  },
369
- async describeSessionSyncApprovalTarget(botId, targetId, sessionId) {
370
- const { conversationKey } = await syncTarget(botId, targetId, sessionId);
371
- return { conversationKey };
372
- },
481
+ describeSessionSyncApprovalTarget: describeSyncTarget,
482
+ describeSessionSyncQuestionTarget: describeSyncTarget,
373
483
  async presentSessionSyncApproval(botId, targetId, sessionId, interaction, options = {}) {
374
- const original = await syncTarget(botId, targetId, sessionId);
375
- if (typeof coreController.presentSessionSyncApproval !== 'function') {
376
- throw sessionSyncUnavailable('This channel cannot present synced approvals');
377
- }
378
- const validate = async () => {
379
- const current = await syncTarget(botId, targetId, sessionId);
380
- if (current.conversationKey !== original.conversationKey || options.signal?.aborted) {
381
- throw sessionSyncUnavailable('The approval target changed or the approval ended');
382
- }
383
- };
384
- const guarded = {
385
- ...interaction,
386
- respond: async (result, responseOptions) => {
387
- try { await validate(); }
388
- catch (error) {
389
- await interaction.withdraw?.();
390
- throw Object.assign(new Error('Approval route is no longer available', { cause: error }), {
391
- code: 'interaction-not-pending',
392
- });
393
- }
394
- return interaction.respond(result, responseOptions);
395
- },
396
- };
397
- return coreController.presentSessionSyncApproval(botId, original.target, guarded, {
398
- ...options, key: original.conversationKey, validate,
399
- });
484
+ return presentSyncInteraction('presentSessionSyncApproval', botId, targetId, sessionId, interaction, options);
485
+ },
486
+ async presentSessionSyncQuestion(botId, targetId, sessionId, interaction, options = {}) {
487
+ return presentSyncInteraction('presentSessionSyncQuestion', botId, targetId, sessionId, interaction, options);
400
488
  },
401
489
  async sendSessionSyncText(botId, targetId, sessionId, text, options = {}) {
402
490
  if (typeof text !== 'string' || !text.trim()) throw new TypeError('text is required');
@@ -4,6 +4,10 @@ import { resolveRpcAuthority } from './rpc-authority.mjs';
4
4
  export const DELIVERY_RPC_CHANNEL = '/dsh-im-delivery';
5
5
  export const DELIVERY_TEST_MESSAGE = 'DSH-IM 主动投递测试成功。';
6
6
  export const DELIVERY_ENDPOINTS = Object.freeze({
7
+ listDsBotSessions: 'ds-bot.sessions.list',
8
+ dsBotStatus: 'ds-bot.status',
9
+ bindDsBot: 'ds-bot.bind',
10
+ unbindDsBot: 'ds-bot.unbind',
7
11
  send: 'message.send',
8
12
  listTargets: 'target.list',
9
13
  listSuggestions: 'target.suggestion.list',
@@ -16,6 +20,11 @@ export const DELIVERY_ENDPOINTS = Object.freeze({
16
20
 
17
21
  const ENDPOINTS = new Set(Object.values(DELIVERY_ENDPOINTS));
18
22
  const PUBLIC_ERRORS = new Set([
23
+ 'ds-bot-unavailable',
24
+ 'ds-bot-not-found',
25
+ 'ds-bot-bound',
26
+ 'ds-bot-private-required',
27
+ 'ds-bot-binding-conflict',
19
28
  'bad-request',
20
29
  'unknown-bot',
21
30
  'unknown-target',
@@ -46,6 +55,11 @@ function validTargetId(value) {
46
55
  return typeof value === 'string' && /^[A-Za-z0-9._:@-]{1,128}$/.test(value);
47
56
  }
48
57
 
58
+ function validConversationKey(value) {
59
+ return typeof value === 'string' && Boolean(value) && value.length <= 1_024
60
+ && value.trim() === value && !/[\u0000-\u001f\u007f]/u.test(value);
61
+ }
62
+
49
63
  function validTarget(value, { targetId }) {
50
64
  const keys = targetId ? ['targetId', 'name', 'kind', 'route'] : ['name', 'kind', 'route'];
51
65
  if (!isRecord(value) || Object.keys(value).some((key) => !keys.includes(key))) return false;
@@ -64,6 +78,7 @@ function validDraftTarget(value) {
64
78
 
65
79
  function validPayload(endpoint, payload) {
66
80
  if (!ENDPOINTS.has(endpoint) || !isRecord(payload)) return false;
81
+ if (endpoint === DELIVERY_ENDPOINTS.listDsBotSessions) return exactKeys(payload, []);
67
82
  if (endpoint === DELIVERY_ENDPOINTS.send) {
68
83
  return (exactKeys(payload, ['botId', 'targetId', 'text'])
69
84
  || (exactKeys(payload, ['botId', 'targetId', 'text', 'format'])
@@ -72,9 +87,18 @@ function validPayload(endpoint, payload) {
72
87
  && typeof payload.text === 'string' && Boolean(payload.text.trim());
73
88
  }
74
89
  if (endpoint === DELIVERY_ENDPOINTS.listTargets
90
+ || endpoint === DELIVERY_ENDPOINTS.dsBotStatus
75
91
  || endpoint === DELIVERY_ENDPOINTS.listSuggestions) {
76
92
  return exactKeys(payload, ['botId']) && validBotId(payload.botId);
77
93
  }
94
+ if (endpoint === DELIVERY_ENDPOINTS.bindDsBot) {
95
+ return exactKeys(payload, ['botId', 'conversationKey', 'dsBotId'])
96
+ && validBotId(payload.botId) && validConversationKey(payload.conversationKey) && validBotId(payload.dsBotId);
97
+ }
98
+ if (endpoint === DELIVERY_ENDPOINTS.unbindDsBot) {
99
+ return exactKeys(payload, ['botId', 'conversationKey'])
100
+ && validBotId(payload.botId) && validConversationKey(payload.conversationKey);
101
+ }
78
102
  if (endpoint === DELIVERY_ENDPOINTS.createTarget) {
79
103
  return exactKeys(payload, ['botId', 'target'])
80
104
  && validBotId(payload.botId) && validTarget(payload.target, { targetId: true });
@@ -129,7 +153,15 @@ export function createDeliveryRpcHandler(service) {
129
153
  }
130
154
  try {
131
155
  let value;
132
- if (endpoint === DELIVERY_ENDPOINTS.send) {
156
+ if (endpoint === DELIVERY_ENDPOINTS.listDsBotSessions) {
157
+ value = await service.listDsBotSessions();
158
+ } else if (endpoint === DELIVERY_ENDPOINTS.dsBotStatus) {
159
+ value = await service.dsBotStatus(payload.botId);
160
+ } else if (endpoint === DELIVERY_ENDPOINTS.bindDsBot) {
161
+ value = await service.bindDsBot(payload.botId, payload.conversationKey, payload.dsBotId);
162
+ } else if (endpoint === DELIVERY_ENDPOINTS.unbindDsBot) {
163
+ value = await service.unbindDsBot(payload.botId, payload.conversationKey);
164
+ } else if (endpoint === DELIVERY_ENDPOINTS.send) {
133
165
  value = await service.send(payload.botId, payload.targetId, payload.text, {
134
166
  signal,
135
167
  ...(payload.format === undefined ? {} : { format: payload.format }),
@@ -20,6 +20,11 @@ const ADAPTER_METHODS = Object.freeze([
20
20
  ]);
21
21
 
22
22
  const DELIVERY_ERROR_CODES = new Set([
23
+ 'ds-bot-unavailable',
24
+ 'ds-bot-not-found',
25
+ 'ds-bot-bound',
26
+ 'ds-bot-private-required',
27
+ 'ds-bot-binding-conflict',
23
28
  'bad-request',
24
29
  'account-unverified',
25
30
  'account-changed',
@@ -74,6 +79,14 @@ function targetIdOf(value) {
74
79
  return value;
75
80
  }
76
81
 
82
+ function conversationKeyOf(value) {
83
+ if (typeof value !== 'string' || !value || value.length > 1_024
84
+ || value.trim() !== value || /[\u0000-\u001f\u007f]/u.test(value)) {
85
+ throw deliveryError('bad-request', 'Invalid private conversation');
86
+ }
87
+ return value;
88
+ }
89
+
77
90
  function targetObject(value, { includesTargetId } = {}) {
78
91
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
79
92
  throw deliveryError('bad-request', 'Invalid target');
@@ -132,8 +145,9 @@ function sessionSyncState(value, available) {
132
145
  export class DeliveryService {
133
146
  #adapters = new Map();
134
147
  #unavailableSessionSyncChannels;
148
+ dsBot;
135
149
 
136
- constructor({ unavailableSessionSyncChannels = [] } = {}) {
150
+ constructor({ unavailableSessionSyncChannels = [], dsBot } = {}) {
137
151
  if (!Array.isArray(unavailableSessionSyncChannels)
138
152
  || unavailableSessionSyncChannels.some((channel) => (
139
153
  typeof channel !== 'string' || !CHANNEL_PATTERN.test(channel)
@@ -141,6 +155,61 @@ export class DeliveryService {
141
155
  throw new TypeError('unavailableSessionSyncChannels must contain valid channel ids');
142
156
  }
143
157
  this.#unavailableSessionSyncChannels = new Set(unavailableSessionSyncChannels);
158
+ this.dsBot = dsBot;
159
+ }
160
+
161
+ async listDsBotSessions() {
162
+ const ids = new Set();
163
+ for (const { adapter } of this.#adapters.values()) {
164
+ if (!this.#supportsSessionSync(adapter)) continue;
165
+ for (const binding of await adapter.listDsBotBindings?.() ?? []) ids.add(binding.dsBotId);
166
+ }
167
+ if (!ids.size) return [];
168
+ const result = await this.dsBot?.status();
169
+ if (result?.state !== 'ready') return [];
170
+ // Only current, bound sessions and public appearance; no private routes,
171
+ // account configuration, conversation contents, or historical parts.
172
+ return result.bots.filter((bot) => ids.has(bot.id)).map(({ sessionId, id, name, color, avatar }) => ({
173
+ sessionId,
174
+ bot: { id, name, ...(color ? { color } : {}), ...(avatar ? { avatar } : {}) },
175
+ }));
176
+ }
177
+
178
+ async dsBotStatus(botId) {
179
+ const adapter = await this.#adapterFor(botIdOf(botId));
180
+ const result = this.#supportsSessionSync(adapter)
181
+ ? await this.dsBot?.status() ?? { state: 'unavailable', bots: [] }
182
+ : { state: 'remote', bots: [] };
183
+ return {
184
+ state: result.state,
185
+ bots: result.bots.map(({ id, name, color, avatar }) => ({
186
+ id, name, ...(color ? { color } : {}), ...(avatar ? { avatar } : {}),
187
+ })),
188
+ conversations: await adapter.listDsBotConversations?.(botId) ?? [],
189
+ };
190
+ }
191
+
192
+ async bindDsBot(botId, conversationKey, dsBotId) {
193
+ const id = botIdOf(botId);
194
+ const adapter = await this.#adapterFor(id);
195
+ if (!this.#supportsSessionSync(adapter) || !adapter.bindDsBot) {
196
+ throw deliveryError('ds-bot-unavailable');
197
+ }
198
+ try {
199
+ return await adapter.bindDsBot(id, conversationKeyOf(conversationKey), botIdOf(dsBotId));
200
+ } catch (error) {
201
+ throw publicOperationError(error);
202
+ }
203
+ }
204
+
205
+ async unbindDsBot(botId, conversationKey) {
206
+ const id = botIdOf(botId);
207
+ const adapter = await this.#adapterFor(id);
208
+ try {
209
+ return await adapter.unbindDsBot(id, conversationKeyOf(conversationKey));
210
+ } catch (error) {
211
+ throw publicOperationError(error);
212
+ }
144
213
  }
145
214
 
146
215
  registerAdapter(value) {
@@ -288,6 +357,48 @@ export class DeliveryService {
288
357
  return targets;
289
358
  }
290
359
 
360
+ /** Offer a question to one unambiguous bound private chat, like synced approvals. */
361
+ async presentSessionSyncQuestion(sessionId, interaction, options = {}) {
362
+ const { signal } = options;
363
+ const targets = await this.listSessionSyncTargets(sessionId);
364
+ if (signal?.aborted || targets.length === 0) return false;
365
+ const candidates = new Map();
366
+ let unresolvedTarget = false;
367
+ for (const target of targets) {
368
+ try {
369
+ const adapter = await this.#adapterFor(target.botId);
370
+ if (typeof adapter.describeSessionSyncQuestionTarget !== 'function') {
371
+ unresolvedTarget = true;
372
+ continue;
373
+ }
374
+ const info = await adapter.describeSessionSyncQuestionTarget(target.botId, target.targetId, sessionId);
375
+ candidates.set(JSON.stringify([target.channel, target.botId, info.conversationKey]), { adapter, target });
376
+ } catch {
377
+ unresolvedTarget = true;
378
+ }
379
+ }
380
+ if (signal?.aborted) return false;
381
+ if (!unresolvedTarget && candidates.size === 1) {
382
+ const { adapter, target } = candidates.values().next().value;
383
+ try {
384
+ if (await adapter.presentSessionSyncQuestion?.(target.botId, target.targetId, sessionId, interaction, options)) {
385
+ return true;
386
+ }
387
+ } catch (error) {
388
+ if (!signal?.aborted) console.warn('[dsh-im] synced question unavailable:', error?.code ?? error?.name);
389
+ }
390
+ }
391
+ if (!signal?.aborted) {
392
+ const results = await Promise.allSettled(targets.map((target) => this.sendSessionSyncText(
393
+ target.botId, target.targetId, sessionId, t('本会话有问题等待回答,请在桌面端回答。'), { signal },
394
+ )));
395
+ if (results.every((result) => result.status === 'rejected')) {
396
+ console.warn('[dsh-im] synced question notice could not be delivered');
397
+ }
398
+ }
399
+ return false;
400
+ }
401
+
291
402
  /** Offer one existing bound private chat the same approval the Host is awaiting. */
292
403
  async presentSessionSyncApproval(sessionId, interaction, { signal, completion } = {}) {
293
404
  const targets = (await this.listSessionSyncTargets(sessionId))
@@ -9,6 +9,7 @@ const CHANNELS = new Set([
9
9
  'telegram',
10
10
  'discord',
11
11
  'whatsapp',
12
+ 'imessage',
12
13
  'matrix',
13
14
  ]);
14
15
 
@@ -123,6 +124,15 @@ export function deliverySuggestionFromConversationKey(channel, key) {
123
124
  return discordSuggestion(key);
124
125
  case 'whatsapp':
125
126
  return whatsappSuggestion(key);
127
+ case 'imessage': {
128
+ const chatGuid = key.startsWith('direct:') ? key.slice('direct:'.length) : '';
129
+ // Older iMessage runtimes recorded every conversation as direct. Its
130
+ // native GUID's single-recipient marker must also match; + denotes groups.
131
+ return /^(?:iMessage|any);-;[^;]+$/u.test(chatGuid)
132
+ && chatGuid.length <= 512 && chatGuid.trim() === chatGuid
133
+ && !/[\u0000-\u001f\u007f]/u.test(chatGuid)
134
+ ? { kind: 'user', route: { chatGuid } } : null;
135
+ }
126
136
  case 'matrix':
127
137
  return matrixSuggestion(key.replace(/^(direct|group):/, ''));
128
138
  default:
@@ -146,6 +156,7 @@ export function privateDeliverySuggestionFromConversationKey(channel, key) {
146
156
  telegram: 'direct',
147
157
  discord: 'direct',
148
158
  whatsapp: 'direct',
159
+ imessage: 'direct',
149
160
  matrix: 'dm',
150
161
  }[channel];
151
162
  if (!privatePrefix || prefix !== privatePrefix) return null;