@xmanrui/dsh-im 5.9.1 → 5.11.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 (135) hide show
  1. package/PROACTIVE_DELIVERY.en.md +33 -9
  2. package/PROACTIVE_DELIVERY.md +33 -9
  3. package/README.en.md +42 -7
  4. package/README.md +46 -8
  5. package/bin/dsh-im.mjs +65 -0
  6. package/docs/client-integration.md +4 -0
  7. package/lib/client.js +1735 -203
  8. package/lib/index.js +367 -341
  9. package/package.json +7 -6
  10. package/plugin-src/client/access-policy-settings.js +210 -12
  11. package/plugin-src/client/bot-general-settings.js +44 -3
  12. package/plugin-src/client/delivery-settings.js +2 -0
  13. package/plugin-src/client/delivery-sync-settings.js +269 -0
  14. package/plugin-src/client/global-settings.js +45 -7
  15. package/plugin-src/client/i18n-ru.js +112 -0
  16. package/plugin-src/client/i18n.js +110 -0
  17. package/plugin-src/client/im-channels.js +419 -0
  18. package/plugin-src/client/index.js +50 -2
  19. package/plugin-src/client/model-setting.js +6 -3
  20. package/plugin-src/client/styles.js +23 -7
  21. package/plugin-src/client/update-panel.js +2 -1
  22. package/plugin-src/host/channel-list-rpc.mjs +280 -0
  23. package/plugin-src/host/channels/dingtalk/production.mjs +28 -10
  24. package/plugin-src/host/channels/dingtalk/rpc.mjs +10 -1
  25. package/plugin-src/host/channels/feishu/production.mjs +50 -37
  26. package/plugin-src/host/channels/feishu/rpc.mjs +10 -1
  27. package/plugin-src/host/channels/matrix/production.mjs +28 -10
  28. package/plugin-src/host/channels/matrix/rpc.mjs +10 -0
  29. package/plugin-src/host/channels/qq/production.mjs +30 -11
  30. package/plugin-src/host/channels/qq/rpc.mjs +10 -1
  31. package/plugin-src/host/channels/shared/access-policy-production.mjs +9 -0
  32. package/plugin-src/host/channels/shared/binding-events.mjs +109 -0
  33. package/plugin-src/host/channels/shared/production.mjs +14 -1
  34. package/plugin-src/host/channels/shared/reply-content-rpc.mjs +17 -0
  35. package/plugin-src/host/channels/shared/rpc.mjs +9 -0
  36. package/plugin-src/host/channels/shared/workspace-rpc.mjs +1 -0
  37. package/plugin-src/host/channels/slack/production.mjs +28 -10
  38. package/plugin-src/host/channels/slack/rpc.mjs +10 -0
  39. package/plugin-src/host/channels/telegram/production.mjs +5 -0
  40. package/plugin-src/host/channels/wecom/production.mjs +28 -10
  41. package/plugin-src/host/channels/wecom/rpc.mjs +10 -1
  42. package/plugin-src/host/channels/wecom-app/production.mjs +28 -10
  43. package/plugin-src/host/channels/wecom-app/rpc.mjs +9 -0
  44. package/plugin-src/host/channels/weixin/production.mjs +28 -10
  45. package/plugin-src/host/channels/weixin/rpc.mjs +10 -1
  46. package/plugin-src/host/channels/whatsapp/production.mjs +28 -10
  47. package/plugin-src/host/channels/whatsapp/rpc.mjs +10 -1
  48. package/plugin-src/host/delivery-adapter.mjs +35 -20
  49. package/plugin-src/host/delivery-service.mjs +99 -1
  50. package/plugin-src/host/delivery-suggestions.mjs +31 -1
  51. package/plugin-src/host/delivery-sync-rpc.mjs +100 -0
  52. package/plugin-src/host/harness-connection.mjs +2 -1
  53. package/plugin-src/host/harness-peer.mjs +3 -1
  54. package/plugin-src/host/host-language-rpc.mjs +16 -2
  55. package/plugin-src/host/host-language.mjs +29 -0
  56. package/plugin-src/host/index.mjs +30 -1
  57. package/plugin-src/host/modern-harness-api.mjs +5 -1
  58. package/plugin-src/host/root-scope.mjs +32 -0
  59. package/plugin-src/host/session-sync-coordinator.mjs +290 -122
  60. package/plugin-src/host/session-sync-targets.mjs +71 -0
  61. package/plugin-src/management-rpc.mjs +18 -2
  62. package/scripts/verify-package.mjs +48 -10
  63. package/src/channels/dingtalk/dingtalk-bridge.mjs +50 -6
  64. package/src/channels/dingtalk/state-store.mjs +56 -0
  65. package/src/channels/discord/discord-api.mjs +2 -1
  66. package/src/channels/feishu/bridge.mjs +154 -58
  67. package/src/channels/feishu/feishu-cards.mjs +10 -4
  68. package/src/channels/feishu/feishu-runtime.mjs +11 -3
  69. package/src/channels/feishu/message-utils.mjs +106 -30
  70. package/src/channels/feishu/slash-command-panel.mjs +26 -0
  71. package/src/channels/feishu/state-store.mjs +14 -0
  72. package/src/channels/matrix/matrix-api.mjs +2 -1
  73. package/src/channels/qq/qq-bridge.mjs +114 -14
  74. package/src/channels/qq/state-store.mjs +55 -1
  75. package/src/channels/shared/access-policy.mjs +60 -7
  76. package/src/channels/shared/action-card.mjs +83 -7
  77. package/src/channels/shared/bot-workspace-store.mjs +255 -11
  78. package/src/channels/shared/busy-message-dispatcher.mjs +2 -2
  79. package/src/channels/shared/channel-capabilities.mjs +44 -0
  80. package/src/channels/shared/command-catalog.mjs +68 -3
  81. package/src/channels/shared/command-permission.mjs +6 -2
  82. package/src/channels/shared/conversation-state-store.mjs +16 -0
  83. package/src/channels/shared/deferred-delivery-coordinator.mjs +6 -1
  84. package/src/channels/shared/deferred-delivery.mjs +4 -0
  85. package/src/channels/shared/delivery-sync-settings-store.mjs +86 -0
  86. package/src/channels/shared/delivery-sync-settings.mjs +122 -0
  87. package/src/channels/shared/diagnostic-details.mjs +6 -1
  88. package/src/channels/shared/failure-log-file.mjs +79 -0
  89. package/src/channels/shared/harness-client.mjs +259 -96
  90. package/src/channels/shared/i18n-en/diagnostics.mjs +1 -0
  91. package/src/channels/shared/i18n-en/feishu.mjs +2 -2
  92. package/src/channels/shared/i18n-en/shared-a.mjs +13 -2
  93. package/src/channels/shared/i18n-en/shared-b.mjs +73 -4
  94. package/src/channels/shared/i18n-en/shared-d.mjs +144 -0
  95. package/src/channels/shared/i18n-en/weixin.mjs +4 -0
  96. package/src/channels/shared/i18n-en.mjs +2 -0
  97. package/src/channels/shared/i18n-ru/diagnostics.mjs +1 -0
  98. package/src/channels/shared/i18n-ru/feishu.mjs +2 -2
  99. package/src/channels/shared/i18n-ru/shared-a.mjs +13 -2
  100. package/src/channels/shared/i18n-ru/shared-b.mjs +72 -4
  101. package/src/channels/shared/i18n-ru/shared-d.mjs +144 -0
  102. package/src/channels/shared/i18n-ru/weixin.mjs +4 -0
  103. package/src/channels/shared/i18n-ru.mjs +2 -0
  104. package/src/channels/shared/inbound-access.mjs +10 -0
  105. package/src/channels/shared/interface-language-store.mjs +49 -10
  106. package/src/channels/shared/interface-language.mjs +19 -1
  107. package/src/channels/shared/markdown-chunks.mjs +5 -0
  108. package/src/channels/shared/message-failure.mjs +22 -1
  109. package/src/channels/shared/model-setting.mjs +6 -3
  110. package/src/channels/shared/new-command.mjs +158 -4
  111. package/src/channels/shared/plan-goal-command.mjs +132 -0
  112. package/src/channels/shared/qrcode.mjs +5 -0
  113. package/src/channels/shared/reply-content.mjs +102 -0
  114. package/src/channels/shared/reset-command.mjs +46 -0
  115. package/src/channels/shared/semantic/artifact.mjs +133 -29
  116. package/src/channels/shared/semantic/reply-reference.mjs +18 -3
  117. package/src/channels/shared/session-nav-command.mjs +999 -0
  118. package/src/channels/shared/session-ring-support.mjs +184 -0
  119. package/src/channels/shared/session-ring.mjs +202 -0
  120. package/src/channels/shared/session-title.mjs +11 -0
  121. package/src/channels/shared/status-command.mjs +2 -1
  122. package/src/channels/shared/text-harness-bridge.mjs +166 -7
  123. package/src/channels/shared/workspace-command.mjs +567 -31
  124. package/src/channels/shared/workspace-session.mjs +52 -4
  125. package/src/channels/slack/slack-api.mjs +2 -1
  126. package/src/channels/telegram/config-store.mjs +10 -2
  127. package/src/channels/telegram/telegram-api.mjs +19 -1
  128. package/src/channels/telegram/telegram-rich-message.mjs +17 -5
  129. package/src/channels/telegram/telegram-runtime.mjs +14 -1
  130. package/src/channels/wecom/state-store.mjs +13 -1
  131. package/src/channels/wecom/wecom-bridge.mjs +183 -26
  132. package/src/channels/wecom-app/state-store.mjs +13 -1
  133. package/src/channels/wecom-app/wecom-app-bridge.mjs +44 -4
  134. package/src/channels/weixin/state-store.mjs +13 -1
  135. package/src/channels/weixin/weixin-bridge.mjs +71 -4
