@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
@@ -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,
@@ -15,5 +15,7 @@ export function createProductionController(ctx, config = {}, internals = {}) {
15
15
  HarnessClient: TelegramHarnessClient,
16
16
  Controller: TelegramController,
17
17
  Runtime: TelegramRuntime,
18
+ // The per-group reply rules list chats from the shared group archive.
19
+ controllerGroupHistory: true,
18
20
  });
19
21
  }
@@ -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');
@@ -232,13 +258,17 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
232
258
  throw new TypeError('delivery adapter requires a bot state getter');
233
259
  }
234
260
  const syncTarget = async (botId, targetId, sessionId) => {
235
- const configured = sessionSyncConfigs(workspaces, botId).find((entry) => entry.targetId === targetId);
236
- const target = workspaces.deliveryTargetFor(botId, targetId);
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 || 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
274
  return { target, conversationKey: configured.conversationKey };
@@ -270,6 +300,9 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
270
300
  },
271
301
  ownsBot: (botId) => workspaces.has(botId),
272
302
  listBots: () => workspaces.listBotIds(),
303
+ listDsBotBindings: () => workspaces.listDsBotBindings().filter(({ conversationKey }) => (
304
+ privateDeliverySuggestionFromConversationKey(channel, conversationKey)
305
+ )),
273
306
  async listTargets(botId) {
274
307
  const targets = workspaces.listDeliveryTargets(botId);
275
308
  const configured = new Map(
@@ -286,6 +319,51 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
286
319
  sessionSync: sessionSyncView(channel, target, sessions, configured.get(target.targetId)),
287
320
  }));
288
321
  },
