@xmanrui/dsh-im 5.10.0 → 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 (114) hide show
  1. package/README.en.md +39 -5
  2. package/README.md +42 -5
  3. package/bin/dsh-im.mjs +65 -0
  4. package/docs/client-integration.md +4 -0
  5. package/lib/client.js +1202 -95
  6. package/lib/index.js +365 -339
  7. package/package.json +7 -6
  8. package/plugin-src/client/access-policy-settings.js +210 -12
  9. package/plugin-src/client/bot-general-settings.js +44 -3
  10. package/plugin-src/client/i18n-ru.js +85 -0
  11. package/plugin-src/client/i18n.js +83 -0
  12. package/plugin-src/client/im-channels.js +419 -0
  13. package/plugin-src/client/index.js +33 -1
  14. package/plugin-src/client/styles.js +7 -7
  15. package/plugin-src/client/update-panel.js +2 -1
  16. package/plugin-src/host/channel-list-rpc.mjs +280 -0
  17. package/plugin-src/host/channels/dingtalk/production.mjs +28 -10
  18. package/plugin-src/host/channels/dingtalk/rpc.mjs +10 -1
  19. package/plugin-src/host/channels/feishu/production.mjs +39 -10
  20. package/plugin-src/host/channels/feishu/rpc.mjs +10 -1
  21. package/plugin-src/host/channels/matrix/production.mjs +28 -10
  22. package/plugin-src/host/channels/matrix/rpc.mjs +10 -0
  23. package/plugin-src/host/channels/qq/production.mjs +30 -11
  24. package/plugin-src/host/channels/qq/rpc.mjs +10 -1
  25. package/plugin-src/host/channels/shared/access-policy-production.mjs +9 -0
  26. package/plugin-src/host/channels/shared/binding-events.mjs +109 -0
  27. package/plugin-src/host/channels/shared/production.mjs +14 -1
  28. package/plugin-src/host/channels/shared/reply-content-rpc.mjs +17 -0
  29. package/plugin-src/host/channels/shared/rpc.mjs +9 -0
  30. package/plugin-src/host/channels/slack/production.mjs +28 -10
  31. package/plugin-src/host/channels/slack/rpc.mjs +10 -0
  32. package/plugin-src/host/channels/telegram/production.mjs +5 -0
  33. package/plugin-src/host/channels/wecom/production.mjs +28 -10
  34. package/plugin-src/host/channels/wecom/rpc.mjs +10 -1
  35. package/plugin-src/host/channels/wecom-app/production.mjs +28 -10
  36. package/plugin-src/host/channels/wecom-app/rpc.mjs +9 -0
  37. package/plugin-src/host/channels/weixin/production.mjs +28 -10
  38. package/plugin-src/host/channels/weixin/rpc.mjs +10 -1
  39. package/plugin-src/host/channels/whatsapp/production.mjs +28 -10
  40. package/plugin-src/host/channels/whatsapp/rpc.mjs +10 -1
  41. package/plugin-src/host/delivery-service.mjs +3 -4
  42. package/plugin-src/host/delivery-suggestions.mjs +3 -1
  43. package/plugin-src/host/harness-connection.mjs +2 -1
  44. package/plugin-src/host/harness-peer.mjs +3 -1
  45. package/plugin-src/host/index.mjs +8 -1
  46. package/plugin-src/host/modern-harness-api.mjs +5 -1
  47. package/plugin-src/host/root-scope.mjs +32 -0
  48. package/plugin-src/host/session-sync-coordinator.mjs +2 -1
  49. package/plugin-src/management-rpc.mjs +18 -2
  50. package/scripts/verify-package.mjs +36 -7
  51. package/src/channels/dingtalk/dingtalk-bridge.mjs +50 -6
  52. package/src/channels/dingtalk/state-store.mjs +56 -0
  53. package/src/channels/discord/discord-api.mjs +2 -1
  54. package/src/channels/feishu/bridge.mjs +154 -58
  55. package/src/channels/feishu/feishu-cards.mjs +10 -4
  56. package/src/channels/feishu/feishu-runtime.mjs +11 -3
  57. package/src/channels/feishu/message-utils.mjs +106 -30
  58. package/src/channels/feishu/slash-command-panel.mjs +26 -0
  59. package/src/channels/feishu/state-store.mjs +14 -0
  60. package/src/channels/matrix/matrix-api.mjs +2 -1
  61. package/src/channels/qq/qq-bridge.mjs +105 -14
  62. package/src/channels/qq/state-store.mjs +13 -1
  63. package/src/channels/shared/access-policy.mjs +60 -7
  64. package/src/channels/shared/bot-workspace-store.mjs +155 -3
  65. package/src/channels/shared/busy-message-dispatcher.mjs +2 -2
  66. package/src/channels/shared/channel-capabilities.mjs +44 -0
  67. package/src/channels/shared/command-catalog.mjs +68 -3
  68. package/src/channels/shared/command-permission.mjs +6 -2
  69. package/src/channels/shared/conversation-state-store.mjs +16 -0
  70. package/src/channels/shared/deferred-delivery-coordinator.mjs +6 -1
  71. package/src/channels/shared/deferred-delivery.mjs +4 -0
  72. package/src/channels/shared/diagnostic-details.mjs +6 -1
  73. package/src/channels/shared/failure-log-file.mjs +79 -0
  74. package/src/channels/shared/harness-client.mjs +111 -6
  75. package/src/channels/shared/i18n-en/feishu.mjs +2 -2
  76. package/src/channels/shared/i18n-en/shared-a.mjs +13 -2
  77. package/src/channels/shared/i18n-en/shared-b.mjs +67 -4
  78. package/src/channels/shared/i18n-en/shared-d.mjs +144 -0
  79. package/src/channels/shared/i18n-en/weixin.mjs +4 -0
  80. package/src/channels/shared/i18n-en.mjs +2 -0
  81. package/src/channels/shared/i18n-ru/feishu.mjs +2 -2
  82. package/src/channels/shared/i18n-ru/shared-a.mjs +13 -2
  83. package/src/channels/shared/i18n-ru/shared-b.mjs +67 -4
  84. package/src/channels/shared/i18n-ru/shared-d.mjs +144 -0
  85. package/src/channels/shared/i18n-ru/weixin.mjs +4 -0
  86. package/src/channels/shared/i18n-ru.mjs +2 -0
  87. package/src/channels/shared/inbound-access.mjs +10 -0
  88. package/src/channels/shared/markdown-chunks.mjs +5 -0
  89. package/src/channels/shared/message-failure.mjs +22 -1
  90. package/src/channels/shared/new-command.mjs +158 -4
  91. package/src/channels/shared/plan-goal-command.mjs +132 -0
  92. package/src/channels/shared/qrcode.mjs +5 -0
  93. package/src/channels/shared/reply-content.mjs +102 -0
  94. package/src/channels/shared/reset-command.mjs +46 -0
  95. package/src/channels/shared/semantic/artifact.mjs +133 -29
  96. package/src/channels/shared/semantic/reply-reference.mjs +18 -3
  97. package/src/channels/shared/session-nav-command.mjs +999 -0
  98. package/src/channels/shared/session-ring-support.mjs +184 -0
  99. package/src/channels/shared/session-ring.mjs +202 -0
  100. package/src/channels/shared/session-title.mjs +11 -0
  101. package/src/channels/shared/status-command.mjs +2 -1
  102. package/src/channels/shared/text-harness-bridge.mjs +166 -7
  103. package/src/channels/shared/workspace-command.mjs +567 -31
  104. package/src/channels/shared/workspace-session.mjs +39 -3
  105. package/src/channels/slack/slack-api.mjs +2 -1
  106. package/src/channels/telegram/config-store.mjs +10 -2
  107. package/src/channels/telegram/telegram-rich-message.mjs +17 -5
  108. package/src/channels/telegram/telegram-runtime.mjs +14 -1
  109. package/src/channels/wecom/state-store.mjs +13 -1
  110. package/src/channels/wecom/wecom-bridge.mjs +183 -26
  111. package/src/channels/wecom-app/state-store.mjs +13 -1
  112. package/src/channels/wecom-app/wecom-app-bridge.mjs +44 -4
  113. package/src/channels/weixin/state-store.mjs +13 -1
  114. package/src/channels/weixin/weixin-bridge.mjs +71 -4
