@xmanrui/dsh-im 5.7.0 → 5.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.en.md +42 -7
  2. package/README.md +53 -7
  3. package/docs/preset-workspaces.md +37 -0
  4. package/lib/client.js +375 -160
  5. package/lib/index.js +330 -325
  6. package/package.json +3 -1
  7. package/plugin-src/client/channels/feishu/api.js +5 -0
  8. package/plugin-src/client/channels/feishu/conversation-directory-settings.js +73 -0
  9. package/plugin-src/client/channels/feishu/index.js +1 -0
  10. package/plugin-src/client/connection-error.js +1 -1
  11. package/plugin-src/client/delivery-settings.js +4 -0
  12. package/plugin-src/client/i18n-ru.js +17 -0
  13. package/plugin-src/client/i18n.js +17 -0
  14. package/plugin-src/client/styles.js +6 -0
  15. package/plugin-src/client/workspace-editor.js +6 -5
  16. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  17. package/plugin-src/host/channels/feishu/production.mjs +2 -1
  18. package/plugin-src/host/channels/feishu/rpc.mjs +25 -0
  19. package/plugin-src/host/channels/matrix/production.mjs +2 -1
  20. package/plugin-src/host/channels/qq/production.mjs +2 -1
  21. package/plugin-src/host/channels/shared/binding-events.mjs +130 -0
  22. package/plugin-src/host/channels/shared/production.mjs +32 -3
  23. package/plugin-src/host/channels/shared/workspace-rpc.mjs +2 -0
  24. package/plugin-src/host/channels/slack/production.mjs +2 -1
  25. package/plugin-src/host/channels/wecom/production.mjs +2 -1
  26. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  27. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  28. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  29. package/plugin-src/host/delivery-adapter.mjs +122 -1
  30. package/plugin-src/host/delivery-service.mjs +40 -0
  31. package/plugin-src/host/ds-bot-client.mjs +28 -2
  32. package/plugin-src/host/index.mjs +24 -1
  33. package/plugin-src/host/modern-harness-api.mjs +3 -0
  34. package/scripts/telegram-menu-scopes.mjs +57 -0
  35. package/scripts/verify-interface-language.mjs +60 -15
  36. package/scripts/verify-package.mjs +17 -6
  37. package/src/channels/dingtalk/dingtalk-bridge.mjs +2 -3
  38. package/src/channels/dingtalk/dingtalk-menu.mjs +4 -5
  39. package/src/channels/email/transports/imap-smtp.mjs +21 -11
  40. package/src/channels/feishu/bridge.mjs +75 -22
  41. package/src/channels/feishu/feishu-cards.mjs +96 -25
  42. package/src/channels/feishu/message-utils.mjs +1 -0
  43. package/src/channels/qq/qq-menu.mjs +3 -4
  44. package/src/channels/shared/action-card.mjs +331 -0
  45. package/src/channels/shared/bot-workspace-store.mjs +369 -6
  46. package/src/channels/shared/command-catalog.mjs +20 -5
  47. package/src/channels/shared/conversation/describe.mjs +116 -0
  48. package/src/channels/shared/conversation-directory-ensure.mjs +46 -0
  49. package/src/channels/shared/conversation-directory.mjs +29 -0
  50. package/src/channels/shared/conversation-state-store.mjs +62 -0
  51. package/src/channels/shared/diagnostic-details.mjs +38 -0
  52. package/src/channels/shared/harness-approval.mjs +58 -13
  53. package/src/channels/shared/harness-client.mjs +85 -2
  54. package/src/channels/shared/harness-session-binding.mjs +13 -1
  55. package/src/channels/shared/i18n-en/diagnostics.mjs +2 -0
  56. package/src/channels/shared/i18n-en/feishu.mjs +6 -0
  57. package/src/channels/shared/i18n-en/shared-a.mjs +14 -0
  58. package/src/channels/shared/i18n-en/telegram.mjs +14 -0
  59. package/src/channels/shared/i18n-ru/diagnostics.mjs +2 -0
  60. package/src/channels/shared/i18n-ru/feishu.mjs +6 -0
  61. package/src/channels/shared/i18n-ru/shared-a.mjs +14 -0
  62. package/src/channels/shared/i18n-ru/telegram.mjs +14 -0
  63. package/src/channels/shared/message-failure.mjs +8 -0
  64. package/src/channels/shared/model-command.mjs +5 -0
  65. package/src/channels/shared/new-command.mjs +7 -0
  66. package/src/channels/shared/preset-workspaces.mjs +48 -0
  67. package/src/channels/shared/qr-encoding-error.mjs +8 -2
  68. package/src/channels/shared/semantic/reply-reference.mjs +25 -5
  69. package/src/channels/shared/status-command.mjs +159 -0
  70. package/src/channels/shared/text-harness-bridge.mjs +89 -6
  71. package/src/channels/shared/workspace-command.mjs +36 -15
  72. package/src/channels/shared/workspace-session.mjs +30 -5
  73. package/src/channels/telegram/approval-card.mjs +379 -0
  74. package/src/channels/telegram/telegram-api.mjs +10 -1
  75. package/src/channels/telegram/telegram-bridge.mjs +7 -0
  76. package/src/channels/telegram/telegram-runtime.mjs +125 -13
  77. package/src/channels/wecom/wecom-bridge.mjs +5 -3
