@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,6 +1,8 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
1
2
  import { ensurePresetWorkspace } from './preset-workspaces.mjs';
2
3
  import { t } from './i18n.mjs';
3
4
  import { normalizeBusyMessageMode, validateBusyMessageMode } from './message-mode.mjs';
5
+ import { isDefaultReplyContent, normalizeReplyContent, validateReplyContent } from './reply-content.mjs';
4
6
  import { atConnectionStage, connectionStageError, extractConnectionEvidence } from './connection-error.mjs';
5
7
  import { validateBotAlias, withBotAlias } from './bot-alias.mjs';
6
8
  import { defaultImWorkspace, ensureImWorkspaceDirectory, sameWorkspacePath } from './default-workspace.mjs';
@@ -25,7 +27,7 @@ import {
25
27
  validateAccessPolicy,
26
28
  } from './access-policy.mjs';
27
29
  import { CONNECTION_TEST_STATE_IDENTITY } from './connection-test.mjs';
28
- import { SESSION_BINDING_STATE_IDENTITY } from './session-binding-lock.mjs';
30
+ import { SESSION_BINDING_STATE_IDENTITY, withSessionBindingLock } from './session-binding-lock.mjs';
29
31
  import {
30
32
  DEFAULT_CONTEXT_ENHANCEMENT_CONFIG,
31
33
  normalizeContextEnhancementConfig,
@@ -384,6 +386,17 @@ function normalizeDocument(value) {
384
386
  if (Object.hasOwn(workspaces, id) && mode === 'steer') busyMessageModes[id] = mode;
385
387
  }
386
388
  }
389
+ // A damaged switch set must not take the bot's workspace or preset with it:
390
+ // every unreadable entry falls back to the full-content default.
391
+ const replyContents = Object.create(null);
392
+ if (value.replyContents && typeof value.replyContents === 'object'
393
+ && !Array.isArray(value.replyContents)) {
394
+ for (const [id, content] of Object.entries(value.replyContents)) {
395
+ if (/^[A-Za-z0-9_-]{1,128}$/.test(id) && Object.hasOwn(workspaces, id)) {
396
+ replyContents[id] = normalizeReplyContent(content);
397
+ }
398
+ }
399
+ }
387
400
  const accessPolicies = normalizeAccessPolicies(value.accessPolicies, workspaces);
388
401
  const conversationDirectory = normalizeConversationDirectory(value.conversationDirectory);
389
402
  const conversationDirectories = normalizeConversationDirectoryOverrides(value.conversationDirectories);
@@ -409,6 +422,7 @@ function normalizeDocument(value) {
409
422
  accessPolicies,
410
423
  aliases,
411
424
  busyMessageModes,
425
+ replyContents,
412
426
  };
413
427
  }
414
428
 
