@xmanrui/dsh-im 5.7.0 → 5.9.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 (77) hide show
  1. package/README.en.md +42 -7
  2. package/README.md +53 -7
  3. package/docs/preset-workspaces.md +37 -0
  4. package/lib/client.js +375 -160
  5. package/lib/index.js +330 -325
  6. package/package.json +3 -1
  7. package/plugin-src/client/channels/feishu/api.js +5 -0
  8. package/plugin-src/client/channels/feishu/conversation-directory-settings.js +73 -0
  9. package/plugin-src/client/channels/feishu/index.js +1 -0
  10. package/plugin-src/client/connection-error.js +1 -1
  11. package/plugin-src/client/delivery-settings.js +4 -0
  12. package/plugin-src/client/i18n-ru.js +17 -0
  13. package/plugin-src/client/i18n.js +17 -0
  14. package/plugin-src/client/styles.js +6 -0
  15. package/plugin-src/client/workspace-editor.js +6 -5
  16. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  17. package/plugin-src/host/channels/feishu/production.mjs +2 -1
  18. package/plugin-src/host/channels/feishu/rpc.mjs +25 -0
  19. package/plugin-src/host/channels/matrix/production.mjs +2 -1
  20. package/plugin-src/host/channels/qq/production.mjs +2 -1
  21. package/plugin-src/host/channels/shared/binding-events.mjs +130 -0
  22. package/plugin-src/host/channels/shared/production.mjs +32 -3
  23. package/plugin-src/host/channels/shared/workspace-rpc.mjs +2 -0
  24. package/plugin-src/host/channels/slack/production.mjs +2 -1
  25. package/plugin-src/host/channels/wecom/production.mjs +2 -1
  26. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  27. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  28. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  29. package/plugin-src/host/delivery-adapter.mjs +122 -1
  30. package/plugin-src/host/delivery-service.mjs +40 -0
  31. package/plugin-src/host/ds-bot-client.mjs +28 -2
  32. package/plugin-src/host/index.mjs +24 -1
  33. package/plugin-src/host/modern-harness-api.mjs +3 -0
  34. package/scripts/telegram-menu-scopes.mjs +57 -0
  35. package/scripts/verify-interface-language.mjs +60 -15
  36. package/scripts/verify-package.mjs +17 -6
  37. package/src/channels/dingtalk/dingtalk-bridge.mjs +2 -3
  38. package/src/channels/dingtalk/dingtalk-menu.mjs +4 -5
  39. package/src/channels/email/transports/imap-smtp.mjs +21 -11
  40. package/src/channels/feishu/bridge.mjs +75 -22
  41. package/src/channels/feishu/feishu-cards.mjs +96 -25
  42. package/src/channels/feishu/message-utils.mjs +1 -0
  43. package/src/channels/qq/qq-menu.mjs +3 -4
  44. package/src/channels/shared/action-card.mjs +331 -0
  45. package/src/channels/shared/bot-workspace-store.mjs +369 -6
  46. package/src/channels/shared/command-catalog.mjs +20 -5
  47. package/src/channels/shared/conversation/describe.mjs +116 -0
  48. package/src/channels/shared/conversation-directory-ensure.mjs +46 -0
  49. package/src/channels/shared/conversation-directory.mjs +29 -0
  50. package/src/channels/shared/conversation-state-store.mjs +62 -0
  51. package/src/channels/shared/diagnostic-details.mjs +38 -0
  52. package/src/channels/shared/harness-approval.mjs +58 -13
  53. package/src/channels/shared/harness-client.mjs +85 -2
  54. package/src/channels/shared/harness-session-binding.mjs +13 -1
  55. package/src/channels/shared/i18n-en/diagnostics.mjs +2 -0
  56. package/src/channels/shared/i18n-en/feishu.mjs +6 -0
  57. package/src/channels/shared/i18n-en/shared-a.mjs +14 -0
  58. package/src/channels/shared/i18n-en/telegram.mjs +14 -0
  59. package/src/channels/shared/i18n-ru/diagnostics.mjs +2 -0
  60. package/src/channels/shared/i18n-ru/feishu.mjs +6 -0
  61. package/src/channels/shared/i18n-ru/shared-a.mjs +14 -0
  62. package/src/channels/shared/i18n-ru/telegram.mjs +14 -0
  63. package/src/channels/shared/message-failure.mjs +8 -0
  64. package/src/channels/shared/model-command.mjs +5 -0
  65. package/src/channels/shared/new-command.mjs +7 -0
  66. package/src/channels/shared/preset-workspaces.mjs +48 -0
  67. package/src/channels/shared/qr-encoding-error.mjs +8 -2
  68. package/src/channels/shared/semantic/reply-reference.mjs +25 -5
  69. package/src/channels/shared/status-command.mjs +159 -0
  70. package/src/channels/shared/text-harness-bridge.mjs +89 -6
  71. package/src/channels/shared/workspace-command.mjs +36 -15
  72. package/src/channels/shared/workspace-session.mjs +30 -5
  73. package/src/channels/telegram/approval-card.mjs +379 -0
  74. package/src/channels/telegram/telegram-api.mjs +10 -1
  75. package/src/channels/telegram/telegram-bridge.mjs +7 -0
  76. package/src/channels/telegram/telegram-runtime.mjs +125 -13
  77. package/src/channels/wecom/wecom-bridge.mjs +5 -3
