@xmanrui/dsh-im 5.3.0 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/PROACTIVE_DELIVERY.en.md +15 -0
  2. package/PROACTIVE_DELIVERY.md +15 -0
  3. package/README.en.md +44 -3
  4. package/README.md +44 -3
  5. package/THIRD_PARTY_NOTICES.md +209 -0
  6. package/docs/client-integration.md +2 -2
  7. package/lib/client.js +3737 -433
  8. package/lib/index.js +415 -344
  9. package/package.json +1 -1
  10. package/plugin-src/client/channel-card-meta.js +6 -2
  11. package/plugin-src/client/channels/shared/token-api.js +13 -0
  12. package/plugin-src/client/channels/telegram/group-triggers-settings.js +393 -0
  13. package/plugin-src/client/channels/telegram/styles.js +4 -0
  14. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  15. package/plugin-src/client/delivery-settings.js +23 -3
  16. package/plugin-src/client/ds-bot-avatar-data.js +537 -0
  17. package/plugin-src/client/ds-bot-avatar.js +55 -0
  18. package/plugin-src/client/ds-bot-session-avatars.js +77 -0
  19. package/plugin-src/client/ds-bot-settings.js +194 -0
  20. package/plugin-src/client/i18n-ru.js +1615 -0
  21. package/plugin-src/client/i18n.js +130 -1
  22. package/plugin-src/client/index.js +20 -2
  23. package/plugin-src/client/plugin-page.js +3 -8
  24. package/plugin-src/client/styles.js +25 -5
  25. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  26. package/plugin-src/host/channels/feishu/production.mjs +13 -5
  27. package/plugin-src/host/channels/qq/production.mjs +2 -1
  28. package/plugin-src/host/channels/shared/group-triggers-rpc.mjs +110 -0
  29. package/plugin-src/host/channels/shared/production.mjs +12 -1
  30. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  31. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  32. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  33. package/plugin-src/host/channels/slack/production.mjs +2 -1
  34. package/plugin-src/host/channels/telegram/index.mjs +1 -0
  35. package/plugin-src/host/channels/telegram/production.mjs +9 -0
  36. package/plugin-src/host/channels/telegram/rpc.mjs +17 -2
  37. package/plugin-src/host/channels/wecom/production.mjs +4 -1
  38. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  39. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  40. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  41. package/plugin-src/host/delivery-adapter.mjs +129 -41
  42. package/plugin-src/host/delivery-rpc.mjs +33 -1
  43. package/plugin-src/host/delivery-service.mjs +112 -1
  44. package/plugin-src/host/delivery-suggestions.mjs +11 -0
  45. package/plugin-src/host/ds-bot-client.mjs +87 -0
  46. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  47. package/plugin-src/host/index.mjs +8 -1
  48. package/plugin-src/host/modern-harness-api.mjs +53 -8
  49. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  50. package/scripts/verify-package.mjs +17 -5
  51. package/src/channels/feishu/bridge.mjs +83 -5
  52. package/src/channels/feishu/feishu-cards.mjs +11 -7
  53. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  54. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  55. package/src/channels/shared/AGENTS.md +19 -0
  56. package/src/channels/shared/bot-workspace-store.mjs +136 -7
  57. package/src/channels/shared/clear-command.mjs +2 -1
  58. package/src/channels/shared/compact-command.mjs +2 -1
  59. package/src/channels/shared/conversation-queue.mjs +49 -0
  60. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  61. package/src/channels/shared/group-history-store.mjs +26 -0
  62. package/src/channels/shared/harness-client.mjs +5 -4
  63. package/src/channels/shared/history-command.mjs +2 -1
  64. package/src/channels/shared/i18n-en/feishu.mjs +1 -0
  65. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  66. package/src/channels/shared/i18n-en/shared-b.mjs +2 -2
  67. package/src/channels/shared/i18n-en/shared-c.mjs +3 -2
  68. package/src/channels/shared/i18n-en/wecom.mjs +4 -0
  69. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  70. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  71. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  72. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  73. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  74. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  75. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  76. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  77. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  78. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  79. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  80. package/src/channels/shared/i18n-ru/shared-b.mjs +257 -0
  81. package/src/channels/shared/i18n-ru/shared-c.mjs +173 -0
  82. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  83. package/src/channels/shared/i18n-ru/telegram.mjs +25 -0
  84. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  85. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  86. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  87. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  88. package/src/channels/shared/i18n-ru.mjs +48 -0
  89. package/src/channels/shared/i18n.mjs +47 -12
  90. package/src/channels/shared/inbound-access.mjs +1 -1
  91. package/src/channels/shared/interface-language.mjs +3 -3
  92. package/src/channels/shared/message-failure.mjs +3 -2
  93. package/src/channels/shared/model-command.mjs +2 -1
  94. package/src/channels/shared/permission-command.mjs +2 -1
  95. package/src/channels/shared/send-limit.mjs +38 -0
  96. package/src/channels/shared/session-binding-lock.mjs +2 -0
  97. package/src/channels/shared/session-error.mjs +3 -0
  98. package/src/channels/shared/status-reaction.mjs +2 -0
  99. package/src/channels/shared/text-harness-bridge.mjs +4 -0
  100. package/src/channels/shared/thinking-cadence.mjs +36 -0
  101. package/src/channels/shared/workspace-command.mjs +2 -1
  102. package/src/channels/shared/workspace-session.mjs +5 -1
  103. package/src/channels/telegram/config-store.mjs +38 -1
  104. package/src/channels/telegram/group-triggers.mjs +229 -0
  105. package/src/channels/telegram/telegram-api.mjs +223 -32
  106. package/src/channels/telegram/telegram-bridge.mjs +4 -1
  107. package/src/channels/telegram/telegram-controller.mjs +139 -1
  108. package/src/channels/telegram/telegram-runtime.mjs +522 -178
  109. package/src/channels/telegram/voice.mjs +250 -0
  110. package/src/channels/wecom/stream-supervisor.mjs +184 -0
  111. package/src/channels/wecom/wecom-bridge.mjs +25 -11
  112. package/src/channels/wecom/wecom-runtime.mjs +12 -1
