@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
@@ -123,6 +123,34 @@ if (forbiddenDshLockPaths.length > 0) {
123
123
  );
124
124
  }
125
125
 
126
+ // The client inject list and the compatibility baseline both name host-side
127
+ // packages and releases that live outside this repository, so a stale entry
128
+ // passes every bundle assertion below while it silently costs the client row its
129
+ // load order (or advertises a baseline the build was never verified against).
130
+ const compatibility = manifest.dsh?.compatibility ?? {};
131
+ const clientInject = manifest.dsh?.client?.inject ?? [];
132
+ if (typeof compatibility.dsh !== 'string'
133
+ || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(compatibility.dsh)
134
+ || compatibility.dshReleases?.[compatibility.dsh] !== 'compatible') {
135
+ throw new Error('dsh.compatibility.dsh must name a release that dshReleases marks compatible');
136
+ }
137
+ if (clientInject.length === 0 || new Set(clientInject).size !== clientInject.length) {
138
+ throw new Error('dsh.client.inject must list unique DSH client packages');
139
+ }
140
+ for (const name of clientInject) {
141
+ if (!/^@deepseek-ai\/dsh-client-[a-z0-9-]+$/u.test(name)) {
142
+ throw new Error(`dsh.client.inject must name DSH client packages: ${name}`);
143
+ }
144
+ }
145
+ // Neither package is a Web client row on DSH 0.2.2-rc.5: the runtime package
146
+ // stopped publishing after 0.1.1-rc.2 and ui-slots is the registry core without
147
+ // a client entry. Injecting them waits for rows that never arrive.
148
+ for (const retired of ['@deepseek-ai/dsh-client-runtime', '@deepseek-ai/dsh-client-ui-slots']) {
149
+ if (clientInject.includes(retired)) {
150
+ throw new Error(`${retired} is not a loadable DSH 0.2.2-rc.5 client row`);
151
+ }
152
+ }
153
+
126
154
  if (!/\bid\s*:\s*["']@xmanrui\/dsh-im["']/u.test(client)) {
127
155
  throw new Error('client bundle does not register the dsh-im loader id');
128
156
  }
@@ -149,38 +177,48 @@ if (client.includes('settings.plugins.tab') || clientSources.includes('settings.
149
177
  // Connections still have no channel-enable toggle. Checkable inputs are owned
150
178
  // only by the shared context editor, the saved-target Session sync row, the
151
179
  // email settings, the Telegram thinking-traces block, Feishu panel settings,
152
- // and the conversation-directory settings form.
180
+ // the conversation-directory settings form, and the general Delivery tab.
153
181
  // The context editor contains one switch template and one mapped field-input
154
182
  // template; the delivery target adds one ordinary checkbox template; the
155
183
  // Telegram thinking-traces block adds two ordinary checkbox templates (traces
156
- // and frame numbering). General settings adds one mapped switch template for
157
- // the two Feishu panel preferences. Conversation-directory settings adds one
158
- // switch template reused for the bot override and channel default.
184
+ // and frame numbering). General settings adds two mapped switch templates: one
185
+ // for the shared reply-content switches, one for the two Feishu panel
186
+ // preferences. Conversation-directory settings adds one
187
+ // switch template reused for the bot override and channel default. The Delivery
188
+ // tab adds one ordinary checkbox template mapped over its two switches (mirror
189
+ // Web input, deliver model answers).
159
190
  const contextEditorSource = await readFile(resolve(root, 'plugin-src/client/context-enhancement.js'), 'utf8');
160
191
  const deliverySettingsSource = await readFile(resolve(root, 'plugin-src/client/delivery-settings.js'), 'utf8');
161
192
  const emailSettingsSource = await readFile(resolve(root, 'plugin-src/client/channels/email/index.js'), 'utf8');
162
193
  const thinkingTracesSource = await readFile(resolve(root, 'plugin-src/client/channels/telegram/thinking-traces.js'), 'utf8');
163
194
  const botGeneralSettingsSource = await readFile(resolve(root, 'plugin-src/client/bot-general-settings.js'), 'utf8');
164
195
  const conversationDirectorySettingsSource = await readFile(resolve(root, 'plugin-src/client/channels/feishu/conversation-directory-settings.js'), 'utf8');
196
+ const deliverySyncSettingsSource = await readFile(
197
+ resolve(root, 'plugin-src/client/delivery-sync-settings.js'),
198
+ 'utf8',
199
+ );
165
200
  const otherClientSources = clientSources
166
201
  .replace(contextEditorSource, '')
167
202
  .replace(deliverySettingsSource, '')
168
203
  .replace(emailSettingsSource, '')
169
204
  .replace(thinkingTracesSource, '')
170
205
  .replace(botGeneralSettingsSource, '')
171
- .replace(conversationDirectorySettingsSource, '');
206
+ .replace(conversationDirectorySettingsSource, '')
207
+ .replace(deliverySyncSettingsSource, '');
172
208
  if (/role:\s*["']switch|type:\s*["']checkbox/.test(otherClientSources)
173
209
  || (deliverySettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
174
210
  || /role:\s*["']switch["']/u.test(deliverySettingsSource)
175
211
  || (thinkingTracesSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 2
176
212
  || /role:\s*["']switch["']/u.test(thinkingTracesSource)
177
- || (botGeneralSettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
178
- || (botGeneralSettingsSource.match(/role:\s*["']switch["']/g) ?? []).length !== 1
213
+ || (botGeneralSettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 2
214
+ || (botGeneralSettingsSource.match(/role:\s*["']switch["']/g) ?? []).length !== 2
179
215
  || (conversationDirectorySettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
180
216
  || (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');
217
+ || (deliverySyncSettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
218
+ || /role:\s*["']switch["']/u.test(deliverySyncSettingsSource)
219
+ || (client.match(/role:\s*["']switch["']/g) ?? []).length !== 4
220
+ || (client.match(/type:\s*["']checkbox["']/g) ?? []).length !== 9) {
221
+ throw new Error('checkable inputs must be limited to context enhancement, Session sync, email settings, Telegram thinking traces, Feishu panel settings, reply content, conversation-directory settings, and the Delivery tab');
184
222
  }
185
223
  for (const marker of ['bot.conversation-directory.set', 'bot.conversation-directory.default.set']) {
186
224
  if (!host.includes(marker) || !client.includes(marker)) {
@@ -1,4 +1,5 @@
1
1
  import { BusyMessageDispatcher, canAutomaticallySteer } from '../shared/busy-message-dispatcher.mjs';
2
+ import { SESSION_NAV_HELP_LINES } from '../shared/command-catalog.mjs';
2
3
  import { createDeferredDeliveryCoordinator, deferredOutcomeText } from '../shared/deferred-delivery-coordinator.mjs';
3
4
  import {
4
5
  DINGTALK_DONE_REACTION_NAME,
@@ -17,6 +18,7 @@ import {
17
18
  import { HarnessApprovalQueue } from '../shared/harness-approval.mjs';
18
19
  import { runCompactCommand } from '../shared/compact-command.mjs';
19
20
  import { isClearCommand, runClearCommand } from '../shared/clear-command.mjs';
21
+ import { isResetCommand, runResetCommand } from '../shared/reset-command.mjs';
20
22
  import { isHistoryCommand, runHistoryCommand } from '../shared/history-command.mjs';
21
23
  import {
22
24
  isControlCommand,
@@ -32,6 +34,11 @@ import {
32
34
  } from '../shared/preset-command.mjs';
33
35
  import { conversationSessionWorkspace, runWorkspaceCommand } from '../shared/workspace-command.mjs';
34
36
  import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
37
+ import {
38
+ isSessionNavCommand,
39
+ runSessionNavTextCommand,
40
+ } from '../shared/session-nav-command.mjs';
41
+ import { createConversationSession, isNewCommand, newCommandTitle } from '../shared/new-command.mjs';
35
42
  import {
36
43
  captureContextEnhancement,
37
44
  captureContextEnhancementSource,
@@ -95,8 +102,10 @@ const HELP_TEXT_LINES = [
95
102
  '/workspacelist 列出工作区绝对路径',
96
103
  '/ws、/wsl、/workspaces 工作区命令别名',
97
104
  '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题',
105
+ '/sessionlist --all 跨工作区汇总会话(每个工作区默认显示 10 个,可用 --limit N 调整)',
98
106
  '/sessionlist --limit N 仅列出当前工作区前 N 个会话',
99
- '/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话',
107
+ '/session Session ID、当前工作区序号或标题关键词 将当前聊天绑定到指定会话',
108
+ ...SESSION_NAV_HELP_LINES,
100
109
  '/models 按序号列出所有可用模型',
101
110
  '/reasoninglist 或 /reasonings 按序号列出当前模型可用推理等级',
102
111
  '/reasoning [序号、等级ID或 --default] 查看或切换当前推理等级',
@@ -721,6 +730,7 @@ export class DingtalkHarnessBridge {
721
730
  && !hasInboundFiles(promptMessage) && !hasInboundImages(promptMessage)
722
731
  ? async () => { await this.#showMenu(message, key); }
723
732
  : isClearCommand(commandText) ? runClearCommand
733
+ : isResetCommand(commandText) ? runResetCommand
724
734
  : isHistoryCommand(commandText) ? runHistoryCommand
725
735
  : hasInboundFiles(promptMessage) ? null : isControlCommand(commandText)
726
736
  ? runControlCommand
@@ -949,8 +959,8 @@ export class DingtalkHarnessBridge {
949
959
  && !['/stop', '/help', '/status', '/history'].includes(command)) {
950
960
  result = { message: t('当前任务尚未结束,请先停止任务或等待完成后再操作。') };
951
961
  } else if (command === '/new') {
952
- await this.#state.clearSession(key);
953
- result = { message: t('已开启新会话。请发送你的问题。') };
962
+ const created = await createConversationSession({ state: this.#state, harness: this.#harness, key });
963
+ result = { message: created.failed ? t('暂时无法创建新会话,请稍后重试。') : t('已开启新会话。请发送你的问题。') };
954
964
  } else if (command === '/status') {
955
965
  await this.#harness.ensureRunning({ signal: this.#signal });
956
966
  result = { message: t('钉钉机器人与 DeepSeek Harness 连接正常。') };
@@ -959,6 +969,7 @@ export class DingtalkHarnessBridge {
959
969
  } else {
960
970
  result = await runWorkspaceCommand(command, this.#harness, key)
961
971
  ?? await runClearCommand(command, this.#harness, this.#state, key, options)
972
+ ?? await runResetCommand(command, this.#harness, this.#state, key, options)
962
973
  ?? await runCompactCommand(command, this.#harness, this.#state, key, options)
963
974
  ?? await runControlCommand(command, this.#harness, this.#state, key, options)
964
975
  ?? await runHistoryCommand(command, this.#harness, this.#state, key, options)
@@ -1334,9 +1345,33 @@ export class DingtalkHarnessBridge {
1334
1345
  await this.#send(sessionWebhook, t('钉钉机器人与 DeepSeek Harness 连接正常。'), this.#atUsersFor(message));
1335
1346
  return;
1336
1347
  }
1337
- if (isPlainText && !hasImages && !hasFiles && command === '/new') {
1338
- await this.#state.clearSession(key);
1339
- await this.#send(sessionWebhook, t('已开启新会话。请发送你的问题。'), this.#atUsersFor(message));
1348
+ if (isPlainText && !hasImages && !hasFiles && isNewCommand(text)) {
1349
+ const created = await createConversationSession({ state: this.#state, harness: this.#harness, key, title: newCommandTitle(text) });
1350
+ await this.#send(sessionWebhook, created.failed ? t('暂时无法创建新会话,请稍后重试。') : t('已开启新会话。请发送你的问题。'), this.#atUsersFor(message));
1351
+ return;
1352
+ }
1353
+ if (isPlainText && !hasImages && !hasFiles && isSessionNavCommand(text)) {
1354
+ const nav = await runSessionNavTextCommand(text, this.#harness, this.#state, key, {
1355
+ signal: this.#signal,
1356
+ });
1357
+ if (nav) {
1358
+ for (const reply of nav.messages ?? [nav.message]) {
1359
+ await this.#send(sessionWebhook, reply, this.#atUsersFor(message));
1360
+ }
1361
+ if (nav.askText) {
1362
+ const followUp = this.#enqueueMessage(
1363
+ { ...message, msgtype: 'text', text: { content: nav.askText } },
1364
+ `${messageId}-ask`,
1365
+ sender,
1366
+ key,
1367
+ { statusReaction },
1368
+ );
1369
+ followUp.catch((error) => {
1370
+ this.#logger.warn?.(`[dsh-im:dingtalk] follow-up ask after a nav command failed:`, error?.message ?? error);
1371
+ this.#send(sessionWebhook, t('切换后的提问发送失败,请重试。'), this.#atUsersFor(message)).catch(() => undefined);
1372
+ });
1373
+ }
1374
+ }
1340
1375
  return;
1341
1376
  }
1342
1377
  const workspaceCommand = isPlainText && !hasImages && !hasFiles
@@ -1397,6 +1432,15 @@ export class DingtalkHarnessBridge {
1397
1432
  cardStarted = await cardStream.start(t(CARD_INITIAL_TEXT));
1398
1433
  if (cardStarted) cardStartedAt = startedAt;
1399
1434
  }
1435
+ try {
1436
+ await this.#state.rememberAuthor?.(key, {
1437
+ senderId: sender,
1438
+ senderName: message.senderNick,
1439
+ isBot: message.senderIsBot === true,
1440
+ });
1441
+ } catch (error) {
1442
+ this.#logger.warn?.('[dsh-dingtalk] failed to remember the conversation author:', error);
1443
+ }
1400
1444
  const { answer, artifacts = [] } = await askInWorkspaceSession({
1401
1445
  onNotice: (notice) => this.#send(sessionWebhook, notice, this.#atUsersFor(message)),
1402
1446
  deferredDelivery: () => ({ coordinator: this.#deferred, target: { ...cardTarget(message, sender), robotCode: this.#clientId } }),
@@ -1,4 +1,5 @@
1
1
  import { deferredStateAccess, normalizeDeferredState } from '../shared/deferred-state.mjs';
2
+ import { createSessionRingSupport, normalizePendingTitles, normalizeSessionRings } from '../shared/session-ring-support.mjs';
2
3
  import { randomUUID } from 'node:crypto';
3
4
  import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
4
5
  import { dirname } from 'node:path';
@@ -17,6 +18,7 @@ export const DINGTALK_RECENT_OUTBOUND_LIMIT = 200;
17
18
  export const DINGTALK_RECENT_OUTBOUND_TTL_MS = 30 * 24 * 60 * 60 * 1_000;
18
19
  export const DINGTALK_RECENT_OUTBOUND_TEXT_LIMIT = 8_000;
19
20
  export const DINGTALK_RECENT_OUTBOUND_MATCH_TOLERANCE_MS = 15_000;
21
+ const AUTHOR_LIMIT = 500;
20
22
 
21
23
  function nonEmptyString(value) {
22
24
  return typeof value === 'string' && value.trim() ? value.trim() : null;
@@ -85,6 +87,27 @@ function normalizePendingSender(value, fallbackRequestId) {
85
87
  };
86
88
  }
87
89
 
90
+ function normalizeAuthor(value) {
91
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
92
+ const senderId = typeof value.senderId === 'string' ? value.senderId : '';
93
+ if (!senderId) return null;
94
+ const author = { senderId, isBot: value.isBot === true };
95
+ if (typeof value.senderName === 'string' && value.senderName) author.senderName = value.senderName;
96
+ if (typeof value.senderUsername === 'string' && value.senderUsername) author.senderUsername = value.senderUsername;
97
+ if (typeof value.at === 'string' && value.at) author.at = value.at;
98
+ return author;
99
+ }
100
+
101
+ function normalizeAuthors(value) {
102
+ const authors = {};
103
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return authors;
104
+ for (const key of Object.keys(value).slice(-AUTHOR_LIMIT)) {
105
+ const author = normalizeAuthor(value[key]);
106
+ if (author) authors[key] = author;
107
+ }
108
+ return authors;
109
+ }
110
+
88
111
  function normalizeState(value) {
89
112
  if (!value || typeof value !== 'object') return structuredClone(EMPTY_STATE);
90
113
  const sessions = {};
@@ -112,15 +135,23 @@ function normalizeState(value) {
112
135
  }
113
136
  }
114
137
 
138
+ // A file written before the navigation ring existed loads unchanged: the keys
139
+ // are only added when they hold something.
140
+ const rings = normalizeSessionRings(value.rings);
141
+ const pendingTitles = normalizePendingTitles(value.pendingTitles);
142
+ const authors = normalizeAuthors(value.authors);
115
143
  return {
116
144
  version: 1,
117
145
  sessions,
146
+ ...(Object.keys(authors).length ? { authors } : {}),
118
147
  ...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}),
119
148
  seenMessageIds: Array.isArray(value.seenMessageIds)
120
149
  ? [...new Set(value.seenMessageIds.map(nonEmptyString).filter(Boolean))].slice(-1_000)
121
150
  : [],
122
151
  pendingSenders,
123
152
  recentOutboundMessages: recentOutboundMessages(value.recentOutboundMessages),
153
+ ...(Object.keys(rings).length ? { rings } : {}),
154
+ ...(Object.keys(pendingTitles).length ? { pendingTitles } : {}),
124
155
  };
125
156
  }
126
157
 
@@ -140,6 +171,12 @@ export class DingtalkStateStore {
140
171
  this.#path = path;
141
172
  this.#idFactory = idFactory;
142
173
  this.#now = now;
174
+ // The navigation ring is a view over this store's state, shared with the
175
+ // channels that inherit `ConversationStateStore`.
176
+ Object.assign(this, createSessionRingSupport({
177
+ state: () => this.#state,
178
+ persist: () => this.#persist(),
179
+ }));
143
180
  }
144
181
 
145
182
  async load() {
@@ -162,6 +199,25 @@ export class DingtalkStateStore {
162
199
  return this.#state.sessions[key] ?? null;
163
200
  }
164
201
 
202
+ authorFor(key) {
203
+ const author = this.#state.authors?.[key];
204
+ return author ? structuredClone(author) : null;
205
+ }
206
+
207
+ async rememberAuthor(key, value) {
208
+ const author = normalizeAuthor({ at: this.#now(), ...value });
209
+ if (typeof key !== 'string' || !key || !author) return null;
210
+ const authors = this.#state.authors ??= {};
211
+ delete authors[key];
212
+ authors[key] = author;
213
+ const keys = Object.keys(authors);
214
+ if (keys.length > AUTHOR_LIMIT) {
215
+ for (const stale of keys.slice(0, keys.length - AUTHOR_LIMIT)) delete authors[stale];
216
+ }
217
+ await this.#persist();
218
+ return structuredClone(author);
219
+ }
220
+
165
221
  async setSession(key, sessionId) {
166
222
  const normalizedKey = nonEmptyString(key);
167
223
  const normalizedSession = nonEmptyString(sessionId);
@@ -73,8 +73,9 @@ function delay(ms, signal) {
73
73
  reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
74
74
  return;
75
75
  }
76
+ // Deliberately NOT unref'd: a rate-limit backoff is the only thing the caller
77
+ // is waiting for, so the timer must keep the loop alive until it fires.
76
78
  const timer = setTimeout(resolve, ms);
77
- timer?.unref?.();
78
79
  signal?.addEventListener('abort', () => {
79
80
  clearTimeout(timer);
80
81
  reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));