@@ -50,7 +50,7 @@ export async function createProductionController(ctx, config = {}, internals = {
50
50
  const { defaultWorkspace, ungroupedWorkspace } = await prepareBotWorkspace(config);
51
51
  const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
52
52
  const workspaces = internals.workspaces
53
- ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace }).load();
53
+ ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace, groupByAgentPreset: config.groupByAgentPreset }).load();
54
54
  const configuredBots = configStore.list();
55
55
  await workspaces.reconcile(configuredBots.map((bot) => bot.botId));
56
56
  await Promise.all(configuredBots.map((bot) => workspaces.ensure(bot.botId, {
@@ -148,6 +148,7 @@ export async function createProductionController(ctx, config = {}, internals = {
148
148
  },
149
149
  });
150
150
  const controller = createWorkspaceAwareController(coreController, {
151
+ harness,
151
152
  workspaces,
152
153
  stateFor,
153
154
  agentPresetCatalog,
@@ -60,7 +60,7 @@ export async function createProductionController(ctx, config = {}, internals = {
60
60
  const { defaultWorkspace, ungroupedWorkspace } = await prepareBotWorkspace(config);
61
61
  const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
62
62
  const workspaces = internals.workspaces
63
- ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace }).load();
63
+ ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace, groupByAgentPreset: config.groupByAgentPreset }).load();
64
64
  const configuredBots = configStore.list();
65
65
  await workspaces.reconcile(configuredBots.map((bot) => bot.botId));
66
66
  await Promise.all(configuredBots.map((bot) => workspaces.ensure(bot.botId, {
@@ -163,6 +163,7 @@ export async function createProductionController(ctx, config = {}, internals = {
163
163
  },
164
164
  });
165
165
  const controller = createWorkspaceAwareController(coreController, {
166
+ harness,
166
167
  workspaces,
167
168
  stateFor,
168
169
  agentPresetCatalog,
@@ -74,7 +74,7 @@ export async function createProductionController(ctx, config = {}, internals = {
74
74
  const { defaultWorkspace, ungroupedWorkspace } = await prepareBotWorkspace(config);
75
75
  const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
76
76
  const workspaces = internals.workspaces
77
- ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace }).load();
77
+ ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace, groupByAgentPreset: config.groupByAgentPreset }).load();
78
78
  const configuredBots = configStore.list();
79
79
  await workspaces.reconcile(configuredBots.map((bot) => bot.botId));
80
80
  await Promise.all(configuredBots.map((bot) => workspaces.ensure(bot.botId, {
@@ -194,6 +194,7 @@ export async function createProductionController(ctx, config = {}, internals = {
194
194
  },
195
195
  });
196
196
  const controller = createWorkspaceAwareController(coreController, {
197
+ harness,
197
198
  workspaces,
198
199
  stateFor,
199
200
  agentPresetCatalog,
@@ -103,7 +103,7 @@ export async function createProductionController(ctx, config = {}, internals = {
103
103
  const { defaultWorkspace, ungroupedWorkspace } = await prepareBotWorkspace(config);
104
104
  const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
105
105
  const workspaces = diagnosticWorkspaces(internals.workspaces
106
- ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace }).load());
106
+ ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace, groupByAgentPreset: config.groupByAgentPreset }).load());
107
107
  const configuredBots = configStore.list();
108
108
  await workspaces.reconcile(configuredBots.map((bot) => bot.botId));
109
109
  await Promise.all(configuredBots.map((bot) => workspaces.ensure(bot.botId, {
@@ -203,6 +203,7 @@ export async function createProductionController(ctx, config = {}, internals = {
203
203
  },
204
204
  });
205
205
  const workspaceController = createWorkspaceAwareController(coreController, {
206
+ harness,
206
207
  workspaces,
207
208
  stateFor,
208
209
  agentPresetCatalog,
@@ -71,7 +71,7 @@ export async function createProductionController(ctx, config = {}, internals = {
71
71
  const { defaultWorkspace, ungroupedWorkspace } = await prepareBotWorkspace(config);
72
72
  const WorkspaceStore = internals.WorkspaceStore ?? BotWorkspaceStore;
73
73
  const workspaces = internals.workspaces
74
- ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace }).load();
74
+ ?? await new WorkspaceStore(paths.workspaces, { defaultWorkspace, ungroupedWorkspace, groupByAgentPreset: config.groupByAgentPreset }).load();
75
75
  const configuredBots = configStore.list();
76
76
  await workspaces.reconcile(configuredBots.map((bot) => bot.botId));
77
77
  await Promise.all(configuredBots.map((bot) => workspaces.ensure(bot.botId, {
@@ -173,6 +173,7 @@ export async function createProductionController(ctx, config = {}, internals = {
173
173
  },
174
174
  });
175
175
  const controller = createWorkspaceAwareController(coreController, {
176
+ harness,
176
177
  workspaces,
177
178
  stateFor,
178
179
  agentPresetCatalog,
@@ -5,6 +5,7 @@ import {
5
5
  privateDeliverySuggestionFromConversationKey,
6
6
  resolvePrivateConversationKey,
7
7
  } from './delivery-suggestions.mjs';
8
+ import { parseConversationKey } from '../../src/channels/shared/conversation/describe.mjs';
8
9
  import { withSessionBindingLock } from '../../src/channels/shared/session-binding-lock.mjs';
9
10
  import { dsBotError } from './ds-bot-client.mjs';
10
11
 
@@ -217,6 +218,85 @@ export function sessionSyncTarget(channel, workspaces, configured) {
217
218
  return target ? { ...target, targetId: configured.targetId } : null;
218
219
  }
219
220
 
221
+ /** Describe the conversation of one channel's state that owns `sessionId`. */
222
+ function describeFromState(state, sessionId, channel) {
223
+ const sessions = stateSessions(state);
224
+ if (!sessions) return null;
225
+ const conversationKey = Object.keys(sessions).find((key) => sessions[key] === sessionId);
226
+ if (!conversationKey) return null;
227
+ const snapshot = typeof state.snapshot === 'function' ? state.snapshot() : null;
228
+ const authors = snapshot?.authors && typeof snapshot.authors === 'object'
229
+ && !Array.isArray(snapshot.authors) ? snapshot.authors : null;
230
+ const parsed = parseConversationKey(conversationKey, { channel });
231
+ const author = authors?.[conversationKey] ?? null;
232
+ return {
233
+ conversationKey,
234
+ chatType: parsed?.chatType ?? null,
235
+ chatId: parsed?.chatId ?? null,
236
+ threadId: parsed?.threadId ?? null,
237
+ chatTitle: null,
238
+ senderId: author?.senderId ?? parsed?.senderId ?? null,
239
+ senderName: author?.senderName ?? null,
240
+ senderUsername: author?.senderUsername ?? null,
241
+ senderIsBot: author ? author.isBot === true : null,
242
+ };
243
+ }
244
+
245
+ function botIdsOfChannel(workspaces) {
246
+ try {
247
+ return workspaces.listBotIds();
248
+ } catch {
249
+ return [];
250
+ }
251
+ }
252
+
253
+ /** The bot and the conversation binding that own `sessionId`, awaiting each state. */
254
+ async function findBySession(workspaces, stateOf, sessionId, channel) {
255
+ if (typeof sessionId !== 'string' || sessionId === '') return null;
256
+ for (const botId of botIdsOfChannel(workspaces)) {
257
+ let state;
258
+ try {
259
+ state = await stateOf(botId);
260
+ } catch {
261
+ continue;
262
+ }
263
+ let binding = null;
264
+ try {
265
+ binding = describeFromState(state, sessionId, channel);
266
+ } catch {
267
+ continue;
268
+ }
269
+ if (binding !== null) return { botId, binding };
270
+ }
271
+ return null;
272
+ }
273
+
274
+ /**
275
+ * The same lookup over states that are already in memory. Never awaits: prompt
276
+ * assembly is synchronous, and a lookup that cannot answer right now has to say
277
+ * `null` instead of starting work the caller will never see.
278
+ */
279
+ function findBySessionSync(workspaces, stateOf, sessionId, channel) {
280
+ if (typeof sessionId !== 'string' || sessionId === '') return null;
281
+ for (const botId of botIdsOfChannel(workspaces)) {
282
+ let state;
283
+ try {
284
+ state = stateOf(botId);
285
+ } catch {
286
+ continue;
287
+ }
288
+ if (!state) continue;
289
+ let binding = null;
290
+ try {
291
+ binding = describeFromState(state, sessionId, channel);
292
+ } catch {
293
+ continue;
294
+ }
295
+ if (binding !== null) return { botId, binding };
296
+ }
297
+ return null;
298
+ }
299
+
220
300
  function stateSessions(state) {
221
301
  if (!state || typeof state.snapshot !== 'function') return null;
222
302
  const sessions = state.snapshot()?.sessions;
@@ -246,7 +326,14 @@ function sessionSyncView(channel, target, sessions, configured) {
246
326
  }
247
327
 
248
328
  /** Bind one channel's existing workspace store and unwrapped controller to DeliveryService. */
249
- export function createDeliveryAdapter({ channel, workspaces, coreController, stateFor, dsBot }) {
329
+ export function createDeliveryAdapter({
330
+ channel,
331
+ workspaces,
332
+ coreController,
333
+ stateFor,
334
+ stateForSync = null,
335
+ dsBot,
336
+ }) {
250
337
  if (!supportsDeliveryChannel(channel)) throw new TypeError(`Unsupported delivery channel: ${channel}`);
251
338
  if (!workspaces || typeof workspaces !== 'object') {
252
339
  throw new TypeError('delivery adapter requires a workspace store');
@@ -335,6 +422,40 @@ export function createDeliveryAdapter({ channel, workspaces, coreController, sta
335
422
  listDsBotBindings: () => workspaces.listDsBotBindings().filter(({ conversationKey }) => (
336
423
  privateDeliverySuggestionFromConversationKey(channel, conversationKey)
337
424
  )),
425
+ /**
426
+ * Reverse lookup for a session: which conversation of this channel owns it.
427
+ * Reads only what the channel already keeps (its state file), never the
428
+ * network, and never throws — an unknown session is simply `null`.
429
+ */
430
+ async describeConversationBySession(sessionId) {
431
+ const found = await findBySession(workspaces, stateFor, sessionId, channel);
432
+ if (found === null) return null;
433
+ const { botId, binding } = found;
434
+ let botName = null;
435
+ try {
436
+ if (typeof coreController.describeDeliveryAccount === 'function') {
437
+ botName = (await coreController.describeDeliveryAccount(botId))?.name ?? null;
438
+ }
439
+ } catch {
440
+ botName = null;
441
+ }
442
+ return { channel, botId, botName, ...binding };
443
+ },
444
+
445
+ /**
446
+ * The same lookup without a single `await`: prompt assembly is synchronous and
447
+ * cannot wait for a promise. Reads only state that is already loaded in this
448
+ * process, so a session of a bot that was never touched answers `null` — the
449
+ * caller decides what an unknown session means. `botName` is left out on
450
+ * purpose: naming a bot needs the network, and a never-awaited lookup must not
451
+ * start one.
452
+ */
453
+ describeConversationBySessionSync(sessionId) {
454
+ if (typeof stateForSync !== 'function') return null;
455
+ const found = findBySessionSync(workspaces, stateForSync, sessionId, channel);
456
+ if (found === null) return null;
457
+ return { channel, botId: found.botId, botName: null, ...found.binding };
458
+ },
338
459
  async listTargets(botId) {
339
460
  const targets = workspaces.listDeliveryTargets(botId);
340
461
  const configured = new Map(
@@ -482,6 +482,46 @@ export class DeliveryService {
482
482
  }
483
483
  }
484
484
 
485
+ /**
486
+ * Describe the conversation a session belongs to, or null when no channel
487
+ * owns it. Pure lookup: no network, no session creation, no throwing.
488
+ * @param {string} sessionId harness session id
489
+ */
490
+ async describeConversation(sessionId) {
491
+ if (typeof sessionId !== 'string' || sessionId === '') return null;
492
+ for (const { adapter } of this.#adapters.values()) {
493
+ if (typeof adapter.describeConversationBySession !== 'function') continue;
494
+ try {
495
+ const described = await adapter.describeConversationBySession(sessionId);
496
+ if (described) return described;
497
+ } catch {
498
+ // A channel that cannot answer must not hide the others.
499
+ continue;
500
+ }
501
+ }
502
+ return null;
503
+ }
504
+
505
+ /**
506
+ * The same lookup, answered from memory only: no await, no network. A session
507
+ * whose channel has not loaded its state yet answers null — which is exactly the
508
+ * truth a synchronous prompt assembly can act on.
509
+ * @param {string} sessionId harness session id
510
+ */
511
+ describeConversationSync(sessionId) {
512
+ if (typeof sessionId !== 'string' || sessionId === '') return null;
513
+ for (const { adapter } of this.#adapters.values()) {
514
+ if (typeof adapter.describeConversationBySessionSync !== 'function') continue;
515
+ try {
516
+ const described = adapter.describeConversationBySessionSync(sessionId);
517
+ if (described) return described;
518
+ } catch {
519
+ continue;
520
+ }
521
+ }
522
+ return null;
523
+ }
524
+
485
525
  async describeBot(botId) {
486
526
  const id = botIdOf(botId);
487
527
  const registration = await this.#checkedRegistrationFor(id);
@@ -20,13 +20,16 @@ function appearance(bot) {
20
20
  /** Read DS Bot through the current Host's registered route, without a second
21
21
  * runtime, credentials, or assumptions about its configured storage directory. */
22
22
  export function createDsBotClient(ctx) {
23
- async function call(endpoint, payload = {}) {
23
+ async function call(endpoint, payload = {}, options = {}) {
24
+ options.signal?.throwIfAborted();
24
25
  const connection = ctx.connection;
25
26
  if (typeof connection?.createSharedFetchHandler !== 'function') throw dsBotError();
27
+ const timeout = AbortSignal.timeout(15_000);
28
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
26
29
  const response = await connection.createSharedFetchHandler('/api').fetch(new Request(
27
30
  'http://localhost/api/bot', {
28
31
  method: 'POST', headers: { 'content-type': 'application/json' },
29
- body: JSON.stringify({ endpoint, payload }), signal: AbortSignal.timeout(15_000),
32
+ body: JSON.stringify({ endpoint, payload }), signal,
30
33
  },
31
34
  ), harnessPeer(ctx));
32
35
  if (!response.ok) throw dsBotError();
@@ -76,6 +79,29 @@ export function createDsBotClient(ctx) {
76
79
  answerQuestion(sessionId, questionId, answer) {
77
80
  return call('answer-question', { sessionId, questionId, answer });
78
81
  },
82
+ async updateBotModel(id, selection, options = {}) {
83
+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)
84
+ || typeof selection?.provider !== 'string' || !selection.provider
85
+ || typeof selection?.model !== 'string' || !selection.model
86
+ || (selection.reasoningEffort !== undefined
87
+ && (typeof selection.reasoningEffort !== 'string' || !selection.reasoningEffort))) {
88
+ throw dsBotError('model-unavailable');
89
+ }
90
+ // DS Bot owns both its persisted model and all of its sessions. A model
91
+ // change without an explicit effort resets to that model's default.
92
+ const ref = `${selection.provider}/${selection.model}`;
93
+ const updated = await call('update-bot', {
94
+ id, model: ref, effort: selection.reasoningEffort ?? null,
95
+ }, options);
96
+ if (updated?.id !== id || updated?.model !== ref || updated?.appliedModel !== ref) {
97
+ throw dsBotError('model-selection-mismatch');
98
+ }
99
+ return { selected: {
100
+ provider: selection.provider,
101
+ model: selection.model,
102
+ ...(updated.appliedEffort ? { reasoningEffort: updated.appliedEffort } : {}),
103
+ } };
104
+ },
79
105
  async resolve(id) {
80
106
  const result = await status();
81
107
  if (result.state !== 'ready') throw dsBotError();
@@ -36,7 +36,11 @@ export const inject = [
36
36
  ];
37
37
 
38
38
  function channelConfig(config, name, deliveryService) {
39
- const channel = { ...(config.dshHome ? { dshHome: config.dshHome } : {}), ...config[name] };
39
+ const channel = {
40
+ ...(config.dshHome ? { dshHome: config.dshHome } : {}),
41
+ ...(config.groupByAgentPreset === undefined ? {} : { groupByAgentPreset: config.groupByAgentPreset }),
42
+ ...config[name],
43
+ };
40
44
  const withAuthority = config.rpcAuthority === undefined
41
45
  ? channel
42
46
  : { ...channel, rpcAuthority: config.rpcAuthority };
@@ -97,6 +101,21 @@ export function createImHostPlugin(internals = {}) {
97
101
  unavailableSessionSyncChannels: unavailableSessionSyncChannels.map((channel) => channel === 'wecomApp' ? 'wecom-app' : channel),
98
102
  dsBot: createDsBotClient(ctx),
99
103
  });
104
+ /** Sessions already reported, so the log stays one line per session. */
105
+ const describedSessions = new Set();
106
+ const describeConversationLogged = async (sessionId) => {
107
+ const described = await deliveryService.describeConversation(sessionId);
108
+ if (described && !describedSessions.has(sessionId)) {
109
+ describedSessions.add(sessionId);
110
+ const log = typeof ctx?.logger === 'function' ? ctx.logger(name) : (ctx?.logger ?? console);
111
+ try {
112
+ log?.info?.(`describeConversation session=${sessionId} chat=${described.conversationKey} sender=${described.senderId ?? '-'}`);
113
+ } catch {
114
+ // Logging must never break the lookup.
115
+ }
116
+ }
117
+ return described;
118
+ };
100
119
  if (typeof ctx?.provide === 'function') {
101
120
  ctx.provide('dshIm', Object.freeze({
102
121
  contractVersion: 1,
@@ -105,6 +124,10 @@ export function createImHostPlugin(internals = {}) {
105
124
  consumeInbound: (botId, options) => deliveryService.consumeInbound(botId, options),
106
125
  historyChecked: (botId, route, query, options) => deliveryService.historyChecked(botId, route, query, options),
107
126
  replyChecked: (botId, route, text, options) => deliveryService.replyChecked(botId, route, text, options),
127
+ describeConversation: (sessionId) => describeConversationLogged(sessionId),
128
+ // Prompt assembly is synchronous, so a caller that needs the identity
129
+ // before the first step cannot await the async variant.
130
+ describeConversationSync: (sessionId) => deliveryService.describeConversationSync(sessionId),
108
131
  describeBot: (botId) => deliveryService.describeBot(botId),
109
132
  sendChecked: (botId, targetId, text, options) => deliveryService.sendChecked(botId, targetId, text, options),
110
133
  send: (botId, targetId, text, options) => (
@@ -225,6 +225,9 @@ class ModernHarnessApi {
225
225
  describe: (request) => rpcResult(request, () => ({ ready: true, transport: 'typert' })),
226
226
  });
227
227
  this.workspace = Object.freeze({
228
+ rename: (request, signal) => rpcResult(request, () => this.#invoke(
229
+ 'workspace', 'rename', { request: request.payload }, signal,
230
+ )),
228
231
  list: (request, signal) => rpcResult(request, () => this.#workspaceList(signal)),
229
232
  create: (request, signal) => rpcResult(request, () => this.#invoke(
230
233
  'workspace', 'create', { request: request.payload }, signal,
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Scoped Telegram command-menu bookkeeping for the live acceptance script.
3
+ *
4
+ * The bot registers commands per BotCommandScope (see
5
+ * src/channels/telegram/telegram-runtime.mjs). An acceptance script that saved,
6
+ * polled and restored only the default scope would (a) never see the menu the
7
+ * plugin now writes into `all_private_chats`, and (b) restore an old default
8
+ * list that the plugin had already cleared. Both the save and the restore must
9
+ * therefore cover all three scopes.
10
+ *
11
+ * The helpers are pure wrappers around a `callTelegram(method, payload)`
12
+ * function so they can be unit-tested without any network access.
13
+ */
14
+ import { TELEGRAM_COMMAND_MENU_SCOPES } from '../src/channels/telegram/telegram-runtime.mjs';
15
+
16
+ export const DEFAULT_COMMAND_SCOPE = null;
17
+ export const PRIVATE_COMMAND_SCOPE = TELEGRAM_COMMAND_MENU_SCOPES.private;
18
+ export const GROUP_COMMAND_SCOPE = TELEGRAM_COMMAND_MENU_SCOPES.group;
19
+
20
+ /** Every scope the plugin may write, in registration order. */
21
+ export const VERIFY_COMMAND_SCOPES = Object.freeze([
22
+ Object.freeze({ name: 'default', scope: DEFAULT_COMMAND_SCOPE }),
23
+ Object.freeze({ name: 'private', scope: PRIVATE_COMMAND_SCOPE }),
24
+ Object.freeze({ name: 'group', scope: GROUP_COMMAND_SCOPE }),
25
+ ]);
26
+
27
+ export function commandPayloadFor(scope) {
28
+ return scope ? { scope } : {};
29
+ }
30
+
31
+ /** Snapshot every scope the plugin can touch, so the original state can be restored. */
32
+ export async function saveScopedMenus(callTelegram) {
33
+ const saved = new Map();
34
+ for (const { name, scope } of VERIFY_COMMAND_SCOPES) {
35
+ saved.set(name, await callTelegram('getMyCommands', commandPayloadFor(scope)));
36
+ }
37
+ return saved;
38
+ }
39
+
40
+ /**
41
+ * Restore a snapshot. Scoped lists go first and the default scope goes last:
42
+ * if a restore fails midway, a leftover scoped menu still wins over a partially
43
+ * restored default scope, which is the safer failure direction.
44
+ */
45
+ export async function restoreScopedMenus(callTelegram, saved) {
46
+ for (const { name, scope } of [...VERIFY_COMMAND_SCOPES].reverse()) {
47
+ const commands = saved.get(name) ?? [];
48
+ if (commands.length > 0) {
49
+ await callTelegram('setMyCommands', {
50
+ commands,
51
+ ...commandPayloadFor(scope),
52
+ });
53
+ } else {
54
+ await callTelegram('deleteMyCommands', commandPayloadFor(scope));
55
+ }
56
+ }
57
+ }
@@ -8,8 +8,13 @@
8
8
  * user-settings document.
9
9
  *
10
10
  * Set DSH_IM_TELEGRAM_TOKEN to additionally bind a real bot and assert the
11
- * command menu Telegram itself stores. That step is skipped without a token,
12
- * and it restores the bot's original menu when it finishes.
11
+ * command menu Telegram itself stores. That step is skipped without a token.
12
+ * The plugin registers its menu per BotCommandScope, so the live check saves,
13
+ * polls and restores all three scopes (default, all_private_chats,
14
+ * all_group_chats); polling only the default scope would wait forever.
15
+ *
16
+ * Offline: `node scripts/verify-interface-language.mjs --check-scopes` prints
17
+ * the scope plan and exits without a Harness checkout, network or token.
13
18
  */
14
19
  import assert from 'node:assert/strict';
15
20
  import { spawn } from 'node:child_process';
@@ -18,11 +23,34 @@ import { request as httpRequest } from 'node:http';
18
23
  import { tmpdir } from 'node:os';
19
24
  import { dirname, join, resolve } from 'node:path';
20
25
 
26
+ import {
27
+ GROUP_COMMAND_SCOPE,
28
+ PRIVATE_COMMAND_SCOPE,
29
+ VERIFY_COMMAND_SCOPES,
30
+ restoreScopedMenus,
31
+ saveScopedMenus,
32
+ } from './telegram-menu-scopes.mjs';
33
+
21
34
  const harnessRoot = process.argv[2];
22
- if (!harnessRoot || process.argv.includes('--help')) {
35
+ if (process.argv.includes('--help')) {
23
36
  console.log('Usage: node scripts/verify-interface-language.mjs /path/to/built/deepseek-harness');
37
+ console.log(' node scripts/verify-interface-language.mjs --check-scopes (offline scope self-check)');
24
38
  console.log(' DSH_IM_TELEGRAM_TOKEN=<token> node scripts/verify-interface-language.mjs ... (adds the live menu check)');
25
- process.exit(harnessRoot ? 0 : 1);
39
+ process.exit(0);
40
+ }
41
+ if (process.argv.includes('--check-scopes')) {
42
+ console.table(VERIFY_COMMAND_SCOPES.map(({ name, scope }) => ({
43
+ scope: name,
44
+ payload: JSON.stringify(scope ? { scope } : {}),
45
+ })));
46
+ console.log(`Offline self-check passed: ${VERIFY_COMMAND_SCOPES.length} Telegram command scopes`
47
+ + ' (default/private/group) are saved, polled and restored.');
48
+ process.exit(0);
49
+ }
50
+ if (!harnessRoot) {
51
+ console.log('Usage: node scripts/verify-interface-language.mjs /path/to/built/deepseek-harness');
52
+ console.log(' node scripts/verify-interface-language.mjs --check-scopes (offline scope self-check)');
53
+ process.exit(1);
26
54
  }
27
55
  const pluginRoot = resolve(import.meta.dirname, '..');
28
56
  await access(join(pluginRoot, 'lib/index.js'));
@@ -56,7 +84,7 @@ async function resolveHarness(root) {
56
84
  const harness = await resolveHarness(harnessRoot);
57
85
  const cli = harness.cli;
58
86
  const botToken = process.env.DSH_IM_TELEGRAM_TOKEN;
59
- let telegramMenu;
87
+ let savedMenus;
60
88
  const directory = await mkdtemp(join(tmpdir(), 'dsh-im-language-test-'));
61
89
  const home = join(directory, 'home');
62
90
  const profile = join(home, 'profiles/web');
@@ -264,7 +292,9 @@ try {
264
292
  record('the language route refuses malformed payloads', '4 cases');
265
293
 
266
294
  if (botToken) {
267
- telegramMenu = await telegram('getMyCommands');
295
+ // The plugin writes per scope; save every scope it may touch before binding
296
+ // so the original state can be restored exactly.
297
+ savedMenus = await saveScopedMenus(telegram);
268
298
  const bound = await rpc(browser, 'telegram', 'bot.bind-credentials', { token: botToken });
269
299
  assert.equal(bound.ok, true, 'the bot must bind');
270
300
  const botId = bound.value.bots.at(-1).botId;
@@ -272,16 +302,32 @@ try {
272
302
  const status = await rpc(browser, 'telegram', 'connection.status');
273
303
  return status.value?.bots?.find(item => item.botId === botId)?.connected ? true : null;
274
304
  });
275
- const english = await waitFor('Telegram stores the English menu', async () => {
276
- const commands = await telegram('getMyCommands');
305
+ const english = await waitFor('Telegram stores the English menu in the private-chat scope', async () => {
306
+ const commands = await telegram('getMyCommands', { scope: PRIVATE_COMMAND_SCOPE });
277
307
  const help = commands.find(item => item.command === 'help');
278
308
  return help && !HAN.test(help.description) ? commands : null;
279
309
  });
280
- record('Telegram stores the English command menu while DSH is English', `${english.length} commands`);
310
+ record('Telegram stores the English command menu in the private-chat scope',
311
+ `${english.length} commands`);
312
+
313
+ await waitFor('the legacy default-scope menu is cleared', async () => {
314
+ const commands = await telegram('getMyCommands');
315
+ return commands.length === 0 ? true : null;
316
+ });
317
+ record('the scoped registration clears the legacy default-scope menu', 'default scope empty');
318
+
319
+ const groupCommands = await telegram('getMyCommands', { scope: GROUP_COMMAND_SCOPE });
320
+ for (const directOnly of ['history', 'batch', 'send', 'cancel']) {
321
+ assert.equal(groupCommands.some(item => item.command === directOnly), false,
322
+ `the group menu must not advertise /${directOnly}`);
323
+ }
324
+ assert.equal(groupCommands.length, english.length - 4,
325
+ 'the group menu is the private menu without the four direct-chat-only commands');
326
+ record('the group scope omits direct-chat-only commands', `${groupCommands.length} commands`);
281
327
 
282
328
  await selectInterfaceLanguage('zh');
283
329
  const chinese = await waitFor('Telegram stores the Chinese menu after the switch', async () => {
284
- const commands = await telegram('getMyCommands');
330
+ const commands = await telegram('getMyCommands', { scope: PRIVATE_COMMAND_SCOPE });
285
331
  const help = commands.find(item => item.command === 'help');
286
332
  return help && HAN.test(help.description) ? commands : null;
287
333
  });
@@ -316,17 +362,16 @@ try {
316
362
  console.table(results);
317
363
  console.log(`Passed ${results.length} real HTTP checks against an unmodified DSH CLI (${harness.kind} layout).`);
318
364
  console.log(botToken
319
- ? 'The live Telegram menu was exercised and the bot\'s original menu was restored.'
365
+ ? 'The live Telegram menu was exercised; the bot\'s original menus were restored in all three scopes.'
320
366
  : 'Set DSH_IM_TELEGRAM_TOKEN to additionally assert the menu Telegram itself stores.');
321
367
  console.log('The temporary home contains no bot credentials and is removed after the server stops.');
322
368
  } finally {
323
369
  await stop();
324
- if (botToken && telegramMenu !== undefined) {
370
+ if (botToken && savedMenus !== undefined) {
325
371
  try {
326
- if (telegramMenu.length > 0) await telegram('setMyCommands', { commands: telegramMenu });
327
- else await telegram('deleteMyCommands');
372
+ await restoreScopedMenus(telegram, savedMenus);
328
373
  } catch {
329
- console.error('could not restore the bot\'s original command menu');
374
+ console.error('could not restore the bot\'s original command menus');
330
375
  }
331
376
  }
332
377
  await rm(directory, { recursive: true, force: true });
@@ -148,23 +148,27 @@ if (client.includes('settings.plugins.tab') || clientSources.includes('settings.
148
148
  }
149
149
  // Connections still have no channel-enable toggle. Checkable inputs are owned
150
150
  // only by the shared context editor, the saved-target Session sync row, the
151
- // email settings, the Telegram thinking-traces block, and Feishu panel settings.
151
+ // email settings, the Telegram thinking-traces block, Feishu panel settings,
152
+ // and the conversation-directory settings form.
152
153
  // The context editor contains one switch template and one mapped field-input
153
154
  // template; the delivery target adds one ordinary checkbox template; the
154
155
  // Telegram thinking-traces block adds two ordinary checkbox templates (traces
155
156
  // and frame numbering). General settings adds one mapped switch template for
156
- // the two Feishu panel preferences.
157
+ // the two Feishu panel preferences. Conversation-directory settings adds one
158
+ // switch template reused for the bot override and channel default.
157
159
  const contextEditorSource = await readFile(resolve(root, 'plugin-src/client/context-enhancement.js'), 'utf8');
158
160
  const deliverySettingsSource = await readFile(resolve(root, 'plugin-src/client/delivery-settings.js'), 'utf8');
159
161
  const emailSettingsSource = await readFile(resolve(root, 'plugin-src/client/channels/email/index.js'), 'utf8');
160
162
  const thinkingTracesSource = await readFile(resolve(root, 'plugin-src/client/channels/telegram/thinking-traces.js'), 'utf8');
161
163
  const botGeneralSettingsSource = await readFile(resolve(root, 'plugin-src/client/bot-general-settings.js'), 'utf8');
164
+ const conversationDirectorySettingsSource = await readFile(resolve(root, 'plugin-src/client/channels/feishu/conversation-directory-settings.js'), 'utf8');
162
165
  const otherClientSources = clientSources
163
166
  .replace(contextEditorSource, '')
164
167
  .replace(deliverySettingsSource, '')
165
168
  .replace(emailSettingsSource, '')
166
169
  .replace(thinkingTracesSource, '')
167
- .replace(botGeneralSettingsSource, '');
170
+ .replace(botGeneralSettingsSource, '')
171
+ .replace(conversationDirectorySettingsSource, '');
168
172
  if (/role:\s*["']switch|type:\s*["']checkbox/.test(otherClientSources)
169
173
  || (deliverySettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
170
174
  || /role:\s*["']switch["']/u.test(deliverySettingsSource)
@@ -172,9 +176,16 @@ if (/role:\s*["']switch|type:\s*["']checkbox/.test(otherClientSources)
172
176
  || /role:\s*["']switch["']/u.test(thinkingTracesSource)
173
177
  || (botGeneralSettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
174
178
  || (botGeneralSettingsSource.match(/role:\s*["']switch["']/g) ?? []).length !== 1
175
- || (client.match(/role:\s*["']switch["']/g) ?? []).length !== 2
176
- || (client.match(/type:\s*["']checkbox["']/g) ?? []).length !== 6) {
177
- throw new Error('checkable inputs must be limited to context enhancement, Session sync, email settings, Telegram thinking traces, and Feishu panel settings');
179
+ || (conversationDirectorySettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
180
+ || (conversationDirectorySettingsSource.match(/role:\s*["']switch["']/g) ?? []).length !== 1
181
+ || (client.match(/role:\s*["']switch["']/g) ?? []).length !== 3
182
+ || (client.match(/type:\s*["']checkbox["']/g) ?? []).length !== 7) {
183
+ throw new Error('checkable inputs must be limited to context enhancement, Session sync, email settings, Telegram thinking traces, Feishu panel settings, and conversation-directory settings');
184
+ }
185
+ for (const marker of ['bot.conversation-directory.set', 'bot.conversation-directory.default.set']) {
186
+ if (!host.includes(marker) || !client.includes(marker)) {
187
+ throw new Error(`conversation-directory RPC endpoint missing from Host or Client bundle: ${marker}`);
188
+ }
178
189
  }
179
190
  for (const marker of ['bot.context-enhancement.set', '<dsh_im_source>', '<dsh_im_source_guidance>']) {
180
191
  if (!host.includes(marker) || !client.includes(marker)) {
@@ -30,7 +30,7 @@ import {
30
30
  isPresetCommand,
31
31
  runPresetCommand,
32
32
  } from '../shared/preset-command.mjs';
33
- import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
33
+ import { conversationSessionWorkspace, runWorkspaceCommand } from '../shared/workspace-command.mjs';
34
34
  import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
35
35
  import {
36
36
  captureContextEnhancement,
@@ -940,8 +940,7 @@ export class DingtalkHarnessBridge {
940
940
  });
941
941
  return;
942
942
  }
943
- const sessionWorkspace = typeof this.#harness.currentConversationWorkspace === 'function'
944
- ? this.#harness.currentConversationWorkspace(key) : this.#harness.currentWorkspace?.();
943
+ const sessionWorkspace = await conversationSessionWorkspace(this.#harness, key, { signal: this.#signal });
945
944
  if (entry.workspace !== this.#harness.currentWorkspace?.()
946
945
  || entry.sessionWorkspace !== sessionWorkspace
947
946
  || entry.sessionId !== this.#state.sessionFor(key)) {