@@ -0,0 +1,87 @@
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 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
+ }
39
+ async function status() {
40
+ try {
41
+ const manager = ctx.get?.('pluginManager');
42
+ if (typeof manager?.listBundles === 'function') {
43
+ const bundles = await manager.listBundles();
44
+ const bundle = bundles.find((entry) => entry.name === 'ds-bot');
45
+ if (!bundle?.installed) return { state: 'missing', bots: [] };
46
+ if (!bundle.enabled) return { state: 'disabled', bots: [] };
47
+ }
48
+ const value = await call('state');
49
+ if (!Array.isArray(value?.bots)) {
50
+ return { state: 'unavailable', bots: [] };
51
+ }
52
+ if (value.readOnly) return { state: 'readonly', bots: [] };
53
+ const bots = value.bots.filter((bot) => (
54
+ typeof bot.id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(bot.id)
55
+ && typeof bot.sessionId === 'string' && Boolean(bot.sessionId)
56
+ && typeof bot.name === 'string'
57
+ )).map((bot) => ({
58
+ id: bot.id, name: bot.name, sessionId: bot.sessionId, ...appearance(bot),
59
+ ...(Array.isArray(bot.parts) ? { parts: bot.parts.filter((id) => typeof id === 'string') } : {}),
60
+ }));
61
+ return { state: 'ready', bots };
62
+ } catch {
63
+ return { state: 'unavailable', bots: [] };
64
+ }
65
+ }
66
+ return Object.freeze({
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
+ },
79
+ async resolve(id) {
80
+ const result = await status();
81
+ if (result.state !== 'ready') throw dsBotError();
82
+ const bot = result.bots.find((entry) => entry.id === id);
83
+ if (!bot) throw dsBotError('ds-bot-not-found');
84
+ return bot;
85
+ },
86
+ });
87
+ }
@@ -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
+ }
@@ -19,6 +19,8 @@ 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';
23
+ import { installDsBotQuestionSync } from './ds-bot-question-sync.mjs';
22
24
  import { installInboundTtlRpc } from './inbound-ttl-rpc.mjs';