@@ -0,0 +1,379 @@
1
+ import { t } from '../shared/i18n.mjs';
2
+ import {
3
+ ACTION_CARD_STATUS,
4
+ ActionCardRegistry,
5
+ actionCardStateText,
6
+ createCallbackNamespace,
7
+ } from '../shared/action-card.mjs';
8
+ import { harnessApprovalText, APPROVAL_SUBMIT_RESULT } from '../shared/harness-approval.mjs';
9
+
10
+ /**
11
+ * Telegram approval buttons on top of the shared HarnessApprovalQueue `render`
12
+ * hook and the shared action-card foundation.
13
+ *
14
+ * A press is handled in this order, which is the whole safety story:
15
+ * 1. answerCallbackQuery first (the spinner stops even when the press loses);
16
+ * 2. actor check (only the user who started the turn can decide; a stranger
17
+ * gets a toast and does not consume the owner's press);
18
+ * 3. a synchronous first-press claim (duplicate/concurrent taps submit once);
19
+ * 4. submit through the shared queue, then edit the original message into a
20
+ * terminal receipt and clear its keyboard. `message is not modified` is
21
+ * success (the client already shows the receipt).
22
+ *
23
+ * The plain-text "请精准回复「批准」或「拒绝」" path is never replaced by the
24
+ * card: a channel without keyboard support or a refused card send falls back to
25
+ * the exact text the bridge sent before this feature.
26
+ */
27
+
28
+ /** Versioned namespace so a stale `a1|`/future `ap2|` payload can never be replayed. */
29
+ export const TELEGRAM_APPROVAL_NAMESPACE_PREFIX = 'ap1';
30
+ export const TELEGRAM_APPROVAL_ACTIONS = Object.freeze({ approve: 'a', reject: 'd' });
31
+ export const TELEGRAM_APPROVAL_CALLBACK = createCallbackNamespace(
32
+ TELEGRAM_APPROVAL_NAMESPACE_PREFIX,
33
+ );
34
+
35
+ const OUTCOME_BY_DECISION = Object.freeze({
36
+ approve: 'allowed-once',
37
+ reject: 'rejected',
38
+ });
39
+ const ACTION_BY_DECISION = Object.freeze({
40
+ approve: TELEGRAM_APPROVAL_ACTIONS.approve,
41
+ reject: TELEGRAM_APPROVAL_ACTIONS.reject,
42
+ });
43
+ const DECISION_BY_ACTION = Object.freeze({
44
+ [TELEGRAM_APPROVAL_ACTIONS.approve]: 'approve',
45
+ [TELEGRAM_APPROVAL_ACTIONS.reject]: 'reject',
46
+ });
47
+ const BUTTON_TEXT = Object.freeze({
48
+ approve: '✅ 批准一次',
49
+ reject: '❌ 拒绝',
50
+ });
51
+ /** The card body keeps the tool/argument summary; the buttons replace the prompt. */
52
+ const TERMINAL_LABEL = Object.freeze({
53
+ 'allowed-once': '✅ 已批准(仅本次)',
54
+ rejected: '❌ 已拒绝',
55
+ expired: '⏰ 已过期',
56
+ unavailable: '⛔ 已失效',
57
+ });
58
+ /** Telegram rejects a single message body over this many characters. */
59
+ export const TELEGRAM_APPROVAL_CARD_MAX_CHARS = 4_096;
60
+ const EMPTY_KEYBOARD = Object.freeze({ inline_keyboard: [] });
61
+ const TERMINAL_STATUS_BY_OUTCOME = Object.freeze({
62
+ 'allowed-once': ACTION_CARD_STATUS.RESOLVED,
63
+ rejected: ACTION_CARD_STATUS.RESOLVED,
64
+ expired: ACTION_CARD_STATUS.EXPIRED,
65
+ unavailable: ACTION_CARD_STATUS.REVOKED,
66
+ });
67
+ const DEFAULT_STATE_TEXT_OVERRIDES = Object.freeze({
68
+ [ACTION_CARD_STATUS.CLAIMED]: '正在提交审批决定,请稍候。',
69
+ [ACTION_CARD_STATUS.RESOLVED]: '该审批已处理,无需重复操作。',
70
+ [ACTION_CARD_STATUS.EXPIRED]: '该审批已过期,已自动拒绝。',
71
+ [ACTION_CARD_STATUS.SUPERSEDED]: '该审批已被新提示取代,请使用最新一条。',
72
+ [ACTION_CARD_STATUS.STALE]: '该审批已失效,请等待新的审批提示。',
73
+ [ACTION_CARD_STATUS.REVOKED]: '该审批已失效,请等待新的审批提示。',
74
+ [ACTION_CARD_STATUS.UNKNOWN]: '该审批已处理或不存在,无需重复操作。',
75
+ });
76
+ const APPROVAL_CARD_NOTICES = Object.freeze({
77
+ ownerOnly: '只有发起当前任务的用户可以处理这条审批。',
78
+ });
79
+
80
+ /** Encode one approval button payload (`ap1|<nonce>|<a|d>`). */
81
+ export function telegramApprovalCallbackData(nonce, decision) {
82
+ const action = ACTION_BY_DECISION[decision];
83
+ if (!action) throw new TypeError('An approval decision must be approve or reject');
84
+ return TELEGRAM_APPROVAL_CALLBACK.encode({ nonce, action });
85
+ }
86
+
87
+ /** Parse one of our button payloads; null for anything else (question cards, etc.). */
88
+ export function parseTelegramApprovalCallback(data) {
89
+ const parsed = TELEGRAM_APPROVAL_CALLBACK.parse(data);
90
+ if (!parsed) return null;
91
+ const decision = DECISION_BY_ACTION[parsed.action];
92
+ if (!decision) return null;
93
+ return { nonce: parsed.nonce, action: decision };
94
+ }
95
+
96
+ /** The two-button keyboard for one presentation. */
97
+ export function telegramApprovalMarkup(nonce) {
98
+ return {
99
+ inline_keyboard: [[
100
+ {
101
+ text: t(BUTTON_TEXT.approve),
102
+ callback_data: telegramApprovalCallbackData(nonce, 'approve'),
103
+ },
104
+ {
105
+ text: t(BUTTON_TEXT.reject),
106
+ callback_data: telegramApprovalCallbackData(nonce, 'reject'),
107
+ },
108
+ ]],
109
+ };
110
+ }
111
+
112
+ /**
113
+ * The card body: today's approval text (tool + arguments + reason) without the
114
+ * "type 批准/拒绝" prompt, which a button makes obsolete. The plain-text path
115
+ * still uses the unmodified `harnessApprovalText` output.
116
+ */
117
+ export function telegramApprovalCardText(pending) {
118
+ const text = harnessApprovalText(pending?.interaction?.payload, {
119
+ toolCall: pending?.toolCall,
120
+ requiresMention: pending?.requiresMention === true,
121
+ hasButtons: true,
122
+ });
123
+ return typeof text === 'string' && text ? text : (pending?.text ?? '');
124
+ }
125
+
126
+ function terminalCardText(cardText, outcome, resolvedText) {
127
+ const label = TERMINAL_LABEL[outcome]
128
+ ? t(TERMINAL_LABEL[outcome])
129
+ : (typeof resolvedText === 'string' ? resolvedText : '');
130
+ return label ? `${cardText}\n\n${label}` : cardText;
131
+ }
132
+
133
+ /**
134
+ * Telegram adapter for the shared approval queue. One instance lives per bridge
135
+ * and owns the nonce registry, so stale cards from earlier turns are recognisable
136
+ * and a new approval in the same conversation supersedes the old keyboard.
137
+ */
138
+ export class TelegramApprovalCard {
139
+ #registry;
140
+ #logger;
141
+ #notices;
142
+
143
+ constructor({
144
+ logger = console,
145
+ registry,
146
+ stateTexts = {},
147
+ ttlMs = 65 * 60_000,
148
+ } = {}) {
149
+ this.#registry = registry instanceof ActionCardRegistry
150
+ ? registry
151
+ : new ActionCardRegistry({ ttlMs });
152
+ this.#logger = logger;
153
+ this.#notices = {
154
+ ...DEFAULT_STATE_TEXT_OVERRIDES,
155
+ ...stateTexts,
156
+ };
157
+ }
158
+
159
+ get registry() {
160
+ return this.#registry;
161
+ }
162
+
163
+ /**
164
+ * Build the `render` / `onResolved` / `send` context handed to
165
+ * HarnessApprovalQueue. Returns an empty object when the bot cannot carry a
166
+ * keyboard, leaving the queue's plain-text flow completely untouched.
167
+ */
168
+ createContext({ key, actor, target, send, bot } = {}) {
169
+ if (typeof bot?.sendInteractionCard !== 'function'
170
+ || typeof bot?.editInteractionCard !== 'function') {
171
+ return {};
172
+ }
173
+ const rawSend = typeof send === 'function' ? send : async () => {};
174
+ let card = null;
175
+ // Nonce of the card being rendered, known before its message id is.
176
+ let cardNonce = null;
177
+ // A decision can land while `sendInteractionCard` is still in flight: the
178
+ // buttons are visible but `card` (and therefore the message id) is not set
179
+ // yet. Store the outcome so the terminal state is applied the moment the id
180
+ // arrives instead of silently leaving a live keyboard behind.
181
+ let pendingResolution = null;
182
+ // The queue sends the terminal receipt as a separate text right after
183
+ // `onResolved`; when the card edit already delivered it, that copy is noise.
184
+ let swallowResolvedText = null;
185
+
186
+ const guardedSend = async (text) => {
187
+ if (swallowResolvedText !== null && text === swallowResolvedText) {
188
+ swallowResolvedText = null;
189
+ return;
190
+ }
191
+ return rawSend(text);
192
+ };
193
+
194
+ /**
195
+ * Replace the card body with the receipt and clear its keyboard.
196
+ * Returns true only when the chat already shows the receipt.
197
+ */
198
+ const applyTerminalState = async (settledCard, resolvedText, outcome) => {
199
+ if (settledCard.messageId === null) return false;
200
+ try {
201
+ await bot.editInteractionCard(target, settledCard.messageId, {
202
+ text: terminalCardText(settledCard.text, outcome, resolvedText),
203
+ markup: EMPTY_KEYBOARD,
204
+ });
205
+ return true;
206
+ } catch (error) {
207
+ this.#logger.warn?.(
208
+ '[dsh-im:telegram] could not update a resolved approval card; the text receipt follows:',
209
+ error?.message ?? error,
210
+ );
211
+ await this.#retireKeyboard(bot, target, settledCard.messageId);
212
+ return false;
213
+ }
214
+ };
215
+
216
+ return {
217
+ send: guardedSend,
218
+ render: async (pending) => {
219
+ const text = telegramApprovalCardText(pending);
220
+ // sendInteractionCard cannot split a body, and sendMessage rejects
221
+ // anything over 4096 characters. A body that big keeps the text path,
222
+ // which splits the same bytes instead of logging a doomed 400.
223
+ if (text.length > TELEGRAM_APPROVAL_CARD_MAX_CHARS) {
224
+ this.#logger.warn?.(
225
+ '[dsh-im:telegram] approval body exceeds the Telegram message limit; using the plain-text approval:',
226
+ `${text.length} chars`,
227
+ );
228
+ await rawSend(pending.text);
229
+ return;
230
+ }
231
+ const entry = this.#registry.issue({
232
+ conversationKey: key,
233
+ kind: 'approval',
234
+ payload: { approvalId: pending.approvalId, actor },
235
+ });
236
+ cardNonce = entry.nonce;
237
+ try {
238
+ const sent = await bot.sendInteractionCard(target, {
239
+ text,
240
+ markup: telegramApprovalMarkup(entry.nonce),
241
+ });
242
+ card = {
243
+ nonce: entry.nonce,
244
+ approvalId: pending.approvalId,
245
+ messageId: sent?.providerMessageIds?.at(-1) ?? null,
246
+ text,
247
+ };
248
+ // The card now owns the decision guidance and the terminal receipt.
249
+ pending.interactiveCard = true;
250
+ // A decision raced the send: finish the terminal edit that
251
+ // `onResolved` could not do while the message id was unknown.
252
+ if (pendingResolution) {
253
+ const { resolvedText, outcome } = pendingResolution;
254
+ pendingResolution = null;
255
+ await applyTerminalState(card, resolvedText, outcome);
256
+ }
257
+ } catch (error) {
258
+ // A platform that refuses the keyboard must not lose the approval:
259
+ // clear the registration and send the exact pre-card prompt instead.
260
+ this.#registry.settle(entry.nonce, ACTION_CARD_STATUS.REVOKED);
261
+ card = null;
262
+ pendingResolution = null;
263
+ this.#logger.warn?.(
264
+ '[dsh-im:telegram] could not deliver an approval card; falling back to the plain-text approval:',
265
+ error?.message ?? error,
266
+ );
267
+ await rawSend(pending.text);
268
+ }
269
+ },
270
+ onResolved: async (resolvedText, outcome) => {
271
+ const nonce = card?.nonce ?? cardNonce;
272
+ if (!nonce) return false;
273
+ // Settle first: a press arriving while the edit is in flight must be
274
+ // refused instead of submitting the same decision twice.
275
+ this.#registry.settle(
276
+ nonce,
277
+ TERMINAL_STATUS_BY_OUTCOME[outcome] ?? ACTION_CARD_STATUS.RESOLVED,
278
+ );
279
+ if (!card) {
280
+ // The send response is still pending. Let the queue deliver the text
281
+ // receipt now — the decision must never be lost — and remember the
282
+ // outcome so `render` clears the buttons once the id is known.
283
+ pendingResolution = { resolvedText, outcome };
284
+ return false;
285
+ }
286
+ const delivered = await applyTerminalState(card, resolvedText, outcome);
287
+ // The edit landed (or the client already shows it): tell the queue the
288
+ // receipt is delivered so it skips the duplicate terminal text.
289
+ if (delivered) swallowResolvedText = resolvedText;
290
+ return delivered;
291
+ },
292
+ };
293
+ }
294
+
295
+ /**
296
+ * Handle one inline-keyboard press. Returns false for payloads this card did
297
+ * not produce, so question cards keep using their own path.
298
+ */
299
+ async handlePress(callback, { bot, answer, submit } = {}) {
300
+ const parsed = parseTelegramApprovalCallback(callback?.data);
301
+ if (!parsed) return false;
302
+ const senderId = typeof callback?.senderId === 'string' ? callback.senderId : '';
303
+ const entry = this.#registry.get(parsed.nonce);
304
+
305
+ // Check the actor before claiming: a stranger's press must not consume the
306
+ // owner's only chance to decide.
307
+ if (entry
308
+ && (entry.status === ACTION_CARD_STATUS.ACTIVE || entry.status === ACTION_CARD_STATUS.CLAIMED)
309
+ && typeof entry.payload?.actor === 'string'
310
+ && entry.payload.actor !== senderId) {
311
+ await answer?.(t(APPROVAL_CARD_NOTICES.ownerOnly));
312
+ return true;
313
+ }
314
+
315
+ // Synchronous claim: whoever gets here first owns the decision; a second tap
316
+ // (or a second client) is told what happened without submitting again.
317
+ const claimed = this.#registry.claim(parsed.nonce);
318
+ if (claimed.status !== ACTION_CARD_STATUS.ACTIVE) {
319
+ await answer?.(actionCardStateText(claimed.status, this.#notices));
320
+ if (claimed.status !== ACTION_CARD_STATUS.CLAIMED) {
321
+ await this.#retireKeyboard(bot, callback?.replyTarget, callback?.providerMessageId);
322
+ }
323
+ return true;
324
+ }
325
+
326
+ const live = claimed.entry;
327
+ // Acknowledge before doing anything that can fail or take time.
328
+ await answer?.();
329
+ if (typeof submit !== 'function') {
330
+ this.#registry.settle(parsed.nonce, ACTION_CARD_STATUS.STALE);
331
+ return true;
332
+ }
333
+ const outcome = OUTCOME_BY_DECISION[parsed.action];
334
+ let submitted = APPROVAL_SUBMIT_RESULT.RETRYABLE;
335
+ try {
336
+ // `detailed` distinguishes a landed decision, an in-flight decision,
337
+ // a retryable failure and an invalid card that must be retired.
338
+ submitted = await submit(live.payload?.approvalId, outcome, { actor: senderId, detailed: true });
339
+ } catch (error) {
340
+ this.#logger.warn?.(
341
+ '[dsh-im:telegram] failed to submit an approval card decision:',
342
+ error?.message ?? error,
343
+ );
344
+ submitted = APPROVAL_SUBMIT_RESULT.RETRYABLE;
345
+ }
346
+ if (submitted === APPROVAL_SUBMIT_RESULT.SUBMITTED) return true;
347
+ if (submitted === APPROVAL_SUBMIT_RESULT.RETRYABLE
348
+ || submitted === APPROVAL_SUBMIT_RESULT.BUSY) {
349
+ // Keep the keyboard available after a failure or while a typed decision
350
+ // is in flight. The queue blocks duplicate submissions; its resolution
351
+ // hook retires the card on success. A later RPC failure can then be retried
352
+ // with this same button instead of leaving it claimed or permanently stale.
353
+ // The callback is already acknowledged; no second toast is needed.
354
+ this.#registry.releaseClaim(parsed.nonce);
355
+ return true;
356
+ }
357
+ // The live queue no longer has this approval (resolved elsewhere, route
358
+ // closed). Retire the card instead of leaving a keyboard that keeps failing.
359
+ this.#registry.settle(parsed.nonce, ACTION_CARD_STATUS.STALE);
360
+ await this.#retireKeyboard(bot, callback?.replyTarget, callback?.providerMessageId);
361
+ return true;
362
+ }
363
+
364
+ async #retireKeyboard(bot, target, providerMessageId) {
365
+ if (typeof bot?.updateInteractionCard !== 'function') return;
366
+ // Card delivery hands back string ids (Bot API message ids are numbers), so
367
+ // normalise before validating; a string guard silently skipped every cleanup.
368
+ const messageId = Number(providerMessageId);
369
+ if (!target || !Number.isSafeInteger(messageId)) return;
370
+ try {
371
+ await bot.updateInteractionCard(target, messageId, { markup: EMPTY_KEYBOARD });
372
+ } catch (error) {
373
+ this.#logger.warn?.(
374
+ '[dsh-im:telegram] could not clear a stale approval keyboard:',
375
+ error?.message ?? error,
376
+ );
377
+ }
378
+ }
379
+ }
@@ -590,10 +590,18 @@ export class TelegramApi {
590
590
  this.#logger?.warn?.(message);
591
591
  }
