@xmanrui/dsh-im 5.2.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 (65) hide show
  1. package/THIRD_PARTY_NOTICES.md +209 -0
  2. package/docs/client-integration.md +8 -4
  3. package/lib/client.js +1988 -250
  4. package/lib/index.js +327 -321
  5. package/package.json +1 -1
  6. package/plugin-src/client/channels/telegram/group-triggers-settings.js +393 -0
  7. package/plugin-src/client/connection-error.js +2 -1
  8. package/plugin-src/client/delivery-settings.js +21 -1
  9. package/plugin-src/client/ds-bot-avatar-data.js +537 -0
  10. package/plugin-src/client/ds-bot-avatar.js +55 -0
  11. package/plugin-src/client/ds-bot-session-avatars.js +77 -0
  12. package/plugin-src/client/ds-bot-settings.js +194 -0
  13. package/plugin-src/client/global-settings.js +2 -1
  14. package/plugin-src/client/i18n.js +67 -1
  15. package/plugin-src/client/index.js +49 -18
  16. package/plugin-src/client/plugin-page.js +39 -17
  17. package/plugin-src/client/sidebar-settings.js +129 -0
  18. package/plugin-src/client/styles.js +33 -5
  19. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  20. package/plugin-src/host/channels/dingtalk/rpc.mjs +5 -1
  21. package/plugin-src/host/channels/feishu/production.mjs +13 -5
  22. package/plugin-src/host/channels/feishu/rpc.mjs +5 -1
  23. package/plugin-src/host/channels/qq/production.mjs +2 -1
  24. package/plugin-src/host/channels/qq/rpc.mjs +5 -1
  25. package/plugin-src/host/channels/shared/group-triggers-rpc.mjs +110 -0
  26. package/plugin-src/host/channels/shared/production.mjs +7 -1
  27. package/plugin-src/host/channels/slack/production.mjs +2 -1
  28. package/plugin-src/host/channels/telegram/index.mjs +1 -0
  29. package/plugin-src/host/channels/telegram/production.mjs +2 -0
  30. package/plugin-src/host/channels/telegram/rpc.mjs +17 -2
  31. package/plugin-src/host/channels/wecom/production.mjs +4 -1
  32. package/plugin-src/host/channels/wecom/rpc.mjs +5 -1
  33. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  34. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  35. package/plugin-src/host/channels/weixin/rpc.mjs +3 -2
  36. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  37. package/plugin-src/host/channels/whatsapp/rpc.mjs +5 -1
  38. package/plugin-src/host/delivery-adapter.mjs +89 -9
  39. package/plugin-src/host/delivery-rpc.mjs +33 -1
  40. package/plugin-src/host/delivery-service.mjs +70 -1
  41. package/plugin-src/host/delivery-suggestions.mjs +11 -0
  42. package/plugin-src/host/ds-bot-client.mjs +74 -0
  43. package/plugin-src/host/index.mjs +12 -1
  44. package/plugin-src/host/sidebar-settings.mjs +113 -0
  45. package/src/channels/feishu/feishu-cards.mjs +11 -7
  46. package/src/channels/imessage/imessage-api.mjs +67 -2
  47. package/src/channels/shared/bot-workspace-store.mjs +136 -7
  48. package/src/channels/shared/connection-error.mjs +5 -5
  49. package/src/channels/shared/diagnostic-details.mjs +15 -1
  50. package/src/channels/shared/group-history-store.mjs +26 -0
  51. package/src/channels/shared/i18n-en/diagnostics.mjs +5 -0
  52. package/src/channels/shared/i18n-en/feishu.mjs +1 -0
  53. package/src/channels/shared/i18n-en/wecom.mjs +4 -0
  54. package/src/channels/shared/qr-encoding-error.mjs +39 -0
  55. package/src/channels/shared/session-binding-lock.mjs +2 -0
  56. package/src/channels/shared/workspace-session.mjs +5 -1
  57. package/src/channels/telegram/config-store.mjs +5 -1
  58. package/src/channels/telegram/group-triggers.mjs +229 -0
  59. package/src/channels/telegram/telegram-api.mjs +12 -0
  60. package/src/channels/telegram/telegram-controller.mjs +110 -1
  61. package/src/channels/telegram/telegram-runtime.mjs +15 -2
  62. package/src/channels/wecom/stream-supervisor.mjs +184 -0
  63. package/src/channels/wecom/wecom-bridge.mjs +25 -11
  64. package/src/channels/wecom/wecom-runtime.mjs +12 -1
  65. package/src/channels/weixin/connection-error.mjs +1 -0
@@ -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,7 +19,9 @@ 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';
24
+ import { installSidebarSettingsRpc } from './sidebar-settings.mjs';
23
25
  import { installInjectedContext } from './injected-context.mjs';
