@xmanrui/dsh-im 5.4.0 → 5.6.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 (105) hide show
  1. package/PROACTIVE_DELIVERY.en.md +15 -0
  2. package/PROACTIVE_DELIVERY.md +15 -0
  3. package/README.en.md +46 -5
  4. package/README.md +46 -5
  5. package/lib/client.js +2579 -664
  6. package/lib/index.js +406 -339
  7. package/package.json +4 -4
  8. package/plugin-src/client/channel-card-meta.js +6 -2
  9. package/plugin-src/client/channels/dingtalk/index.js +12 -9
  10. package/plugin-src/client/channels/feishu/group-settings.js +5 -5
  11. package/plugin-src/client/channels/feishu/index.js +33 -25
  12. package/plugin-src/client/channels/qq/index.js +5 -5
  13. package/plugin-src/client/channels/shared/token-api.js +25 -7
  14. package/plugin-src/client/channels/shared/token-channel.js +18 -11
  15. package/plugin-src/client/channels/telegram/styles.js +4 -0
  16. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  17. package/plugin-src/client/channels/wecom/index.js +5 -5
  18. package/plugin-src/client/channels/wecom-app/index.js +3 -3
  19. package/plugin-src/client/channels/weixin/index.js +2 -2
  20. package/plugin-src/client/channels/whatsapp/index.js +6 -6
  21. package/plugin-src/client/credential-binding.js +3 -2
  22. package/plugin-src/client/delivery-settings.js +4 -4
  23. package/plugin-src/client/ds-bot-settings.js +3 -3
  24. package/plugin-src/client/global-settings.js +5 -2
  25. package/plugin-src/client/i18n-ru.js +1637 -0
  26. package/plugin-src/client/i18n.js +281 -124
  27. package/plugin-src/client/index.js +8 -1
  28. package/plugin-src/host/channels/shared/production.mjs +5 -0
  29. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  30. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  31. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  32. package/plugin-src/host/channels/telegram/production.mjs +7 -0
  33. package/plugin-src/host/delivery-adapter.mjs +41 -33
  34. package/plugin-src/host/delivery-service.mjs +42 -0
  35. package/plugin-src/host/ds-bot-client.mjs +31 -18
  36. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  37. package/plugin-src/host/index.mjs +3 -0
  38. package/plugin-src/host/modern-harness-api.mjs +53 -8
  39. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  40. package/scripts/verify-package.mjs +18 -6
  41. package/src/channels/dingtalk/dingtalk-bridge.mjs +1 -0
  42. package/src/channels/feishu/bridge.mjs +107 -7
  43. package/src/channels/feishu/feishu-cards.mjs +1 -45
  44. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  45. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  46. package/src/channels/feishu/slash-command-panel.mjs +2 -5
  47. package/src/channels/qq/qq-bridge.mjs +1 -0
  48. package/src/channels/shared/AGENTS.md +19 -0
  49. package/src/channels/shared/bot-workspace-store.mjs +1 -1
  50. package/src/channels/shared/clear-command.mjs +2 -1
  51. package/src/channels/shared/command-catalog.mjs +8 -5
  52. package/src/channels/shared/compact-command.mjs +2 -1
  53. package/src/channels/shared/conversation-queue.mjs +49 -0
  54. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  55. package/src/channels/shared/delivery-failure-log.mjs +111 -0
  56. package/src/channels/shared/diagnostic-details.mjs +1 -0
  57. package/src/channels/shared/harness-client.mjs +16 -9
  58. package/src/channels/shared/history-command.mjs +2 -1
  59. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  60. package/src/channels/shared/i18n-en/shared-b.mjs +7 -2
  61. package/src/channels/shared/i18n-en/shared-c.mjs +6 -2
  62. package/src/channels/shared/i18n-en/telegram.mjs +6 -0
  63. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  64. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  65. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  66. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  67. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  68. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  69. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  70. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  71. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  72. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  73. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  74. package/src/channels/shared/i18n-ru/shared-b.mjs +262 -0
  75. package/src/channels/shared/i18n-ru/shared-c.mjs +176 -0
  76. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  77. package/src/channels/shared/i18n-ru/telegram.mjs +30 -0
  78. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  79. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  80. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  81. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  82. package/src/channels/shared/i18n-ru.mjs +48 -0
  83. package/src/channels/shared/i18n.mjs +47 -12
  84. package/src/channels/shared/inbound-access.mjs +1 -1
  85. package/src/channels/shared/interface-language.mjs +3 -3
  86. package/src/channels/shared/message-failure.mjs +8 -4
  87. package/src/channels/shared/model-command.mjs +2 -1
  88. package/src/channels/shared/permission-command.mjs +2 -1
  89. package/src/channels/shared/send-limit.mjs +38 -0
  90. package/src/channels/shared/session-error.mjs +11 -0
  91. package/src/channels/shared/status-reaction.mjs +2 -0
  92. package/src/channels/shared/text-harness-bridge.mjs +205 -3
  93. package/src/channels/shared/thinking-cadence.mjs +36 -0
  94. package/src/channels/shared/workspace-command.mjs +43 -17
  95. package/src/channels/shared/workspace-labels.mjs +65 -0
  96. package/src/channels/shared/workspace-session.mjs +24 -4
  97. package/src/channels/telegram/config-store.mjs +34 -1
  98. package/src/channels/telegram/telegram-api.mjs +240 -32
  99. package/src/channels/telegram/telegram-bridge.mjs +62 -1
  100. package/src/channels/telegram/telegram-controller.mjs +29 -0
  101. package/src/channels/telegram/telegram-runtime.mjs +592 -179
  102. package/src/channels/telegram/voice.mjs +250 -0
  103. package/src/channels/wecom/wecom-bridge.mjs +1 -0
  104. package/src/channels/wecom-app/wecom-app-bridge.mjs +1 -0
  105. package/src/channels/weixin/weixin-bridge.mjs +1 -0