@@ -20,6 +20,7 @@ import { prepareBotWorkspace } from '../../../../src/channels/shared/default-wor
20
20
  import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-preset.mjs';
21
21
  import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
22
22
  import { createDeliveryAdapter } from '../../delivery-adapter.mjs';
23
+ import { createAnnouncedStateStore, createBindingAnnouncer } from '../shared/binding-events.mjs';
23
24
  import { createConnectionSupervisor } from './connection-supervisor.mjs';
24
25
  import { createHarnessCommandExecutor } from '../../harness-command-executor.mjs';
25
26
  import { harnessConnection } from '../../harness-connection.mjs';
@@ -75,14 +76,30 @@ export async function createProductionController(ctx, config = {}, internals = {
75
76
  const qrAuth = internals.qrAuth ?? new QrAuth({ source: config.qrSource ?? 'deepseek-harness' });
76
77
  const stateStores = new Map();
77
78
  const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
78
- const stateFor = async (botId) => {
79
- let state = stateStores.get(botId);
80
- if (!state) {
81
- state = await new StateStore(statePath(botId), { logger }).load();
82
- stateStores.set(botId, state);
83
- }
84
- return state;
85
- };
79
+ /**
80
+ * Every binding change is announced the moment it is written: a bind before the
81
+ * Session exists, an unbind when the conversation moves to another session or
82
+ * its binding is cleared. Listeners run synchronously.
83
+ */
84
+ const announcer = createBindingAnnouncer({
85
+ channel: 'qq',
86
+ emit: (event, payload) => ctx.emit(event, payload),
87
+ authorsOf: (botId) => (typeof stateStores.get(botId)?.snapshot === 'function'
88
+ ? stateStores.get(botId).snapshot()?.authors ?? null
89
+ : null),
90
+ });
91
+ const { stateFor, stateForSync, prime, forget } = createAnnouncedStateStore({
92
+ announcer,
93
+ StateStore,
94
+ statePath,
95
+ storeOptions: { logger },
96
+ states: stateStores,
97
+ logger,
98
+ });
99
+ // Warm the per-bot state memo now: the synchronous identity lookup can only
100
+ // answer from state that is already loaded in this process, and the first prompt
101
+ // of a session arrives long before any delivery call would load it.
102
+ await prime(configuredBots.map((bot) => bot.botId));
86
103
  const commandExecutor = createHarnessCommandExecutor(ctx, internals.commandExecutor);
87
104
  const inboundTtl = internals.inboundTtl ?? getInboundTtlRuntime(ctx, config);
88
105
  const inboundTtlService = inboundTtl?.service ?? inboundTtl;
@@ -146,8 +163,8 @@ export async function createProductionController(ctx, config = {}, internals = {
146
163
  });
147
164
  },
148
165
  deleteState: async ({ botId }) => {
149
- const state = stateStores.get(botId);
150
- stateStores.delete(botId);
166
+ const state = stateForSync(botId);
167
+ forget(botId);
151
168
  if (state && typeof state.remove === 'function') {
152
169
  await state.remove();
153
170
  } else {
@@ -175,7 +192,9 @@ export async function createProductionController(ctx, config = {}, internals = {
175
192
  }).start();
176
193
  return {
177
194
  controller,
178
- deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot, channel: 'qq', workspaces, coreController, stateFor }),
195
+ deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot, channel: 'qq', workspaces, coreController, stateFor,
196
+ // The same store, without the await: it is a memo of already loaded bots.
197
+ stateForSync }),
179
198
  ready: supervisor.ready,
