@xmanrui/dsh-im 5.4.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 (79) 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/lib/client.js +2293 -444
  6. package/lib/index.js +402 -335
  7. package/package.json +1 -1
  8. package/plugin-src/client/channel-card-meta.js +6 -2
  9. package/plugin-src/client/channels/shared/token-api.js +13 -0
  10. package/plugin-src/client/channels/telegram/styles.js +4 -0
  11. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  12. package/plugin-src/client/delivery-settings.js +2 -2
  13. package/plugin-src/client/i18n-ru.js +1615 -0
  14. package/plugin-src/client/i18n.js +71 -0
  15. package/plugin-src/client/index.js +8 -1
  16. package/plugin-src/host/channels/shared/production.mjs +5 -0
  17. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  18. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  19. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  20. package/plugin-src/host/channels/telegram/production.mjs +7 -0
  21. package/plugin-src/host/delivery-adapter.mjs +41 -33
  22. package/plugin-src/host/delivery-service.mjs +42 -0
  23. package/plugin-src/host/ds-bot-client.mjs +31 -18
  24. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  25. package/plugin-src/host/index.mjs +3 -0
  26. package/plugin-src/host/modern-harness-api.mjs +53 -8
  27. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  28. package/scripts/verify-package.mjs +17 -5
  29. package/src/channels/feishu/bridge.mjs +83 -5
  30. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  31. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  32. package/src/channels/shared/AGENTS.md +19 -0
  33. package/src/channels/shared/clear-command.mjs +2 -1
  34. package/src/channels/shared/compact-command.mjs +2 -1
  35. package/src/channels/shared/conversation-queue.mjs +49 -0
  36. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  37. package/src/channels/shared/harness-client.mjs +5 -4
  38. package/src/channels/shared/history-command.mjs +2 -1
  39. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  40. package/src/channels/shared/i18n-en/shared-b.mjs +2 -2
  41. package/src/channels/shared/i18n-en/shared-c.mjs +3 -2
  42. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  43. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  44. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  45. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  46. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  47. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  48. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  49. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  50. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  51. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  52. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  53. package/src/channels/shared/i18n-ru/shared-b.mjs +257 -0
  54. package/src/channels/shared/i18n-ru/shared-c.mjs +173 -0
  55. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  56. package/src/channels/shared/i18n-ru/telegram.mjs +25 -0
  57. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  58. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  59. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  60. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  61. package/src/channels/shared/i18n-ru.mjs +48 -0
  62. package/src/channels/shared/i18n.mjs +47 -12
  63. package/src/channels/shared/inbound-access.mjs +1 -1
  64. package/src/channels/shared/interface-language.mjs +3 -3
  65. package/src/channels/shared/message-failure.mjs +3 -2
  66. package/src/channels/shared/model-command.mjs +2 -1
  67. package/src/channels/shared/permission-command.mjs +2 -1
  68. package/src/channels/shared/send-limit.mjs +38 -0
  69. package/src/channels/shared/session-error.mjs +3 -0
  70. package/src/channels/shared/status-reaction.mjs +2 -0
  71. package/src/channels/shared/text-harness-bridge.mjs +4 -0
  72. package/src/channels/shared/thinking-cadence.mjs +36 -0
  73. package/src/channels/shared/workspace-command.mjs +2 -1
  74. package/src/channels/telegram/config-store.mjs +34 -1
  75. package/src/channels/telegram/telegram-api.mjs +211 -32
  76. package/src/channels/telegram/telegram-bridge.mjs +4 -1
  77. package/src/channels/telegram/telegram-controller.mjs +29 -0
  78. package/src/channels/telegram/telegram-runtime.mjs +507 -176
  79. package/src/channels/telegram/voice.mjs +250 -0
@@ -1,6 +1,7 @@
1
1
  import imageInput from '../../src/channels/shared/i18n-en/image-input.mjs';
2
2
  import diagnostics from '../../src/channels/shared/i18n-en/diagnostics.mjs';
3
3
  import weixinDiagnostics from '../../src/channels/weixin/connection-error.en.mjs';
4
+ import { RU } from './i18n-ru.js';
4
5
  import * as React from 'react';
5
6
 
6
7
  export const IM_LOCALE_NAMESPACE = 'dsh-im';