24
26
  import { installSessionSyncCoordinator } from './session-sync-coordinator.mjs';
25
27
  import { installSessionTitlePrefix } from './session-title-prefix.mjs';
@@ -45,6 +47,7 @@ export function createImHostPlugin(internals = {}) {
45
47
  const startHostLanguageRpc = internals.installHostLanguageRpc ?? installHostLanguageRpc;
46
48
  const startUpdate = internals.installUpdateRpc ?? installUpdateRpc;
47
49
  const startInboundTtl = internals.installInboundTtlRpc ?? installInboundTtlRpc;
50
+ const startSidebarSettings = internals.installSidebarSettingsRpc ?? installSidebarSettingsRpc;
48
51
  const startInjectedContext = internals.installInjectedContext ?? installInjectedContext;
49
52
  const startDelivery = internals.installDeliveryRpc ?? installDeliveryRpc;
50
53
  const startDeliveryHttp = internals.installDeliveryHttp ?? installDeliveryHttp;
@@ -89,7 +92,10 @@ export function createImHostPlugin(internals = {}) {
89
92
  .map(([channel]) => channel)
90
93
  .filter((channel) => channel !== 'office'
91
94
  && config[channel]?.harnessBaseUrl !== undefined);
92
- const deliveryService = makeDeliveryService({ unavailableSessionSyncChannels });
95
+ const deliveryService = makeDeliveryService({
96
+ unavailableSessionSyncChannels: unavailableSessionSyncChannels.map((channel) => channel === 'wecomApp' ? 'wecom-app' : channel),
97
+ dsBot: createDsBotClient(ctx),
98
+ });
93
99
  if (typeof ctx?.provide === 'function') {
94
100
  ctx.provide('dshIm', Object.freeze({
95
101
  contractVersion: 1,
@@ -175,6 +181,11 @@ export function createImHostPlugin(internals = {}) {
175
181
  } catch (error) {
176
182
  logger.error?.('[dsh-im] failed to activate update management; continuing with channels', error);
177
183
  }
184
+ try {
185
+ startSidebarSettings(ctx, { config });
186
+ } catch (error) {
187
+ logger.error?.('[dsh-im] failed to activate sidebar settings; continuing with channels', error);
188
+ }
178
189
  try {
179
190
  startInboundTtl(ctx, { config });
180
191
  } catch (error) {
@@ -0,0 +1,113 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { registerManagementRpc } from '../management-rpc.mjs';
6
+
7
+ import { PluginConfigStore } from '../../src/channels/feishu/plugin-config-store.mjs';
8
+ import { WeixinConfigStore } from '../../src/channels/weixin/config-store.mjs';
9
+ import { DingtalkConfigStore } from '../../src/channels/dingtalk/config-store.mjs';
10
+ import { WecomConfigStore } from '../../src/channels/wecom/config-store.mjs';
11
+ import { WecomAppConfigStore } from '../../src/channels/wecom-app/config-store.mjs';
12
+ import { QqConfigStore } from '../../src/channels/qq/config-store.mjs';
13
+ import { SlackConfigStore } from '../../src/channels/slack/config-store.mjs';
14
+ import { TelegramConfigStore } from '../../src/channels/telegram/config-store.mjs';
15
+ import { DiscordConfigStore } from '../../src/channels/discord/config-store.mjs';
16
+ import { WhatsappConfigStore } from '../../src/channels/whatsapp/config-store.mjs';
17
+ import { IMessageConfigStore } from '../../src/channels/imessage/config-store.mjs';
18
+ import { EmailConfigStore } from '../../src/channels/email/config-store.mjs';
19
+ import { MatrixConfigStore } from '../../src/channels/matrix/matrix-config-store.mjs';
20
+ import { OfficeConfigStore } from '../../src/channels/office/config-store.mjs';
21
+
22
+ export const SIDEBAR_SETTINGS_RPC_CHANNEL = '/dsh-im-sidebar';
23
+ export const SIDEBAR_SETTINGS_ENDPOINTS = Object.freeze({
24
+ get: 'settings.sidebar-entry.get', set: 'settings.sidebar-entry.set',
25
+ });
26
+ const MODES = new Set(['auto', 'show', 'hide']);
27
+ const CHANNEL_STORES = [
28
+ ['feishu', PluginConfigStore], ['weixin', WeixinConfigStore],
29
+ ['dingtalk', DingtalkConfigStore], ['wecom', WecomConfigStore],
30
+ ['wecomApp', WecomAppConfigStore, 'wecom-app'], ['qq', QqConfigStore],
31
+ ['slack', SlackConfigStore], ['telegram', TelegramConfigStore],
32
+ ['discord', DiscordConfigStore], ['whatsapp', WhatsappConfigStore],
33
+ ['imessage', IMessageConfigStore], ['email', EmailConfigStore],
34
+ ['matrix', MatrixConfigStore], ['office', OfficeConfigStore],
35
+ ];
36
+
37
+ function dshHome(config) {
38
+ return resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
39
+ }
40
+
41
+ /** Read saved accounts, not connection state or workspace history. An offline
42
+ * bot still counts; an unfinished QR login does not. Reuse each channel's schema
43
+ * and the same per-channel path overrides as production. */
44
+ export async function hasConfiguredChannel(config = {}) {
45
+ const results = await Promise.allSettled(CHANNEL_STORES.map(async ([key, Store, channel = key]) => {
46
+ const options = { dshHome: dshHome(config), ...config[key] };
47
+ const root = resolve(options.dataDir ?? join(dshHome(options), 'integrations', `dsh-${channel}`));
48
+ const store = await new Store(resolve(options.configPath ?? join(root, 'config.json'))).load();
49
+ return key === 'office' ? store.get() !== null : store.list().length > 0;
50
+ }));
51
+ if (results.some((result) => result.status === 'fulfilled' && result.value)) return true;
52
+ // Unknown configuration must not be mistaken for deleting the last channel.
53
+ const failed = results.find((result) => result.status === 'rejected');
54
+ if (failed) throw failed.reason;
55
+ return false;
56
+ }
57
+
58
+ export class SidebarSettingsStore {
59
+ #path;
60
+ #writes = Promise.resolve();
61
+ constructor(path) { this.#path = path; }
62
+
63
+ async get() {
64
+ let raw;
65
+ try { raw = await readFile(this.#path, 'utf8'); }
66
+ catch (error) { if (error.code === 'ENOENT') return 'auto'; throw error; }
67
+ const value = JSON.parse(raw);
68
+ if (value?.version !== 1 || !MODES.has(value.mode)) throw new Error('Invalid sidebar settings');
69
+ return value.mode;
70
+ }
71
+
72
+ async set(mode) {
73
+ if (!MODES.has(mode)) throw new TypeError('Invalid sidebar mode');
74
+ const operation = this.#writes.catch(() => {}).then(async () => {
75
+ await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
76
+ const temporary = `${this.#path}.${randomUUID()}.tmp`;
77
+ try {
78
+ await writeFile(temporary, `${JSON.stringify({ version: 1, mode }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
79
+ await rename(temporary, this.#path);
80
+ } finally { await rm(temporary, { force: true }); }
81
+ return mode;
82
+ });
83
+ this.#writes = operation;
84
+ return operation;
85
+ }
86
+ }
87
+
88
+ export function createSidebarSettingsRpcHandler({ config = {}, store, configured } = {}) {
89
+ store ??= new SidebarSettingsStore(join(dshHome(config), 'integrations', 'dsh-im', 'sidebar-settings.json'));
90
+ configured ??= () => hasConfiguredChannel(config);
91
+ return async (endpoint, payload, signal) => {
92
+ const valid = payload && typeof payload === 'object' && !Array.isArray(payload)
93
+ && (endpoint === SIDEBAR_SETTINGS_ENDPOINTS.get ? Object.keys(payload).length === 0
94
+ : endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set && Object.keys(payload).length === 1 && MODES.has(payload.mode));
95
+ if (!valid) return { ok: false, error: { code: 'bad-request', message: 'Invalid sidebar settings.' } };
96
+ if (signal?.aborted) return { ok: false, error: { code: 'cancelled', message: 'Request cancelled.' } };
97
+ try {
98
+ const mode = endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set ? payload.mode : await store.get();
99
+ const visible = mode === 'show' || (mode === 'auto' && !await configured());
100
+ if (endpoint === SIDEBAR_SETTINGS_ENDPOINTS.set) await store.set(mode);
101
+ return { ok: true, value: { mode, visible } };
102
+ } catch {
103
+ return { ok: false, error: { code: 'sidebar-settings-unavailable', message: '无法读取或保存侧边栏设置,请稍后重试。' } };
104
+ }
105
+ };
106
+ }
107
+
108
+ export function installSidebarSettingsRpc(ctx, { config = {} } = {}) {
109
+ // Visibility follows ordinary channel management authority. Keep it separate
110
+ // from the general settings route, whose TTL operations remain loopback-only.
111
+ return registerManagementRpc(ctx, SIDEBAR_SETTINGS_RPC_CHANNEL,
112
+ createSidebarSettingsRpcHandler({ config }), { authority: config.rpcAuthority });
113
+ }
@@ -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 答案,卡片补上引导入口。