592
592
 
593
- async editMessageText({ chatId, messageId, text, richMessage, signal }) {
593
+ async editMessageText({ chatId, messageId, text, richMessage, replyMarkup, signal }) {
594
594
  if ((text === undefined) === (richMessage === undefined)) {
595
595
  throw new TypeError('Telegram message edit requires exactly one of text or richMessage');
596
596
  }
597
+ // Product invariant (route map F7): a rich answer never carries an inline
598
+ // keyboard — cards always use regular text. The Bot API would technically
599
+ // accept reply_markup next to rich_message, so this guard is deliberate.
600
+ if (richMessage !== undefined && replyMarkup !== undefined) {
601
+ throw new TypeError(
602
+ 'A rich Telegram answer never carries an inline keyboard; use regular text for cards',
603
+ );
604
+ }
597
605
  return this.#callUnbudgeted('editMessageText', {
598
606
  chat_id: chatId,
599
607
  message_id: messageId,
@@ -601,6 +609,7 @@ export class TelegramApi {
601
609
  text,
602
610
  link_preview_options: { is_disabled: true },
603
611
  }),
612
+ ...(replyMarkup === undefined ? {} : { reply_markup: inputReplyMarkup(replyMarkup) }),
604
613
  }, { signal });
605
614
  }
606
615
 