@@ -838,6 +839,15 @@ const EN = Object.freeze({
838
839
  '思考过程留痕': 'Thinking traces',
839
840
  '实时显示思考步骤与工具调用,最终答案单独成条': 'Show thinking steps and tool calls as they happen; the final answer arrives as its own message',
840
841
  '请提交有效的思考过程留痕设置。': 'Submit a valid thinking-traces setting.',
842
+ '编号思考帧': 'Number trace frames',
843
+ '在每帧前加上本轮序号;被节奏跳过的帧也计数,所以编号会跳号(需先打开思考过程留痕)': 'Prefix each frame with its number in the turn; paced-away frames still count, so numbers jump. Requires thinking traces.',
844
+ '最多每隔多久发送一帧(秒)': 'Send at most one frame every (seconds)',
845
+ '突发时只发送窗口里最新的一帧,过期的帧丢弃,不排队也不重发': 'A burst sends only its latest frame; stale frames are dropped, not queued or resent',
846
+ '不限制(0)': 'No limit (0)',
847
+ '请提交有效的思考帧节奏设置。': 'Submit a valid trace cadence setting.',
848
+ '消息发送上限': 'Message limit',
849
+ '每个聊天每分钟的消息数;机器人会等待而不是丢弃': 'Per chat, messages per minute; the bot waits instead of dropping',
850
+ '请提交有效的消息发送上限。': 'Submit a valid message limit.',
841
851
  '正在使用{name}…': 'Using {name}…',
842
852
  '访问模式': 'Access mode',
843
853
  'Telegram 访问模式': 'Telegram access mode',
@@ -1259,16 +1269,77 @@ export const zh = Object.freeze(Object.fromEntries(
1259
1269
  Object.keys(EN).map((key) => [key, key === '$locale' ? 'zh' : key]),
1260
1270
  ));
1261
1271
 
1272
+ // Russian, narrowed to the keys this UI asks for: the shared Host modules it is
1273
+ // built from also carry strings no settings surface renders, and a namespace
1274
+ // dictionary holding keys the English one does not know would let a mistyped
1275
+ // Chinese key hide behind a lookup that happens to miss. The English text is the
1276
+ // last resort for a key the narrowed dictionary somehow lost.
1277
+ export const ru = Object.freeze(Object.fromEntries(
1278
+ Object.keys(EN).map((key) => [key, RU[key] ?? EN[key]]),
1279
+ ));
1280
+
1262
1281
  let translate = (key) => key;
1263
1282
 
1264
1283
  export function setImTranslator(next) {
1265
1284
  translate = typeof next === 'function' ? next : (key) => key;
1266
1285
  }
1267
1286
 
1287
+ // The language these dictionaries are rendering in. Read through the `$locale`
1288
+ // entry rather than a snapshot taken at load time, so a locale whose dictionary
1289
+ // registers later is still reported correctly. Anything unrecognized means
1290
+ // Chinese, the identity language.
1291
+ export function imLocale() {
1292
+ const id = translate('$locale');
1293
+ return id === 'en' || id === 'ru' ? id : 'zh';
1294
+ }
1295
+
1268
1296
  export function isEnglish() {
1269
1297
  return translate('$locale') === 'en';
1270
1298
  }
1271
1299
 
1300
+ export const IM_RUSSIAN_LANGUAGE = Object.freeze({ id: 'ru', label: 'Русский', fallback: 'en' });
1301
+
1302
+ /**
1303
+ * Register Russian with the DSH locale registry: the definition makes it
1304
+ * selectable and chains its lookups to English, and the dictionary goes in as
1305
+ * one single-locale entry because `ru` is a language pack rather than one of the
1306
+ * two built-in locales.
1307
+ *
1308
+ * The definition is skipped when the id is already occupied — another language
1309
+ * pack may have registered `ru` first, and an occupied id is a hard error there.
1310
+ * The dictionary is registered either way, so Russian strings still resolve.
1311
+ *
1312
+ * @param locale - the client `locale` service.
1313
+ * @returns an idempotent disposer for both registrations.
1314
+ */
1315
+ export function installImRussianLocale(locale) {
1316
+ if (typeof locale?.register !== 'function') return () => {};
1317
+ const disposers = [];
1318
+ const defined = (locale.getLocale?.()?.locales ?? []).some(
1319
+ (entry) => entry?.id === IM_RUSSIAN_LANGUAGE.id,
1320
+ );
1321
+ if (!defined && typeof locale.addLanguage === 'function') {
1322
+ try {
1323
+ disposers.push(locale.addLanguage(IM_RUSSIAN_LANGUAGE));
1324
+ } catch (error) {
1325
+ // The id may have been taken between the check and this call; that pack
1326
+ // owns the definition now, and registering the dictionary is still safe.
1327
+ if (!/already registered/iu.test(String(error?.message ?? ''))) throw error;
1328
+ }
1329
+ }
1330
+ disposers.push(locale.register(IM_LOCALE_NAMESPACE, IM_RUSSIAN_LANGUAGE.id, ru));
1331
+ return () => {
1332
+ // Reverse order: the dictionary goes before the definition that chains to it.
1333
+ for (const dispose of disposers.reverse()) {
1334
+ try {
1335
+ dispose?.();
1336
+ } catch {
1337
+ // A registry that already dropped the entry must not block teardown.
1338
+ }
1339
+ }
1340
+ };
1341
+ }
1342
+
1272
1343
  function channelName(value) {
1273
1344
  return localizeText(value);
1274
1345
  }
@@ -58,7 +58,7 @@ import { installEmailStyles } from './channels/email/styles.js';
58
58
  import { MATRIX_RPC_CHANNEL } from './channels/matrix/api.js';
59
59
  import { MatrixSettingsTab } from './channels/matrix/index.js';
60
60
  import { installMatrixStyles } from './channels/matrix/styles.js';
61
- import { en, h, IM_LOCALE_NAMESPACE, setImTranslator, zh } from './i18n.js';
61
+ import { en, h, IM_LOCALE_NAMESPACE, installImRussianLocale, setImTranslator, zh } from './i18n.js';
62
62
  import {
63
63
  HOST_LANGUAGE_RPC_CHANNEL,
64
64
  installInterfaceLanguageMirror,
@@ -456,6 +456,13 @@ export function apply(ctx) {
456
456
  () => ctx.locale.register(IM_LOCALE_NAMESPACE, { zh, en }),
457
457
  'im-settings: bilingual dictionaries',
458
458
  );
459
+ // Russian is a language pack rather than a built-in locale: it needs its own
460
+ // definition so it shows up in the Language row, and its lookups chain to
461
+ // English before falling back to the Chinese key itself.
462
+ ctx.effect(
463
+ () => installImRussianLocale(ctx.locale),
464
+ 'im-settings: Russian language pack',
465
+ );
459
466
  const t = ctx.locale.bind(IM_LOCALE_NAMESPACE);
460
467
  setImTranslator(t);
461
468
 
@@ -189,6 +189,11 @@ export async function createTokenProductionController(ctx, config, internals, de
189
189
  harness: workspaceScope.harness,
190
190
  state: workspaceScope.state,
191
191
  groupHistory: internals.groupHistory ?? (['telegram', 'discord'].includes(channel) ? getGroupHistoryStore(ctx, config) : undefined),
192
+ // A transport that carries voice notes composes its own transcriber
193
+ // from Host services; without one voice messages stay textless.
194
+ ...(typeof definitions.createVoiceTranscriber === 'function'
195
+ ? { voice: definitions.createVoiceTranscriber(ctx, config, internals) }
196
+ : {}),
192
197
  contextEnhancement: { botId, getSettings: () => workspaces.contextEnhancementFor(botId) },
193
198
  accessPolicy: accessPolicyProvider(workspaces, botId, { channel, config: botConfig }),
194
199
  replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
@@ -17,6 +17,8 @@ import {
17
17
  } from './agent-preset-rpc.mjs';
18
18
  import { SET_MODEL_ENDPOINT, validModelPayload } from './model-setting-rpc.mjs';
19
19
  import { SET_THINKING_TRACES_ENDPOINT, validThinkingTracesPayload } from './thinking-traces-rpc.mjs';
20
+ import { SET_THINKING_CADENCE_ENDPOINT, validThinkingCadencePayload } from './thinking-cadence-rpc.mjs';
21
+ import { SET_SEND_LIMIT_ENDPOINT, validSendLimitPayload } from './send-limit-rpc.mjs';
20
22
 
21
23
  export const TOKEN_BOT_ENDPOINTS = Object.freeze({
22
24
  status: 'connection.status',
@@ -31,6 +33,8 @@ export const TOKEN_BOT_ENDPOINTS = Object.freeze({
31
33
  setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
32
34
  setAlias: SET_ALIAS_ENDPOINT,
33
35
  setThinkingTraces: SET_THINKING_TRACES_ENDPOINT,
36
+ setThinkingCadence: SET_THINKING_CADENCE_ENDPOINT,
37
+ setSendLimit: SET_SEND_LIMIT_ENDPOINT,
34
38
  });
35
39
 
36
40
  const ENDPOINTS = Object.freeze(Object.values(TOKEN_BOT_ENDPOINTS));
@@ -109,6 +113,14 @@ function payloadFailure(endpoint, payload) {
109
113
  return validThinkingTracesPayload(payload)
110
114
  ? null : '请提交有效的思考过程留痕设置。';
111
115
  }
116
+ if (endpoint === TOKEN_BOT_ENDPOINTS.setThinkingCadence) {
117
+ return validThinkingCadencePayload(payload)
118
+ ? null : '请提交有效的思考帧节奏设置。';
119
+ }
120
+ if (endpoint === TOKEN_BOT_ENDPOINTS.setSendLimit) {
121
+ return validSendLimitPayload(payload)
122
+ ? null : '请提交有效的消息发送上限。';
123
+ }
112
124
  return 'Unknown bot endpoint.';
113
125
  }
114
126
 
@@ -212,6 +224,15 @@ export function createTokenBotRpcHandler(controller, { channel }) {
212
224
  } else if (endpoint === TOKEN_BOT_ENDPOINTS.setThinkingTraces) {
213
225
  if (typeof controller.setThinkingTraces !== 'function') throw new Error('Thinking traces update is unavailable');
214
226
  value = await controller.setThinkingTraces(payload.botId, payload.thinkingTraces);
227
+ } else if (endpoint === TOKEN_BOT_ENDPOINTS.setThinkingCadence) {
228
+ if (typeof controller.setThinkingCadence !== 'function') throw new Error('Thinking trace cadence update is unavailable');
229
+ value = await controller.setThinkingCadence(payload.botId, {
230
+ thinkingNumbering: payload.thinkingNumbering,
231
+ thinkingIntervalSeconds: payload.thinkingIntervalSeconds,
232
+ });
233
+ } else if (endpoint === TOKEN_BOT_ENDPOINTS.setSendLimit) {
234
+ if (typeof controller.setSendLimitPerMinute !== 'function') throw new Error('Send limit update is unavailable');
235
+ value = await controller.setSendLimitPerMinute(payload.botId, payload.sendLimitPerMinute);
215
236
  } else {
216
237
  value = await controller.deleteBot(payload.botId);
217
238
  }
@@ -0,0 +1,13 @@
1
+ export { SET_SEND_LIMIT_ENDPOINT } from '../../../../src/channels/shared/send-limit.mjs';
2
+
3
+ export function validSendLimitPayload(payload) {
4
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)
5
+ || Reflect.ownKeys(payload).length !== 2
6
+ || !Object.hasOwn(payload, 'botId') || !Object.hasOwn(payload, 'sendLimitPerMinute')
7
+ || typeof payload.botId !== 'string'
8
+ || !/^[A-Za-z0-9_-]{1,128}$/.test(payload.botId)) return false;
9
+ // The value is only checked for shape: the controller clamps it, so a bad
10
+ // form entry can never leave a bot unusable.
11
+ const value = payload.sendLimitPerMinute;
12
+ return typeof value === 'number' || typeof value === 'string';
13
+ }
@@ -0,0 +1,16 @@
1
+ export { SET_THINKING_CADENCE_ENDPOINT } from '../../../../src/channels/shared/thinking-cadence.mjs';
2
+
3
+ export function validThinkingCadencePayload(payload) {
4
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)
5
+ || Reflect.ownKeys(payload).length !== 3
6
+ || !Object.hasOwn(payload, 'botId')
7
+ || !Object.hasOwn(payload, 'thinkingNumbering')
8
+ || !Object.hasOwn(payload, 'thinkingIntervalSeconds')
9
+ || typeof payload.botId !== 'string'
10
+ || !/^[A-Za-z0-9_-]{1,128}$/.test(payload.botId)
11
+ || typeof payload.thinkingNumbering !== 'boolean') return false;
12
+ // The interval is only checked for shape: the controller clamps it, so a bad
13
+ // form entry can never leave a bot stuck at an unusable pace.
14
+ const value = payload.thinkingIntervalSeconds;
15
+ return typeof value === 'number' || typeof value === 'string';
16
+ }
@@ -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';
@@ -17,5 +18,11 @@ export function createProductionController(ctx, config = {}, internals = {}) {
17
18
  Runtime: TelegramRuntime,
18
19
  // The per-group reply rules list chats from the shared group archive.
19
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
+ }),
20
27
  });
