@xmanrui/dsh-im 5.4.0 → 5.6.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 (105) hide show
  1. package/PROACTIVE_DELIVERY.en.md +15 -0
  2. package/PROACTIVE_DELIVERY.md +15 -0
  3. package/README.en.md +46 -5
  4. package/README.md +46 -5
  5. package/lib/client.js +2579 -664
  6. package/lib/index.js +406 -339
  7. package/package.json +4 -4
  8. package/plugin-src/client/channel-card-meta.js +6 -2
  9. package/plugin-src/client/channels/dingtalk/index.js +12 -9
  10. package/plugin-src/client/channels/feishu/group-settings.js +5 -5
  11. package/plugin-src/client/channels/feishu/index.js +33 -25
  12. package/plugin-src/client/channels/qq/index.js +5 -5
  13. package/plugin-src/client/channels/shared/token-api.js +25 -7
  14. package/plugin-src/client/channels/shared/token-channel.js +18 -11
  15. package/plugin-src/client/channels/telegram/styles.js +4 -0
  16. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  17. package/plugin-src/client/channels/wecom/index.js +5 -5
  18. package/plugin-src/client/channels/wecom-app/index.js +3 -3
  19. package/plugin-src/client/channels/weixin/index.js +2 -2
  20. package/plugin-src/client/channels/whatsapp/index.js +6 -6
  21. package/plugin-src/client/credential-binding.js +3 -2
  22. package/plugin-src/client/delivery-settings.js +4 -4
  23. package/plugin-src/client/ds-bot-settings.js +3 -3
  24. package/plugin-src/client/global-settings.js +5 -2
  25. package/plugin-src/client/i18n-ru.js +1637 -0
  26. package/plugin-src/client/i18n.js +281 -124
  27. package/plugin-src/client/index.js +8 -1
  28. package/plugin-src/host/channels/shared/production.mjs +5 -0
  29. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  30. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  31. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  32. package/plugin-src/host/channels/telegram/production.mjs +7 -0
  33. package/plugin-src/host/delivery-adapter.mjs +41 -33
  34. package/plugin-src/host/delivery-service.mjs +42 -0
  35. package/plugin-src/host/ds-bot-client.mjs +31 -18
  36. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  37. package/plugin-src/host/index.mjs +3 -0
  38. package/plugin-src/host/modern-harness-api.mjs +53 -8
  39. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  40. package/scripts/verify-package.mjs +18 -6
  41. package/src/channels/dingtalk/dingtalk-bridge.mjs +1 -0
  42. package/src/channels/feishu/bridge.mjs +107 -7
  43. package/src/channels/feishu/feishu-cards.mjs +1 -45
  44. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  45. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  46. package/src/channels/feishu/slash-command-panel.mjs +2 -5
  47. package/src/channels/qq/qq-bridge.mjs +1 -0
  48. package/src/channels/shared/AGENTS.md +19 -0
  49. package/src/channels/shared/bot-workspace-store.mjs +1 -1
  50. package/src/channels/shared/clear-command.mjs +2 -1
  51. package/src/channels/shared/command-catalog.mjs +8 -5
  52. package/src/channels/shared/compact-command.mjs +2 -1
  53. package/src/channels/shared/conversation-queue.mjs +49 -0
  54. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  55. package/src/channels/shared/delivery-failure-log.mjs +111 -0
  56. package/src/channels/shared/diagnostic-details.mjs +1 -0
  57. package/src/channels/shared/harness-client.mjs +16 -9
  58. package/src/channels/shared/history-command.mjs +2 -1
  59. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  60. package/src/channels/shared/i18n-en/shared-b.mjs +7 -2
  61. package/src/channels/shared/i18n-en/shared-c.mjs +6 -2
  62. package/src/channels/shared/i18n-en/telegram.mjs +6 -0
  63. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  64. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  65. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  66. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  67. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  68. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  69. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  70. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  71. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  72. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  73. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  74. package/src/channels/shared/i18n-ru/shared-b.mjs +262 -0
  75. package/src/channels/shared/i18n-ru/shared-c.mjs +176 -0
  76. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  77. package/src/channels/shared/i18n-ru/telegram.mjs +30 -0
  78. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  79. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  80. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  81. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  82. package/src/channels/shared/i18n-ru.mjs +48 -0
  83. package/src/channels/shared/i18n.mjs +47 -12
  84. package/src/channels/shared/inbound-access.mjs +1 -1
  85. package/src/channels/shared/interface-language.mjs +3 -3
  86. package/src/channels/shared/message-failure.mjs +8 -4
  87. package/src/channels/shared/model-command.mjs +2 -1
  88. package/src/channels/shared/permission-command.mjs +2 -1
  89. package/src/channels/shared/send-limit.mjs +38 -0
  90. package/src/channels/shared/session-error.mjs +11 -0
  91. package/src/channels/shared/status-reaction.mjs +2 -0
  92. package/src/channels/shared/text-harness-bridge.mjs +205 -3
  93. package/src/channels/shared/thinking-cadence.mjs +36 -0
  94. package/src/channels/shared/workspace-command.mjs +43 -17
  95. package/src/channels/shared/workspace-labels.mjs +65 -0
  96. package/src/channels/shared/workspace-session.mjs +24 -4
  97. package/src/channels/telegram/config-store.mjs +34 -1
  98. package/src/channels/telegram/telegram-api.mjs +240 -32
  99. package/src/channels/telegram/telegram-bridge.mjs +62 -1
  100. package/src/channels/telegram/telegram-controller.mjs +29 -0
  101. package/src/channels/telegram/telegram-runtime.mjs +592 -179
  102. package/src/channels/telegram/voice.mjs +250 -0
  103. package/src/channels/wecom/wecom-bridge.mjs +1 -0
  104. package/src/channels/wecom-app/wecom-app-bridge.mjs +1 -0
  105. package/src/channels/weixin/weixin-bridge.mjs +1 -0