23
25
  import { installSidebarSettingsRpc } from './sidebar-settings.mjs';
24
26
  import { installInjectedContext } from './injected-context.mjs';
@@ -91,7 +93,10 @@ export function createImHostPlugin(internals = {}) {
91
93
  .map(([channel]) => channel)
92
94
  .filter((channel) => channel !== 'office'
93
95
  && config[channel]?.harnessBaseUrl !== undefined);
94
- const deliveryService = makeDeliveryService({ unavailableSessionSyncChannels });
96
+ const deliveryService = makeDeliveryService({
97
+ unavailableSessionSyncChannels: unavailableSessionSyncChannels.map((channel) => channel === 'wecomApp' ? 'wecom-app' : channel),
98
+ dsBot: createDsBotClient(ctx),
99
+ });
95
100
  if (typeof ctx?.provide === 'function') {
96
101
  ctx.provide('dshIm', Object.freeze({
97
102
  contractVersion: 1,
@@ -106,6 +111,7 @@ export function createImHostPlugin(internals = {}) {
106
111
  deliveryService.send(botId, targetId, text, options)
107
112
  ),
108
113
  listTargets: async (botId) => (await deliveryService.listTargets(botId)).targets,
114
+ createTarget: (botId, target) => deliveryService.createTarget(botId, target),
109
115
  listBots: () => deliveryService.listBots(),
110
116
  }));
111
117
  }
@@ -213,6 +219,7 @@ export function createImHostPlugin(internals = {}) {
213
219
  logger,
214
220
  inputScope: ctx.root ?? ctx,
215
221
  });
222
+ installDsBotQuestionSync(ctx, deliveryService, { logger });
216
223
  } catch (error) {
217
224
  logger.error?.('[dsh-im] failed to activate Session sync; continuing with channels', error);
218
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>']) {
@@ -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.');
@@ -6078,6 +6078,7 @@ export class FeishuHarnessBridge {
6078
6078
  });
6079
6079
  }
6080
6080
  pending.chatId = event.message.chat_id;
6081
+ pending.receiveIdType = 'chat_id';
6081
6082
  if (pending.needsPresentation) {
6082
6083
  try {
6083
6084
  await this.#presentInteraction(pending);
@@ -6133,9 +6134,17 @@ export class FeishuHarnessBridge {
6133
6134
  }
6134
6135
 
6135
6136
  async #submitQuestionAnswer(pending, answerText, { chatId, messageId, questionMessageId } = {}) {
6137
+ const expectedIndex = pending.index;
6138
+ try { if (pending.validate) await pending.validate(); }
6139
+ catch {
6140
+ if (chatId) await this.#send(chatId, INTERACTION_RESOLVED_TEXT(), { replyTo: messageId }).catch(() => undefined);
6141
+ return;
6142
+ }
6143
+ if (pending.inactive || pending.submitting || pending.index !== expectedIndex) return;
6136
6144
  const question = pending.questions[pending.index];
6137
6145
  if (!question) return;
6138
6146
  pending.chatId = chatId ?? pending.chatId;
6147
+ if (chatId) pending.receiveIdType = 'chat_id';
6139
6148
 
6140
6149
  // issue #162:已答状态卡以推进前的题号渲染,并整卡替换原提问卡。
6141
6150
  const answeredIndex = pending.index;
@@ -6270,12 +6279,69 @@ export class FeishuHarnessBridge {
6270
6279
  });
6271
6280
  }
6272
6281
 
