@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
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Shared display labels for workspace pickers.
3
+ *
4
+ * Paths and their snapshot order stay the callback identity; only the visible
5
+ * text is derived here. Every channel that offers a workspace selector (Feishu
6
+ * cards, Telegram inline keyboards, …) must use the same rules so the same
7
+ * workspace reads the same way everywhere:
8
+ *
9
+ * - a usable title wins, otherwise the folder name
10
+ * - colliding labels grow a parent-folder suffix until unique or rooted
11
+ * - overlong labels keep the head and tail with an ellipsis in the middle
12
+ *
13
+ * The rules originate from the Feishu workspace-list card (issue #300).
14
+ */
15
+
16
+ import { posix, win32 } from 'node:path';
17
+
18
+ const WORKSPACE_LABEL_LENGTH = 22;
19
+
20
+ function cleanLabelText(value) {
21
+ return String(value ?? '').replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ')
22
+ .replace(/\s+/gu, ' ').trim();
23
+ }
24
+
25
+ /** Display labels only: paths and their snapshot order remain the callback identity. */
26
+ export function workspaceLabels(paths, titles = {}) {
27
+ const entries = paths.map((path) => {
28
+ const api = /^[a-z]:[\\/]|^\\\\/iu.test(path) ? win32 : posix;
29
+ const normalized = api.normalize(path);
30
+ const name = cleanLabelText(api.basename(normalized) || api.parse(normalized).root);
31
+ const base = (typeof titles[path] === 'string' && cleanLabelText(titles[path])) || name;
32
+ return {
33
+ api, base, label: base, parent: api.dirname(normalized),
34
+ context: base === name ? '' : api.basename(normalized),
35
+ };
36
+ });
37
+ const counts = () => {
38
+ const result = new Map();
39
+ for (const { label } of entries) result.set(label, (result.get(label) ?? 0) + 1);
40
+ return result;
41
+ };
42
+ // Grow only ambiguous path suffixes; stop at the root even if display text collides.
43
+ for (;;) {
44
+ const repeated = counts();
45
+ let changed = false;
46
+ for (const entry of entries) {
47
+ if (repeated.get(entry.label) < 2 || entry.parent === null) continue;
48
+ const { api, parent } = entry;
49
+ entry.context = api.join(api.basename(parent) || parent, entry.context);
50
+ entry.label = `${entry.base} · ${cleanLabelText(entry.context)}`;
51
+ const next = api.dirname(parent);
52
+ entry.parent = next === parent ? null : next;
53
+ changed = true;
54
+ }
55
+ if (!changed) break;
56
+ }
57
+ for (const entry of entries) {
58
+ const chars = Array.from(entry.label);
59
+ if (chars.length > WORKSPACE_LABEL_LENGTH) {
60
+ entry.label = `${chars.slice(0, 11).join('')}…${chars.slice(-10).join('')}`;
61
+ }
62
+ }
63
+ const repeated = counts();
64
+ return entries.map(({ label }) => ({ label, numbered: repeated.get(label) > 1 }));
65
+ }
@@ -1,6 +1,7 @@
1
1
  import { withSessionBindingLock } from './session-binding-lock.mjs';
2
2
  import { initialSessionTitle } from './session-title.mjs';
3
- import { messageDiagnosticError } from './connection-error.mjs';
3
+ import { extractConnectionEvidence, messageDiagnosticError } from './connection-error.mjs';
4
+ import { t } from './i18n.mjs';
4
5
 
5
6
  export const WORKSPACE_SESSION_STALE = 'workspace-session-stale';
6
7
 
@@ -103,6 +104,7 @@ export async function askInWorkspaceSession({
103
104
  existsOptions,
104
105
  askOptions,
105
106
  deferredDelivery,
107
+ onNotice,
106
108
  }) {
107
109
  const initialTitle = contextEnhanced
108
110
  ? initialSessionTitle({
@@ -114,16 +116,20 @@ export async function askInWorkspaceSession({
114
116
  const renameSignal = createOptions?.signal
115
117
  ?? (typeof askOptions === 'object' ? askOptions?.signal : undefined);
116
118
  const renameOptions = renameSignal ? { signal: renameSignal } : undefined;
119
+ let unreadableSessionId;
117
120
  while (true) {
118
121
  const diagnostic = { stage: 'session.prepare', submissionState: 'not-submitted' };
122
+ let dsBotSession = false;
119
123
  try {
120
124
  const binding = await withSessionBindingLock(state, key, async () => {
121
125
  await awaitPendingConversationSwitch(harness, key);
122
126
  const dsBotSessionId = await harness.resolveDsBotSession?.(key);
127
+ dsBotSession = Boolean(dsBotSessionId);
123
128
  let sessionId = dsBotSessionId || state.sessionFor(key);
124
129
  diagnostic.sessionId = sessionId;
125
130
  let session = sessionId ? workspaceSession(harness, sessionId, key) : null;
126
- if (!session || !(await sessionExists(session, existsOptions))) {
131
+ const replacingUnreadable = sessionId && sessionId === unreadableSessionId;
132
+ if (!session || replacingUnreadable || !(await sessionExists(session, existsOptions))) {
127
133
  if (dsBotSessionId) {
128
134
  throw Object.assign(new Error('DS Bot 的当前会话不可用。'), { code: 'ds-bot-unavailable' });
129
135
  }
@@ -153,12 +159,15 @@ export async function askInWorkspaceSession({
153
159
  if (conversationGenerationMoved(harness, key, conversationGeneration)) {
154
160
  throw workspaceSessionStaleError();
155
161
  }
156
- return { sessionId, session };
162
+ return { sessionId, session, recovered: replacingUnreadable };
157
163
  }
158
164
  return { sessionId, session };
159
165
  });
160
166
  if (!binding) continue;
161
167
  diagnostic.sessionId = binding.sessionId;
168
+ if (binding.recovered) {
169
+ await onNotice?.(t('绑定会话的日志已损坏,已切换到新会话并继续处理本条消息。原会话记录已保留,历史上下文不会自动带入。'));
170
+ }
162
171
  diagnostic.stage = 'prompt.prepare';
163
172
  const artifacts = [];
164
173
  const originalOnArtifact = typeof askOptions === 'object'
@@ -203,7 +212,18 @@ export async function askInWorkspaceSession({
203
212
  ...(artifacts.length > 0 ? { artifacts } : {}),
204
213
  };
205
214
  } catch (error) {
206
- if (error?.code !== WORKSPACE_SESSION_STALE) throw messageDiagnosticError(error, diagnostic);
215
+ const failure = messageDiagnosticError(error, diagnostic);
216
+ // Retry once, only with positive evidence that no prompt was submitted.
217
+ // The binding lock rechecks identity so a concurrent /new or workspace
218
+ // switch cannot be overwritten by recovery of the previous Session.
219
+ if (!unreadableSessionId && !dsBotSession && diagnostic.sessionId
220
+ && error?.code === 'session-unreadable'
221
+ && !renameSignal?.aborted && !existsOptions?.signal?.aborted
222
+ && extractConnectionEvidence(failure).details.submissionState === 'not-submitted') {
223
+ unreadableSessionId = diagnostic.sessionId;
224
+ continue;
225
+ }
226
+ if (error?.code !== WORKSPACE_SESSION_STALE) throw failure;
207
227
  }
208
228
  }
209
229
  }
@@ -5,6 +5,27 @@ import {
5
5
  TokenBotConfigStore,
6
6
  } from '../shared/token-config-store.mjs';
7
7
  import { normalizeGroupTriggers } from './group-triggers.mjs';
8
+ import {
9
+ normalizeThinkingIntervalSeconds,
10
+ normalizeThinkingNumbering,
11
+ } from '../shared/thinking-cadence.mjs';
12
+
13
+ export {
14
+ DEFAULT_THINKING_INTERVAL_SECONDS,
15
+ normalizeThinkingIntervalSeconds,
16
+ normalizeThinkingNumbering,
17
+ SET_THINKING_CADENCE_ENDPOINT,
18
+ THINKING_INTERVAL_MAX_SECONDS,
19
+ } from '../shared/thinking-cadence.mjs';
20
+ import { normalizeSendLimitPerMinute } from '../shared/send-limit.mjs';
21
+
22
+ export {
23
+ DEFAULT_SEND_LIMIT_PER_MINUTE,
24
+ normalizeSendLimitPerMinute,
25
+ SEND_LIMIT_MAX_PER_MINUTE,
26
+ SEND_LIMIT_MIN_PER_MINUTE,
27
+ SET_SEND_LIMIT_ENDPOINT,
28
+ } from '../shared/send-limit.mjs';
8
29
 
9
30
  const IDENTITY_OPTIONS = Object.freeze({
10
31
  botPrefix: 'telegram',
@@ -53,7 +74,11 @@ function normalizeTelegramBotExtension(value) {
53
74
  const hasAllowedUsers = Object.hasOwn(value, 'allowedUsers');
54
75
  const hasThinkingTraces = Object.hasOwn(value, 'thinkingTraces');
55
76
  const hasGroupTriggers = Object.hasOwn(value, 'groupTriggers');
56
- if (!hasAccessMode && !hasAllowedUsers && !hasThinkingTraces && !hasGroupTriggers) return {};
77
+ const hasThinkingNumbering = Object.hasOwn(value, 'thinkingNumbering');
78
+ const hasThinkingInterval = Object.hasOwn(value, 'thinkingIntervalSeconds');
79
+ const hasSendLimit = Object.hasOwn(value, 'sendLimitPerMinute');
80
+ if (!hasAccessMode && !hasAllowedUsers && !hasThinkingTraces && !hasGroupTriggers
81
+ && !hasThinkingNumbering && !hasThinkingInterval && !hasSendLimit) return {};
57
82
  try {
58
83
  const policy = normalizeTelegramAccessPolicy(value);
59
84
  return {
@@ -63,6 +88,14 @@ function normalizeTelegramBotExtension(value) {
63
88
  ...(hasThinkingTraces ? { thinkingTraces: value.thinkingTraces === true } : {}),
64
89
  // Per-group reply triggers; absent means "no rule configured".
65
90
  ...(hasGroupTriggers ? { groupTriggers: normalizeGroupTriggers(value.groupTriggers) } : {}),
91
+ // Trace cadence: stored clamped, so a bad value never reaches the runtime.
92
+ ...(hasThinkingNumbering
93
+ ? { thinkingNumbering: normalizeThinkingNumbering(value.thinkingNumbering) } : {}),
94
+ ...(hasThinkingInterval
95
+ ? { thinkingIntervalSeconds: normalizeThinkingIntervalSeconds(value.thinkingIntervalSeconds) }
96
+ : {}),
97
+ // Stored clamped so a bad value never reaches the runtime.
98
+ ...(hasSendLimit ? { sendLimitPerMinute: normalizeSendLimitPerMinute(value.sendLimitPerMinute) } : {}),
66
99
  };
67
100
  } catch {
68
101
  return null;
@@ -1,11 +1,19 @@
1
1
  import { fetchFileStream } from '../shared/file-download.mjs';
2
2
  import { fetchImageBuffer } from '../shared/image-prompt.mjs';
3
3
  import { t } from '../shared/i18n.mjs';
4
+ import { DEFAULT_SEND_LIMIT_PER_MINUTE } from '../shared/send-limit.mjs';
4
5
 
5
6
  const DEFAULT_BASE_URL = 'https://api.telegram.org/';
6
7
  const TELEGRAM_FILE_HOSTS = Object.freeze(['api.telegram.org']);
7
8
  const DEFAULT_FILE_UPLOAD_TIMEOUT_MS = 120_000;
8
9
 
10
+ /** Telegram budgets new messages per chat, so the window is not configurable. */
11
+ const SEND_WINDOW_MS = 60_000;
12
+ /** One original call plus three retries after 429. */
13
+ const MAX_SEND_ATTEMPTS = 4;
14
+ /** A 429 that asks for more than this is reported instead of waited out. */
15
+ const MAX_RATE_LIMIT_WAIT_MS = 60_000;
16
+
9
17
  function cleanString(value) {
10
18
  return typeof value === 'string' && value.trim() ? value.trim() : null;
11
19
  }
@@ -26,6 +34,36 @@ function positiveTimeout(value, name) {
26
34
  return value;
27
35
  }
28
36
 
37
+ /** Resolve after `ms`, or reject as soon as the caller aborts. */
38
+ function waitForDelay(ms, signal) {
39
+ if (!(ms > 0)) return Promise.resolve();
40
+ return new Promise((resolve, reject) => {
41
+ const onAbort = () => {
42
+ clearTimeout(timer);
43
+ reject(abortReason(signal));
44
+ };
45
+ const timer = setTimeout(() => {
46
+ signal?.removeEventListener?.('abort', onAbort);
47
+ resolve();
48
+ }, ms);
49
+ signal?.addEventListener?.('abort', onAbort, { once: true });
50
+ });
51
+ }
52
+
53
+ /**
54
+ * Seconds Telegram asked us to wait, or null when the error is not a 429.
55
+ *
56
+ * Only message-creating calls are retried; a 429 on an edit or a draft means a
57
+ * skipped stream frame, not a lost message.
58
+ */
59
+ function rateLimitRetryAfter(error) {
60
+ if (error?.providerCode !== 429 && error?.status !== 429 && error?.code !== 'telegram-429') {
61
+ return null;
62
+ }
63
+ const seconds = Number(error?.retry_after);
64
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : 1;
65
+ }
66
+
29
67
  function preserveProviderMetadata(target, source) {
30
68
  if (source?.providerCode !== undefined) target.providerCode = source.providerCode;
31
69
  if (source?.retry_after !== undefined) {
@@ -33,9 +71,36 @@ function preserveProviderMetadata(target, source) {
33
71
  target.retryAfter = source.retry_after;
34
72
  }
35
73
  if (Number.isInteger(source?.status)) target.status = source.status;
74
+ // A wrapped artifact error keeps the attempt history of the call it wraps.
75
+ if (Array.isArray(source?.sendAttempts)) target.sendAttempts = source.sendAttempts;
36
76
  return target;
37
77
  }
38
78
 
79
+ /**
80
+ * One record per attempt of a message-creating call.
81
+ *
82
+ * A delivery that ends up unconfirmed may have spent several attempts -- the
83
+ * 2026-10-22 Telegram notice appeared 41 seconds after the incoming message --
84
+ * so the interface status and Telegram's own description are kept for every
85
+ * try, not just the last one the caller finally sees.
86
+ */
87
+ function sendAttemptRecord(method, attempt, error) {
88
+ const status = Number(error?.status ?? error?.httpStatus);
89
+ const retryAfter = Number(error?.retry_after);
90
+ return {
91
+ attempt,
92
+ method,
93
+ status: Number.isInteger(status) ? status : null,
94
+ description: typeof error?.message === 'string' && error.message ? error.message : null,
95
+ retry_after: Number.isFinite(retryAfter) && retryAfter >= 0 ? retryAfter : null,
96
+ };
97
+ }
98
+
99
+ function withSendAttempts(error, attempts) {
100
+ if (error && typeof error === 'object') error.sendAttempts = attempts;
101
+ return error;
102
+ }
103
+
39
104
  function inputRichMessage(value) {
40
105
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
41
106
  throw new TypeError('A Telegram rich message is required');
@@ -152,6 +217,12 @@ export class TelegramApi {
152
217
  #FormDataImpl;
153
218
  #baseUrl;
154
219
  #fileUploadTimeoutMs;
220
+ #sendLimit;
221
+ #logger;
222
+ // Per chat: timestamps of the messages this bot created in the last window.
223
+ #sendTimestamps = new Map();
224
+ // Per chat: tail of the send queue, so parallel callers share one budget.
225
+ #sendQueue = new Map();
155
226
 
156
227
  constructor({
157
228
  token,
@@ -159,6 +230,8 @@ export class TelegramApi {
159
230
  FormDataImpl = globalThis.FormData,
160
231
  baseUrl = DEFAULT_BASE_URL,
161
232
  fileUploadTimeoutMs = DEFAULT_FILE_UPLOAD_TIMEOUT_MS,
233
+ sendLimitPerMinute = DEFAULT_SEND_LIMIT_PER_MINUTE,
234
+ logger = null,
162
235
  }) {
163
236
  if (!validTelegramToken(token)) throw new TypeError('Telegram Bot Token is invalid');
164
237
  if (typeof fetchImpl !== 'function') throw new TypeError('TelegramApi requires fetch');
@@ -168,6 +241,10 @@ export class TelegramApi {
168
241
  this.#FormDataImpl = FormDataImpl;
169
242
  this.#baseUrl = new URL(baseUrl);
170
243
  this.#fileUploadTimeoutMs = positiveTimeout(fileUploadTimeoutMs, 'fileUploadTimeoutMs');
244
+ this.#sendLimit = Number.isInteger(sendLimitPerMinute) && sendLimitPerMinute >= 1
245
+ ? sendLimitPerMinute
246
+ : DEFAULT_SEND_LIMIT_PER_MINUTE;
247
+ this.#logger = logger;
171
248
  }
172
249
 
173
250
  async getMe(options = {}) {
@@ -252,7 +329,7 @@ export class TelegramApi {
252
329
  }
253
330
 
254
331
  async sendMessage({ chatId, text, replyToMessageId, messageThreadId, replyMarkup, signal }) {
255
- return this.#call('sendMessage', {
332
+ return this.#sendMessageCall('sendMessage', {
256
333
  chat_id: chatId,
257
334
  text,
258
335
  link_preview_options: { is_disabled: true },
@@ -280,7 +357,7 @@ export class TelegramApi {
280
357
  if (!Number.isSafeInteger(messageId)) {
281
358
  throw new TypeError('Telegram message id must be a safe integer');
282
359
  }
283
- return this.#call('editMessageReplyMarkup', {
360
+ return this.#callUnbudgeted('editMessageReplyMarkup', {
284
361
  chat_id: chatId,
285
362
  message_id: messageId,
286
363
  ...(replyMarkup === undefined ? {} : { reply_markup: inputReplyMarkup(replyMarkup) }),
@@ -303,7 +380,7 @@ export class TelegramApi {
303
380
  messageThreadId,
304
381
  signal,
305
382
  }) {
306
- return this.#call('sendRichMessage', {
383
+ return this.#sendMessageCall('sendRichMessage', {
307
384
  chat_id: chatId,
308
385
  rich_message: inputRichMessage(richMessage),
309
386
  ...(replyToMessageId ? {
@@ -317,7 +394,7 @@ export class TelegramApi {
317
394
  if (!Number.isSafeInteger(draftId) || draftId === 0) {
318
395
  throw new TypeError('Telegram rich message draft id must be a non-zero integer');
319
396
  }
320
- return this.#call('sendRichMessageDraft', {
397
+ return this.#callUnbudgeted('sendRichMessageDraft', {
321
398
  chat_id: chatId,
322
399
  draft_id: draftId,
323
400
  rich_message: inputRichMessage(richMessage),
@@ -357,45 +434,167 @@ export class TelegramApi {
357
434
  || !Buffer.isBuffer(file.bytes)) {
358
435
  throw new TypeError(`A Telegram ${mediaLabel} is required`);
359
436
  }
360
- const payload = new this.#FormDataImpl();
361
- payload.append('chat_id', String(chatId));
362
- payload.append(
363
- fieldName,
364
- new Blob([file.bytes], { type: file.mediaType ?? 'application/octet-stream' }),
365
- file.fileName,
366
- );
367
- if (replyToMessageId) {
368
- payload.append('reply_parameters', JSON.stringify({
369
- message_id: replyToMessageId,
370
- allow_sending_without_reply: true,
371
- }));
372
- }
373
- if (messageThreadId) payload.append('message_thread_id', String(messageThreadId));
374
437
  if (signal?.aborted) throw abortReason(signal);
375
- const uploadSignal = requestSignal(signal, this.#fileUploadTimeoutMs);
438
+ // A multipart body can be consumed only once, so every attempt rebuilds it.
439
+ const dispatch = async () => {
440
+ // The upload timeout starts here, not when the caller asked for the send:
441
+ // a file queued behind the chat's send budget (or behind a 429 retry)
442
+ // would otherwise expire before its first request even opens, and the
443
+ // file would be reported as uncertain although nothing was sent.
444
+ const uploadSignal = requestSignal(signal, this.#fileUploadTimeoutMs);
445
+ const payload = new this.#FormDataImpl();
446
+ payload.append('chat_id', String(chatId));
447
+ payload.append(
448
+ fieldName,
449
+ new Blob([file.bytes], { type: file.mediaType ?? 'application/octet-stream' }),
450
+ file.fileName,
451
+ );
452
+ if (replyToMessageId) {
453
+ payload.append('reply_parameters', JSON.stringify({
454
+ message_id: replyToMessageId,
455
+ allow_sending_without_reply: true,
456
+ }));
457
+ }
458
+ if (messageThreadId) payload.append('message_thread_id', String(messageThreadId));
459
+ try {
460
+ return await this.#call(method, payload, {
461
+ signal: uploadSignal,
462
+ timeoutMs: this.#fileUploadTimeoutMs,
463
+ multipart: true,
464
+ });
465
+ } catch (error) {
466
+ if (signal?.aborted) throw abortReason(signal);
467
+ if (error?.deliveryOutcome === 'unknown') {
468
+ throw uncertainTelegramDelivery(error?.cause ?? error, mediaLabel);
469
+ }
470
+ if (error?.code?.startsWith?.('telegram-')) {
471
+ throw telegramArtifactProviderError(error, mediaLabel);
472
+ }
473
+ throw uncertainTelegramDelivery(error, mediaLabel);
474
+ }
475
+ };
476
+ return this.#sendMessageCall(method, { chat_id: chatId }, { signal }, dispatch);
477
+ }
478
+
479
+ /**
480
+ * Run a message-creating call inside the chat's send budget and retry it
481
+ * while Telegram answers 429.
482
+ *
483
+ * Only these calls are budgeted: Telegram charges its per-chat limit for new
484
+ * messages, while edits, drafts, typing actions, reactions and callback
485
+ * acknowledgements are free and must stay responsive during a burst.
486
+ */
487
+ async #sendMessageCall(method, payload, options, dispatch = null) {
488
+ const { signal } = options;
489
+ const chatId = String(payload.chat_id ?? '');
490
+ await this.#reserveSendSlot(method, chatId, signal);
491
+ let waitedMs = 0;
492
+ const attempts = [];
493
+ for (let attempt = 1; ; attempt += 1) {
494
+ try {
495
+ return await (dispatch ?? (() => this.#call(method, payload, options)))();
496
+ } catch (error) {
497
+ attempts.push(sendAttemptRecord(method, attempt, error));
498
+ const retryAfter = rateLimitRetryAfter(error);
499
+ if (retryAfter === null) throw withSendAttempts(error, attempts);
500
+ const delayMs = Math.ceil(retryAfter * 1000);
501
+ if (attempt >= MAX_SEND_ATTEMPTS || waitedMs + delayMs > MAX_RATE_LIMIT_WAIT_MS) {
502
+ const limited = preserveProviderMetadata(new Error(
503
+ `Telegram ${method} is rate limited in chat ${chatId}`,
504
+ { cause: error },
505
+ ), error);
506
+ limited.code = 'channel-rate-limit';
507
+ // The caller still has to tell the user when the chat frees up.
508
+ limited.retry_after = retryAfter;
509
+ limited.retryAfter = retryAfter;
510
+ throw withSendAttempts(limited, attempts);
511
+ }
512
+ waitedMs += delayMs;
513
+ this.#log(
514
+ `[dsh-im:telegram] chat ${chatId} ${method} rate limited by Telegram,`
515
+ + ` retrying in ${delayMs} ms (attempt ${attempt + 1} of ${MAX_SEND_ATTEMPTS})`,
516
+ );
517
+ await waitForDelay(delayMs, signal);
518
+ }
519
+ }
520
+ }
521
+
522
+ /**
523
+ * Wait until this chat has a free slot in its budget.
524
+ *
525
+ * The budget belongs to the chat, not to the bot, so one busy group cannot
526
+ * starve the others. Waiting beats dropping: the caller's message is what the
527
+ * user asked for, and a slot always comes free within the window.
528
+ */
529
+ async #reserveSendSlot(method, chatId, signal) {
530
+ // Parallel callers to the same chat must queue up, otherwise they would all
531
+ // read the same free budget and overshoot the limit together.
532
+ const previous = this.#sendQueue.get(chatId) ?? Promise.resolve();
533
+ let release = () => {};
534
+ const gate = new Promise((resolve) => { release = resolve; });
535
+ const tail = previous.then(() => gate);
536
+ this.#sendQueue.set(chatId, tail);
537
+ await previous;
376
538
  try {
377
- return await this.#call(method, payload, {
378
- signal: uploadSignal,
379
- timeoutMs: this.#fileUploadTimeoutMs,
380
- multipart: true,
381
- });
382
- } catch (error) {
539
+ await this.#waitForSendBudget(method, chatId, signal);
540
+ } finally {
541
+ release();
542
+ if (this.#sendQueue.get(chatId) === tail) this.#sendQueue.delete(chatId);
543
+ }
544
+ }
545
+
546
+ async #waitForSendBudget(method, chatId, signal) {
547
+ for (;;) {
383
548
  if (signal?.aborted) throw abortReason(signal);
384
- if (error?.deliveryOutcome === 'unknown') {
385
- throw uncertainTelegramDelivery(error?.cause ?? error, mediaLabel);
549
+ const now = Date.now();
550
+ const recent = (this.#sendTimestamps.get(chatId) ?? [])
551
+ .filter((at) => now - at < SEND_WINDOW_MS);
552
+ if (recent.length < this.#sendLimit) {
553
+ recent.push(now);
554
+ this.#sendTimestamps.set(chatId, recent);
555
+ return;
386
556
  }
387
- if (error?.code?.startsWith?.('telegram-')) {
388
- throw telegramArtifactProviderError(error, mediaLabel);
389
- }
390
- throw uncertainTelegramDelivery(error, mediaLabel);
557
+ const delayMs = SEND_WINDOW_MS - (now - recent[0]);
558
+ this.#sendTimestamps.set(chatId, recent);
559
+ this.#log(
560
+ `[dsh-im:telegram] chat ${chatId} ${method} waits ${delayMs} ms`
561
+ + ` for the next send slot (limit ${this.#sendLimit} per minute)`,
562
+ );
563
+ await waitForDelay(delayMs, signal);
391
564
  }
392
565
  }
393
566
 
567
+ /**
568
+ * Call a method that Telegram does not charge against the send budget.
569
+ *
570
+ * A 429 here is not retried: the frame it carries is already superseded by the
571
+ * next one, and waiting would stall the stream. It resolves to `undefined`
572
+ * instead of rejecting, because a rejected edit has nobody waiting for it and
573
+ * would surface as an unhandled rejection; a caller that needs the edit to be
574
+ * on screen checks for `undefined` and falls back.
575
+ */
576
+ async #callUnbudgeted(method, payload, options = {}) {
577
+ try {
578
+ return await this.#call(method, payload, options);
579
+ } catch (error) {
580
+ if (rateLimitRetryAfter(error) === null) throw error;
581
+ this.#log(
582
+ `[dsh-im:telegram] chat ${String(payload.chat_id ?? '')} ${method}`
583
+ + ' rate limited; skipping this update',
584
+ );
585
+ return undefined;
586
+ }
587
+ }
588
+
589
+ #log(message) {
590
+ this.#logger?.warn?.(message);
591
+ }
592
+
394
593
  async editMessageText({ chatId, messageId, text, richMessage, signal }) {
395
594
  if ((text === undefined) === (richMessage === undefined)) {
396
595
  throw new TypeError('Telegram message edit requires exactly one of text or richMessage');
397
596
  }
398
- return this.#call('editMessageText', {
597
+ return this.#callUnbudgeted('editMessageText', {
399
598
  chat_id: chatId,
400
599
  message_id: messageId,
401
600
  ...(text === undefined ? { rich_message: inputRichMessage(richMessage) } : {
@@ -405,6 +604,15 @@ export class TelegramApi {
405
604
  }, { signal });
406
605
  }
407
606
 
607
+ /** Telegram notifies on new messages only, never on edits, so dropping the
608
+ * progress placeholder takes a delete rather than a rewrite. */
609
+ async deleteMessage({ chatId, messageId, signal }) {
610
+ return this.#call('deleteMessage', {
611
+ chat_id: chatId,
612
+ message_id: messageId,
613
+ }, { signal });
614
+ }
615
+
408
616
  async sendChatAction({ chatId, messageThreadId, signal }) {
409
617
  return this.#call('sendChatAction', {
410
618
  chat_id: chatId,
@@ -1,11 +1,16 @@
1
1
  import { harnessQuestionText } from '../shared/harness-question.mjs';
2
+ import { t } from '../shared/i18n.mjs';
2
3
  import { TextHarnessBridge, createTextBridgeStatus } from '../shared/text-harness-bridge.mjs';
4
+ import { workspaceLabels } from '../shared/workspace-labels.mjs';
3
5
 
4
6
  export const TELEGRAM_DESCRIPTOR = Object.freeze({
5
7
  key: 'telegram',
6
8
  label: 'Telegram',
7
9
  connectionLabel: ' Bot API 长轮询',
8
- reactions: Object.freeze({ processing: '👀', success: '👍', error: '👎' }),
10
+ // A finished turn leaves no reaction behind: Telegram keeps offering reaction
11
+ // controls on a message that carries one, which repeats for the reader even
12
+ // with reaction notifications off. A failure still keeps its mark.
13
+ reactions: Object.freeze({ processing: '👀', success: null, error: '👎' }),
9
14
  });
10
15
 
11
16
  /** One keyboard row per option; beyond this the list stops being scannable. */
@@ -68,11 +73,67 @@ export const TELEGRAM_INTERACTION_CARD = Object.freeze({
68
73
  parse: parseTelegramCardCallback,
69
74
  });
70
75
 
76
+ /**
77
+ * One keyboard row per workspace. Rows stack with no pagination: beyond this
78
+ * the phone view becomes a wall of buttons, so the bridge falls back to the
79
+ * text list that already answers `/ws <index>` (explicit degradation).
80
+ */
81
+ const MAX_WORKSPACE_BUTTONS = 20;
82
+
83
+ /**
84
+ * Encode one workspace button. The path cannot ride in `callback_data` (64-byte
85
+ * budget), so the press carries a presentation nonce plus the index into the
86
+ * snapshot the bridge cached when it sent the card. A stale card therefore
87
+ * cannot switch to a workspace that a fresher list no longer contains.
88
+ */
89
+ function workspaceCardCallbackData(nonce, index) {
90
+ // Versioned namespace (upstream convention, cf. openclaw tga1:/tgq1:): a future
91
+ // payload change can tell an old card apart instead of mis-parsing it.
92
+ return `w1|${nonce}|${index}`;
93
+ }
94
+
95
+ /** Parse a press produced by {@link workspaceCardCallbackData}; null for foreign payloads. */
96
+ export function parseTelegramWorkspaceCallback(data) {
97
+ const match = typeof data === 'string'
98
+ ? /^w1\|([A-Za-z0-9_-]{1,16})\|(\d{1,3})$/u.exec(data)
99
+ : null;
100
+ if (!match) return null;
101
+ return { nonce: match[1], index: Number(match[2]) };
102
+ }
103
+
104
+ /**
105
+ * Inline-keyboard presentation for the merged `/ws` listing.
106
+ *
107
+ * The card text is deliberately state-free: after a press only the keyboard is
108
+ * replaced (`editMessageReplyMarkup`), so a "current: …" sentence in the body
109
+ * would immediately lie about which workspace is current.
110
+ */
111
+ export const TELEGRAM_WORKSPACE_CARD = Object.freeze({
112
+ render(listing, { nonce } = {}) {
113
+ if (typeof nonce !== 'string' || !nonce) return null;
114
+ const paths = Array.isArray(listing?.paths) ? listing.paths : [];
115
+ if (paths.length === 0 || paths.length > MAX_WORKSPACE_BUTTONS) return null;
116
+ const current = typeof listing?.current === 'string' ? listing.current : null;
117
+ const labels = workspaceLabels(paths, listing?.titles ?? {});
118
+ return {
119
+ text: t('选择要切换的工作区(共 {count} 个):', { count: paths.length }),
120
+ markup: {
121
+ inline_keyboard: paths.map((path, index) => [{
122
+ text: `${path === current ? '✓ ' : ''}${index + 1}. ${labels[index].label}`,
123
+ callback_data: workspaceCardCallbackData(nonce, index),
124
+ }]),
125
+ },
126
+ };
127
+ },
128
+ parse: parseTelegramWorkspaceCallback,
129
+ });
130
+
71
131
  export class TelegramHarnessBridge extends TextHarnessBridge {
72
132
  constructor(options) {
73
133
  super({
74
134
  descriptor: TELEGRAM_DESCRIPTOR,
75
135
  interactionCard: TELEGRAM_INTERACTION_CARD,
136
+ workspaceCard: TELEGRAM_WORKSPACE_CARD,
76
137
  ...options,
77
138
  });
78
139
  }