21
28
  }
@@ -257,7 +257,7 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
257
257
  if (typeof stateFor !== 'function') {
258
258
  throw new TypeError('delivery adapter requires a bot state getter');
259
259
  }
260
- const syncTarget = async (botId, targetId, sessionId) => {
260
+ const syncTarget = async (botId, targetId, sessionId, { allowParts = true } = {}) => {
261
261
  const configured = configuredSessionSyncTargets(workspaces, botId).find((entry) => entry.targetId === targetId);
262
262
  const target = sessionSyncTarget(channel, workspaces, configured);
263
263
  if (!configured || !target || !privateConversationKeyMatchesTarget(channel, configured.conversationKey, target)) {
@@ -266,12 +266,44 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
266
266
  const sessions = stateSessions(await stateFor(botId));
267
267
  const bot = configured.dsBotId ? await dsBot?.resolve(configured.dsBotId) : null;
268
268
  const matches = configured.dsBotId
269
- ? bot && (bot.sessionId === sessionId || bot.parts?.includes(sessionId))
269
+ ? bot && (bot.sessionId === sessionId || (allowParts && bot.parts?.includes(sessionId)))
270
270
  : sessions?.[configured.conversationKey] === sessionId;
271
271
  if (!matches) {
272
272
  throw sessionSyncUnavailable('Session sync target is no longer bound to this Session');
273
273
  }
274
- 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
+ });
275
307
  };