180
199
  async close() {
181
200
  await supervisor.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
  import {
8
9
  connectionTestTargetUnavailable,
@@ -30,6 +31,7 @@ export const QQ_ENDPOINTS = Object.freeze({
30
31
  setAgentPreset: SET_AGENT_PRESET_ENDPOINT,
31
32
  setContextEnhancement: SET_CONTEXT_ENHANCEMENT_ENDPOINT,
32
33
  setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
34
+ setReplyContent: SET_REPLY_CONTENT_ENDPOINT,
33
35
  setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
34
36
  setAlias: SET_ALIAS_ENDPOINT,
35
37
  });
@@ -93,6 +95,10 @@ function payloadFailure(endpoint, payload) {
93
95
  return validAgentPresetPayload(payload)
94
96
  ? null : '请选择 Agent Preset。';
95
97
  }
98
+ if (endpoint === QQ_ENDPOINTS.setReplyContent) {
99
+ return validReplyContentPayload(payload)
100
+ ? null : '请选择要投递的回复内容。';
101
+ }
96
102
  if (endpoint === QQ_ENDPOINTS.setBusyMessageMode) {
97
103
  return validMessageModePayload(payload)
98
104
  ? null : '请提交有效的消息处理方式。';
@@ -214,6 +220,9 @@ export function createQqRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
214
220
  await controller.updateModel(payload.botId, payload.model),
215
221
  cachedEncode,
216
222
  );
223
+ } else if (endpoint === QQ_ENDPOINTS.setReplyContent) {
224
+ if (typeof controller.updateReplyContent !== 'function') throw new Error('Reply content update is unavailable');
225
+ value = await controller.updateReplyContent(payload.botId, payload.replyContent);
217
226
  } else if (endpoint === QQ_ENDPOINTS.setBusyMessageMode) {
218
227
  if (typeof controller.updateBusyMessageMode !== 'function') throw new Error('Message mode update is unavailable');
219
228
  value = await controller.updateBusyMessageMode(
@@ -104,6 +104,15 @@ export function initialAccessPolicyFor(channel, config = {}) {
104
104
  */
105
105
  export function newBotAccessPolicyFor(channel, config = {}) {
106
106
  const key = String(channel ?? '').trim().toLowerCase();
107
+ // New Telegram bots must not implicitly admit every group participant.
108
+ // Saved policies and the legacy migration path deliberately remain unchanged.
109
+ if (key === 'telegram') {
110
+ const users = cleanIds(config.allowedUsers);
111
+ return createAccessPolicy({
112
+ direct: allowlistScope(users),
113
+ group: allowlistScope(users),
114
+ });
115
+ }
107
116
  if (key === 'feishu' || key === 'qq') {
108
117
  return createAccessPolicy({ direct: openScope(), group: openScope() });
109
118
  }
@@ -128,3 +128,112 @@ export function createBindingAnnouncer({
128
128
 
129
129
  return { bind, unbind, wrap };
130
130
  }
131
+
132
+ /**
133
+ * The state half of the announcement contract, shared by every channel that
134
+ * assembles its own production controller.
135
+ *
136
+ * A channel loads one state store per bot on demand, and two rules follow from
137
+ * the events above:
138
+ *
139
+ * - the store a conversation binds through must be the wrapped one, otherwise no
140
+ * `session-pre-bind` is ever announced;
141
+ * - the synchronous identity lookup answers only from stores already in memory,
142
+ * so the memo has to be warmed before the first prompt, not by the first
143
+ * delivery.
144
+ *
145
+ * `stateFor(subject)` loads once per key and returns the wrapped store;
146
+ * `stateForSync(subject)` answers from that memo without a single await;
147
+ * `prime(subjects)` warms it and never fails the channel's start.
148
+ *
149
+ * `subject` is what a channel identifies a bot by: a bot id for most of them, a
150
+ * bot configuration where the store path depends on it. `keyOf` turns it into
151
+ * the memo key, and `states` is the memo itself — pass an existing Map to keep
152
+ * the channel's own reference to it, or read the one returned here.
153
+ */
154
+ export function createAnnouncedStateStore({
155
+ announcer,
156
+ StateStore,
157
+ statePath,
158
+ storeOptions = null,
159
+ keyOf = (subject) => String(subject ?? ''),
160
+ states = new Map(),
161
+ logger = null,
162
+ } = {}) {
163
+ if (announcer === null || typeof announcer !== 'object' || typeof announcer.wrap !== 'function') {
164
+ throw new TypeError('announcer is required');
165
+ }
166
+ if (typeof StateStore !== 'function') throw new TypeError('StateStore is required');
167
+ if (typeof statePath !== 'function') throw new TypeError('statePath is required');
168
+ if (typeof keyOf !== 'function') throw new TypeError('keyOf must be a function');
169
+ if (!(states instanceof Map)) throw new TypeError('states must be a Map');
170
+
171
+ // `key -> { token, promise }`. The token identifies the load in flight, so a
172
+ // `forget()` that lands during it wins: a store finished after the bot was
173
+ // deleted must not be memoisd back as if the bot still existed.
174
+ const loading = new Map();
175
+
176
+ const load = async (subject, key) => {
177
+ const path = statePath(subject);
178
+ const options = typeof storeOptions === 'function' ? storeOptions(subject) : storeOptions;
179
+ const store = options === null || options === undefined
180
+ ? await new StateStore(path).load()
181
+ : await new StateStore(path, options).load();
182
+ // The memo only ever holds a wrapped store, so the wrapper is applied once.
183
+ return announcer.wrap(key, store);
184
+ };
185
+
186
+ const stateFor = (subject) => {
187
+ const key = keyOf(subject);
188
+ const loaded = states.get(key);
189
+ if (loaded !== undefined) return Promise.resolve(loaded);
190
+ // Two concurrent callers (a prime and the first delivery, say) share one
191
+ // load: a second store for the same bot would be a second wrapper and a
192
+ // second set of bindings.
193
+ const inFlight = loading.get(key);
194
+ if (inFlight !== undefined) return inFlight.promise;
195
+ const entry = { token: Symbol(key), promise: null };
196
+ entry.promise = load(subject, key).then((store) => {
197
+ if (loading.get(key) === entry) {
198
+ states.set(key, store);
199
+ loading.delete(key);
200
+ }
201
+ return store;
202
+ }, (error) => {
203
+ if (loading.get(key) === entry) loading.delete(key);
204
+ throw error;
205
+ });
206
+ loading.set(key, entry);
207
+ return entry.promise;
208
+ };
209
+
210
+ const stateForSync = (subject) => states.get(keyOf(subject)) ?? null;
211
+
212
+ // A bot whose state cannot be read is that bot's problem: the channel starts,
213
+ // the others answer, and the failure resurfaces on the first use. It is named
214
+ // once here, because a silent miss leaves every session of that bot unknown
215
+ // with nothing in the log to explain why.
216
+ const prime = (subjects) => Promise.all(
217
+ [...(subjects ?? [])].map((subject) => stateFor(subject).catch((error) => {
218
+ try {
219
+ logger?.warn?.(
220
+ `[dsh-im] cannot read the state of ${keyOf(subject)} at start-up:`,
221
+ error?.message ?? error,
222
+ );
223
+ } catch {
224
+ // a logger must never turn a failed read into a failed start
225
+ }
226
+ return null;
227
+ })),
228
+ );
229
+
230
+ // The bot is gone: drop the memo and any load in flight, so neither the memo
231
+ // nor the late resolution can answer identity for it afterwards.
232
+ const forget = (subject) => {
233
+ const key = keyOf(subject);
234
+ states.delete(key);
235
+ loading.delete(key);
236
+ };
237
+
238
+ return { stateFor, stateForSync, prime, forget, states };
239
+ }
@@ -22,6 +22,10 @@ import {
22
22
  import { prepareBotWorkspace } from '../../../../src/channels/shared/default-workspace.mjs';
23
23
  import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-preset.mjs';
24
24
  import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
25
+ import {
26
+ SHARED_COMMAND_CATALOG,
27
+ availableCommandCatalog,
28
+ } from '../../../../src/channels/shared/command-catalog.mjs';
25
29
  import {
26
30
  createDeliveryAdapter,
27
31
  supportsDeliveryChannel,
@@ -64,6 +68,11 @@ export async function createTokenProductionController(ctx, config, internals, de
64
68
  // Telegram is the only token channel with a legacy access model. Other
65
69
  // current token channels preserve their fully-open baseline.
66
70
  : (bot) => initialAccessPolicyFor(channel === 'telegram' ? 'telegram' : 'discord', bot);
71
+ // Startup must retain the channel's migration/recovery seed for configured bots.
72
+ // Only a workspace first created after startup uses the onboarding default.
73
+ const newBotAccessPolicy = typeof definitions.newBotAccessPolicyForBot === 'function'
74
+ ? definitions.newBotAccessPolicyForBot
75
+ : seedAccessPolicy;
67
76
  const logger = typeof ctx.logger === 'function'
68
77
  ? ctx.logger(`dsh-im:${channel}`) : (ctx.logger ?? console);
69
78
  const agentPresetCatalog = () => listAgentPresetCatalog(ctx);
@@ -90,7 +99,7 @@ export async function createTokenProductionController(ctx, config, internals, de
90
99
  // repeat: ensure() only seeds the policy when the bot has none yet.
91
100
  const ensureWorkspace = (botId, botConfig) => workspaces.ensure(botId, {
92
101
  defaultAgentPreset: config.agentPreset,
93
- initialAccessPolicy: seedAccessPolicy(botConfig),
102
+ initialAccessPolicy: newBotAccessPolicy(botConfig),
94
103
  });
95
104
  const stateStores = new Map();
96
105
  const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
@@ -208,6 +217,10 @@ export async function createTokenProductionController(ctx, config, internals, de
208
217
  ...(typeof createTransport === 'function' ? { createTransport } : {}),
209
218
  harness: workspaceScope.harness,
210
219
  state: workspaceScope.state,
220
+ // Hide /fork when the host facade cannot actually branch a session.
221
+ commandCatalog: availableCommandCatalog(SHARED_COMMAND_CATALOG, {
222
+ supportsFork: harness.supportsSessionFork?.(),
223
+ }),
211
224
  groupHistory: internals.groupHistory ?? (['telegram', 'discord'].includes(channel) ? getGroupHistoryStore(ctx, config) : undefined),
212
225
  // A transport that carries voice notes composes its own transcriber
213
226
  // from Host services; without one voice messages stay textless.
@@ -0,0 +1,17 @@
1
+ import { isReplyContent } from '../../../../src/channels/shared/reply-content.mjs';
2
+
3
+ export { SET_REPLY_CONTENT_ENDPOINT } from '../../../../src/channels/shared/reply-content.mjs';
4
+
5
+ /**
6
+ * `{ botId, replyContent: { narration, tools, thinking } }` and nothing else.
7
+ * Every switch must be a boolean: the settings page sends the whole set, so a
8
+ * partial set means the caller lost state rather than asked for a change.
9
+ */
10
+ export function validReplyContentPayload(payload) {
11
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)
12
+ || Reflect.ownKeys(payload).length !== 2
13
+ || !Object.hasOwn(payload, 'botId') || !Object.hasOwn(payload, 'replyContent')
14
+ || typeof payload.botId !== 'string'
15
+ || !/^[A-Za-z0-9_-]{1,128}$/.test(payload.botId)) return false;
16
+ return isReplyContent(payload.replyContent);
17
+ }
@@ -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 './reply-content-rpc.mjs';
2
3
  import { createConnectionDiagnostics, diagnosticRpcResult } from '../../../../src/channels/shared/connection-error.mjs';
3
4
  import { SET_ALIAS_ENDPOINT, validAliasPayload } from './bot-alias-rpc.mjs';
4
5
  import { registerManagementRpc } from '../../../management-rpc.mjs';
@@ -30,6 +31,7 @@ export const TOKEN_BOT_ENDPOINTS = Object.freeze({
30
31
  setAgentPreset: SET_AGENT_PRESET_ENDPOINT,
31
32
  setContextEnhancement: SET_CONTEXT_ENHANCEMENT_ENDPOINT,
32
33
  setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
34
+ setReplyContent: SET_REPLY_CONTENT_ENDPOINT,
33
35
  setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
34
36
  setAlias: SET_ALIAS_ENDPOINT,
35
37
  setThinkingTraces: SET_THINKING_TRACES_ENDPOINT,
@@ -93,6 +95,10 @@ function payloadFailure(endpoint, payload) {
93
95
  return validAgentPresetPayload(payload)
94
96
  ? null : '请选择 Agent Preset。';
95
97
  }
98
+ if (endpoint === TOKEN_BOT_ENDPOINTS.setReplyContent) {
99
+ return validReplyContentPayload(payload)
100
+ ? null : '请选择要投递的回复内容。';
101
+ }
96
102
  if (endpoint === TOKEN_BOT_ENDPOINTS.setBusyMessageMode) {
97
103
  return validMessageModePayload(payload)
98
104
  ? null : '请提交有效的消息处理方式。';
@@ -206,6 +212,9 @@ export function createTokenBotRpcHandler(controller, { channel }) {
206
212
  } else if (endpoint === TOKEN_BOT_ENDPOINTS.setModel) {
207
213
  if (typeof controller.updateModel !== 'function') throw new Error('Model update is unavailable');
208
214
  value = await controller.updateModel(payload.botId, payload.model);
215
+ } else if (endpoint === TOKEN_BOT_ENDPOINTS.setReplyContent) {
216
+ if (typeof controller.updateReplyContent !== 'function') throw new Error('Reply content update is unavailable');
217
+ value = await controller.updateReplyContent(payload.botId, payload.replyContent);
209
218
  } else if (endpoint === TOKEN_BOT_ENDPOINTS.setBusyMessageMode) {
210
219
  if (typeof controller.updateBusyMessageMode !== 'function') throw new Error('Message mode update is unavailable');
211
220
  value = await controller.updateBusyMessageMode(payload.botId, payload.busyMessageMode);
@@ -18,6 +18,7 @@ import { prepareBotWorkspace } from '../../../../src/channels/shared/default-wor
18
18
  import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-preset.mjs';
19
19
  import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
20
20
  import { createDeliveryAdapter } from '../../delivery-adapter.mjs';
21
+ import { createAnnouncedStateStore, createBindingAnnouncer } from '../shared/binding-events.mjs';
21
22
  import { createTokenConnectionSupervisor } from '../shared/connection-supervisor.mjs';
22
23
  import { pluginPaths } from '../shared/production.mjs';
23
24
  import { createHarnessCommandExecutor } from '../../harness-command-executor.mjs';
@@ -62,14 +63,29 @@ export async function createProductionController(ctx, config = {}, internals = {
62
63
  : configStore;
63
64
  const stateStores = new Map();
64
65
  const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
65
- const stateFor = async (botId) => {
66
- let state = stateStores.get(botId);
67
- if (!state) {
68
- state = await new ResolvedStateStore(statePath(botId)).load();
69
- stateStores.set(botId, state);
70
- }
71
- return state;
72
- };
66
+ /**
67
+ * Every binding change is announced the moment it is written: a bind before the
68
+ * Session exists, an unbind when the conversation moves to another session or
69
+ * its binding is cleared. Listeners run synchronously.
70
+ */
71
+ const announcer = createBindingAnnouncer({
72
+ channel: 'slack',
73
+ emit: (event, payload) => ctx.emit(event, payload),
74
+ authorsOf: (botId) => (typeof stateStores.get(botId)?.snapshot === 'function'
75
+ ? stateStores.get(botId).snapshot()?.authors ?? null
76
+ : null),
77
+ });
78
+ const { stateFor, stateForSync, prime, forget } = createAnnouncedStateStore({
79
+ announcer,
80
+ StateStore: ResolvedStateStore,
81
+ statePath,
82
+ states: stateStores,
83
+ logger,
84
+ });
85
+ // Warm the per-bot state memo now: the synchronous identity lookup can only
86
+ // answer from state that is already loaded in this process, and the first prompt
87
+ // of a session arrives long before any delivery call would load it.
88
+ await prime(configuredBots.map((bot) => bot.botId));
73
89
  const commandExecutor = createHarnessCommandExecutor(ctx, internals.commandExecutor);
74
90
  const inboundTtl = internals.inboundTtl ?? getInboundTtlRuntime(ctx, config);
75
91
  const inboundTtlService = inboundTtl?.service ?? inboundTtl;
@@ -134,8 +150,8 @@ export async function createProductionController(ctx, config = {}, internals = {
134
150
  });
135
151
  },
136
152
  deleteState: async ({ botId }) => {
137
- const state = stateStores.get(botId);
138
- stateStores.delete(botId);
153
+ const state = stateForSync(botId);
154
+ forget(botId);
139
155
  if (state && typeof state.remove === 'function') {
140
156
  await state.remove();
141
157
  } else {
@@ -166,6 +182,8 @@ export async function createProductionController(ctx, config = {}, internals = {
166
182
  controller,
167
183
  deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
168
184
  channel: 'slack', workspaces, coreController, stateFor,
185
+ // The same store, without the await: it is a memo of already loaded bots.
186
+ stateForSync,
169
187
  }),
170
188
  ready: supervisor.ready,
171
189
  async close() {
@@ -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';
@@ -28,6 +29,7 @@ export const SLACK_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
  setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
32
34
  setAlias: SET_ALIAS_ENDPOINT,
33
35
  });
@@ -90,6 +92,10 @@ function payloadFailure(endpoint, payload) {
90
92
  return validAgentPresetPayload(payload)
91
93
  ? null : '请选择 Agent Preset。';
92
94
  }
95
+ if (endpoint === SLACK_ENDPOINTS.setReplyContent) {
96
+ return validReplyContentPayload(payload)
97
+ ? null : '请选择要投递的回复内容。';
98
+ }
93
99
  if (endpoint === SLACK_ENDPOINTS.setBusyMessageMode) {
94
100
  return validMessageModePayload(payload)
95
101
  ? null : '请提交有效的消息处理方式。';
@@ -190,6 +196,10 @@ export function createSlackRpcHandler(controller) {
190
196
  if (typeof controller.updateModel !== 'function') throw new Error('Model update is unavailable');
191
197
  value = await controller.updateModel(payload.botId, payload.model);
192
198
  }
199
+ else if (endpoint === SLACK_ENDPOINTS.setReplyContent) {
200
+ if (typeof controller.updateReplyContent !== 'function') throw new Error('Reply content update is unavailable');
201
+ value = await controller.updateReplyContent(payload.botId, payload.replyContent);
202
+ }
193
203
  else if (endpoint === SLACK_ENDPOINTS.setBusyMessageMode) {
194
204
  if (typeof controller.updateBusyMessageMode !== 'function') throw new Error('Message mode update is unavailable');
195
205
  value = await controller.updateBusyMessageMode(payload.botId, payload.busyMessageMode);
@@ -5,12 +5,17 @@ import { TelegramRuntime } from '../../../../src/channels/telegram/telegram-runt
5
5
  import { TelegramStateStore } from '../../../../src/channels/telegram/state-store.mjs';
6
6
  import { createTelegramVoiceTranscriber } from '../../../../src/channels/telegram/voice.mjs';
7
7
  import { createTokenProductionController } from '../shared/production.mjs';
8
+ import { initialAccessPolicyFor, newBotAccessPolicyFor } from '../shared/access-policy-production.mjs';
8
9
 
9
10
  export { normalizeTelegramAllowedUsers } from '../../../../src/channels/telegram/config-store.mjs';
10
11
 
11
12
  export function createProductionController(ctx, config = {}, internals = {}) {
12
13
  return createTokenProductionController(ctx, config, internals, {
13
14
  channel: 'telegram',
15
+ initialAccessPolicyForBot: (bot) => bot.senderAccessDefault === 'allowlist'
16
+ ? newBotAccessPolicyFor('telegram', bot)
17
+ : initialAccessPolicyFor('telegram', bot),
18
+ newBotAccessPolicyForBot: (bot) => newBotAccessPolicyFor('telegram', bot),
14
19
  ConfigStore: TelegramConfigStore,
15
20
  StateStore: TelegramStateStore,
16
21
  HarnessClient: TelegramHarnessClient,
@@ -19,6 +19,7 @@ import { prepareBotWorkspace } from '../../../../src/channels/shared/default-wor
19
19
  import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-preset.mjs';
20
20
  import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
21
21
  import { createDeliveryAdapter } from '../../delivery-adapter.mjs';
22
+ import { createAnnouncedStateStore, createBindingAnnouncer } from '../shared/binding-events.mjs';
22
23
  import { createConnectionSupervisor } from './connection-supervisor.mjs';
23
24
  import { createHarnessCommandExecutor } from '../../harness-command-executor.mjs';
24
25
  import { harnessConnection } from '../../harness-connection.mjs';
@@ -76,14 +77,29 @@ export async function createProductionController(ctx, config = {}, internals = {
76
77
  });
77
78
  const stateStores = new Map();
78
79
  const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
79
- const stateFor = async (botId) => {
80
- let state = stateStores.get(botId);
81
- if (!state) {
82
- state = await new StateStore(statePath(botId)).load();
83
- stateStores.set(botId, state);
84
- }
85
- return state;
86
- };
80
+ /**
81
+ * Every binding change is announced the moment it is written: a bind before the
82
+ * Session exists, an unbind when the conversation moves to another session or
83
+ * its binding is cleared. Listeners run synchronously.
84
+ */
85
+ const announcer = createBindingAnnouncer({
86
+ channel: 'wecom',
87
+ emit: (event, payload) => ctx.emit(event, payload),
88
+ authorsOf: (botId) => (typeof stateStores.get(botId)?.snapshot === 'function'
89
+ ? stateStores.get(botId).snapshot()?.authors ?? null
90
+ : null),
91
+ });
92
+ const { stateFor, stateForSync, prime, forget } = createAnnouncedStateStore({
93
+ announcer,
94
+ StateStore,
95
+ statePath,
96
+ states: stateStores,
97
+ logger,
98
+ });
99
+ // Warm the per-bot state memo now: the synchronous identity lookup can only
100
+ // answer from state that is already loaded in this process, and the first prompt
101
+ // of a session arrives long before any delivery call would load it.
102
+ await prime(configuredBots.map((bot) => bot.botId));
87
103
  const commandExecutor = createHarnessCommandExecutor(ctx, internals.commandExecutor);
88
104
  const inboundTtl = internals.inboundTtl ?? getInboundTtlRuntime(ctx, config);
89
105
  const inboundTtlService = inboundTtl?.service ?? inboundTtl;
@@ -149,8 +165,8 @@ export async function createProductionController(ctx, config = {}, internals = {
149
165
  });
150
166
  },
151
167
  deleteState: async ({ botId }) => {
152
- const state = stateStores.get(botId);
153
- stateStores.delete(botId);
168
+ const state = stateForSync(botId);
169
+ forget(botId);
154
170
  if (state && typeof state.remove === 'function') {
155
171
  await state.remove();
156
172
  } else {
@@ -180,6 +196,8 @@ export async function createProductionController(ctx, config = {}, internals = {
180
196
  controller,
181
197
  deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
182
198
  channel: 'wecom', workspaces, coreController, stateFor,
199
+ // The same store, without the await: it is a memo of already loaded bots.
200
+ stateForSync,
183
201
  }),
184
202
  ready: supervisor.ready,
185
203
  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
  import { SET_CONTEXT_ENHANCEMENT_ENDPOINT, validContextEnhancementPayload } from '../shared/context-enhancement-rpc.mjs';
8
9
  import { SET_ACCESS_POLICY_ENDPOINT, validAccessPolicyPayload } from '../shared/access-policy-rpc.mjs';
@@ -29,6 +30,7 @@ export const WECOM_ENDPOINTS = Object.freeze({
29
30
  setAgentPreset: SET_AGENT_PRESET_ENDPOINT,
30
31
  setContextEnhancement: SET_CONTEXT_ENHANCEMENT_ENDPOINT,
31
32
  setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
33
+ setReplyContent: SET_REPLY_CONTENT_ENDPOINT,
32
34
  setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
33
35
  setAlias: SET_ALIAS_ENDPOINT,
34
36
  });
@@ -92,6 +94,10 @@ function payloadFailure(endpoint, payload) {
92
94
  return validAgentPresetPayload(payload)
93
95
  ? null : '请选择 Agent Preset。';
94
96
  }
97
+ if (endpoint === WECOM_ENDPOINTS.setReplyContent) {
98
+ return validReplyContentPayload(payload)
99
+ ? null : '请选择要投递的回复内容。';
100
+ }
95
101
  if (endpoint === WECOM_ENDPOINTS.setBusyMessageMode) {
96
102
  return validMessageModePayload(payload)
97
103
  ? null : '请提交有效的消息处理方式。';
@@ -214,6 +220,9 @@ export function createWecomRpcHandler(controller, { encodeQr = qrDataUrl } = {})
214
220
  await controller.updateModel(payload.botId, payload.model),
215
221
  cachedEncode,
216
222
  );
223
+ } else if (endpoint === WECOM_ENDPOINTS.setReplyContent) {
224
+ if (typeof controller.updateReplyContent !== 'function') throw new Error('Reply content update is unavailable');
225
+ value = await controller.updateReplyContent(payload.botId, payload.replyContent);
217
226
  } else if (endpoint === WECOM_ENDPOINTS.setBusyMessageMode) {
218
227
  if (typeof controller.updateBusyMessageMode !== 'function') throw new Error('Message mode update is unavailable');
219
228
  value = await controller.updateBusyMessageMode(
@@ -19,6 +19,7 @@ import { prepareBotWorkspace } from '../../../../src/channels/shared/default-wor
19
19
  import { listAgentPresetCatalog } from '../../../../src/channels/shared/agent-preset.mjs';
20
20
  import { listModelCatalog } from '../../../../src/channels/shared/model-setting.mjs';
21
21
  import { createDeliveryAdapter } from '../../delivery-adapter.mjs';
22
+ import { createAnnouncedStateStore, createBindingAnnouncer } from '../shared/binding-events.mjs';
22
23
  import { createConnectionSupervisor } from '../wecom/connection-supervisor.mjs';
23
24
  import { createHarnessCommandExecutor } from '../../harness-command-executor.mjs';
24
25
  import { harnessConnection } from '../../harness-connection.mjs';
@@ -110,14 +111,29 @@ export async function createProductionController(ctx, config = {}, internals = {
110
111
  };
111
112
  const stateStores = new Map();
112
113
  const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
113
- const stateFor = async (botId) => {
114
- let state = stateStores.get(botId);
115
- if (!state) {
116
- state = await new StateStore(statePath(botId)).load();
117
- stateStores.set(botId, state);
118
- }
119
- return state;
120
- };
114
+ /**
115
+ * Every binding change is announced the moment it is written: a bind before the
116
+ * Session exists, an unbind when the conversation moves to another session or
117
+ * its binding is cleared. Listeners run synchronously.
118
+ */
119
+ const announcer = createBindingAnnouncer({
120
+ channel: 'wecom-app',
121
+ emit: (event, payload) => ctx.emit(event, payload),
122
+ authorsOf: (botId) => (typeof stateStores.get(botId)?.snapshot === 'function'
123
+ ? stateStores.get(botId).snapshot()?.authors ?? null
124
+ : null),
125
+ });
126
+ const { stateFor, stateForSync, prime, forget } = createAnnouncedStateStore({
127
+ announcer,
128
+ StateStore,
129
+ statePath,
130
+ states: stateStores,
131
+ logger,
132
+ });
133
+ // Warm the per-bot state memo now: the synchronous identity lookup can only
134
+ // answer from state that is already loaded in this process, and the first prompt
135
+ // of a session arrives long before any delivery call would load it.
136
+ await prime(configuredBots.map((bot) => bot.botId));
121
137
  const commandExecutor = createHarnessCommandExecutor(ctx, internals.commandExecutor);
122
138
  const inboundTtl = internals.inboundTtl ?? getInboundTtlRuntime(ctx, config);
123
139
  const inboundTtlService = inboundTtl?.service ?? inboundTtl;
@@ -180,8 +196,8 @@ export async function createProductionController(ctx, config = {}, internals = {
180
196
  });
181
197
  },
182
198
  deleteState: async ({ botId }) => {
183
- const state = stateStores.get(botId);
184
- stateStores.delete(botId);
199
+ const state = stateForSync(botId);
200
+ forget(botId);
185
201
  if (state && typeof state.remove === 'function') {
186
202
  await state.remove();
187
203
  } else {
@@ -211,6 +227,8 @@ export async function createProductionController(ctx, config = {}, internals = {
211
227
  controller,
212
228
  deliveryAdapter: createDeliveryAdapter({ dsBot: config.deliveryService?.dsBot,
213
229
  channel: 'wecom-app', workspaces, coreController, stateFor,
230
+ // The same store, without the await: it is a memo of already loaded bots.
231
+ stateForSync,
214
232
  }),
215
233
  ready: supervisor.ready,
216
234
  async close() {