322
+ async listDsBotConversations(botId) {
323
+ const sessions = stateSessions(await stateFor(botId)) ?? {};
324
+ const keys = new Set([...Object.keys(sessions), ...workspaces.dsBotConversationKeys(botId)]);
325
+ return [...keys].flatMap((conversationKey) => {
326
+ const route = privateDeliverySuggestionFromConversationKey(channel, conversationKey);
327
+ if (!route) return [];
328
+ const binding = workspaces.dsBotBindingFor(botId, conversationKey);
329
+ const address = String(Object.values(route.route)[0]);
330
+ return [{ conversationKey, address, ...(binding ? { dsBotId: binding.dsBotId } : {}) }];
331
+ });
332
+ },
333
+ async bindDsBot(botId, conversationKey, dsBotId) {
334
+ if (!dsBot) throw dsBotError();
335
+ if (!privateDeliverySuggestionFromConversationKey(channel, conversationKey)) {
336
+ throw dsBotError('ds-bot-private-required');
337
+ }
338
+ const state = await stateFor(botId);
339
+ return withSessionBindingLock(state, conversationKey, async () => {
340
+ if (workspaces.listDsBotBindings(botId).some((binding) => (
341
+ binding.conversationKey === conversationKey || binding.dsBotId === dsBotId
342
+ ))) throw dsBotError('ds-bot-binding-conflict');
343
+ if (!state.sessionFor(conversationKey) && !workspaces.dsBotConversationKeys(botId).includes(conversationKey)) {
344
+ throw dsBotError('ds-bot-private-required');
345
+ }
346
+ const bot = await dsBot.resolve(dsBotId);
347
+ const previousSession = state.sessionFor(conversationKey);
348
+ await state.setSession(conversationKey, bot.sessionId);
349
+ try {
350
+ return await workspaces.setDsBotBinding(botId, conversationKey, dsBotId);
351
+ } catch (error) {
352
+ if (previousSession) await state.setSession(conversationKey, previousSession);
353
+ else await state.clearSession(conversationKey);
354
+ throw error;
355
+ }
356
+ });
357
+ },
358
+ async unbindDsBot(botId, conversationKey) {
359
+ const state = await stateFor(botId);
360
+ return withSessionBindingLock(state, conversationKey, async () => {
361
+ if (!workspaces.dsBotBindingFor(botId, conversationKey)) return false;
362
+ await state.clearSession(conversationKey);
363
+ await workspaces.setDsBotBinding(botId, conversationKey, null);
364
+ return true;
365
+ });
366
+ },
289
367
  async listSuggestions(botId) {
290
368
  const state = await stateFor(botId);
291
369
  if (!state || typeof state.snapshot !== 'function') {
@@ -347,20 +425,22 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
347
425
  throw new TypeError('sessionId is required');
348
426
  }
349
427
  const matches = [];
350
- for (const configured of sessionSyncConfigs(workspaces)) {
351
- const target = workspaces.deliveryTargetFor(configured.botId, configured.targetId);
428
+ for (const configured of configuredSessionSyncTargets(workspaces)) {
429
+ const target = sessionSyncTarget(channel, workspaces, configured);
352
430
  if (!target || !privateConversationKeyMatchesTarget(
353
431
  channel,
354
432
  configured.conversationKey,
355
433
  target,
356
434
  )) continue;
357
- let sessions;
435
+ let currentId;
358
436
  try {
359
- sessions = stateSessions(await stateFor(configured.botId));
437
+ currentId = configured.dsBotId
438
+ ? (await dsBot?.resolve(configured.dsBotId))?.sessionId
439
+ : stateSessions(await stateFor(configured.botId))?.[configured.conversationKey];
360
440
  } catch {
361
441
  continue;
362
442
  }
363
- if (sessions?.[configured.conversationKey] === sessionId) {
443
+ if (currentId === sessionId) {
364
444
  matches.push({ botId: configured.botId, targetId: configured.targetId });
365
445
  }
366
446
  }
@@ -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) {
@@ -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;
@@ -0,0 +1,74 @@
1
+ import { harnessPeer } from './harness-peer.mjs';
2
+
3
+ export function dsBotError(code = 'ds-bot-unavailable') {
4
+ return Object.assign(new Error(code), { code });
5
+ }
6
+
7
+ function appearance(bot) {
8
+ const avatar = {};
9
+ if (/^[a-z][\w-]{0,31}$/u.test(bot.avatar?.shape ?? '')) avatar.shape = bot.avatar.shape;
10
+ if (typeof bot.avatar?.image === 'string' && bot.avatar.image.length <= 1_500_000
11
+ && /^data:image\/(?:png|jpeg|webp|gif);base64,[A-Za-z0-9+/=]+$/.test(bot.avatar.image)) {
12
+ avatar.image = bot.avatar.image;
13
+ }
14
+ return {
15
+ ...(/^(?:#[0-9a-fA-F]{6}|[a-z][\w-]{0,31})$/u.test(bot.color ?? '') ? { color: bot.color } : {}),
16
+ ...(Object.keys(avatar).length ? { avatar } : {}),
17
+ };
18
+ }
19
+
20
+ /** Read DS Bot through the current Host's registered route, without a second
21
+ * runtime, credentials, or assumptions about its configured storage directory. */
22
+ export function createDsBotClient(ctx) {
23
+ async function status() {
24
+ try {
25
+ const manager = ctx.get?.('pluginManager');
26
+ if (typeof manager?.listBundles === 'function') {
27
+ const bundles = await manager.listBundles();
28
+ const bundle = bundles.find((entry) => entry.name === 'ds-bot');
29
+ if (!bundle?.installed) return { state: 'missing', bots: [] };
30
+ if (!bundle.enabled) return { state: 'disabled', bots: [] };
31
+ }
32
+ const connection = ctx.connection;
33
+ if (typeof connection?.createSharedFetchHandler !== 'function') {
34
+ return { state: 'unavailable', bots: [] };
35
+ }
36
+ const response = await connection.createSharedFetchHandler('/api').fetch(new Request(
37
+ 'http://localhost/api/bot',
38
+ {
39
+ method: 'POST',
40
+ headers: { 'content-type': 'application/json' },
41
+ body: JSON.stringify({ endpoint: 'state', payload: {} }),
42
+ signal: AbortSignal.timeout(15_000),
43
+ },
44
+ ), harnessPeer(ctx));
45
+ if (!response.ok) return { state: 'unavailable', bots: [] };
46
+ const result = await response.json();
47
+ if (result?.ok !== true || !Array.isArray(result.value?.bots)) {
48
+ return { state: 'unavailable', bots: [] };
49
+ }
50
+ if (result.value.readOnly) return { state: 'readonly', bots: [] };
51
+ const bots = result.value.bots.filter((bot) => (
52
+ typeof bot.id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(bot.id)
53
+ && typeof bot.sessionId === 'string' && Boolean(bot.sessionId)
54
+ && typeof bot.name === 'string'
55
+ )).map((bot) => ({
56
+ id: bot.id, name: bot.name, sessionId: bot.sessionId, ...appearance(bot),
57
+ ...(Array.isArray(bot.parts) ? { parts: bot.parts.filter((id) => typeof id === 'string') } : {}),
58
+ }));
59
+ return { state: 'ready', bots };
60
+ } catch {
61
+ return { state: 'unavailable', bots: [] };
62
+ }
63
+ }
64
+ return Object.freeze({
65
+ status,
66
+ async resolve(id) {
67
+ const result = await status();
68
+ if (result.state !== 'ready') throw dsBotError();
69
+ const bot = result.bots.find((entry) => entry.id === id);
70
+ if (!bot) throw dsBotError('ds-bot-not-found');
71
+ return bot;
72
+ },
73
+ });
74
+ }
@@ -19,6 +19,7 @@ import { installHostLanguageRpc } from './host-language-rpc.mjs';
19
19
  import { installDeliveryRpc } from './delivery-rpc.mjs';
20
20
  import { installDeliveryHttp } from './delivery-http.mjs';
21
21
  import { createDeliveryService } from './delivery-service.mjs';
22
+ import { createDsBotClient } from './ds-bot-client.mjs';
22
23
  import { installInboundTtlRpc } from './inbound-ttl-rpc.mjs';
23
24
  import { installSidebarSettingsRpc } from './sidebar-settings.mjs';
24
25
  import { installInjectedContext } from './injected-context.mjs';
@@ -91,7 +92,10 @@ export function createImHostPlugin(internals = {}) {
91
92
  .map(([channel]) => channel)
92
93
  .filter((channel) => channel !== 'office'
93
94
  && config[channel]?.harnessBaseUrl !== undefined);
94
- const deliveryService = makeDeliveryService({ unavailableSessionSyncChannels });
95
+ const deliveryService = makeDeliveryService({
96
+ unavailableSessionSyncChannels: unavailableSessionSyncChannels.map((channel) => channel === 'wecomApp' ? 'wecom-app' : channel),
97
+ dsBot: createDsBotClient(ctx),
98
+ });
95
99
  if (typeof ctx?.provide === 'function') {
96
100
  ctx.provide('dshIm', Object.freeze({
97
101
  contractVersion: 1,
@@ -1292,8 +1292,8 @@ export function splitStepStreamCardBlocks(
1292
1292
  }
1293
1293
 
1294
1294
  /**
1295
- * Interactive question card. When the question carries options, each option is
1296
- * rendered as its own button; the selected option label is submitted via a
1295
+ * Interactive question card. Each option is shown in wrapping body text with
1296
+ * a short numbered button; the selected option label is submitted via a
1297
1297
  * card callback. Multi-select questions fall back to the plain-text flow (the
1298
1298
  * caller decides), because a multi-select needs a confirm step.
1299
1299
  * A resolvedText replaces the buttons when an image ends the question flow.
@@ -1314,18 +1314,22 @@ export function questionCard({ interactionId, header, question, detail, options,
1314
1314
 
1315
1315
  if (Array.isArray(options) && options.length > 0) {
1316
1316
  elements.push({ tag: 'hr' });
1317
- for (const option of options) {
1317
+ for (const [optionIndex, option] of options.entries()) {
1318
1318
  const label = typeof option?.label === 'string' ? option.label : '';
1319
1319
  if (!label) continue;
1320
1320
  const description = typeof option?.description === 'string' && option.description.trim()
1321
1321
  ? option.description.trim()
1322
1322
  : '';
1323
- // Include the option description in the button so the user sees the full
1324
- // meaning (mirrors the text form "1. label — description").
1325
- const buttonText = description ? `${label}\n${description}` : label;
1323
+ // Long button labels are clipped by Feishu. Keep the complete option in
1324
+ // non-interactive body text, numbered like the text-reply fallback.
1325
+ const number = optionIndex + 1;
1326
+ elements.push({
1327
+ tag: 'div',
1328
+ text: plainText(`${number}. ${label}${description ? `\n${description}` : ''}`),
1329
+ });
1326
1330
  // Action carries the question index so a stale card from a previous
1327
1331
  // question cannot be applied to the current one: answer:<interactionId>:<index>:<label>
1328
- elements.push(button(buttonText, `answer:${interactionId}:${index}:${label}`));
1332
+ elements.push(button(t('选择 {number}', { number }), `answer:${interactionId}:${index}:${label}`));
1329
1333
  }
1330
1334
  // issue #162:自定义答案入口与 menuCard/steerCard 的「✏️ 更多 / 自定义…」
1331
1335
  // 对齐——文字流本就支持 custom 答案,卡片补上引导入口。