@@ -1,6 +1,7 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
1
2
  import { connectionHint, extractConnectionEvidence, messageDiagnosticError, runtimeDiagnosticDetails } from './connection-error.mjs';
3
+ import { createFailureReferenceId } from './delivery-failure-log.mjs';
2
4
  import { diagnosticFields } from './diagnostic-details.mjs';
3
- import { randomUUID } from 'node:crypto';
4
5
 
5
6
  import { t } from './i18n.mjs';
6
7
 
@@ -74,8 +75,10 @@ const FAILURE_MESSAGES = Object.freeze({
74
75
  '任务被意外中断,本次未完成。请重试。',
75
76
  SESSION_NOT_FOUND:
76
77
  '当前会话已不存在。请发送 /new 创建新会话后重试。',
78
+ SESSION_UNREADABLE:
79
+ '当前会话日志已损坏,无法继续读取。请先到 DSH 查看任务状态,再发送 /new 创建新会话;原会话记录会保留。',
77
80
  SESSION_ARCHIVED:
78
- '当前会话已归档,无法继续处理。请在 DSH 中取消归档,或发送 /new 创建新会话。',
81
+ '当前会话已归档,无法继续处理。有命令权限时可发送 /new 创建新会话;否则请联系管理员在 DSH 中取消归档,或为你开启命令权限。',
79
82
  SESSION_BUSY:
80
83
  '当前会话仍在处理上一项任务。请等待完成,或发送 /stop 后重试。',
81
84
  SESSION_STALE:
@@ -145,7 +148,8 @@ function failureCode(error, details) {
145
148
  if (code === 'model-max-tokens') return 'MODEL_OUTPUT_LIMIT';
146
149
  if (code === 'turn-blocked') return 'TURN_BLOCKED';
147
150
  if (['turn-interrupted', 'turn-aborted'].includes(code)) return 'TURN_INTERRUPTED';
148
- if (code === 'session-not-found') return 'SESSION_NOT_FOUND';
151
+ if (isSessionNotFound(code)) return 'SESSION_NOT_FOUND';
152
+ if (code === 'session-unreadable') return 'SESSION_UNREADABLE';
149
153
  if (code === 'session-archived') return 'SESSION_ARCHIVED';
150
154
  if (code === 'agent-busy') return 'SESSION_BUSY';
151
155
  if (code === 'workspace-session-stale') return 'SESSION_STALE';
@@ -197,7 +201,7 @@ function transportFailureCode(error, details) {
197
201
  function safeReferenceId(value) {
198
202
  return typeof value === 'string' && /^[A-Z0-9-]{6,40}$/u.test(value)
199
203
  ? value
200
- : `MF-${randomUUID().slice(0, 8).toUpperCase()}`;
204
+ : createFailureReferenceId();
201
205
  }
202
206
 
203
207
  function safeFailureReason(value) {
@@ -1,3 +1,4 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
1
2
  import { splitWorkspaceCommandMessage } from './workspace-command.mjs';
2
3
  import { t } from './i18n.mjs';
3
4
  import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs';
@@ -390,7 +391,7 @@ function modelErrorMessage(error, action) {
390
391
  if (code === 'agent-busy') {
391
392
  return t('当前任务正在运行,请等待完成或先发送 /stop。');
392
393
  }
393
- if (code === 'session-not-found') {
394
+ if (isSessionNotFound(code)) {
394
395
  return t('当前聊天绑定的会话已不存在,请重试。');
395
396
  }
396
397
  if (code === 'model-unavailable' || code === 'session/model-unavailable') {
@@ -1,3 +1,4 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
1
2
  import { createCommandListSnapshots } from './command-list-snapshots.mjs';
2
3
  import { t } from './i18n.mjs';
3
4
  import { withSessionBindingLock } from './session-binding-lock.mjs';
@@ -50,7 +51,7 @@ function errorMessage(error, writing) {
50
51
  if (code === WORKSPACE_SESSION_STALE || code === 'workspace-bot-not-found') {
51
52
  return t('工作区或机器人状态已发生变化,请重试。');
52
53
  }
53
- if (['session-not-found', 'session/not-found', 'agent-not-found'].includes(code)) {
54
+ if (isSessionNotFound(code) || code === 'agent-not-found') {
54
55
  return t('当前聊天绑定的会话已不存在,请先绑定或建立会话。');
55
56
  }
56
57
  if (['commands-unavailable', 'permissions-unavailable', 'harness-api-not-found',
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Per-chat send limit for Telegram.
3
+ *
4
+ * Telegram counts the messages a bot creates per chat and answers 429 once the
5
+ * budget for a chat is gone. The bot therefore paces its own new messages and
6
+ * waits for the next free slot instead of dropping them. The value lives in the
7
+ * bot config, is editable from the settings page, and is clamped on both sides:
8
+ * an unparseable form entry must never leave a bot unable to send.
9
+ *
10
+ * Kept free of Node imports so the Web client can share the same rules.
11
+ */
12
+
13
+ export const SET_SEND_LIMIT_ENDPOINT = 'bot.send-limit.set';
14
+ export const DEFAULT_SEND_LIMIT_PER_MINUTE = 15;
15
+ export const SEND_LIMIT_MIN_PER_MINUTE = 1;
16
+ /** Above this the bot would only wait for a budget Telegram never grants. */
17
+ export const SEND_LIMIT_MAX_PER_MINUTE = 30;
18
+
19
+ function clampSendLimit(value) {
20
+ return Math.min(
21
+ SEND_LIMIT_MAX_PER_MINUTE,
22
+ Math.max(SEND_LIMIT_MIN_PER_MINUTE, Math.round(value)),
23
+ );
24
+ }
25
+
26
+ /**
27
+ * A usable limit per minute: 1..30, default 15.
28
+ *
29
+ * Numeric strings from the form are accepted; anything else — missing, NaN,
30
+ * booleans, objects, garbage text — falls back to the default.
31
+ */
32
+ export function normalizeSendLimitPerMinute(value) {
33
+ const numeric = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
34
+ if (typeof numeric !== 'number' || !Number.isFinite(numeric)) {
35
+ return DEFAULT_SEND_LIMIT_PER_MINUTE;
36
+ }
37
+ return clampSendLimit(numeric);
38
+ }
@@ -0,0 +1,11 @@
1
+ export function isSessionNotFound(code) {
2
+ return code === 'session-not-found' || code === 'session/not-found';
3
+ }
4
+
5
+ // Older Hosts report corrupt logs as generic internal errors. Only recognize
6
+ // storage/format signatures on Session RPCs, never arbitrary internal failures.
7
+ export function isSessionLogCorrupt(error) {
8
+ return ['internal', 'gateway/internal'].includes(error?.code)
9
+ && ['session.history', 'session.prompt'].includes(error?.method)
10
+ && /stored log is corrupt|stored session "[^"\n]+" is corrupt|SessionFormatError:/u.test(error?.message ?? '');
11
+ }
@@ -66,6 +66,8 @@ export function beginStatusReaction({
66
66
  }
67
67
  };
68
68
 
69
+ // `emoji` may be null: the transition then only removes the previous
70
+ // reaction, which is how a channel asks for a clean message at the end.
69
71
  const transition = async (emoji) => {
70
72
  if (currentReaction !== null) {
71
73
  const previous = currentReaction;
@@ -1,5 +1,5 @@
1
1
  import { BusyMessageDispatcher, canAutomaticallySteer } from './busy-message-dispatcher.mjs';
2
- import { randomUUID } from 'node:crypto';
2
+ import { randomBytes, randomUUID } from 'node:crypto';
3
3
 
4
4
  import { createDeferredDeliveryCoordinator, deferredOutcomeText } from './deferred-delivery-coordinator.mjs';
5
5
  import { t } from './i18n.mjs';
@@ -13,7 +13,7 @@ import {
13
13
  captureContextEnhancementSource,
14
14
  enhanceContextContent,
15
15
  } from './context-enhancement.mjs';
16
- import { runWorkspaceCommand } from './workspace-command.mjs';
16
+ import { runWorkspaceCommand, workspaceSwitchFailureText } from './workspace-command.mjs';
17
17
  import { runCompactCommand } from './compact-command.mjs';
18
18
  import { isClearCommand, runClearCommand } from './clear-command.mjs';
19
19
  import { isHistoryCommand, runHistoryCommand } from './history-command.mjs';
@@ -73,8 +73,14 @@ import {
73
73
  messageFailureText,
74
74
  setLastMessageFailure,
75
75
  } from './message-failure.mjs';
76
+ import { logDeliveryFailure } from './delivery-failure-log.mjs';
76
77
  import { beginStatusReaction } from './status-reaction.mjs';
77
78
 
79
+ /** Cap and TTL for the in-memory workspace-picker snapshots behind button presses. */
80
+ const MAX_WORKSPACE_CARDS = 50;
81
+ const WORKSPACE_CARD_TTL_MS = 60 * 60 * 1000;
82
+ const WORKSPACE_CARD_NONCE_BYTES = 9;
83
+
78
84
  const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
79
85
  const FILE_ONLY_COMPLETION_TEXT = '任务已完成。';
80
86
 
@@ -202,6 +208,11 @@ export class TextHarnessBridge {
202
208
  #approvals;
203
209
  #batches = new BatchInputManager();
204
210
  #interactionCard;
211
+ #workspaceCard;
212
+ // Workspace picker snapshots by nonce: the press carries an index, not a path.
213
+ #workspaceCards = new Map();
214
+ // Conversation key → the one picker card that is still authoritative there.
215
+ #workspaceCardKeys = new Map();
205
216
  #contextHooks = null;
206
217
  // Delivery attempts per message id. A failed turn releases its `markSeen` so
207
218
  // the next poll can retry, and this counter is what keeps that from becoming
@@ -229,6 +240,7 @@ export class TextHarnessBridge {
229
240
  signal,
230
241
  keepaliveIntervalMs = 4_000,
231
242
  interactionCard = null,
243
+ workspaceCard = null,
232
244
  contextHooks = null,
233
245
  autoSteerSameSender = false,
234
246
  autoSteerLimit = 0,
@@ -250,6 +262,7 @@ export class TextHarnessBridge {
250
262
  this.#signal = signal;
251
263
  this.#keepaliveIntervalMs = keepaliveIntervalMs;
252
264
  this.#interactionCard = interactionCard ?? null;
265
+ this.#workspaceCard = workspaceCard ?? null;
253
266
  // Opt-in follow-up lanes for channels whose groups run on rapid consecutive
254
267
  // posts: fold a same sender's burst into one dispatch, and steer that
255
268
  // sender's own mid-turn follow-ups into the in-flight turn instead of
@@ -1118,6 +1131,9 @@ export class TextHarnessBridge {
1118
1131
  const workspaceCommand = !hasImages && !hasFiles
1119
1132
  ? await runWorkspaceCommand(text, this.#harness, conversationKey)
1120
1133
  : null;
1134
+ if (workspaceCommand && await this.#presentWorkspaceCommand(
1135
+ target, workspaceCommand, conversationKey,
1136
+ )) return;
1121
1137
  if (workspaceCommand) {
1122
1138
  for (const reply of workspaceCommand.messages ?? [workspaceCommand.message]) {
1123
1139
  await this.#bot.sendText(target, reply);
@@ -1274,6 +1290,7 @@ export class TextHarnessBridge {
1274
1290
  // the message instead of replaying a turn the Harness may already own.
1275
1291
  await this.#markPendingSubmitted(conversationKey, messageId);
1276
1292
  const { sessionId, answer, artifacts = [] } = await askInWorkspaceSession({
1293
+ onNotice: (notice) => this.#bot.sendText(target, notice),
1277
1294
  deferredDelivery: () => ({ coordinator: this.#deferred, target: this.#descriptor.key === 'whatsapp' ? { jid: target.jid, selfChat: target.selfChat } : target }),
1278
1295
  harness: this.#harness,
1279
1296
  state: this.#state,
@@ -1308,6 +1325,10 @@ export class TextHarnessBridge {
1308
1325
  return;
1309
1326
  }
1310
1327
  if (update.type === 'reasoning') return;
1328
+ // A carrier that delivers the answer as its own message must not
1329
+ // stream that answer into itself first: the reader would see the
1330
+ // reply twice, and every preview costs an edit.
1331
+ if (update.type === 'text' && stream.previewAnswer === false) return;
1311
1332
  const progress = update.type === 'text' ? update.text
1312
1333
  : update.type === 'tool' ? t('正在使用{name}…', { name: update.name }) : update.text;
1313
1334
  if (progress) {
@@ -1355,12 +1376,16 @@ export class TextHarnessBridge {
1355
1376
  const answerFormat = fileOnlyCompletion ? 'plain' : 'markdown';
1356
1377
  let textDeliveryError = null;
1357
1378
  let textReceipt = null;
1379
+ // What the channel observed about the send itself; it is written to the
1380
+ // log together with the reference id the user is shown.
1381
+ let deliveryEvidence = null;
1358
1382
  if (stream) {
1359
1383
  try {
1360
1384
  const result = await stream.finish(semanticStream || thinkingStream
1361
1385
  ? createTextDeliveryBlock(visibleAnswer, answerFormat)
1362
1386
  : visibleAnswer);
1363
1387
  streamFinished = true;
1388
+ deliveryEvidence = result?.deliveryEvidence ?? deliveryEvidence;
1364
1389
  textReceipt = createDeliveryReceipt({
1365
1390
  deliveryId: messageId,
1366
1391
  presentation: result?.presentation
@@ -1390,6 +1415,7 @@ export class TextHarnessBridge {
1390
1415
  createTextDeliveryBlock(visibleAnswer, answerFormat),
1391
1416
  )
1392
1417
  : await this.#bot.sendText(answerTarget, visibleAnswer);
1418
+ deliveryEvidence = result?.deliveryEvidence ?? deliveryEvidence;
1393
1419
  textReceipt = createDeliveryReceipt({
1394
1420
  deliveryId: messageId,
1395
1421
  presentation: result?.presentation ?? `${this.#descriptor.key}-text`,
@@ -1399,6 +1425,7 @@ export class TextHarnessBridge {
1399
1425
  });
1400
1426
  } catch (error) {
1401
1427
  textDeliveryError = channelDeliveryFailure(error);
1428
+ deliveryEvidence = error?.deliveryEvidence ?? deliveryEvidence;
1402
1429
  }
1403
1430
  }
1404
1431
  const finalDeliveryUnknown = textReceipt?.deliveryOutcome === 'unknown';
@@ -1412,6 +1439,11 @@ export class TextHarnessBridge {
1412
1439
  Object.assign(new Error('Final text delivery outcome is unknown'), { code: textReceipt.reason }),
1413
1440
  );
1414
1441
  }
1442
+ if (textDeliveryError && deliveryEvidence) {
1443
+ // The catch further down reports this error, and the log line must
1444
+ // carry the same evidence the channel recorded for the failed send.
1445
+ textDeliveryError.deliveryEvidence = deliveryEvidence;
1446
+ }
1415
1447
  // A failed final text must not discard an already registered result file.
1416
1448
  // Settle the independent attachment path before surfacing the text error.
1417
1449
  const delivery = await this.#deliverArtifacts(target, messageId, artifacts, textReceipt);
@@ -1420,7 +1452,8 @@ export class TextHarnessBridge {
1420
1452
  throw textDeliveryError;
1421
1453
  }
1422
1454
  if (textDeliveryError && delivery.artifactSendErrors === 0) {
1423
- setLastMessageFailure(this.#status, textDeliveryError);
1455
+ const failure = setLastMessageFailure(this.#status, textDeliveryError);
1456
+ logDeliveryFailure(this.#logger, this.#descriptor.key, failure, textDeliveryError.deliveryEvidence);
1424
1457
  }
1425
1458
  if (delivery.userVisible) {
1426
1459
  this.#status.messagesReplied += 1;
@@ -1507,6 +1540,9 @@ export class TextHarnessBridge {
1507
1540
  `[dsh-im:${this.#descriptor.key}] failed to process a message [${failure.referenceId}]:`,
1508
1541
  messageFailureDiagnostic(error, failure),
1509
1542
  );
1543
+ // One line per failed or unconfirmed delivery, carrying the same id the
1544
+ // user will quote back: a reference id nobody can grep is useless.
1545
+ logDeliveryFailure(this.#logger, this.#descriptor.key, failure, error?.deliveryEvidence);
1510
1546
  if (await presentStreamFailure(failureText)) {
1511
1547
  return error.deliveryReceipt;
1512
1548
  }
@@ -1800,6 +1836,10 @@ export class TextHarnessBridge {
1800
1836
  if (!conversationId || !senderId || !messageId || callback?.senderIsBot === true) return;
1801
1837
  const kind = callback.kind === 'group' ? 'group' : 'direct';
1802
1838
  const key = `${kind}:${conversationId}`;
1839
+ // Workspace pickers are stateless cards, not pending questions: route their
1840
+ // namespace before the question bookkeeping so a press can never touch it.
1841
+ const workspacePress = this.#workspaceCard?.parse?.(callback.data) ?? null;
1842
+ if (workspacePress) return this.#handleWorkspaceCardPress(callback, key, workspacePress);
1803
1843
  const pending = this.#pendingInteractions.get(key);
1804
1844
  const notice = (text) => this.#answerInteractionCallback(callback, text);
1805
1845
  if (!pending) return notice(t('该问题已处理,无需再次选择。'));
@@ -1867,6 +1907,168 @@ export class TextHarnessBridge {
1867
1907
  });
1868
1908
  }
1869
1909
 
1910
+ /**
1911
+ * Send the merged /ws listing as an interactive picker when the channel and
1912
+ * the payload support one. Returns false so the caller can fall back to the
1913
+ * text list: a failed or impossible card must never lose the listing.
1914
+ */
1915
+ async #presentWorkspaceCommand(target, command, conversationKey) {
1916
+ const listing = command?.listing;
1917
+ if (!listing
1918
+ || typeof this.#workspaceCard?.render !== 'function'
1919
+ || typeof this.#bot.sendInteractionCard !== 'function') return false;
1920
+ const nonce = randomBytes(WORKSPACE_CARD_NONCE_BYTES).toString('base64url');
1921
+ const card = this.#workspaceCard.render(listing, { nonce });
1922
+ if (!card) return false;
1923
+ const entry = { listing, key: conversationKey, target, createdAt: Date.now(), submitting: false };
1924
+ this.#rememberWorkspaceCard(nonce, entry);
1925
+ try {
1926
+ const sent = await this.#bot.sendInteractionCard(target, card);
1927
+ entry.messageId = Array.isArray(sent?.providerMessageIds) && sent.providerMessageIds.length > 0
1928
+ ? String(sent.providerMessageIds[0])
1929
+ : undefined;
1930
+ await this.#activateWorkspaceCard(conversationKey, nonce);
1931
+ return true;
1932
+ } catch (error) {
1933
+ this.#workspaceCards.delete(nonce);
1934
+ this.#logger.warn?.(
1935
+ `[dsh-im:${this.#descriptor.key}] unable to send the workspace picker; `
1936
+ + 'falling back to the text list:',
1937
+ error?.message ?? error,
1938
+ );
1939
+ return false;
1940
+ }
1941
+ }
1942
+
1943
+ /**
1944
+ * Only one picker stays authoritative per conversation. The previous card's
1945
+ * keyboard is retired as soon as its replacement exists, so an old "current"
1946
+ * marker can never be pressed after a newer list is on screen.
1947
+ */
1948
+ async #activateWorkspaceCard(conversationKey, nonce) {
1949
+ const previousNonce = this.#workspaceCardKeys.get(conversationKey);
1950
+ this.#workspaceCardKeys.set(conversationKey, nonce);
1951
+ if (!previousNonce || previousNonce === nonce) return;
1952
+ const previous = this.#workspaceCards.get(previousNonce);
1953
+ this.#workspaceCards.delete(previousNonce);
1954
+ if (!previous?.messageId) return;
1955
+ await this.#retireCardKeyboard(previous.target, previous.messageId, previousNonce);
1956
+ }
1957
+
1958
+ /** Drop a card's keyboard in place; failures are diagnostics, never user-facing. */
1959
+ async #retireCardKeyboard(target, messageId, nonce) {
1960
+ if (!target || !messageId || typeof this.#bot.updateInteractionCard !== 'function') return;
1961
+ try {
1962
+ await this.#bot.updateInteractionCard(target, String(messageId), {
1963
+ markup: { inline_keyboard: [] },
1964
+ });
1965
+ } catch (error) {
1966
+ // "message is not modified" and "message to edit not found" are both fine here.
1967
+ this.#logger.warn?.(
1968
+ `[dsh-im:${this.#descriptor.key}] unable to retire a workspace picker${nonce ? ` (${nonce})` : ''}:`,
1969
+ error?.message ?? error,
1970
+ );
1971
+ }
1972
+ }
1973
+
1974
+ #rememberWorkspaceCard(nonce, entry) {
1975
+ const now = Date.now();
1976
+ for (const [key, stored] of this.#workspaceCards) {
1977
+ if (now - stored.createdAt > WORKSPACE_CARD_TTL_MS) this.#workspaceCards.delete(key);
1978
+ }
1979
+ // Keep the caller's object identity: it is the same entry whose messageId is
1980
+ // filled in once the Bot API answers, and retirement reads it from here.
1981
+ this.#workspaceCards.set(nonce, entry);
1982
+ while (this.#workspaceCards.size > MAX_WORKSPACE_CARDS) {
1983
+ const oldest = this.#workspaceCards.keys().next().value;
1984
+ if (oldest === undefined) break;
1985
+ this.#workspaceCards.delete(oldest);
1986
+ }
1987
+ }
1988
+
1989
+ /** Answer a workspace press through the current card snapshot. */
1990
+ async #handleWorkspaceCardPress(callback, key, press) {
1991
+ if (this.#signal?.aborted) return;
1992
+ const notice = (text) => this.#answerInteractionCallback(callback, text);
1993
+ const expired = t('这个列表已过期,请重新发送 /ws。');
1994
+ const entry = this.#workspaceCards.get(press.nonce);
1995
+ if (!entry || entry.key !== key || Date.now() - entry.createdAt > WORKSPACE_CARD_TTL_MS) {
1996
+ // A card this bridge can still identify gets its dead keyboard removed so
1997
+ // the same press is not offered again; an unrecognized card is only toasted
1998
+ // because editing an id we never issued is not a safe assumption.
1999
+ if (entry && entry.key === key) {
2000
+ this.#workspaceCards.delete(press.nonce);
2001
+ if (this.#workspaceCardKeys.get(key) === press.nonce) this.#workspaceCardKeys.delete(key);
2002
+ await this.#retireCardKeyboard(
2003
+ callback.replyTarget ?? entry.target,
2004
+ String(callback.providerMessageId),
2005
+ press.nonce,
2006
+ );
2007
+ }
2008
+ return notice(expired);
2009
+ }
2010
+ const kind = callback.kind === 'group' ? 'group' : 'direct';
2011
+ // The card is a command surface: the same command-permission gate as typing
2012
+ // the command applies to a press, otherwise a keyboard could bypass it.
2013
+ const decision = evaluateInboundAccess(this.#accessPolicy, {
2014
+ conversationType: kind,
2015
+ senderIds: [cleanText(callback.senderId)].filter(Boolean),
2016
+ isCommand: true,
2017
+ });
2018
+ if (!decision.allowed) return notice(t(COMMAND_PERMISSION_DENIED_MESSAGE));
2019
+ const path = entry.listing?.paths?.[press.index];
2020
+ if (typeof path !== 'string') return notice(expired);
2021
+ // Claim synchronously, before the first await: a second press arriving
2022
+ // while the switch is in flight must not switch a second time.
2023
+ if (entry.submitting) return notice(t('正在切换工作区,请稍候。'));
2024
+ // Idempotency follows the live authoritative current, not the snapshot: a
2025
+ // typed /ws or another card may have switched since this one was sent.
2026
+ let liveCurrent = null;
2027
+ try {
2028
+ if (typeof this.#harness.currentWorkspace === 'function') {
2029
+ liveCurrent = this.#harness.currentWorkspace();
2030
+ }
2031
+ } catch {
2032
+ // A failed read only loses the pre-check; the switch below still reports.
2033
+ }
2034
+ // The card's current marker is only a display snapshot; it cannot prove
2035
+ // that another command or conversation has not changed the bot workspace.
2036
+ if (path === liveCurrent) {
2037
+ return notice(t('已经在工作区:{workspace}', { workspace: path }));
2038
+ }
2039
+ entry.submitting = true;
2040
+ try {
2041
+ const switched = await this.#harness.switchWorkspace(path);
2042
+ const current = typeof switched === 'string' && switched ? switched : path;
2043
+ // Keep the snapshot truthful: the next press compares against this value.
2044
+ entry.listing = { ...entry.listing, current };
2045
+ const card = this.#workspaceCard.render(entry.listing, { nonce: press.nonce });
2046
+ if (card && typeof this.#bot.updateInteractionCard === 'function') {
2047
+ try {
2048
+ await this.#bot.updateInteractionCard(
2049
+ callback.replyTarget ?? entry.target,
2050
+ String(callback.providerMessageId),
2051
+ { markup: card.markup },
2052
+ );
2053
+ } catch (error) {
2054
+ this.#logger.warn?.(
2055
+ `[dsh-im:${this.#descriptor.key}] unable to re-mark the workspace picker:`,
2056
+ error?.message ?? error,
2057
+ );
2058
+ }
2059
+ }
2060
+ return await notice(t('工作区已切换为:{workspace}', { workspace: current }));
2061
+ } catch (error) {
2062
+ // Same classification as the typed command, so a card press and /ws N
2063
+ // cannot word the same failure differently.
2064
+ return notice(
2065
+ workspaceSwitchFailureText(error) ?? t('暂时无法切换工作区,请稍后重试。'),
2066
+ );
2067
+ } finally {
2068
+ entry.submitting = false;
2069
+ }
2070
+ }
2071
+
1870
2072
  async presentSessionSyncApproval(interaction, context, options = {}) {
1871
2073
  return this.#approvals.handleSessionSyncRequested(interaction, context, {
1872
2074
  ...options, runtimeSignal: this.#signal ?? options.runtimeSignal, accessPolicy: this.#accessPolicy,
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Pacing and numbering for Telegram "thinking trace" frames.
3
+ *
4
+ * A busy turn emits dozens of 💭/🔧 messages, so the owner can pace them to at
5
+ * most one frame per N seconds and prefix each frame with its number in the
6
+ * turn. Both values live in the bot config and are clamped here, once, so a
7
+ * half-typed form entry can never reach the runtime.
8
+ *
9
+ * Kept free of Node imports so the Web client can share the same rules.
10
+ */
11
+
12
+ export const SET_THINKING_CADENCE_ENDPOINT = 'bot.thinking-cadence.set';
13
+ /** 0 means "no pacing": every frame goes out as it arrives. */
14
+ export const DEFAULT_THINKING_INTERVAL_SECONDS = 0;
15
+ /** A longer window stops being a trace: the answer would overtake it. */
16
+ export const THINKING_INTERVAL_MAX_SECONDS = 60;
17
+
18
+ /**
19
+ * A usable interval in whole seconds, 0..60.
20
+ *
21
+ * Numeric strings from the form are accepted; anything else — missing, NaN,
22
+ * booleans, objects, fractional or garbage text — becomes 0, because a wrong
23
+ * number must not silently slow the trace down.
24
+ */
25
+ export function normalizeThinkingIntervalSeconds(value) {
26
+ const numeric = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
27
+ if (typeof numeric !== 'number' || !Number.isFinite(numeric) || !Number.isInteger(numeric)) {
28
+ return DEFAULT_THINKING_INTERVAL_SECONDS;
29
+ }
30
+ return Math.min(THINKING_INTERVAL_MAX_SECONDS, Math.max(0, numeric));
31
+ }
32
+
33
+ /** Numbering is off unless the config says otherwise. */
34
+ export function normalizeThinkingNumbering(value) {
35
+ return value === true;
36
+ }
@@ -1,3 +1,4 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
1
2
  import { realpath, stat } from 'node:fs/promises';
2
3
  import { isAbsolute, resolve } from 'node:path';
3
4
 
@@ -25,8 +26,8 @@ const SESSION_LIST_USAGE = [
25
26
  '不带工作区参数时,默认列出当前对话的有效工作区(未设置对话专属工作区时即 bot 默认工作区)。',
26
27
  ].join('\n');
27
28
 
28
- function commandResult(message, messages = [message]) {
29
- return { handled: true, message, messages };
29
+ function commandResult(message, messages = [message], extra = {}) {
30
+ return { handled: true, message, messages, ...extra };
30
31
  }
31
32
 
32
33
  function normalizedWorkspacePath(value) {
@@ -155,13 +156,18 @@ export function splitWorkspaceCommandMessage(message) {
155
156
  return messages;
156
157
  }
157
158
 
158
- async function runWorkspaceListCommand(match, harness) {
159
- if (match[1]?.trim()) return commandResult(t('用法:/workspacelist'));
159
+ /**
160
+ * The shared listing behind /ws, /workspace, /wsl, /workspaces and
161
+ * /workspacelist. Text stays byte-compatible with the pre-merge list so a
162
+ * channel without an interactive picker keeps exactly what it always showed;
163
+ * `listing` is the machine-readable half a channel may render as a picker.
164
+ */
165
+ async function workspaceListingCommand(harness) {
160
166
  if (typeof harness?.listWorkspaces !== 'function') {
161
167
  return commandResult(t('当前机器人暂不支持列出工作区。'));
162
168
  }
163
169
  try {
164
- const { current, paths } = await workspacePathSnapshot(harness);
170
+ const { current, paths, titles } = await workspacePathSnapshot(harness, { includeTitles: true });
165
171
  if (paths.length === 0) {
166
172
  return commandResult(t('当前 Harness Host 上没有仍然存在的已登记工作区。'));
167
173
  }
@@ -177,7 +183,9 @@ async function runWorkspaceListCommand(match, harness) {
177
183
  t('不带工作区参数时,/sessionlist 默认列出当前对话的有效工作区。'),
178
184
  ];
179
185
  const message = lines.join('\n');
180
- return commandResult(message, splitWorkspaceCommandMessage(message));
186
+ return commandResult(message, splitWorkspaceCommandMessage(message), {
187
+ listing: { current: current ?? null, paths, titles: titles ?? {} },
188
+ });
181
189
  } catch (error) {
182
190
  if (error?.code === 'workspace-bot-not-found') {
183
191
  return commandResult(t('机器人正在移除或已重新接入,无法列出原会话的工作区。'));
@@ -186,6 +194,11 @@ async function runWorkspaceListCommand(match, harness) {
186
194
  }
187
195
  }
188
196
 
197
+ async function runWorkspaceListCommand(match, harness) {
198
+ if (match[1]?.trim()) return commandResult(t('用法:/workspacelist'));
199
+ return workspaceListingCommand(harness);
200
+ }
201
+
189
202
  async function conversationEffectiveWorkspace(harness, conversationKey) {
190
203
  if (typeof harness?.currentConversationWorkspace !== 'function'
191
204
  || typeof conversationKey !== 'string' || !conversationKey) return null;
@@ -317,7 +330,7 @@ function sessionBindErrorMessage(error) {
317
330
  return t(`Session ID 格式无效。
318
331
  {usage}`, { usage: t(SESSION_BIND_USAGE) });
319
332
  }
320
- if (['session-not-registered', 'session-not-found'].includes(error?.code)) {
333
+ if (error?.code === 'session-not-registered' || isSessionNotFound(error?.code)) {
321
334
  return t('未找到该会话,请先执行 /sessionlist 确认 Session ID。');
322
335
  }
323
336
  if (error?.code === 'session-subagent-unsupported') {
@@ -483,6 +496,24 @@ async function runConversationWorkspaceCommand(command, harness, conversationKey
483
496
  }
484
497
  }
485
498
 
499
+ /**
500
+ * One failure mapping for every workspace-switch surface. The text command and
501
+ * the Telegram picker card call the same switch, so their receipts must not
502
+ * drift; returns null for errors this layer deliberately does not classify
503
+ * (the caller decides whether to rethrow or degrade).
504
+ */
505
+ export function workspaceSwitchFailureText(error) {
506
+ if (['workspace-not-absolute', 'workspace-not-found', 'workspace-not-directory']
507
+ .includes(error?.code)) {
508
+ return t(`{message}
509
+ 用法:/workspace 工作区序号或绝对路径`, { message: error.message });
510
+ }
511
+ if (error?.code === 'workspace-bot-not-found') {
512
+ return t('机器人正在移除或已重新接入,无法切换原会话的工作区。');
513
+ }
514
+ return null;
515
+ }
516
+
486
517
  export async function runWorkspaceCommand(text, harness, conversationKey) {
487
518
  if (!isWorkspaceCommand(text)) return null;
488
519
  const command = text.trim();
@@ -500,9 +531,9 @@ export async function runWorkspaceCommand(text, harness, conversationKey) {
500
531
  const match = WORKSPACE_COMMAND.exec(command);
501
532
  if (!match) return null;
502
533
  const workspace = match[1]?.trim();
503
- if (!workspace) {
504
- return commandResult(t('用法:/workspace 工作区序号或绝对路径'));
505
- }
534
+ // Merged command: no argument opens the same listing as /wsl, so a channel
535
+ // with an inline keyboard can make the list itself the switcher.
536
+ if (!workspace) return workspaceListingCommand(harness);
506
537
  if (typeof harness?.switchWorkspace !== 'function') {
507
538
  return commandResult(t('当前机器人暂不支持切换工作区。'));
508
539
  }
@@ -522,13 +553,8 @@ export async function runWorkspaceCommand(text, harness, conversationKey) {
522
553
  const current = await harness.switchWorkspace(selected);
523
554
  return commandResult(t('工作区已切换为:{workspace}', { workspace: current }));
524
555
  } catch (error) {
525
- if (['workspace-not-absolute', 'workspace-not-found', 'workspace-not-directory'].includes(error?.code)) {
526
- return commandResult(t(`{message}
527
- 用法:/workspace 工作区序号或绝对路径`, { message: error.message }));
528
- }
529
- if (error?.code === 'workspace-bot-not-found') {
530
- return commandResult(t('机器人正在移除或已重新接入,无法切换原会话的工作区。'));
531
- }
556
+ const failure = workspaceSwitchFailureText(error);
557
+ if (failure) return commandResult(failure);
532
558
  throw error;
533
559
  }
534
560
  }