@@ -427,6 +441,7 @@ function storedDocument({
427
441
  accessPolicies,
428
442
  aliases,
429
443
  busyMessageModes,
444
+ replyContents,
430
445
  }) {
431
446
  const document = { version, workspaces };
432
447
  if (conversationDirectory) document.conversationDirectory = conversationDirectory;
@@ -434,6 +449,7 @@ function storedDocument({
434
449
  if (Object.keys(sessionDirectories).length) document.sessionDirectories = sessionDirectories;
435
450
  if (Object.keys(dsBotBindings).length > 0) document.dsBotBindings = dsBotBindings;
436
451
  if (Object.keys(busyMessageModes).length > 0) document.busyMessageModes = busyMessageModes;
452
+ if (Object.keys(replyContents).length > 0) document.replyContents = replyContents;
437
453
  if (Object.keys(aliases).length > 0) document.aliases = aliases;
438
454
  if (Object.keys(conversationWorkspaces).length > 0) {
439
455
  document.conversationWorkspaces = conversationWorkspaces;
@@ -497,6 +513,7 @@ export class BotWorkspaceStore {
497
513
  #models = {};
498
514
  #aliases = Object.create(null);
499
515
  #busyMessageModes = Object.create(null);
516
+ #replyContents = Object.create(null);
500
517
  #contextEnhancement = {};
501
518
  #deliveryTargets = Object.create(null);
502
519
  #dsBotBindings = Object.create(null);
@@ -534,6 +551,7 @@ export class BotWorkspaceStore {
534
551
  this.#models = normalized.models;
535
552
  this.#aliases = normalized.aliases;
536
553
  this.#busyMessageModes = normalized.busyMessageModes;
554
+ this.#replyContents = normalized.replyContents;
537
555
  this.#contextEnhancement = normalized.contextEnhancement;
538
556
  this.#deliveryTargets = normalized.deliveryTargets;
539
557
  this.#dsBotBindings = normalized.dsBotBindings;
@@ -550,6 +568,7 @@ export class BotWorkspaceStore {
550
568
  this.#models = {};
551
569
  this.#aliases = Object.create(null);
552
570
  this.#busyMessageModes = Object.create(null);
571
+ this.#replyContents = Object.create(null);
553
572
  this.#contextEnhancement = {};
554
573
  this.#deliveryTargets = Object.create(null);
555
574
  this.#dsBotBindings = Object.create(null);
@@ -746,6 +765,11 @@ export class BotWorkspaceStore {
746
765
  return normalizeBusyMessageMode(this.has(id) ? this.#busyMessageModes[id] : undefined);
747
766
  }
748
767
 
768
+ replyContentFor(botId) {
769
+ const id = botIdOf(botId);
770
+ return normalizeReplyContent(this.has(id) ? this.#replyContents[id] : undefined);
771
+ }
772
+
749
773
  contextEnhancementFor(botId) {
750
774
  const id = botIdOf(botId);
751
775
  return this.has(id) && Object.hasOwn(this.#contextEnhancement, id)
@@ -1183,6 +1207,30 @@ export class BotWorkspaceStore {
1183
1207
  });
1184
1208
  }
1185
1209
 
1210
+ async setReplyContent(botId, value, { incarnation } = {}) {
1211
+ const id = botIdOf(botId);
1212
+ const expectedIncarnation = incarnation === undefined ? this.incarnationFor(id) : incarnation;
1213
+ const content = validateReplyContent(value);
1214
+ return this.#enqueue(id, async () => {
1215
+ if (!this.has(id) || expectedIncarnation !== this.incarnationFor(id)) {
1216
+ const error = new Error('找不到要修改的机器人。');
1217
+ error.code = 'workspace-bot-not-found';
1218
+ throw error;
1219
+ }
1220
+ const next = { ...this.#replyContents };
1221
+ // The all-on default is the absence of a record, so a bot that never
1222
+ // changed the switches leaves no field in the document.
1223
+ if (isDefaultReplyContent(content)) delete next[id];
1224
+ else next[id] = content;
1225
+ await this.#persist(this.#contextEnhancement, this.#deliveryTargets,
1226
+ this.#version, this.#accessPolicies, this.#aliases, this.#conversationWorkspaces,
1227
+ this.#busyMessageModes, this.#dsBotBindings, this.#conversationDirectory,
1228
+ this.#conversationDirectories, this.#sessionDirectories, next);
1229
+ this.#replyContents = next;
1230
+ return content;
1231
+ });
1232
+ }
1233
+
1186
1234
  async setContextEnhancement(botId, value, { incarnation } = {}) {
1187
1235
  const id = botIdOf(botId);
1188
1236
  const expectedIncarnation = incarnation === undefined ? this.incarnationFor(id) : incarnation;
@@ -1566,6 +1614,7 @@ export class BotWorkspaceStore {
1566
1614
  ...Object.keys(this.#models),
1567
1615
  ...Object.keys(this.#aliases),
1568
1616
  ...Object.keys(this.#busyMessageModes),
1617
+ ...Object.keys(this.#replyContents),
1569
1618
  ...Object.keys(this.#contextEnhancement),
1570
1619
  ...Object.keys(this.#deliveryTargets),
1571
1620
  ...Object.keys(this.#accessPolicies),
@@ -1595,6 +1644,7 @@ export class BotWorkspaceStore {
1595
1644
  model: this.modelFor(bot.botId),
1596
1645
  contextEnhancement: this.contextEnhancementFor(bot.botId),
1597
1646
  busyMessageMode: this.busyMessageModeFor(bot.botId),
1647
+ replyContent: this.replyContentFor(bot.botId),
1598
1648
  accessPolicy: this.accessPolicyFor(bot.botId),
1599
1649
  }
1600
1650
  : bot),
@@ -1634,6 +1684,7 @@ export class BotWorkspaceStore {
1634
1684
  const hadModel = Object.hasOwn(this.#models, id);
1635
1685
  const hadAlias = Object.hasOwn(this.#aliases, id);
1636
1686
  const hadMessageMode = Object.hasOwn(this.#busyMessageModes, id);
1687
+ const hadReplyContent = Object.hasOwn(this.#replyContents, id);
1637
1688
  const hadContextEnhancement = Object.hasOwn(this.#contextEnhancement, id);
1638
1689
  const hadDeliveryTargets = Object.hasOwn(this.#deliveryTargets, id);
1639
1690
  const hadDsBotBindings = Object.hasOwn(this.#dsBotBindings, id);
@@ -1642,6 +1693,7 @@ export class BotWorkspaceStore {
1642
1693
  const hadDirectoryRecords = Object.hasOwn(this.#conversationDirectories, id) || Object.hasOwn(this.#sessionDirectories, id);
1643
1694
  const needsCleanup = hadWorkspace || hadPreset || hadModel || hadAlias || hadContextEnhancement
1644
1695
  || hadDeliveryTargets || hadDsBotBindings || hadAccessPolicy || hadConversationWorkspaces || hadMessageMode
1696
+ || hadReplyContent
1645
1697
  || hadDirectoryRecords
1646
1698
  || this.#dirtyRemovals.has(id);
1647
1699
  delete this.#workspaces[id];
@@ -1649,6 +1701,7 @@ export class BotWorkspaceStore {
1649
1701
  delete this.#models[id];
1650
1702
  delete this.#aliases[id];
1651
1703
  delete this.#busyMessageModes[id];
1704
+ delete this.#replyContents[id];
1652
1705
  delete this.#contextEnhancement[id];
1653
1706
  delete this.#deliveryTargets[id];
1654
1707
  delete this.#dsBotBindings[id];
@@ -1697,6 +1750,7 @@ export class BotWorkspaceStore {
1697
1750
  conversationDirectory = this.#conversationDirectory,
1698
1751
  conversationDirectories = this.#conversationDirectories,
1699
1752
  sessionDirectories = this.#sessionDirectories,
1753
+ replyContents = this.#replyContents,
1700
1754
  ) {
1701
1755
  await writeStoredDocument(this.#path, storedDocument({
1702
1756
  version,
@@ -1710,6 +1764,7 @@ export class BotWorkspaceStore {
1710
1764
  accessPolicies,
1711
1765
  aliases,
1712
1766
  busyMessageModes,
1767
+ replyContents,
1713
1768
  conversationDirectory,
1714
1769
  conversationDirectories,
1715
1770
  sessionDirectories,
@@ -1723,6 +1778,7 @@ export class BotWorkspaceStore {
1723
1778
  || Object.keys(this.#models).length > 0
1724
1779
  || Object.keys(this.#aliases).length > 0
1725
1780
  || Object.keys(this.#busyMessageModes).length > 0
1781
+ || Object.keys(this.#replyContents).length > 0
1726
1782
  || Object.keys(this.#contextEnhancement).length > 0
1727
1783
  || Object.keys(this.#deliveryTargets).length > 0
1728
1784
  || Object.keys(this.#dsBotBindings).length > 0
@@ -1781,6 +1837,12 @@ function unavailableModel() {
1781
1837
  return error;
1782
1838
  }
1783
1839
 
1840
+ function unavailableModelCatalog(cause) {
1841
+ const error = new Error(t('无法读取所选模型的列表,模型设置未保存,请重试。'), { cause });
1842
+ error.code = 'model-catalog-unavailable';
1843
+ return connectionStageError(error, 'status.read', undefined, { method: 'llm.models' });
1844
+ }
1845
+
1784
1846
  function assertCurrentBotScope(isCurrentScope) {
1785
1847
  if (isCurrentScope()) return;
1786
1848
  const error = new Error('找不到要修改的机器人。');
@@ -1992,14 +2054,30 @@ export function createBotWorkspaceScope(
1992
2054
 
1993
2055
  const scopedHarness = new Proxy(harness, {
1994
2056
  get(target, property) {
2057
+ if (property === 'sessionFor') {
2058
+ // Read-only state lookup used by /sessionlist to mark the binding. The
2059
+ // state proxy owns the generation checks, so delegate instead of
2060
+ // exposing the raw mapping.
2061
+ return (key, ...args) => scopedState.sessionFor(key, ...args);
2062
+ }
1995
2063
  if (property === 'resolveDsBotSession') {
1996
2064
  return async (key) => {
1997
2065
  assertCurrentBotScope(isCurrentScope);
1998
2066
  const binding = dsBinding(key);
1999
2067
  if (!binding) return null;
2000
2068
  if (!dsBot) throw deliveryTargetError('ds-bot-unavailable', 'DS Bot 当前不可用,请检查插件状态。');
2001
- const bot = await dsBot.resolve(binding.dsBotId);
2002
- if (!(await target.sessionExists(bot.sessionId))) {
2069
+ let bot = await dsBot.resolve(binding.dsBotId);
2070
+ if (typeof target.isSessionArchived === 'function' && (await target.isSessionArchived(bot.sessionId))) {
2071
+ for (let i = 0; i < 5; i += 1) {
2072
+ await new Promise((resolve) => setTimeout(resolve, 200));
2073
+ const updated = await dsBot.resolve(binding.dsBotId).catch(() => null);
2074
+ if (updated && updated.sessionId !== bot.sessionId && !(await target.isSessionArchived(updated.sessionId))) {
2075
+ bot = updated;
2076
+ break;
2077
+ }
2078
+ }
2079
+ }
2080
+ if (!(await target.sessionExists(bot.sessionId)) || (typeof target.isSessionArchived === 'function' && (await target.isSessionArchived(bot.sessionId)))) {
2003
2081
  throw deliveryTargetError('ds-bot-not-found', 'DS Bot 的当前会话不可用。');
2004
2082
  }
2005
2083
  assertCurrentBotScope(isCurrentScope);
@@ -2062,6 +2140,11 @@ export function createBotWorkspaceScope(
2062
2140
  if (property === 'currentBusyMessageMode') {
2063
2141
  return () => isCurrentScope() ? workspaces.busyMessageModeFor(botId) : 'queue';
2064
2142
  }
2143
+ if (property === 'currentReplyContent') {
2144
+ return () => (isCurrentScope()
2145
+ ? workspaces.replyContentFor(botId)
2146
+ : normalizeReplyContent(undefined));
2147
+ }
2065
2148
  if (property === 'currentWorkspace') {
2066
2149
  return () => {
2067
2150
  if (!isCurrentScope()) {
@@ -2081,6 +2164,24 @@ export function createBotWorkspaceScope(
2081
2164
  }
2082
2165
  };
2083
2166
  }
2167
+ if (property === 'archiveWorkspaceSession' && typeof target[property] === 'function') {
2168
+ // Archiving mutates Harness state, so it checks the bot scope on both
2169
+ // sides of the call like every other write this scope exposes.
2170
+ return async (...args) => {
2171
+ if (!isCurrentScope()) {
2172
+ const error = new Error('找不到要修改的机器人。');
2173
+ error.code = 'workspace-bot-not-found';
2174
+ throw error;
2175
+ }
2176
+ const result = await target.archiveWorkspaceSession(...args);
2177
+ if (!isCurrentScope()) {
2178
+ const error = new Error('找不到要修改的机器人。');
2179
+ error.code = 'workspace-bot-not-found';
2180
+ throw error;
2181
+ }
2182
+ return result;
2183
+ };
2184
+ }
2084
2185
  if ((property === 'listWorkspaces'
2085
2186
  || property === 'listWorkspaceEntries'
2086
2187
  || property === 'listWorkspaceSessions'
@@ -2282,7 +2383,8 @@ export function createBotWorkspaceScope(
2282
2383
  };
2283
2384
  }
2284
2385
  if (property === 'bindWorkspaceSession') {
2285
- return async (conversationKey, sessionId) => {
2386
+ return async (conversationKey, sessionId, options = {}) => {
2387
+ const { expectedWorkspace } = options;
2286
2388
  assertNoDsBinding(conversationKey);
2287
2389
  if (typeof conversationKey !== 'string' || !conversationKey
2288
2390
  || typeof sessionId !== 'string' || !sessionId) {
@@ -2319,17 +2421,27 @@ export function createBotWorkspaceScope(
2319
2421
  || adopted.sessionId !== sessionId || typeof adopted.workspace !== 'string') {
2320
2422
  throw new TypeError('Harness returned an invalid adopted workspace session');
2321
2423
  }
2424
+ // Title selection is local to the Workspace observed by the search.
2425
+ // Recheck it here before committing; explicit IDs retain their
2426
+ // existing bot-wide switching behavior.
2427
+ const localBinding = expectedWorkspace !== undefined;
2428
+ if (localBinding
2429
+ && (!(await sameWorkspacePath(adopted.workspace, expectedWorkspace))
2430
+ || !(await sameWorkspacePath(adopted.workspace,
2431
+ await scopedHarness.resolveConversationWorkspace(conversationKey))))) {
2432
+ throw workspaceSessionStale('The conversation workspace changed during session selection.');
2433
+ }
2322
2434
  // Selecting another session in the current automatic group must not
2323
2435
  // turn that group into the bot's manual directory and clear every
2324
2436
  // other conversation. Explicit cross-workspace selection keeps its
2325
2437
  // existing bot-wide semantics.
2326
2438
  const baseWorkspace = workspaces.workspaceFor(botId);
2327
- const preserveBotWorkspace = !workspaces.hasConversationWorkspaceOverride(botId, conversationKey)
2439
+ const preserveBotWorkspace = localBinding || (!workspaces.hasConversationWorkspaceOverride(botId, conversationKey)
2328
2440
  && normalizeAgentPresetId(basename(adopted.workspace)) !== null
2329
2441
  && await target.isUngroupedWorkspace?.(baseWorkspace)
2330
2442
  && await sameWorkspacePath(dirname(adopted.workspace), join(baseWorkspace, 'presets'))
2331
2443
  && await sameWorkspacePath(adopted.workspace,
2332
- await scopedHarness.resolveConversationWorkspace(conversationKey));
2444
+ await scopedHarness.resolveConversationWorkspace(conversationKey)));
2333
2445
  const bound = await workspaces.bindWorkspaceSession(botId, adopted.workspace, {
2334
2446
  conversationKey,
2335
2447
  sessionId,
@@ -2360,6 +2472,22 @@ export function createBotWorkspaceScope(
2360
2472
  conversationKey,
2361
2473
  conversationGeneration: bound.conversationGeneration ?? 0,
2362
2474
  });
2475
+ // /session, /go, /prev and /next all bind through this one path, so the
2476
+ // navigation ring records the bind here and stays in sync with the
2477
+ // Session binding itself. Best-effort: a ring write must not fail a bind.
2478
+ // A non-navigation bind (/session adopt) appends the Session as the
2479
+ // ring's current position; /go, /prev and /next manage the visit stack
2480
+ // themselves and pass { navigation: true } to skip this.
2481
+ try {
2482
+ const registered = await state.ensureSessionRing?.(conversationKey, sessionId, {
2483
+ title: typeof adopted.title === 'string' && adopted.title ? adopted.title : undefined,
2484
+ });
2485
+ if (options.navigation !== true && registered?.entry) {
2486
+ await state.appendRing?.(conversationKey, registered.entry.n);
2487
+ }
2488
+ } catch (error) {
2489
+ console.warn('[dsh-im] unable to record the session in the navigation ring:', error?.message ?? error);
2490
+ }
2363
2491
  return {
2364
2492
  ...adopted,
2365
2493
  workspace: bound.workspace,
@@ -2492,8 +2620,10 @@ export function createBotWorkspaceScope(
2492
2620
  // actual outcome even if a workspace switch commits concurrently.
2493
2621
  return target[method](sessionId, ...args);
2494
2622
  };
2623
+ let replySessionId = sessionId;
2495
2624
  return Object.freeze({
2496
2625
  sessionId,
2626
+ get replySessionId() { return replySessionId; },
2497
2627
  async sessionExists(...args) {
2498
2628
  if (!isCurrentSession()) return false;
2499
2629
  const exists = await target.sessionExists(sessionId, ...args);
@@ -2531,7 +2661,15 @@ export function createBotWorkspaceScope(
2531
2661
  }
2532
2662
  // This is a Bot-wide setting. Never mutate only the IM session: DS
2533
2663
  // Bot applies the choice to its own and group sessions as well.
2534
- return dsBot.updateBotModel(dsBotId, selection, options);
2664
+ const result = await dsBot.updateBotModel(dsBotId, selection, options);
2665
+ const selected = result?.selected;
2666
+ if (!selected || selected.reasoningEffort !== undefined) return result;
2667
+ // Without a level DS Bot sends none, and DSH runs the model's
2668
+ // default one: report the level the Session actually runs.
2669
+ const current = (await target.getSessionModels(sessionId, options))?.current;
2670
+ return current?.provider === selected.provider && current?.model === selected.model
2671
+ ? { selected: { ...current } }
2672
+ : result;
2535
2673
  },
2536
2674
  isRunning(...args) {
2537
2675
  return invokeCurrentSession('isSessionRunning', args, 'run-state check');
@@ -2566,7 +2704,63 @@ export function createBotWorkspaceScope(
2566
2704
  throw workspaceSessionStale('DS Bot changed before this prompt started.');
2567
2705
  }
2568
2706
  }
2569
- return target.ask(sessionId, ...args);
2707
+ if (!dsBotId) return target.ask(sessionId, ...args);
2708
+ const options = typeof args[1] === 'number' ? { timeoutMs: args[1] } : args[1] ?? {};
2709
+ const handoffResources = { stagedBatches: [] };
2710
+ let currentSessionId = sessionId;
2711
+ let promptRpcId;
2712
+ const assertStillBound = () => {
2713
+ options.signal?.throwIfAborted();
2714
+ if (!isCurrentSession()) {
2715
+ // This input was already accepted. A stale-session error here
2716
+ // would cause the outer loop to submit it again after unbind.
2717
+ throw new DOMException('DS Bot binding changed while awaiting a reply.', 'AbortError');
2718
+ }
2719
+ };
2720
+ for (;;) {
2721
+ try {
2722
+ const answer = promptRpcId
2723
+ ? await target.waitForTransferredReply(currentSessionId, {
2724
+ ...options, handoffResources, promptRpcId, assertCurrent: assertStillBound,
2725
+ })
2726
+ : await target.ask(sessionId, args[0], { ...options, handoffResources });
2727
+ if (promptRpcId) assertStillBound();
2728
+ replySessionId = currentSessionId;
2729
+ return answer;
2730
+ } catch (askError) {
2731
+ if (!dsBotId || !['session-archived', 'turn-blocked'].includes(askError?.code)) throw askError;
2732
+ assertStillBound();
2733
+ const evidence = extractConnectionEvidence(askError);
2734
+ const notSubmitted = evidence.details.submissionState === 'not-submitted';
2735
+ const accepted = askError.promptAccepted === true || evidence.details.submissionState === 'accepted';
2736
+ const originalRpcId = promptRpcId ?? askError.details?.promptRpcId ?? evidence.correlation.promptRpcId;
2737
+ // A failed submit can have an unknown outcome. Only explicit
2738
+ // pre-submit evidence permits replay; everything else needs
2739
+ // the durable identity of an accepted message to follow.
2740
+ if (!notSubmitted && (!accepted || !originalRpcId
2741
+ || typeof target.waitForTransferredReply !== 'function')) throw askError;
2742
+ let fresh;
2743
+ for (let attempt = 0; attempt < 6; attempt += 1) {
2744
+ assertStillBound();
2745
+ fresh = await dsBot.resolve(dsBotId).catch(() => null);
2746
+ assertStillBound();
2747
+ if (fresh && fresh.sessionId !== currentSessionId) break;
2748
+ await delay(200, undefined, { signal: options.signal });
2749
+ }
2750
+ if (!fresh || fresh.sessionId === currentSessionId) throw askError;
2751
+ if (notSubmitted) throw workspaceSessionStale('DS Bot rolled over before this prompt was submitted.');
2752
+ currentSessionId = fresh.sessionId;
2753
+ promptRpcId = originalRpcId;
2754
+ await withSessionBindingLock(state, conversationKey, async () => {
2755
+ assertStillBound();
2756
+ await state.setSession(conversationKey, currentSessionId);
2757
+ assertStillBound();
2758
+ sessionGenerations.set(currentSessionId, {
2759
+ generation, conversationKey, conversationGeneration,
2760
+ });
2761
+ });
2762
+ }
2763
+ }
2570
2764
  },
2571
2765
  });
2572
2766
  };
@@ -2581,6 +2775,26 @@ export function createBotWorkspaceScope(
2581
2775
  return target.sessionExists(sessionId, ...args);
2582
2776
  };
2583
2777
  }
2778
+ if (property === 'forkSession') {
2779
+ return async (sessionId, options = {}) => {
2780
+ if (!isCurrentScope()) {
2781
+ throw workspaceSessionStale('The bot workspace changed before the fork.');
2782
+ }
2783
+ if (generationIsStale(sessionGenerations.get(sessionId))) {
2784
+ throw workspaceSessionStale('The session is no longer in the current workspace.');
2785
+ }
2786
+ if (typeof target.forkSession !== 'function') {
2787
+ const error = new Error('The Host does not support forking sessions');
2788
+ error.code = 'harness-api-not-found';
2789
+ throw error;
2790
+ }
2791
+ const result = await target.forkSession(sessionId, options);
2792
+ if (!isCurrentScope()) {
2793
+ throw workspaceSessionStale('The bot workspace changed while the fork was running.');
2794
+ }
2795
+ return result;
2796
+ };
2797
+ }
2584
2798
  if (property === 'ask') {
2585
2799
  return (sessionId, ...args) => {
2586
2800
  const entry = sessionGenerations.get(sessionId);
@@ -2745,9 +2959,18 @@ export function createWorkspaceAwareController(controller, {
2745
2959
  error.code = 'workspace-bot-not-found';
2746
2960
  throw error;
2747
2961
  }
2748
- const catalog = model && modelCatalog
2749
- ? await resolveModelCatalog(modelCatalog, { fresh: true })
2750
- : null;
2962
+ let catalog = null;
2963
+ if (model && modelCatalog) {
2964
+ try {
2965
+ catalog = await resolveModelCatalog(modelCatalog, { fresh: true, throwOnError: true });
2966
+ } catch (error) {
2967
+ if (error?.name === 'AbortError') throw error;
2968
+ throw unavailableModelCatalog(error);
2969
+ }
2970
+ if (catalog?.failures.some((failure) => failure.id === model.provider)) {
2971
+ throw unavailableModelCatalog();
2972
+ }
2973
+ }
2751
2974
  const entry = modelCatalogEntry(catalog, model);
2752
2975
  if (model && (!modelCatalog || !entry)) {
2753
2976
  throw unavailableModel();
@@ -2784,6 +3007,26 @@ export function createWorkspaceAwareController(controller, {
2784
3007
  return result;
2785
3008
  });
2786
3009
  };
3010
+ const updateReplyContent = (botId, value, projectStatus) => {
3011
+ const incarnation = workspaces.incarnationFor(botId);
3012
+ const content = validateReplyContent(value);
3013
+ return withBotTransition(botId, async () => {
3014
+ const snapshot = await decorate(await controller.status());
3015
+ if (!snapshot?.bots?.some((bot) => bot?.botId === botId)) {
3016
+ const error = new Error('找不到要修改的机器人。');
3017
+ error.code = 'workspace-bot-not-found';
3018
+ throw error;
3019
+ }
3020
+ const updated = {
3021
+ ...snapshot,
3022
+ bots: snapshot.bots.map((bot) => (bot.botId === botId
3023
+ ? { ...bot, replyContent: content } : bot)),
3024
+ };
3025
+ const result = projectStatus ? await projectStatus(updated) : updated;
3026
+ await workspaces.setReplyContent(botId, content, { incarnation });
3027
+ return result;
3028
+ });
3029
+ };
2787
3030
  const updateBusyMessageMode = (botId, value, projectStatus) => {
2788
3031
  const incarnation = workspaces.incarnationFor(botId);
2789
3032
  const busyMessageMode = validateBusyMessageMode(value);
@@ -2929,6 +3172,7 @@ export function createWorkspaceAwareController(controller, {
2929
3172
  if (property === 'updateModel') return updateModel;
2930
3173
  if (property === 'updateAlias') return updateAlias;
2931
3174
  if (property === 'updateBusyMessageMode') return updateBusyMessageMode;
3175
+ if (property === 'updateReplyContent') return updateReplyContent;
2932
3176
  if (property === 'updateContextEnhancement') return updateContextEnhancement;
2933
3177
  if (property === 'updateAccessPolicy') return updateAccessPolicy;
2934
3178
  const value = Reflect.get(target, property, target);
@@ -23,7 +23,7 @@ export class BusyMessageDispatcher {
23
23
  key, messageId, text, commandText = text, eligible, harness, state, status,
24
24
  control, signal, enhancement, pendingInteraction, acceptedMessageIds,
25
25
  mode = harness.currentBusyMessageMode?.(), onFailure,
26
- enqueue, isQueued, send, logger = console, onSteered, onError,
26
+ enqueue, isQueued, send, logger = console, onSteered, onError, steerReceipt = true,
27
27
  }) {
28
28
  // Read once, before any await: a settings change cannot reinterpret this input.
29
29
  const steer = normalizeBusyMessageMode(mode) === 'steer'
@@ -61,7 +61,7 @@ export class BusyMessageDispatcher {
61
61
  });
62
62
  if (!submitted) return queue(true);
63
63
  // Submission is final even if its receipt fails.
64
- await send(t('已提交补充指令,Agent 会在下一步读取。'));
64
+ if (steerReceipt) await send(t('已提交补充指令,Agent 会在下一步读取。'));
65
65
  await onSteered?.();
66
66
  status.lastError = null;
67
67
  return {};
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Declared channel capabilities for the session-navigation commands.
3
+ *
4
+ * Declared once here instead of probing the bot adapter per command, so the
5
+ * capability matrix (message buttons, document send) stays auditable in one
6
+ * place. The bridge still verifies the concrete bot method exists before it
7
+ * sends, because a declared capability is not a promise that this bot instance
8
+ * can currently deliver it.
9
+ *
10
+ * - buttons: the preview may carry a native "Hide" button.
11
+ * - fileSend: the /tail export can be delivered as a document attachment.
12
+ */
13
+
14
+ const NO_CAPABILITIES = Object.freeze({ buttons: false, fileSend: false });
15
+
16
+ export const CHANNEL_CAPABILITIES = Object.freeze({
17
+ telegram: Object.freeze({ buttons: true, fileSend: true }),
18
+ slack: Object.freeze({ buttons: false, fileSend: true }),
19
+ discord: Object.freeze({ buttons: false, fileSend: true }),
20
+ // Feishu and DingTalk have their own native card/button systems that are not
21
+ // wired through the shared sendInteractionCard seam, and their file send is
22
+ // not exposed through the shared sendFile seam either — so neither is
23
+ // advertised here until it is actually wired.
24
+ feishu: Object.freeze({ buttons: false, fileSend: false }),
25
+ dingtalk: Object.freeze({ buttons: false, fileSend: false }),
26
+ // whatsapp, matrix, email, office, qq, wecom, wecom-app, weixin, imessage:
27
+ // no native message buttons and no document attachment path today.
28
+ });
29
+
30
+ export function channelCapabilities(channelKey) {
31
+ return CHANNEL_CAPABILITIES[channelKey] ?? NO_CAPABILITIES;
32
+ }
33
+
34
+ /** A document can be delivered only on a file-capable channel with a send method. */
35
+ export function documentSendSupported(channelKey, bot) {
36
+ return channelCapabilities(channelKey).fileSend === true
37
+ && typeof bot?.sendFile === 'function';
38
+ }
39
+
40
+ /** A preview may carry a Hide button only on a button-capable channel with cards. */
41
+ export function buttonPreviewSupported(channelKey, bot) {
42
+ return channelCapabilities(channelKey).buttons === true
43
+ && typeof bot?.sendInteractionCard === 'function';
44
+ }
@@ -23,8 +23,14 @@ function defineCatalogCommand(name, description, help, { aliases = [], ...option
23
23
  // enabled: false removes a definition from both consumers; menuVisible: false
24
24
  // hides a command (or alias) only from the native menu, leaving help available.
25
25
  export const SHARED_COMMAND_CATALOG = Object.freeze([
26
- defineCatalogCommand('new', '开启一个全新会话', [
27
- '/new 开启一个全新会话',
26
+ defineCatalogCommand('new', '开启一个全新会话(可带标题)', [
27
+ '/new [标题] 开启一个全新会话(可指定标题)',
28
+ ]),
29
+ defineCatalogCommand('fork', '从当前会话分支一个新会话', [
30
+ '/fork [标题] 从当前会话分支一个新会话(默认沿用父会话标题加“ (fork)”)',
31
+ ], { requiresSessionFork: true }),
32
+ defineCatalogCommand('reset', '重置当前会话上下文(保留会话编号)', [
33
+ '/reset 重置当前会话上下文(保留会话编号,旧会话可 /session 找回)',
28
34
  ]),
29
35
  defineCatalogCommand('compact', '压缩当前会话的较早上下文', [
30
36
  '/compact 压缩当前会话的较早上下文',
@@ -67,11 +73,42 @@ export const SHARED_COMMAND_CATALOG = Object.freeze([
67
73
  }),
68
74
  defineCatalogCommand('sessionlist', '列出会话 ID 和标题', [
69
75
  '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题',
76
+ '/sessionlist --all 跨工作区汇总会话(每个工作区默认显示 10 个,可用 --limit N 调整)',
70
77
  '/sessionlist --limit N 仅列出当前工作区前 N 个会话',
71
78
  ], { aliases: [{ name: 'sessions', menuVisible: false }] }),
72
79
  defineCatalogCommand('session', '将当前聊天绑定到指定会话', [
73
- '/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话',
80
+ '/session Session ID、当前工作区序号或标题关键词 将当前聊天绑定到指定会话',
81
+ '/sess 同一命令的别名(/session 被客户端同名命令抢占时使用)',
82
+ ], { aliases: [{ name: 'sess', menuVisible: false }] }),
83
+ defineCatalogCommand('sessionarchive', '归档指定会话(DSH 能力)', [
84
+ '/sessionarchive(或 /sessarchive)Session ID 归档一个会话;序号只做预览',
85
+ '/sessionarchive <Session ID> --stop 归档前先停止该会话正在运行的任务',
86
+ ], { aliases: [{ name: 'sessarchive', menuVisible: false }] }),
87
+ defineCatalogCommand('ls', '列出本聊天使用过的会话(按聊天/话题隔离)', [
88
+ '/ls 或 /list 列出本聊天使用过的会话(● 当前,←/→ 可前后切换,✕ 已失效;列表按聊天隔离,论坛群按话题)',
89
+ ], { aliases: [{ name: 'list', menuVisible: false }] }),
90
+ defineCatalogCommand('go', '切换到指定编号的会话', [
91
+ '/go 会话编号 切换到该会话(编号见 /ls)',
92
+ ]),
93
+ defineCatalogCommand('prev', '回到上一个会话', [
94
+ '/prev 回到上一个会话',
95
+ ]),
96
+ defineCatalogCommand('next', '前进到下一个会话', [
97
+ '/next 前进到下一个会话',
98
+ ]),
99
+ defineCatalogCommand('drop', '从会话列表移除一条记录', [
100
+ '/drop 会话编号 从本聊天会话列表移除该条记录(不删除 Harness 会话)',
101
+ '/drop all 移除除当前会话外的全部记录(不删除 Harness 会话)',
102
+ ]),
103
+ defineCatalogCommand('title', '查看或重命名会话标题', [
104
+ '/title 查看当前会话标题',
105
+ '/title 新标题 重命名当前会话',
106
+ '/title 会话编号 新标题 重命名指定会话',
74
107
  ]),
108
+ defineCatalogCommand('tail', '预览或导出会话内容', [
109
+ '/tail 或 /peek [编号] [条数] 预览最近消息(默认 5 条,仅提问与回答)',
110
+ '/tail 或 /peek [编号] file 导出整个会话为 Markdown 文件',
111
+ ], { aliases: [{ name: 'peek', menuVisible: false }] }),
75
112
  defineCatalogCommand('models', '按序号列出所有可用模型', [
76
113
  '/models 按序号列出所有可用模型',
77
114
  ]),
@@ -123,6 +160,34 @@ export function commandsForChannel(channel, catalog = SHARED_COMMAND_CATALOG) {
123
160
  return catalog.filter((item) => item.enabled !== false && item.channels.includes(channel));
124
161
  }
125
162
 
163
+ /**
164
+ * Drop entries whose required Host capability is absent (e.g. /fork when the
165
+ * host facade exposes no sessions.fork member), so the menu and /help never
166
+ * promise a command that always refuses.
167
+ */
168
+ export function availableCommandCatalog(catalog = SHARED_COMMAND_CATALOG, { supportsFork = true } = {}) {
169
+ return catalog.filter((item) => item.requiresSessionFork !== true || supportsFork);
170
+ }
171
+
172
+ /**
173
+ * The session-navigation help lines every channel that handles them should
174
+ * list, without the file-export form of /tail (only file-capable channels
175
+ * document that). Kept here so the non-text bridges cannot drift from /ls.
176
+ */
177
+ export const SESSION_NAV_HELP_LINES = Object.freeze([
178
+ '/ls 或 /list 列出本聊天使用过的会话(● 当前,←/→ 可前后切换,✕ 已失效;列表按聊天隔离,论坛群按话题)',
179
+ '/go 会话编号 切换到该会话(编号见 /ls)',
180
+ '/prev 回到上一个会话',
181
+ '/next 前进到下一个会话',
182
+ '/drop 会话编号 从本聊天会话列表移除该条记录(不删除 Harness 会话)',
183
+ '/title 查看当前会话标题',
184
+ '/title 新标题 重命名当前会话',
185
+ '/title 会话编号 新标题 重命名指定会话',
186
+ '/fork [标题] 从当前会话分支一个新会话(默认沿用父会话标题加“ (fork)”)',
187
+ '/reset 重置当前会话上下文(保留会话编号,旧会话可 /session 找回)',
188
+ '/tail 或 /peek [编号] [条数] 预览最近消息(默认 5 条,仅提问与回答)',
189
+ ]);
190
+
126
191
  export function commandHelpLines(channel, catalog = SHARED_COMMAND_CATALOG) {
127
192
  return commandsForChannel(channel, catalog).flatMap((item) => item.help.map((line) => t(line)));
128
193
  }