@@ -1,4 +1,5 @@
1
1
  import { SET_MESSAGE_MODE_ENDPOINT, validMessageModePayload } from '../../../../src/channels/shared/message-mode.mjs';
2
+ import { SET_REPLY_CONTENT_ENDPOINT, validReplyContentPayload } from '../shared/reply-content-rpc.mjs';
2
3
  import { createConnectionDiagnostics, diagnosticRpcResult } from '../../../../src/channels/shared/connection-error.mjs';
3
4
  import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
4
5
  import { registerManagementRpc } from '../../../management-rpc.mjs';
@@ -26,6 +27,7 @@ export const WECOM_APP_ENDPOINTS = Object.freeze({
26
27
  setAgentPreset: SET_AGENT_PRESET_ENDPOINT,
27
28
  setContextEnhancement: SET_CONTEXT_ENHANCEMENT_ENDPOINT,
28
29
  setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
30
+ setReplyContent: SET_REPLY_CONTENT_ENDPOINT,
29
31
  setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
30
32
  setAlias: SET_ALIAS_ENDPOINT,
31
33
  });
@@ -112,6 +114,10 @@ function payloadFailure(endpoint, payload) {
112
114
  if (endpoint === WECOM_APP_ENDPOINTS.setAgentPreset) {
113
115
  return validAgentPresetPayload(payload) ? null : '请选择 Agent Preset。';
114
116
  }
117
+ if (endpoint === WECOM_APP_ENDPOINTS.setReplyContent) {
118
+ return validReplyContentPayload(payload)
119
+ ? null : '请选择要投递的回复内容。';
120
+ }
115
121
  if (endpoint === WECOM_APP_ENDPOINTS.setBusyMessageMode) {
116
122
  return validMessageModePayload(payload) ? null : '请提交有效的消息处理方式。';
117
123
  }
@@ -196,6 +202,9 @@ export function createWecomAppRpcHandler(controller) {
196
202
  } else if (endpoint === WECOM_APP_ENDPOINTS.setModel) {
197
203
  if (typeof controller.updateModel !== 'function') throw new Error('Model update is unavailable');
198
204
  value = await publicStatus(await controller.updateModel(payload.botId, payload.model));
205
+ } else if (endpoint === WECOM_APP_ENDPOINTS.setReplyContent) {
206
+ if (typeof controller.updateReplyContent !== 'function') throw new Error('Reply content update is unavailable');
207
+ value = await controller.updateReplyContent(payload.botId, payload.replyContent);
199
208
  } else if (endpoint === WECOM_APP_ENDPOINTS.setBusyMessageMode) {
200
209
  if (typeof controller.updateBusyMessageMode !== 'function') throw new Error('Message mode update is unavailable');
201
210
  value = await controller.updateBusyMessageMode(
@@ -24,6 +24,7 @@ import { prepareBotWorkspace } from '../../../../src/channels/shared/default-wor
24
24
  import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-preset.mjs';
25
25
  import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
26
26
  import { createDeliveryAdapter } from '../../delivery-adapter.mjs';
27
+ import { createAnnouncedStateStore, createBindingAnnouncer } from '../shared/binding-events.mjs';
27
28
  import { createConnectionSupervisor } from './connection-supervisor.mjs';
28
29
  import { createHarnessCommandExecutor } from '../../harness-command-executor.mjs';
29
30
  import { harnessConnection } from '../../harness-connection.mjs';
@@ -116,14 +117,29 @@ export async function createProductionController(ctx, config = {}, internals = {
116
117
  const stateStores = new Map();
117
118
 
118
119
  const statePath = (botId) => resolve(paths.accounts, botId, 'state.json');
119
- const stateFor = async (botId) => {
120
- let state = stateStores.get(botId);
121
- if (!state) {
122
- state = await new StateStore(statePath(botId)).load();
123
- stateStores.set(botId, state);
124
- }
125
- return state;
126
- };
120
+ /**
121
+ * Every binding change is announced the moment it is written: a bind before the
122
+ * Session exists, an unbind when the conversation moves to another session or
123
+ * its binding is cleared. Listeners run synchronously.
124
+ */
125
+ const announcer = createBindingAnnouncer({
126
+ channel: 'weixin',
127
+ emit: (event, payload) => ctx.emit(event, payload),
128
+ authorsOf: (botId) => (typeof stateStores.get(botId)?.snapshot === 'function'
129
+ ? stateStores.get(botId).snapshot()?.authors ?? null
130
+ : null),
131
+ });
132
+ const { stateFor, stateForSync, prime, forget } = createAnnouncedStateStore({
133
+ announcer,
134
+ StateStore,
135
+ statePath,
136
+ states: stateStores,
137
+ logger,
138
+ });
139
+ // Warm the per-bot state memo now: the synchronous identity lookup can only
140
+ // answer from state that is already loaded in this process, and the first prompt
141
+ // of a session arrives long before any delivery call would load it.
142
+ await prime(configuredBots.map((bot) => bot.botId));
127
143
  const commandExecutor = createHarnessCommandExecutor(ctx, internals.commandExecutor);
128
144
  const inboundTtl = internals.inboundTtl ?? getInboundTtlRuntime(ctx, config);
129
145
  const inboundTtlService = inboundTtl?.service ?? inboundTtl;
@@ -189,8 +205,8 @@ export async function createProductionController(ctx, config = {}, internals = {
189
205
  });
190
206
  },
191
207
  deleteState: async ({ botId }) => {
192
- const state = stateStores.get(botId);
193
- stateStores.delete(botId);
208
+ const state = stateForSync(botId);
209
+ forget(botId);
194
210
  if (state && typeof state.remove === 'function') {
195
211
  await state.remove();
196
212
  } else {
@@ -239,6 +255,8 @@ export async function createProductionController(ctx, config = {}, internals = {
239
255
  controller,
240
256
  deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
241
257
  channel: 'weixin', workspaces, coreController, stateFor,
258
+ // The same store, without the await: it is a memo of already loaded bots.
259
+ stateForSync,
242
260
  }),
243
261
  ready: supervisor.ready,
244
262
  async close() {
@@ -1,7 +1,8 @@
1
1
  import { SET_MESSAGE_MODE_ENDPOINT, validMessageModePayload } from '../../../../src/channels/shared/message-mode.mjs';
2
+ import { SET_REPLY_CONTENT_ENDPOINT, validReplyContentPayload } from '../shared/reply-content-rpc.mjs';
2
3
  import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
3
4
  import { registerManagementRpc } from '../../../management-rpc.mjs';
4
- import QRCode from 'qrcode';
5
+ import QRCode from '../../../../src/channels/shared/qrcode.mjs';
5
6
  import { qrEncodingError } from '../../../../src/channels/shared/qr-encoding-error.mjs';
6
7
  import { createWeixinDiagnostics, weixinStageError } from '../../../../src/channels/weixin/connection-error.mjs';
7
8
  import { SET_CONTEXT_ENHANCEMENT_ENDPOINT, validContextEnhancementPayload } from '../shared/context-enhancement-rpc.mjs';
@@ -35,6 +36,7 @@ export const WEIXIN_ENDPOINTS = Object.freeze({
35
36
  setAgentPreset: SET_AGENT_PRESET_ENDPOINT,
36
37
  setContextEnhancement: SET_CONTEXT_ENHANCEMENT_ENDPOINT,
37
38
  setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
39
+ setReplyContent: SET_REPLY_CONTENT_ENDPOINT,
38
40
  setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
39
41
  setAlias: SET_ALIAS_ENDPOINT,
40
42
  });
@@ -98,6 +100,10 @@ function payloadFailure(endpoint, payload) {
98
100
  return validAgentPresetPayload(payload)
99
101
  ? null : '请选择 Agent Preset。';
100
102
  }
103
+ if (endpoint === WEIXIN_ENDPOINTS.setReplyContent) {
104
+ return validReplyContentPayload(payload)
105
+ ? null : '请选择要投递的回复内容。';
106
+ }
101
107
  if (endpoint === WEIXIN_ENDPOINTS.setBusyMessageMode) {
102
108
  return validMessageModePayload(payload)
103
109
  ? null : '请提交有效的消息处理方式。';
@@ -242,6 +248,9 @@ export function createWeixinRpcHandler(controller, { encodeQr = qrDataUrl, logge
242
248
  await controller.updateModel(payload.botId, payload.model),
243
249
  cachedEncode,
244
250
  );
251
+ } else if (endpoint === WEIXIN_ENDPOINTS.setReplyContent) {
252
+ if (typeof controller.updateReplyContent !== 'function') throw new Error('Reply content update is unavailable');
253
+ value = await controller.updateReplyContent(payload.botId, payload.replyContent);
245
254
  } else if (endpoint === WEIXIN_ENDPOINTS.setBusyMessageMode) {
246
255
  if (typeof controller.updateBusyMessageMode !== 'function') throw new Error('Message mode update is unavailable');
247
256
  value = await controller.updateBusyMessageMode(
@@ -23,6 +23,7 @@ import { prepareBotWorkspace } from '../../../../src/channels/shared/default-wor
23
23
  import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-preset.mjs';
24
24
  import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
25
25
  import { createDeliveryAdapter } from '../../delivery-adapter.mjs';
26
+ import { createAnnouncedStateStore, createBindingAnnouncer } from '../shared/binding-events.mjs';
26
27
  import { createTokenConnectionSupervisor } from '../shared/connection-supervisor.mjs';
27
28
  import { createHarnessCommandExecutor } from '../../harness-command-executor.mjs';
28
29
  import { harnessConnection } from '../../harness-connection.mjs';
@@ -83,14 +84,29 @@ export async function createProductionController(ctx, config = {}, internals = {
83
84
  : configStore;
84
85
  const stateStores = new Map();
85
86
  const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
86
- const stateFor = async (botId) => {
87
- let state = stateStores.get(botId);
88
- if (!state) {
89
- state = await new StateStore(statePath(botId)).load();
90
- stateStores.set(botId, state);
91
- }
92
- return state;
93
- };
87
+ /**
88
+ * Every binding change is announced the moment it is written: a bind before the
89
+ * Session exists, an unbind when the conversation moves to another session or
90
+ * its binding is cleared. Listeners run synchronously.
91
+ */
92
+ const announcer = createBindingAnnouncer({
93
+ channel: 'whatsapp',
94
+ emit: (event, payload) => ctx.emit(event, payload),
95
+ authorsOf: (botId) => (typeof stateStores.get(botId)?.snapshot === 'function'
96
+ ? stateStores.get(botId).snapshot()?.authors ?? null
97
+ : null),
98
+ });
99
+ const { stateFor, stateForSync, prime, forget } = createAnnouncedStateStore({
100
+ announcer,
101
+ StateStore,
102
+ statePath,
103
+ states: stateStores,
104
+ logger,
105
+ });
106
+ // Warm the per-bot state memo now: the synchronous identity lookup can only
107
+ // answer from state that is already loaded in this process, and the first prompt
108
+ // of a session arrives long before any delivery call would load it.
109
+ await prime(configuredBots.map((bot) => bot.botId));
94
110
  const commandExecutor = createHarnessCommandExecutor(ctx, internals.commandExecutor);
95
111
  const inboundTtl = internals.inboundTtl ?? getInboundTtlRuntime(ctx, config);
96
112
  const inboundTtlService = inboundTtl?.service ?? inboundTtl;
@@ -159,8 +175,8 @@ export async function createProductionController(ctx, config = {}, internals = {
159
175
  force: true,
160
176
  }),
161
177
  deleteState: async ({ botId }) => {
162
- const state = stateStores.get(botId);
163
- stateStores.delete(botId);
178
+ const state = stateForSync(botId);
179
+ forget(botId);
164
180
  if (state && typeof state.remove === 'function') {
165
181
  await state.remove();
166
182
  } else {
@@ -191,6 +207,8 @@ export async function createProductionController(ctx, config = {}, internals = {
191
207
  controller,
192
208
  deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
193
209
  channel: 'whatsapp', workspaces, coreController, stateFor,
210
+ // The same store, without the await: it is a memo of already loaded bots.
211
+ stateForSync,
194
212
  }),
195
213
  ready: supervisor.ready,
196
214
  async close() {
@@ -1,8 +1,9 @@
1
1
  import { SET_MESSAGE_MODE_ENDPOINT, validMessageModePayload } from '../../../../src/channels/shared/message-mode.mjs';
2
+ import { SET_REPLY_CONTENT_ENDPOINT, validReplyContentPayload } from '../shared/reply-content-rpc.mjs';
2
3
  import { createConnectionDiagnostics, diagnosticRpcResult } from '../../../../src/channels/shared/connection-error.mjs';
3
4
  import { SET_ALIAS_ENDPOINT, validAliasPayload } from '../shared/bot-alias-rpc.mjs';
4
5
  import { registerManagementRpc } from '../../../management-rpc.mjs';
5
- import QRCode from 'qrcode';
6
+ import QRCode from '../../../../src/channels/shared/qrcode.mjs';
6
7
  import { qrEncodingError } from '../../../../src/channels/shared/qr-encoding-error.mjs';
7
8
 
8
9
  import { publicConnectionTestResult } from '../../../../src/channels/shared/connection-test.mjs';
@@ -28,6 +29,7 @@ export const WHATSAPP_ENDPOINTS = Object.freeze({
28
29
  setAgentPreset: SET_AGENT_PRESET_ENDPOINT,
29
30
  setContextEnhancement: SET_CONTEXT_ENHANCEMENT_ENDPOINT,
30
31
  setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
32
+ setReplyContent: SET_REPLY_CONTENT_ENDPOINT,
31
33
  });
32
34
  export const WHATSAPP_RPC_ENDPOINTS = Object.freeze(Object.values(WHATSAPP_ENDPOINTS));
33
35
 
@@ -82,6 +84,10 @@ function payloadFailure(endpoint, payload) {
82
84
  return validAgentPresetPayload(payload)
83
85
  ? null : '请选择 Agent Preset。';
84
86
  }
87
+ if (endpoint === WHATSAPP_ENDPOINTS.setReplyContent) {
88
+ return validReplyContentPayload(payload)
89
+ ? null : '请选择要投递的回复内容。';
90
+ }
85
91
  if (endpoint === WHATSAPP_ENDPOINTS.setBusyMessageMode) {
86
92
  return validMessageModePayload(payload)
87
93
  ? null : '请提交有效的消息处理方式。';
@@ -202,6 +208,9 @@ export function createWhatsappRpcHandler(controller, { encodeQr = qrDataUrl } =
202
208
  await controller.updateModel(payload.botId, payload.model),
203
209
  cachedEncode,
204
210
  );
211
+ } else if (endpoint === WHATSAPP_ENDPOINTS.setReplyContent) {
212
+ if (typeof controller.updateReplyContent !== 'function') throw new Error('Reply content update is unavailable');
213
+ value = await controller.updateReplyContent(payload.botId, payload.replyContent);
205
214
  } else if (endpoint === WHATSAPP_ENDPOINTS.setBusyMessageMode) {
206
215
  if (typeof controller.updateBusyMessageMode !== 'function') throw new Error('Message mode update is unavailable');
207
216
  value = await controller.updateBusyMessageMode(
@@ -1,9 +1,11 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import {
3
+ conversationKeyMatchesTarget,
4
+ deliverySuggestionFromConversationKey,
3
5
  deliverySuggestionsFromSessions,
4
6
  privateConversationKeyMatchesTarget,
5
7
  privateDeliverySuggestionFromConversationKey,
6
- resolvePrivateConversationKey,
8
+ resolveConversationKey,
7
9
  } from './delivery-suggestions.mjs';
8
10
  import { parseConversationKey } from '../../src/channels/shared/conversation/describe.mjs';
9
11
  import { withSessionBindingLock } from '../../src/channels/shared/session-binding-lock.mjs';
@@ -196,8 +198,8 @@ function sessionSyncConfigs(workspaces, botId) {
196
198
  return botId === undefined ? targets : targets.filter((target) => target.botId === botId);
197
199
  }
198
200
 
199
- /** Bindings own their private-chat sync while active. Ordinary delivery
200
- * settings remain saved and resume after unbinding, without duplicate mirrors. */
201
+ /** Bindings own their chat sync while active. Ordinary delivery settings remain
202
+ * saved and resume after unbinding, without duplicate mirrors. */
201
203
  export function configuredSessionSyncTargets(workspaces, botId) {
202
204
  const bindings = (workspaces.listDsBotBindings?.(botId) ?? []).map((binding) => ({
203
205
  ...binding,
@@ -214,7 +216,7 @@ export function configuredSessionSyncTargets(workspaces, botId) {
214
216
  export function sessionSyncTarget(channel, workspaces, configured) {
215
217
  if (!configured) return null;
216
218
  if (!configured.dsBotId) return workspaces.deliveryTargetFor(configured.botId, configured.targetId);
217
- const target = privateDeliverySuggestionFromConversationKey(channel, configured.conversationKey);
219
+ const target = deliverySuggestionFromConversationKey(channel, configured.conversationKey);
218
220
  return target ? { ...target, targetId: configured.targetId } : null;
219
221
  }
220
222
 
@@ -305,11 +307,7 @@ function stateSessions(state) {
305
307
 
306
308
  function sessionSyncView(channel, target, sessions, configured) {
307
309
  if (configured) {
308
- const valid = privateConversationKeyMatchesTarget(
309
- channel,
310
- configured.conversationKey,
311
- target,
312
- );
310
+ const valid = conversationKeyMatchesTarget(channel, configured.conversationKey, target);
313
311
  if (!valid || !sessions) return { enabled: true, state: 'unavailable' };
314
312
  return {
315
313
  enabled: true,
@@ -320,7 +318,7 @@ function sessionSyncView(channel, target, sessions, configured) {
320
318
  };
321
319
  }
322
320
  const conversationKey = sessions
323
- ? resolvePrivateConversationKey(channel, sessions, target)
321
+ ? resolveConversationKey(channel, sessions, target)
324
322
  : null;
325
323
  return { enabled: false, state: conversationKey ? 'off' : 'unavailable' };
326
324
  }
@@ -344,11 +342,20 @@ export function createDeliveryAdapter({
344
342
  if (typeof stateFor !== 'function') {
345
343
  throw new TypeError('delivery adapter requires a bot state getter');
346
344
  }
347
- const syncTarget = async (botId, targetId, sessionId, { allowParts = true } = {}) => {
345
+ const syncTarget = async (botId, targetId, sessionId, { allowParts = true, privateOnly = false } = {}) => {
348
346
  const configured = configuredSessionSyncTargets(workspaces, botId).find((entry) => entry.targetId === targetId);
349
347
  const target = sessionSyncTarget(channel, workspaces, configured);
350
- if (!configured || !target || !privateConversationKeyMatchesTarget(channel, configured.conversationKey, target)) {
351
- throw sessionSyncUnavailable('Session sync target is no longer enabled');
348
+ // Mirrored text may follow any route the channel persists. A synced question
349
+ // or approval is different: it is answered by whoever reads the chat, so
350
+ // those two paths keep the private-only gate — a group, a thread or a forum
351
+ // topic never becomes a place where anyone can answer for the reader.
352
+ const keyMatches = privateOnly
353
+ ? privateConversationKeyMatchesTarget(channel, configured?.conversationKey, target)
354
+ : conversationKeyMatchesTarget(channel, configured?.conversationKey, target);
355
+ if (!configured || !target || !keyMatches) {
356
+ throw sessionSyncUnavailable(privateOnly
357
+ ? 'Session sync questions and approvals need one private chat'
358
+ : 'Session sync target is no longer enabled');
352
359
  }
353
360
  const sessions = stateSessions(await stateFor(botId));
354
361
  const bot = configured.dsBotId ? await dsBot?.resolve(configured.dsBotId) : null;
@@ -360,14 +367,15 @@ export function createDeliveryAdapter({
360
367
  }
361
368
  return { target, conversationKey: configured.conversationKey, dsBotId: configured.dsBotId };
362
369
  };
363
- const describeSyncTarget = async (botId, targetId, sessionId) => {
364
- const { conversationKey } = await syncTarget(botId, targetId, sessionId);
370
+ const describeSyncTarget = async (botId, targetId, sessionId, options = {}) => {
371
+ const { conversationKey } = await syncTarget(botId, targetId, sessionId, options);
365
372
  return { conversationKey };
366
373
  };
367
374
  const presentSyncInteraction = async (method, botId, targetId, sessionId, interaction, options = {}) => {
368
375
  // Text from an old part may finish delivery, but a new question answer must
369
- // still belong to the Bot's current session.
370
- const routeOptions = { allowParts: method !== 'presentSessionSyncQuestion' };
376
+ // still belong to the Bot's current session, and both interactions stay
377
+ // private-chat only.
378
+ const routeOptions = { allowParts: method !== 'presentSessionSyncQuestion', privateOnly: true };
371
379
  const original = await syncTarget(botId, targetId, sessionId, routeOptions);
372
380
  if (typeof coreController[method] !== 'function') return false;
373
381
  const validate = async () => {
@@ -568,7 +576,7 @@ export function createDeliveryAdapter({
568
576
  return sessionSyncView(channel, target, sessions, null);
569
577
  }
570
578
  const sessions = stateSessions(await stateFor(botId));
571
- const conversationKey = resolvePrivateConversationKey(channel, sessions, target);
579
+ const conversationKey = resolveConversationKey(channel, sessions, target);
572
580
  if (!conversationKey) throw sessionSyncUnavailable();
573
581
  await workspaces.setDeliveryTargetSessionSync(botId, targetId, conversationKey);
574
582
  return { enabled: true, state: 'active' };
@@ -580,6 +588,9 @@ export function createDeliveryAdapter({
580
588
  const matches = [];
581
589
  for (const configured of configuredSessionSyncTargets(workspaces)) {
582
590
  const target = sessionSyncTarget(channel, workspaces, configured);
591
+ // Listed targets are the candidate range of synced questions and
592
+ // approvals only, so a non-private route never appears here even
593
+ // though mirrored text may be delivered to it.
583
594
  if (!target || !privateConversationKeyMatchesTarget(
584
595
  channel,
585
596
  configured.conversationKey,
@@ -599,8 +610,12 @@ export function createDeliveryAdapter({
599
610
  }
600
611
  return matches;
601
612
  },
602
- describeSessionSyncApprovalTarget: describeSyncTarget,
603
- describeSessionSyncQuestionTarget: describeSyncTarget,
613
+ // Both interaction paths resolve their target through the private-only gate,
614
+ // so a synced group or topic is never offered a question or an approval.
615
+ describeSessionSyncApprovalTarget: (botId, targetId, sessionId) =>
616
+ describeSyncTarget(botId, targetId, sessionId, { privateOnly: true }),
617
+ describeSessionSyncQuestionTarget: (botId, targetId, sessionId) =>
618
+ describeSyncTarget(botId, targetId, sessionId, { privateOnly: true }),
604
619
  async presentSessionSyncApproval(botId, targetId, sessionId, interaction, options = {}) {
605
620
  return presentSyncInteraction('presentSessionSyncApproval', botId, targetId, sessionId, interaction, options);
606
621
  },
@@ -1,7 +1,9 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { normalizeDeliveryTarget } from './delivery-adapter.mjs';
3
+ import { deliverySuggestionFromConversationKey } from './delivery-suggestions.mjs';
3
4
  import { COMPETITIVE_APPROVAL_CHANNELS } from '../../src/channels/shared/harness-approval.mjs';
4
5
  import { t } from '../../src/channels/shared/i18n.mjs';
6
+ import { parseConversationKey } from '../../src/channels/shared/conversation/describe.mjs';
5
7
 
6
8
  const BOT_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
7
9
  const TARGET_ID_PATTERN = /^[A-Za-z0-9._:@-]{1,128}$/;
@@ -145,9 +147,10 @@ function sessionSyncState(value, available) {
145
147
  export class DeliveryService {
146
148
  #adapters = new Map();
147
149
  #unavailableSessionSyncChannels;
150
+ #logger;
148
151
  dsBot;
149
152
 
150
- constructor({ unavailableSessionSyncChannels = [], dsBot } = {}) {
153
+ constructor({ unavailableSessionSyncChannels = [], dsBot, logger = console } = {}) {
151
154
  if (!Array.isArray(unavailableSessionSyncChannels)
152
155
  || unavailableSessionSyncChannels.some((channel) => (
153
156
  typeof channel !== 'string' || !CHANNEL_PATTERN.test(channel)
@@ -155,6 +158,7 @@ export class DeliveryService {
155
158
  throw new TypeError('unavailableSessionSyncChannels must contain valid channel ids');
156
159
  }
157
160
  this.#unavailableSessionSyncChannels = new Set(unavailableSessionSyncChannels);
161
+ this.#logger = logger ?? console;
158
162
  this.dsBot = dsBot;
159
163
  }
160
164
 
@@ -503,6 +507,7 @@ export class DeliveryService {
503
507
  }
504
508
 
505
509
  /**
510
+
506
511
  * The same lookup, answered from memory only: no await, no network. A session
507
512
  * whose channel has not loaded its state yet answers null — which is exactly the
508
513
  * truth a synchronous prompt assembly can act on.
@@ -522,6 +527,99 @@ export class DeliveryService {
522
527
  return null;
523
528
  }
524
529
 
530
+ /**
531
+ * The Session no channel state owns may still be a DS Bot's current session:
532
+ * its chat was bound to the bot, the bot's `sessionId` rolled over without a
533
+ * new inbound message, and only the bot service knows the new session. Reverse
534
+ * the binding through `dsBot.status()` so delivery survives that rollover.
535
+ * An unavailable DS Bot, or a session no bot currently owns, answers `null`.
536
+ */
537
+ async describeViaDsBot(sessionId) {
538
+ try {
539
+ const status = await this.dsBot?.status();
540
+ if (status?.state !== 'ready') return null;
541
+ const bot = status.bots.find((entry) => entry.sessionId === sessionId);
542
+ if (!bot) return null;
543
+ for (const { adapter } of this.#adapters.values()) {
544
+ const bindings = await adapter.listDsBotBindings?.() ?? [];
545
+ const binding = bindings.find((entry) => entry.dsBotId === bot.id);
546
+ if (!binding) continue;
547
+ const parsed = parseConversationKey(binding.conversationKey, { channel: adapter.channel });
548
+ return {
549
+ channel: adapter.channel,
550
+ botId: binding.botId,
551
+ botName: bot.name ?? null,
552
+ conversationKey: binding.conversationKey,
553
+ chatType: parsed?.chatType ?? null,
554
+ chatId: parsed?.chatId ?? null,
555
+ threadId: parsed?.threadId ?? null,
556
+ chatTitle: null,
557
+ senderId: null,
558
+ senderName: null,
559
+ senderUsername: null,
560
+ senderIsBot: null,
561
+ };
562
+ }
563
+ return null;
564
+ } catch {
565
+ return null;
566
+ }
567
+ }
568
+
569
+ /**
570
+ * Deliver one text to the chat this Session is currently bound to.
571
+ *
572
+ * The address is not configured anywhere beforehand: `describeConversation`
573
+ * reads the conversation the channel itself keeps for the Session, and its
574
+ * conversation key becomes the same draft route the manual delivery path
575
+ * accepts. A Session no channel owns simply has nowhere to go, which is a
576
+ * result rather than an error; a real send failure is thrown like `send()`.
577
+ *
578
+ * @param {string} sessionId harness session id
579
+ * @param {string} text message body
580
+ * @param {{format?: 'plain'|'markdown', signal?: AbortSignal}} [options]
581
+ * @returns {Promise<{sent: true} | {sent: false, reason: 'unbound'|'unroutable'}>}
582
+ */
583
+ async deliverSessionText(sessionId, text, { format = 'plain', signal } = {}) {
584
+ if (typeof sessionId !== 'string' || !sessionId
585
+ || typeof text !== 'string' || !text.trim()
586
+ || (format !== 'plain' && format !== 'markdown')) {
587
+ throw deliveryError('bad-request', 'Invalid Session delivery');
588
+ }
589
+ cancellation(signal);
590
+ const described = await this.describeConversation(sessionId) ?? await this.describeViaDsBot(sessionId);
591
+ cancellation(signal);
592
+ if (!described) {
593
+ this.#warnUndelivered(sessionId, 'unbound', null);
594
+ return { sent: false, reason: 'unbound' };
595
+ }
596
+ const draft = deliverySuggestionFromConversationKey(described.channel, described.conversationKey);
597
+ if (!draft) {
598
+ // A key the channel persisted but no route covers stays unroutable.
599
+ // Do not guess a parent chat for an unrecognized key: that would drop a
600
+ // thread id and message the wrong place.
601
+ this.#warnUndelivered(sessionId, 'unroutable', described);
602
+ return { sent: false, reason: 'unroutable' };
603
+ }
604
+ // The draft goes through the ordinary send path, so the adapter validates
605
+ // and normalizes it exactly as it does a saved target.
606
+ return this.send(described.botId, { kind: draft.kind, route: draft.route }, text, { signal, format });
607
+ }
608
+
609
+ /**
610
+ * Report one text that found nowhere to go. Only the identifiers that make the
611
+ * miss diagnosable are logged — Session, channel, conversation key — never the
612
+ * message body, and never a channel credential.
613
+ */
614
+ #warnUndelivered(sessionId, reason, described) {
615
+ const where = described
616
+ ? ` channel=${described.channel} conversationKey=${described.conversationKey}`
617
+ : '';
618
+ this.#logger?.warn?.(
619
+ `[dsh-im] Session text was not delivered [${reason}] session=${sessionId}${where}`,
620
+ );
621
+ }
622
+
525
623
  async describeBot(botId) {
526
624
  const id = botIdOf(botId);
527
625
  const registration = await this.#checkedRegistrationFor(id);
@@ -60,12 +60,16 @@ function slackSuggestion(key) {
60
60
  return { kind: 'thread', route: { channelId: match[1], threadTs: match[2] } };
61
61
  }
62
62
 
63
+ // Telegram-only: numeric chat/topic keys can safely prefill Telegram target fields.
64
+ // Other channels must use their native route fields; never turn their keys into Telegram links.
65
+ // A private chat with Topics persists `direct:<chatId>:<threadId>` (the same
66
+ // message_thread_id a forum topic uses). Route that as a topic. Treating it as
67
+ // a plain chat, or as unroutable, either drops the thread or never delivers.
63
68
  function telegramSuggestion(key) {
64
69
  const match = /^(direct|group):(-?\d+)(?::([1-9]\d*))?$/.exec(key);
65
70
  if (!match) return null;
66
71
  const chatId = Number(match[2]);
67
72
  if (!Number.isSafeInteger(chatId)) return null;
68
- if (match[1] === 'direct' && match[3] !== undefined) return null;
69
73
  if (match[3] === undefined) return { kind: 'chat', route: { chatId: match[2] } };
70
74
  const messageThreadId = Number(match[3]);
71
75
  if (!Number.isSafeInteger(messageThreadId) || messageThreadId <= 0) return null;
@@ -192,6 +196,32 @@ export function resolvePrivateConversationKey(channel, sessions, target) {
192
196
  return matches[0] ?? null;
193
197
  }
194
198
 
199
+ /**
200
+ * Check that one saved conversation key still identifies this target route.
201
+ *
202
+ * Unlike the private variant this accepts every route the channel can persist —
203
+ * a Telegram forum topic (`group:<chatId>:<threadId>`), a Slack thread, a
204
+ * Discord channel — because mirrored text is not limited to private chat.
205
+ * Questions and approvals keep the private gate: they are resolved through
206
+ * `privateConversationKeyMatchesTarget` instead of this function.
207
+ */
208
+ export function conversationKeyMatchesTarget(channel, key, target) {
209
+ const suggestionIdentity = routeIdentity(deliverySuggestionFromConversationKey(channel, key));
210
+ return suggestionIdentity !== null && suggestionIdentity === routeIdentity(target);
211
+ }
212
+
213
+ /** Resolve exactly one current conversation of any route kind for a normalized delivery target. */
214
+ export function resolveConversationKey(channel, sessions, target) {
215
+ if (!CHANNELS.has(channel) || !isRecord(sessions)) return null;
216
+ const matches = [];
217
+ for (const [key, sessionId] of Object.entries(sessions)) {
218
+ if (typeof sessionId !== 'string' || !sessionId) continue;
219
+ if (conversationKeyMatchesTarget(channel, key, target)) matches.push(key);
220
+ if (matches.length > 1) return null;
221
+ }
222
+ return matches[0] ?? null;
223
+ }
224
+
195
225
  /**
196
226
  * Extract and de-duplicate stable delivery routes from a persisted sessions map.
197
227
  * Session ids and every other state field are intentionally ignored.