@@ -2,6 +2,7 @@ import { harnessQuestionText } from '../shared/harness-question.mjs';
2
2
  import { t } from '../shared/i18n.mjs';
3
3
  import { TextHarnessBridge, createTextBridgeStatus } from '../shared/text-harness-bridge.mjs';
4
4
  import { workspaceLabels } from '../shared/workspace-labels.mjs';
5
+ import { TelegramApprovalCard } from './approval-card.mjs';
5
6
 
6
7
  export const TELEGRAM_DESCRIPTOR = Object.freeze({
7
8
  key: 'telegram',
@@ -130,11 +131,17 @@ export const TELEGRAM_WORKSPACE_CARD = Object.freeze({
130
131
 
131
132
  export class TelegramHarnessBridge extends TextHarnessBridge {
132
133
  constructor(options) {
134
+ // Approval cards are on by default; `approvalCard: null` keeps the
135
+ // plain-text approval flow for a caller that wants it (tests/tools).
136
+ // The controller owns the per-conversation nonce registry.
133
137
  super({
134
138
  descriptor: TELEGRAM_DESCRIPTOR,
135
139
  interactionCard: TELEGRAM_INTERACTION_CARD,
136
140
  workspaceCard: TELEGRAM_WORKSPACE_CARD,
137
141
  ...options,
142
+ approvalCard: options && Object.hasOwn(options, 'approvalCard')
143
+ ? options.approvalCard
144
+ : new TelegramApprovalCard({ logger: options?.logger }),
138
145
  });
139
146
  }
140
147
  }
@@ -35,11 +35,22 @@ function commandMenuEntries(catalog, translate) {
35
35
  .map((entry) => ({
36
36
  command: entry.name,
37
37
  description: translate(entry.description ?? item.description),
38
+ // A private-only command's aliases are private-only too, so the group
39
+ // scope never advertises a command it cannot run there.
40
+ privateOnly: (entry.privateOnly ?? item.privateOnly) === true,
38
41
  })));
39
42
  }
40
43
 
44
+ function publicMenuCommands(entries) {
45
+ return entries.map(({ command, description }) => ({ command, description }));
46
+ }
47
+
48
+ /**
49
+ * Flat, scope-agnostic menu (direct-chat superset) used by help/tests and kept
50
+ * as a stable public shape. Runtime registration uses the scoped lists below.
51
+ */
41
52
  export function telegramCommandMenu(catalog = SHARED_COMMAND_CATALOG) {
42
- const commands = commandMenuEntries(catalog, t);
53
+ const commands = publicMenuCommands(commandMenuEntries(catalog, t));
43
54
  validateTelegramCommands(commands, { allowEmpty: true });
44
55
  return commands;
45
56
  }
@@ -47,9 +58,45 @@ export function telegramCommandMenu(catalog = SHARED_COMMAND_CATALOG) {
47
58
  // Retain the source-language export for existing consumers, derived from the
48
59
  // catalog. Runtime synchronization always generates a fresh, localized list.
49
60
  export const TELEGRAM_COMMAND_MENU = Object.freeze(
50
- commandMenuEntries(SHARED_COMMAND_CATALOG, (text) => text).map((item) => Object.freeze(item)),
61
+ publicMenuCommands(commandMenuEntries(SHARED_COMMAND_CATALOG, (text) => text))
62
+ .map((item) => Object.freeze(item)),
51
63
  );
52
64
 
65
+ /**
66
+ * Telegram resolves the commands shown in a chat from the most specific scope
67
+ * that applies: a chat scope, then AllPrivateChats / AllGroupChats, then the
68
+ * default scope. Both lists are registered without a language code, so one
69
+ * menu covers every client language (the labels follow the host language).
70
+ */
71
+ export const TELEGRAM_COMMAND_MENU_SCOPES = Object.freeze({
72
+ private: Object.freeze({ type: 'all_private_chats' }),
73
+ group: Object.freeze({ type: 'all_group_chats' }),
74
+ });
75
+
76
+ /**
77
+ * The two menus the runtime publishes. Private chats receive every command;
78
+ * groups drop commands whose handlers only accept direct chats (history,
79
+ * batch, send, cancel). Hiding a command from a menu never changes the
80
+ * handler's own permission checks.
81
+ */
82
+ export function telegramCommandMenuScopes(catalog = SHARED_COMMAND_CATALOG) {
83
+ const entries = commandMenuEntries(catalog, t);
84
+ const privateCommands = publicMenuCommands(entries);
85
+ const groupCommands = publicMenuCommands(entries.filter((entry) => !entry.privateOnly));
86
+ validateTelegramCommands(privateCommands, { allowEmpty: true });
87
+ validateTelegramCommands(groupCommands, { allowEmpty: true });
88
+ return Object.freeze([
89
+ Object.freeze({
90
+ scope: TELEGRAM_COMMAND_MENU_SCOPES.private,
91
+ commands: Object.freeze(privateCommands),
92
+ }),
93
+ Object.freeze({
94
+ scope: TELEGRAM_COMMAND_MENU_SCOPES.group,
95
+ commands: Object.freeze(groupCommands),
96
+ }),
97
+ ]);
98
+ }
99
+
53
100
  function mentionedUsername(message, username) {
54
101
  if (!username) return false;
55
102
  return [
@@ -274,6 +321,7 @@ export function normalizeTelegramCallback(update, { botId } = {}) {
274
321
  senderName: [callback.from?.first_name, callback.from?.last_name]
275
322
  .filter((value) => typeof value === 'string' && value.trim())
276
323
  .map((value) => value.trim()).join(' ') || callback.from?.username,
324
+ senderUsername: callback.from?.username,
277
325
  conversationTitle: direct ? undefined : message.chat?.title,
278
326
  chatId: String(chatId),
279
327
  threadId: messageThreadId === undefined ? undefined : String(messageThreadId),
@@ -399,6 +447,7 @@ export function normalizeTelegramUpdate(update, {
399
447
  senderName: [message.from?.first_name, message.from?.last_name]
400
448
  .filter((value) => typeof value === 'string' && value.trim())
401
449
  .map((value) => value.trim()).join(' ') || message.from?.username,
450
+ senderUsername: message.from?.username,
402
451
  conversationTitle: direct ? undefined : message.chat?.title,
403
452
  chatId: String(chatId),
404
453
  threadId: messageThreadId === undefined ? undefined : String(messageThreadId),
@@ -714,6 +763,11 @@ export function formatThinkingLine(text) {
714
763
  return `💭 ${truncateCapped(firstParagraph, THINKING_LINE_LIMIT)}`;
715
764
  }
716
765
 
766
+ /** Telegram reports an idempotent edit with HTTP 400; treat it as success. */
767
+ function isMessageNotModified(error) {
768
+ return /message is not modified/iu.test(error?.message ?? '');
769
+ }
770
+
717
771
  export class TelegramBotClient {
718
772
  #api;
719
773
  #signal;
@@ -777,12 +831,62 @@ export class TelegramBotClient {
777
831
 
778
832
  /** Replace a delivered card's keyboard in place; an empty keyboard removes it. */
779
833
  async updateInteractionCard(target, providerMessageId, { markup } = {}) {
780
- await this.#api.editMessageReplyMarkup({
781
- chatId: target.chatId,
782
- messageId: Number(providerMessageId),
783
- replyMarkup: markup,
784
- signal: this.#signal,
785
- });
834
+ try {
835
+ await this.#api.editMessageReplyMarkup({
836
+ chatId: target.chatId,
837
+ messageId: Number(providerMessageId),
838
+ replyMarkup: markup,
839
+ signal: this.#signal,
840
+ });
841
+ } catch (error) {
842
+ // Clearing a keyboard that is already gone is the desired end state.
843
+ if (!isMessageNotModified(error)) throw error;
844
+ }
845
+ }
846
+
847
+ /**
848
+ * Rewrite a delivered card's text and keyboard in one `editMessageText` call.
849
+ *
850
+ * Telegram answers "message is not modified" when the client already holds the
851
+ * exact payload (a duplicate resolution); that is success, not failure. If a
852
+ * Bot API deployment refuses the combined text+keyboard edit, degrade to the
853
+ * two calls this client already supports — the interface stays the same.
854
+ */
855
+ async editInteractionCard(target, providerMessageId, { text, markup } = {}) {
856
+ const messageId = Number(providerMessageId);
857
+ if (!Number.isSafeInteger(messageId)) {
858
+ throw new TypeError('Telegram card message id must be a safe integer');
859
+ }
860
+ try {
861
+ return await this.#api.editMessageText({
862
+ chatId: target.chatId,
863
+ messageId,
864
+ text,
865
+ replyMarkup: markup,
866
+ signal: this.#signal,
867
+ });
868
+ } catch (error) {
869
+ if (isMessageNotModified(error)) return { unchanged: true };
870
+ if (error?.code !== 'telegram-400' || markup === undefined) throw error;
871
+ // Clear the dead keyboard first so a stale card cannot keep submitting.
872
+ try {
873
+ await this.#api.editMessageReplyMarkup({
874
+ chatId: target.chatId,
875
+ messageId,
876
+ replyMarkup: markup,
877
+ signal: this.#signal,
878
+ });
879
+ } catch (markupError) {
880
+ if (!isMessageNotModified(markupError)) throw markupError;
881
+ }
882
+ await this.#api.editMessageText({
883
+ chatId: target.chatId,
884
+ messageId,
885
+ text,
886
+ signal: this.#signal,
887
+ });
888
+ return { fallback: true };
889
+ }
786
890
  }
787
891
 
788
892
  /** Stop the client-side spinner on a pressed button. */
@@ -1630,12 +1734,20 @@ export class TelegramRuntime {
1630
1734
  }
1631
1735
  }