276
308
  return Object.freeze({
277
309
  channel,
@@ -446,37 +478,13 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
446
478
  }
447
479
  return matches;
448
480
  },
449
- async describeSessionSyncApprovalTarget(botId, targetId, sessionId) {
450
- const { conversationKey } = await syncTarget(botId, targetId, sessionId);
451
- return { conversationKey };
452
- },
481
+ describeSessionSyncApprovalTarget: describeSyncTarget,
482
+ describeSessionSyncQuestionTarget: describeSyncTarget,
453
483
  async presentSessionSyncApproval(botId, targetId, sessionId, interaction, options = {}) {
454
- const original = await syncTarget(botId, targetId, sessionId);
455
- if (typeof coreController.presentSessionSyncApproval !== 'function') {
456
- throw sessionSyncUnavailable('This channel cannot present synced approvals');
457
- }
458
- const validate = async () => {
459
- const current = await syncTarget(botId, targetId, sessionId);
460
- if (current.conversationKey !== original.conversationKey || options.signal?.aborted) {
461
- throw sessionSyncUnavailable('The approval target changed or the approval ended');
462
- }
463
- };
464
- const guarded = {
465
- ...interaction,
466
- respond: async (result, responseOptions) => {
467
- try { await validate(); }
468
- catch (error) {
469
- await interaction.withdraw?.();
470
- throw Object.assign(new Error('Approval route is no longer available', { cause: error }), {
471
- code: 'interaction-not-pending',
472
- });
473
- }
474
- return interaction.respond(result, responseOptions);
475
- },
476
- };
477
- return coreController.presentSessionSyncApproval(botId, original.target, guarded, {
478
- ...options, key: original.conversationKey, validate,
479
- });
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);
480
488
  },