6282
+ /** Use the normal question/reply state machine without submitting a new IM prompt. */
6283
+ async presentSessionSyncQuestion(interaction, context, { signal, completion } = {}) {
6284
+ if (signal?.aborted || this.#signal?.aborted || this.#hasPendingInteraction(context.key)) return false;
6285
+ let finished = false;
6286
+ const cleanup = () => {
6287
+ finished = true;
6288
+ signal?.removeEventListener('abort', finish);
6289
+ this.#signal?.removeEventListener('abort', onStop);
6290
+ };
6291
+ const finish = () => {
6292
+ const pending = this.#pendingInteractions.get(context.key);
6293
+ if (pending?.interactionId === interaction.interactionId) {
6294
+ this.#rememberResolvedInteraction(context.key, pending);
6295
+ this.#clearPendingInteraction(context.key, pending.interactionId);
6296
+ }
6297
+ cleanup();
6298
+ };
6299
+ const withdraw = async () => {
6300
+ finish();
6301
+ await interaction.withdraw?.();
6302
+ };
6303
+ const onStop = () => {
6304
+ void withdraw().catch((error) => this.#logger.warn?.('[dsh-feishu] question withdrawal failed:', error?.code));
6305
+ };
6306
+ const validate = async () => {
6307
+ try {
6308
+ await context.validate?.();
6309
+ if (finished || signal?.aborted || this.#signal?.aborted
6310
+ || (!this.#accessPolicy && !this.#allowedSenderOpenIds.has('*')
6311
+ && !this.#allowedSenderOpenIds.has(context.actor))
6312
+ || !context.actor || !evaluateInboundAccess(this.#accessPolicy, {
6313
+ conversationType: 'direct', senderIds: [context.actor], text: 'yes',
6314
+ }).allowed) throw new Error('Question recipient is no longer available');
6315
+ } catch (cause) {
6316
+ await withdraw();
6317
+ throw Object.assign(new Error('Question is no longer answerable', { cause }), { code: 'interaction-not-pending' });
6318
+ }
6319
+ };
6320
+ signal?.addEventListener('abort', finish, { once: true });
6321
+ this.#signal?.addEventListener('abort', onStop, { once: true });
6322
+ Promise.resolve(completion).then(finish, finish);
6323
+ try {
6324
+ await validate();
6325
+ await this.#handleInteraction(interaction, { ...context, validate, onClear: cleanup });
6326
+ if (finished) finish(); // A completion during delivery must not leave a pending behind.
6327
+ const available = !finished && this.#pendingInteractions.get(context.key)?.interactionId === interaction.interactionId;
6328
+ if (!available) cleanup();
6329
+ return available;
6330
+ } catch (error) {
6331
+ await withdraw();
6332
+ throw error;
6333
+ }
6334
+ }
6335
+
6273
6336
  async #handleInteraction(interaction, {
6274
6337
  key,
6275
6338
  actor,
6276
6339
  chatId,
6277
6340
  requiresMention,
6278
6341
  replyToMessageId,
6342
+ receiveIdType,
6343
+ validate,
6344
+ onClear,
6279
6345
  }) {
6280
6346
  if (await this.#approvals.handleRequested(interaction, this.#approvalContext({
6281
6347
  key, actor, chatId, requiresMention, replyToMessageId,
@@ -6322,6 +6388,10 @@ export class FeishuHarnessBridge {
6322
6388
  }
6323
6389
  if (this.#interactionKeys.has(interactionId)) return;
6324
6390
  if (existing) {
6391
+ if (interaction.withdraw) {
6392
+ await interaction.withdraw();
6393
+ return;
6394
+ }
6325
6395
  await interaction.respond({
6326
6396
  ok: false,
6327
6397
  error: {
@@ -6346,6 +6416,9 @@ export class FeishuHarnessBridge {
6346
6416
  index: 0,
6347
6417
  chatId,
6348
6418
  replyToMessageId,
6419
+ receiveIdType,
6420
+ validate,
6421
+ onClear,
6349
6422
  queue: null,
6350
6423
  claimedReplyMessageId: null,
6351
6424
  submitting: false,
@@ -6371,6 +6444,8 @@ export class FeishuHarnessBridge {
6371
6444
  }
6372
6445
 
6373
6446
  async #presentInteraction(pending) {
6447
+ if (pending.validate) await pending.validate();
6448
+ if (pending.inactive) return;
6374
6449
  const question = pending.questions[pending.index];
6375
6450
  if (!question) return;
6376
6451
  const options = Array.isArray(question?.options) ? question.options : [];
@@ -6398,7 +6473,7 @@ export class FeishuHarnessBridge {
6398
6473
  index: pending.index,
6399
6474
  total: pending.questions.length,
6400
6475
  }),
6401
- { key: pending.key, replyTo: pending.replyToMessageId },
6476
+ { key: pending.key, replyTo: pending.replyToMessageId, receiveIdType: pending.receiveIdType },
6402
6477
  ).then((sent) => {
6403
6478
  presentedAsCard = true;
6404
6479
  return sent;
@@ -6406,12 +6481,14 @@ export class FeishuHarnessBridge {
6406
6481
  // Fall back to the plain-text question if the card cannot be sent.
6407
6482
  // If the text send also fails, let the error propagate so the pending
6408
6483
  // question is not marked as presented and the existing retry logic runs.
6484
+ if (pending.inactive) return null;
6485
+ if (pending.validate) await pending.validate();
6409
6486
  return this.#send(
6410
6487
  pending.chatId,
6411
6488
  harnessQuestionText(question, pending.index, pending.questions.length, {
6412
6489
  requiresMention: pending.requiresMention,
6413
6490
  }),
6414
- { replyTo: pending.replyToMessageId },
6491
+ { replyTo: pending.replyToMessageId, receiveIdType: pending.receiveIdType },
6415
6492
  );
6416
6493
  });
6417
6494
  } else {
@@ -6424,7 +6501,7 @@ export class FeishuHarnessBridge {
6424
6501
  pending.questions.length,
6425
6502
  { requiresMention: pending.requiresMention },
6426
6503
  ),
6427
- { replyTo: pending.replyToMessageId },
6504
+ { replyTo: pending.replyToMessageId, receiveIdType: pending.receiveIdType },
6428
6505
  );
6429
6506
  }
6430
6507
  if (messageId) {
@@ -6478,6 +6555,7 @@ export class FeishuHarnessBridge {
6478
6555
  this.#pendingInteractions.delete(key);
6479
6556
  this.#interactionKeys.delete(pending.interactionId);
6480
6557
  pending.inactive = true;
6558
+ pending.onClear?.();
6481
6559
  return pending;
6482
6560
  }
6483
6561
 
@@ -6534,7 +6612,7 @@ export class FeishuHarnessBridge {
6534
6612
  else processingReaction.success();
6535
6613
  }
6536
6614
 
6537
- async #send(chatId, text, { replyTo } = {}) {
6615
+ async #send(chatId, text, { replyTo, receiveIdType = 'chat_id' } = {}) {
6538
6616
  const content = JSON.stringify({ text });
6539
6617
  if (replyTo) {
6540
6618
  try {
@@ -6563,7 +6641,7 @@ export class FeishuHarnessBridge {
6563
6641
  }
6564
6642
  }
6565
6643
  const response = await this.#client.im.v1.message.create({
6566
- params: { receive_id_type: 'chat_id' },
6644
+ params: { receive_id_type: receiveIdType },
6567
6645
  data: {
6568
6646
  receive_id: chatId,
6569
6647
  msg_type: 'text',
@@ -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 答案,卡片补上引导入口。
@@ -713,6 +713,16 @@ export class FeishuRuntime {
713
713
  }, options);
714
714
  }
715
715
 
716
+ async presentSessionSyncQuestion(target, interaction, options = {}) {
717
+ if (!this.#status.ready || !this.#bridge || target?.kind !== 'user') return false;
718
+ const actor = nonEmptyString(target.route?.openId);
719
+ if (!actor) return false;
720
+ return this.#bridge.presentSessionSyncQuestion(interaction, {
721
+ key: options.key, actor, validate: options.validate,
722
+ chatId: actor, receiveIdType: 'open_id', requiresMention: false,
723
+ }, options);
724
+ }
725
+
716
726
  async sendProactiveText(target, text, { signal, format = 'plain', receipt = false } = {}) {
717
727
  if (!this.#status.ready || !this.#client) {
718
728
  const error = new Error('飞书机器人尚未连接');