@@ -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
  }
@@ -510,7 +510,9 @@ class ModernHarnessApi {
510
510
  let subscription;
511
511
  subscription = new MuxSubscription(signal, () => this.#mux.delete(subscription));
512
512
  this.#mux.add(subscription);
513
- for (const pending of this.#pendingQuestions.values()) subscription.push(this.#questionFrame(pending));
513
+ for (const pending of this.#pendingQuestions.values()) {
514
+ if (pending.broadcast) subscription.push(this.#questionFrame(pending));
515
+ }
514
516
  for (const pending of this.#pendingApprovals.values()) {
515
517
  if (pending.broadcast !== false && pending.imAvailable !== false) subscription.push(this.#approvalFrame(pending));
516
518
  }
@@ -547,7 +549,9 @@ class ModernHarnessApi {
547
549
 
548
550
  #requestQuestion(request, next) {
549
551
  const owner = this.#claimableAgent(request?.agent);
550
- if (!owner) return next();
552
+ const sessionId = owner?.sessionId ?? request?.agent?.session?.id ?? request?.agent?.id;
553
+ if (typeof sessionId !== 'string'
554
+ || (!owner && typeof this.#deliveryService?.presentSessionSyncQuestion !== 'function')) return next();
551
555
  const turnSignal = request.signal;
552
556
  if (turnSignal?.aborted) {
553
557
  return Promise.reject(questionError(
@@ -581,11 +585,21 @@ class ModernHarnessApi {
581
585
  // request exclusively used to keep the question out of Web entirely, leaving
582
586
  // whoever happened to be looking at that Session with a card they could not
583
587
  // answer. Racing keeps both surfaces usable: the first answer wins.
584
- const im = this.#askThroughIm(request, owner);
588
+ const im = this.#askThroughIm(request, { sessionId }, { broadcast: Boolean(owner) });
589
+ let imAvailable = true;
590
+ let nativeError;
591
+ const withdraw = () => {
592
+ imAvailable = false;
593
+ im.withdraw();
594
+ // No binding/provider must preserve the native error, not leave the tool waiting forever.
595
+ if (nativeError) im.dismiss(nativeError);
596
+ };
585
597
  let answeredByIm = false;
586
598
  const native = Promise.resolve()
587
599
  .then(() => next())
588
600
  .catch((error) => {
601
+ nativeError = error;
602
+ if (!imAvailable) throw error;
589
603
  // A pure-IM session has no client connected, so the host rejects with
590
604
  // NO_PROVIDER — an expected state rather than a failure — and ASK_ABORTED
591
605
  // is this adapter's own retire signal below. Any other error is real, so
@@ -599,7 +613,7 @@ class ModernHarnessApi {
599
613
  }
600
614
  return new Promise(() => {});
601
615
  });
602
- return Promise.race([
616
+ const result = Promise.race([
603
617
  native,
604
618
  im.promise.then((value) => {
605
619
  answeredByIm = true;
@@ -627,26 +641,45 @@ class ModernHarnessApi {
627
641
  // rejecting alongside us stays an expected retirement rather than a logged
628
642
  // failure.
629
643
  question.abort(questionError('the question was answered on IM', 'ASK_ABORTED'));
644
+ } else if (!owner) {
645
+ // Also stop a bound-chat lookup/delivery still in flight when the Host wins.
646
+ question.abort(questionError('the question ended', 'ASK_ABORTED'));
630
647
  }
631
648
  });
649
+ if (!owner) {
650
+ Promise.resolve().then(() => {
651
+ if (question.signal.aborted) return false;
652
+ return this.#deliveryService.presentSessionSyncQuestion(sessionId, {
653
+ ...im.interaction, withdraw,
654
+ }, { signal: question.signal, completion: result });
655
+ }).then((available) => {
656
+ if (!available) withdraw();
657
+ }, (error) => {
658
+ if (!question.signal.aborted) console.warn('[dsh-im] synced question delivery unavailable:', error?.code ?? error?.name);
659
+ withdraw();
660
+ });
661
+ }
662
+ return result;
632
663
  }
633
664
 
634
665
  /**
635
666
  * Present one question to IM clients. Returns the answer promise plus a
636
667
  * `dismiss` used to retire the pending when the host answers first.
637
668
  */
638
- #askThroughIm(request, owner) {
669
+ #askThroughIm(request, owner, { broadcast = true } = {}) {
639
670
  let pending = null;
640
671
  const promise = new Promise((resolve, reject) => {
641
672
  pending = {
642
673
  rpcId: randomUUID(),
643
674
  sessionId: owner.sessionId,
644
675
  questions: request.questions,
676
+ broadcast,
677
+ imAvailable: true,
645
678
  signal: request.signal,
646
679
  settle: (outcome, value) => {
647
680
  if (!this.#pendingQuestions.delete(pending.rpcId)) return;
648
681
  request.signal?.removeEventListener('abort', onAbort);
649
- this.#broadcast({
682
+ if (broadcast) this.#broadcast({
650
683
  type: 'question/resolved',
651
684
  sessionId: pending.sessionId,
652
685
  questionRpcId: pending.rpcId,
@@ -661,11 +694,23 @@ class ModernHarnessApi {
661
694
  ));
662
695
  this.#pendingQuestions.set(pending.rpcId, pending);
663
696
  request.signal?.addEventListener('abort', onAbort, { once: true });
664
- this.#broadcast(this.#questionFrame(pending).payload, pending.rpcId);
697
+ if (broadcast) this.#broadcast(this.#questionFrame(pending).payload, pending.rpcId);
665
698
  });
666
699
  return {
667
700
  promise,
668
701
  dismiss: (reason) => pending?.settle('cancelled', reason),
702
+ withdraw: () => { pending.imAvailable = false; },
703
+ interaction: {
704
+ kind: 'question', interactionId: pending.rpcId, rpcId: pending.rpcId,
705
+ sessionId: pending.sessionId, payload: this.#questionFrame(pending).payload,
706
+ respond: async (response) => {
707
+ const receipt = this.#respond({ rpcId: pending.rpcId, result: response });
708
+ if (!receipt.accepted) throw new HarnessInteractionError(
709
+ `interaction-${receipt.reason}`, 'This question is no longer answerable',
710
+ );
711
+ return receipt;
712
+ },
713
+ },
669
714
  };
670
715
  }
671
716
 
@@ -869,7 +914,7 @@ class ModernHarnessApi {
869
914
  return { accepted: true };
870
915
  }
871
916
  const question = this.#pendingQuestions.get(message?.rpcId);
872
- if (!question) return { accepted: false, reason: 'not-pending' };
917
+ if (!question || !question.imAvailable) return { accepted: false, reason: 'not-pending' };
873
918
  if (message?.result?.ok !== true) {
874
919
  if (message?.result?.error?.code !== 'cancelled') {
875
920
  return { accepted: false, reason: 'bad-response' };
@@ -23,7 +23,7 @@ function sessionIdOf(session) {
23
23
 
24
24
  function userInputOrigin(scope, event) {
25
25
  const source = event?.data?.source;
26
- if (source?.kind === 'schedule') return 'dsh';
26
+ if (source?.kind === 'schedule' || source?.kind === 'user-question-reply') return 'dsh';
27
27
  if (source?.kind !== 'user' || typeof source.rpcId !== 'string' || !source.rpcId) {
28
28
  return 'other';
29
29
  }
@@ -116,9 +116,9 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
116
116
  if (event.surfaceOp !== 'append') return;
117
117
  if (state.origin === 'unknown') state.origin = origin;
118
118
  if (state.origin !== 'dsh' || origin !== 'dsh') return;
119
- const scheduled = event.data?.source?.kind === 'schedule';
119
+ const internalInput = ['schedule', 'user-question-reply'].includes(event.data?.source?.kind);
120
120
  const text = textFromHarnessContent(event.data?.content);
121
- if (!text && !scheduled) return;
121
+ if (!text && !internalInput) return;
122
122
 
123
123
  let targets;
124
124
  try {
@@ -127,9 +127,9 @@ export function createSessionSyncCoordinator({ deliveryService, logger = console
127
127
  logFailure('lookup', null, error);
128
128
  targets = [];
129
129
  }
130
- // Scheduled framing is internal: select its recipients without echoing it.
130
+ // Reminder/question-answer framing is internal: select recipients without echoing it.
131
131
  // Direct DSH input still requires a successful echo before the final answer.
132
- const recipients = scheduled
132
+ const recipients = internalInput
133
133
  ? new Map(targets.filter(validRecipient).map((target) => [recipientKey(target), target]))
134
134
  : await deliver(sessionId, targets, `${DSH_USER_PREFIX}${text}`, 'user delivery');
135
135
  if (state.recipients === null) {
@@ -151,8 +151,9 @@ if (client.includes('settings.plugins.tab') || clientSources.includes('settings.
151
151
  // email settings, the Telegram thinking-traces block, and Feishu panel settings.
152
152
  // The context editor contains one switch template and one mapped field-input
153
153
  // template; the delivery target adds one ordinary checkbox template; the
154
- // Telegram thinking-traces block adds one ordinary checkbox template. General
155
- // settings adds one mapped switch template for the two Feishu panel preferences.
154
+ // Telegram thinking-traces block adds two ordinary checkbox templates (traces
155
+ // and frame numbering). General settings adds one mapped switch template for
156
+ // the two Feishu panel preferences.
156
157
  const contextEditorSource = await readFile(resolve(root, 'plugin-src/client/context-enhancement.js'), 'utf8');
157
158
  const deliverySettingsSource = await readFile(resolve(root, 'plugin-src/client/delivery-settings.js'), 'utf8');
158
159
  const emailSettingsSource = await readFile(resolve(root, 'plugin-src/client/channels/email/index.js'), 'utf8');
@@ -167,12 +168,12 @@ const otherClientSources = clientSources
167
168
  if (/role:\s*["']switch|type:\s*["']checkbox/.test(otherClientSources)
168
169
  || (deliverySettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
169
170
  || /role:\s*["']switch["']/u.test(deliverySettingsSource)
170
- || (thinkingTracesSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
171
+ || (thinkingTracesSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 2
171
172
  || /role:\s*["']switch["']/u.test(thinkingTracesSource)
172
173
  || (botGeneralSettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
173
174
  || (botGeneralSettingsSource.match(/role:\s*["']switch["']/g) ?? []).length !== 1
174
175
  || (client.match(/role:\s*["']switch["']/g) ?? []).length !== 2
175
- || (client.match(/type:\s*["']checkbox["']/g) ?? []).length !== 5) {
176
+ || (client.match(/type:\s*["']checkbox["']/g) ?? []).length !== 6) {
176
177
  throw new Error('checkable inputs must be limited to context enhancement, Session sync, email settings, Telegram thinking traces, and Feishu panel settings');
177
178
  }
178
179
  for (const marker of ['bot.context-enhancement.set', '<dsh_im_source>', '<dsh_im_source_guidance>']) {
@@ -224,7 +225,7 @@ const directDependencies = {
224
225
  '@tencent-connect/qqbot-nodejs': '1.0.4',
225
226
  '@wecom/aibot-node-sdk': '1.0.7',
226
227
  qrcode: '1.5.4',
227
- undici: '7.29.1',
228
+ undici: '7.30.1',
228
229
  };
229
230
  for (const [name, version] of Object.entries(directDependencies)) {
230
231
  if (manifest.dependencies?.[name] !== version) {
@@ -262,6 +263,17 @@ if (process.platform !== 'win32' && (executable.mode & 0o111) === 0) {
262
263
  if (/private-bot-token|must-be-rolled-back|DEEPSEEK_API_KEY=/.test(client + host)) {
263
264
  throw new Error('built artifacts contain a test or environment secret marker');
264
265
  }
265
- await import(pathToFileURL(resolve(root, 'lib/index.js')).href);
266
+ const { createImHostPlugin } = await import(pathToFileURL(resolve(root, 'lib/index.js')).href);
267
+ let deliveryApi;
268
+ await createImHostPlugin().apply({
269
+ provide(name, service) {
270
+ if (name === 'dshIm') deliveryApi = service;
271
+ },
272
+ // Inspect the published service without starting channels or opening connections.
273
+ inject() {},
274
+ });
275
+ if (typeof deliveryApi?.createTarget !== 'function') {
276
+ throw new Error('host bundle must expose dshIm.createTarget; rebuild before publishing');
277
+ }
266
278
 
267
279
  console.log('Verified dsh-im package artifacts.');
@@ -1399,6 +1399,7 @@ export class DingtalkHarnessBridge {
1399
1399
  if (cardStarted) cardStartedAt = startedAt;
1400
1400
  }
1401
1401
  const { answer, artifacts = [] } = await askInWorkspaceSession({
1402
+ onNotice: (notice) => this.#send(sessionWebhook, notice, this.#atUsersFor(message)),
1402
1403
  deferredDelivery: () => ({ coordinator: this.#deferred, target: { ...cardTarget(message, sender), robotCode: this.#clientId } }),
1403
1404
  harness: this.#harness,
1404
1405
  state: this.#state,