481
489
  async sendSessionSyncText(botId, targetId, sessionId, text, options = {}) {
482
490
  if (typeof text !== 'string' || !text.trim()) throw new TypeError('text is required');
@@ -357,6 +357,48 @@ export class DeliveryService {
357
357
  return targets;
358
358
  }
359
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
+
360
402
  /** Offer one existing bound private chat the same approval the Host is awaiting. */
361
403
  async presentSessionSyncApproval(sessionId, interaction, { signal, completion } = {}) {
362
404
  const targets = (await this.listSessionSyncTargets(sessionId))
@@ -20,6 +20,22 @@ function appearance(bot) {
20
20
  /** Read DS Bot through the current Host's registered route, without a second
21
21
  * runtime, credentials, or assumptions about its configured storage directory. */
22
22
  export function createDsBotClient(ctx) {
23
+ async function call(endpoint, payload = {}) {
24
+ const connection = ctx.connection;
25
+ if (typeof connection?.createSharedFetchHandler !== 'function') throw dsBotError();
26
+ const response = await connection.createSharedFetchHandler('/api').fetch(new Request(
27
+ 'http://localhost/api/bot', {
28
+ method: 'POST', headers: { 'content-type': 'application/json' },
29
+ body: JSON.stringify({ endpoint, payload }), signal: AbortSignal.timeout(15_000),
30
+ },
31
+ ), harnessPeer(ctx));
32
+ if (!response.ok) throw dsBotError();
33
+ const result = await response.json();
34
+ if (result?.ok !== true) {
35
+ throw dsBotError(result?.error?.code === 'bot/stale' ? 'interaction-not-pending' : 'ds-bot-unavailable');
36
+ }
37
+ return result.value;
38
+ }
23
39
  async function status() {
24
40
  try {
25
41
  const manager = ctx.get?.('pluginManager');
@@ -29,26 +45,12 @@ export function createDsBotClient(ctx) {
29
45
  if (!bundle?.installed) return { state: 'missing', bots: [] };
30
46
  if (!bundle.enabled) return { state: 'disabled', bots: [] };
31
47
  }
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
+ const value = await call('state');
49
+ if (!Array.isArray(value?.bots)) {
48
50
  return { state: 'unavailable', bots: [] };
49
51
  }
50
- if (result.value.readOnly) return { state: 'readonly', bots: [] };
51
- const bots = result.value.bots.filter((bot) => (
52
+ if (value.readOnly) return { state: 'readonly', bots: [] };
53
+ const bots = value.bots.filter((bot) => (
52
54
  typeof bot.id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(bot.id)
53
55
  && typeof bot.sessionId === 'string' && Boolean(bot.sessionId)
54
56
  && typeof bot.name === 'string'
@@ -63,6 +65,17 @@ export function createDsBotClient(ctx) {
63
65
  }
64
66
  return Object.freeze({
65
67
  status,
68
+ async question(sessionId) {
69
+ const value = await call('state');
70
+ if (value?.readOnly) throw dsBotError();
71
+ if (!value?.bots?.some((bot) => bot.sessionId === sessionId)) return null;
72
+ const question = value.questions?.[sessionId];
73
+ return typeof question?.id === 'string' && typeof question.question === 'string'
74
+ && Array.isArray(question.options) ? question : null;
75
+ },
76
+ answerQuestion(sessionId, questionId, answer) {
77
+ return call('answer-question', { sessionId, questionId, answer });
78
+ },
66
79
  async resolve(id) {
67
80
  const result = await status();
68
81
  if (result.state !== 'ready') throw dsBotError();
@@ -0,0 +1,78 @@
1
+ /** DS Bot's ask_user ends its turn and stores a card, bypassing user-questions/request.
2
+ * Read that card through DS Bot's route and reuse normal bound-chat question delivery.
3
+ * DS Bot's answer route atomically claims it and queues the follow-up itself. */
4
+ export function installDsBotQuestionSync(ctx, deliveryService, { logger = console } = {}) {
5
+ const pending = new Map();
6
+ let closed = false;
7
+ let queue = Promise.resolve();
8
+
9
+ const refresh = (sessionId) => {
10
+ queue = queue.then(async () => {
11
+ if (closed) return;
12
+ const sessions = await deliveryService.listDsBotSessions();
13
+ const bound = new Set(sessions.map((entry) => entry.sessionId));
14
+ for (const [id, entry] of pending) if (!bound.has(id)) entry.finish();
15
+ for (const id of bound) {
16
+ if (sessionId && id !== sessionId) continue;
17
+ const question = await deliveryService.dsBot.question(id);
18
+ if (closed) return;
19
+ const previous = pending.get(id);
20
+ if (previous?.id === question?.id) continue;
21
+ previous?.finish();
22
+ if (!question) continue;
23
+ const controller = new AbortController();
24
+ let complete;
25
+ const completion = new Promise((resolve) => { complete = resolve; });
26
+ const entry = { id: question.id, responding: false, finish() {
27
+ if (pending.get(id) === entry) pending.delete(id);
28
+ controller.abort();
29
+ complete();
30
+ } };
31
+ pending.set(id, entry);
32
+ const interaction = {
33
+ kind: 'question', interactionId: `ds-bot-${question.id}`, rpcId: `ds-bot-${question.id}`, sessionId: id,
34
+ payload: { sessionId: id, questions: [question] },
35
+ withdraw: () => entry.finish(),
36
+ respond: async (response) => {
37
+ if (controller.signal.aborted || entry.responding) {
38
+ throw Object.assign(new Error('Question is no longer open'), { code: 'interaction-not-pending' });
39
+ }
40
+ const answer = response?.value?.answer?.answers?.[0];
41
+ if (response?.ok !== true || response.value.sessionId !== id || answer?.id !== question.id) {
42
+ throw new Error('Invalid DS Bot question answer');
43
+ }
44
+ entry.responding = true;
45
+ try {
46
+ await deliveryService.dsBot.answerQuestion(id, question.id, answer);
47
+ entry.finish();
48
+ } catch (error) {
49
+ entry.responding = false;
50
+ if (error?.code === 'interaction-not-pending') entry.finish();
51
+ throw error;
52
+ }
53
+ },
54
+ };
55
+ if (!await deliveryService.presentSessionSyncQuestion(id, interaction, {
56
+ signal: controller.signal, completion,
57
+ })) entry.finish();
58
+ }
59
+ }).catch((error) => logger.warn?.('[dsh-im] DS Bot question sync failed:', error?.code ?? error?.name));
60
+ return queue;
61
+ };
62
+ const dispose = ctx.on('session/event', (session, event) => {
63
+ // Turn completion covers desktop, IM, scheduled and automatic Bot turns.
64
+ // A desktop answer also publishes a user message; retire the old IM pending.
65
+ if (event?.type === 'turn/end' || (pending.has(session?.id) && event?.type === 'user/message')) {
66
+ void refresh(session?.id);
67
+ }
68
+ }, { global: true });
69
+ const close = () => {
70
+ closed = true;
71
+ dispose?.();
72
+ for (const entry of pending.values()) entry.finish();
73
+ };
74
+ ctx.effect?.(() => close, 'dsh-im: DS Bot question sync');
75
+ // Recover an unanswered card after the Host/plugin restarts.
76
+ const ready = refresh();
77
+ return { ready, refresh, close };
78
+ }
@@ -20,6 +20,7 @@ import { installDeliveryRpc } from './delivery-rpc.mjs';
20
20
  import { installDeliveryHttp } from './delivery-http.mjs';
21
21
  import { createDeliveryService } from './delivery-service.mjs';
22
22
  import { createDsBotClient } from './ds-bot-client.mjs';
23
+ import { installDsBotQuestionSync } from './ds-bot-question-sync.mjs';
23
24
  import { installInboundTtlRpc } from './inbound-ttl-rpc.mjs';
24
25
  import { installSidebarSettingsRpc } from './sidebar-settings.mjs';
25
26
  import { installInjectedContext } from './injected-context.mjs';
@@ -110,6 +111,7 @@ export function createImHostPlugin(internals = {}) {
110
111
  deliveryService.send(botId, targetId, text, options)
111
112
  ),
112
113
  listTargets: async (botId) => (await deliveryService.listTargets(botId)).targets,
114
+ createTarget: (botId, target) => deliveryService.createTarget(botId, target),
113
115
  listBots: () => deliveryService.listBots(),
114
116
  }));
115
117
  }
@@ -217,6 +219,7 @@ export function createImHostPlugin(internals = {}) {
217
219
  logger,
218
220
  inputScope: ctx.root ?? ctx,
219
221
  });
222
+ installDsBotQuestionSync(ctx, deliveryService, { logger });
220
223
  } catch (error) {
221
224
  logger.error?.('[dsh-im] failed to activate Session sync; continuing with channels', error);
222
225
  }