1632
1736
 
1633
- // Both operations use the existing default scope and language. Sending the
1634
- // full list replaces old entries; an empty catalog clears that list.
1737
+ // Commands are registered per BotCommandScope, and the scopes overlap: a
1738
+ // default-scope list from an earlier version would keep applying wherever a
1739
+ // scoped list is missing and could advertise private-only commands in groups.
1740
+ // The scoped lists are written first and only then is the legacy default
1741
+ // scope cleared, so a failed scoped write leaves the previous (default-scope)
1742
+ // menu usable until the next reconnect instead of blanking the menu. No
1743
+ // language code is sent, so one list covers all client languages.
1635
1744
  async #sendCommandMenu(api, signal) {
1636
- const commands = telegramCommandMenu(this.#commandCatalog);
1637
- if (commands.length > 0) await api.setMyCommands({ commands, signal });
1638
- else await api.deleteMyCommands({ signal });
1745
+ const menus = telegramCommandMenuScopes(this.#commandCatalog);
1746
+ for (const { scope, commands } of menus) {
1747
+ if (commands.length > 0) await api.setMyCommands({ commands, scope, signal });
1748
+ else await api.deleteMyCommands({ scope, signal });
1749
+ }
1750
+ await api.deleteMyCommands({ signal });
1639
1751
  }
1640
1752
 
1641
1753
  /**
@@ -37,7 +37,7 @@ import {
37
37
  isPresetCommand,
38
38
  runPresetCommand,
39
39
  } from '../shared/preset-command.mjs';
40
- import { runWorkspaceCommand, workspacePathSnapshot } from '../shared/workspace-command.mjs';
40
+ import { conversationSessionWorkspace, runWorkspaceCommand, workspacePathSnapshot } from '../shared/workspace-command.mjs';
41
41
  import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
42
42
  import {
43
43
  captureContextEnhancement,
@@ -660,7 +660,8 @@ export class WecomHarnessBridge {
660
660
  const options = { signal: this.#signal };
661
661
  const settled = await Promise.allSettled([
662
662
  workspacePathSnapshot(this.#harness, options),
663
- this.#harness.listWorkspaceSessions?.(workspace, options),
663
+ conversationSessionWorkspace(this.#harness, key, options)
664
+ .then((path) => this.#harness.listWorkspaceSessions?.(path, options)),
664
665
  (async () => {
665
666
  const session = sessionId ? this.#harness.workspaceSession?.(sessionId, key) : null;
666
667
  return typeof session?.models === 'function'
@@ -852,7 +853,8 @@ export class WecomHarnessBridge {
852
853
  let description = '';
853
854
  if (menu.section === 'sessions') {
854
855
  title = t('📋 会话列表');
855
- const listed = await this.#harness.listWorkspaceSessions(this.#harness.currentWorkspace(), options);
856
+ const workspace = await conversationSessionWorkspace(this.#harness, key, options);
857
+ const listed = await this.#harness.listWorkspaceSessions(workspace, options);
856
858
  entries = listed.sessions.map((session) => [
857
859
  `${session.sessionId === this.#state.sessionFor(key) ? '✓ ' : ''}${session.title || t('暂无标题')}`,
858
860
  `/session ${session.sessionId}`,