@xmanrui/dsh-im 5.3.0 → 5.4.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 (49) hide show
  1. package/THIRD_PARTY_NOTICES.md +209 -0
  2. package/docs/client-integration.md +2 -2
  3. package/lib/client.js +1688 -233
  4. package/lib/index.js +322 -318
  5. package/package.json +1 -1
  6. package/plugin-src/client/channels/telegram/group-triggers-settings.js +393 -0
  7. package/plugin-src/client/delivery-settings.js +21 -1
  8. package/plugin-src/client/ds-bot-avatar-data.js +537 -0
  9. package/plugin-src/client/ds-bot-avatar.js +55 -0
  10. package/plugin-src/client/ds-bot-session-avatars.js +77 -0
  11. package/plugin-src/client/ds-bot-settings.js +194 -0
  12. package/plugin-src/client/i18n.js +59 -1
  13. package/plugin-src/client/index.js +12 -1
  14. package/plugin-src/client/plugin-page.js +3 -8
  15. package/plugin-src/client/styles.js +25 -5
  16. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  17. package/plugin-src/host/channels/feishu/production.mjs +13 -5
  18. package/plugin-src/host/channels/qq/production.mjs +2 -1
  19. package/plugin-src/host/channels/shared/group-triggers-rpc.mjs +110 -0
  20. package/plugin-src/host/channels/shared/production.mjs +7 -1
  21. package/plugin-src/host/channels/slack/production.mjs +2 -1
  22. package/plugin-src/host/channels/telegram/index.mjs +1 -0
  23. package/plugin-src/host/channels/telegram/production.mjs +2 -0
  24. package/plugin-src/host/channels/telegram/rpc.mjs +17 -2
  25. package/plugin-src/host/channels/wecom/production.mjs +4 -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 +89 -9
  30. package/plugin-src/host/delivery-rpc.mjs +33 -1
  31. package/plugin-src/host/delivery-service.mjs +70 -1
  32. package/plugin-src/host/delivery-suggestions.mjs +11 -0
  33. package/plugin-src/host/ds-bot-client.mjs +74 -0
  34. package/plugin-src/host/index.mjs +5 -1
  35. package/src/channels/feishu/feishu-cards.mjs +11 -7
  36. package/src/channels/shared/bot-workspace-store.mjs +136 -7
  37. package/src/channels/shared/group-history-store.mjs +26 -0
  38. package/src/channels/shared/i18n-en/feishu.mjs +1 -0
  39. package/src/channels/shared/i18n-en/wecom.mjs +4 -0
  40. package/src/channels/shared/session-binding-lock.mjs +2 -0
  41. package/src/channels/shared/workspace-session.mjs +5 -1
  42. package/src/channels/telegram/config-store.mjs +5 -1
  43. package/src/channels/telegram/group-triggers.mjs +229 -0
  44. package/src/channels/telegram/telegram-api.mjs +12 -0
  45. package/src/channels/telegram/telegram-controller.mjs +110 -1
  46. package/src/channels/telegram/telegram-runtime.mjs +15 -2
  47. package/src/channels/wecom/stream-supervisor.mjs +184 -0
  48. package/src/channels/wecom/wecom-bridge.mjs +25 -11
  49. package/src/channels/wecom/wecom-runtime.mjs +12 -1
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Per-group reply triggers for the Telegram channel.
3
+ *
4
+ * A bot in a group used to wake up only when someone mentioned it or replied to
5
+ * one of its messages. This module owns the richer, per-chat rule set:
6
+ *
7
+ * off — stay quiet (opt-in; chats without a rule keep the legacy
8
+ * "mention or reply" behaviour);
9
+ * mention — reply to @username mentions and replies, from anyone;
10
+ * mention-list — the same, but only from the listed member IDs;
11
+ * all — reply to every message, from anyone;
12
+ * all-list — every message, but only from the listed member IDs.
13
+ *
14
+ * The settings live in the bot config next to `thinkingTraces`/`alias`, so they
15
+ * travel with the account instead of a side file, and every update restarts the
16
+ * runtime through the controller.
17
+ */
18
+
19
+ export const GROUP_TRIGGER_VERSION = 1;
20
+ export const GROUP_TRIGGER_MODES = Object.freeze(['off', 'mention', 'mention-list', 'all', 'all-list']);
21
+ export const GROUP_TRIGGER_LIST_MODES = Object.freeze(['mention-list', 'all-list']);
22
+ export const GROUP_TRIGGER_MAX_SENDERS = 500;
23
+ export const GROUP_TRIGGER_MAX_ID_LENGTH = 64;
24
+ export const GROUP_TRIGGER_DEFAULT_SCOPE = Object.freeze(Object.freeze({
25
+ mode: 'mention',
26
+ senders: Object.freeze([]),
27
+ }));
28
+
29
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/;
30
+ const TELEGRAM_INTERNAL_MESSAGE_LINK = /^(?:https?:\/\/)?t\.me\/c\/(\d{1,20})(?:\/\d{1,20}){0,2}\/?$/i;
31
+ const TELEGRAM_PUBLIC_LINK = /^(?:https?:\/\/)?t\.me\/([A-Za-z0-9_]{4,64})(?:\/\d{1,20}){0,2}\/?$/i;
32
+ const TELEGRAM_INVITE_LINK = /^(?:https?:\/\/)?t\.me\/(?:joinchat\/|\+)([A-Za-z0-9_-]{1,128})\/?$/i;
33
+ const TELEGRAM_HANDLE = /^@([A-Za-z][A-Za-z0-9_]{3,63})$/;
34
+ const NUMERIC_CHAT_ID = /^-?\d{1,20}$/;
35
+
36
+ function isRecord(value) {
37
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
38
+ }
39
+
40
+ export function invalidGroupTriggers(message) {
41
+ const error = new TypeError(message);
42
+ error.code = 'group-triggers-invalid';
43
+ return error;
44
+ }
45
+
46
+ function cleanIdentifier(value) {
47
+ const text = typeof value === 'number' && Number.isSafeInteger(value)
48
+ ? String(value) : typeof value === 'string' ? value.trim() : '';
49
+ if (!text || text.length > GROUP_TRIGGER_MAX_ID_LENGTH || CONTROL_CHARACTERS.test(text)) return '';
50
+ return text;
51
+ }
52
+
53
+ function normalizeSenders(value) {
54
+ if (value === undefined) return Object.freeze([]);
55
+ if (!Array.isArray(value)) throw invalidGroupTriggers('Member IDs must be an array.');
56
+ const senders = [];
57
+ for (const entry of value) {
58
+ const id = cleanIdentifier(entry);
59
+ if (!id) throw invalidGroupTriggers(`Member IDs must be non-empty strings up to ${GROUP_TRIGGER_MAX_ID_LENGTH} characters.`);
60
+ if (!senders.includes(id)) senders.push(id);
61
+ if (senders.length > GROUP_TRIGGER_MAX_SENDERS) {
62
+ throw invalidGroupTriggers(`At most ${GROUP_TRIGGER_MAX_SENDERS} member IDs are supported per group.`);
63
+ }
64
+ }
65
+ return Object.freeze(senders);
66
+ }
67
+
68
+ export function normalizeGroupTriggerScope(value) {
69
+ const source = isRecord(value) ? value : {};
70
+ const mode = GROUP_TRIGGER_MODES.includes(source.mode) ? source.mode : GROUP_TRIGGER_DEFAULT_SCOPE.mode;
71
+ return Object.freeze({ mode, senders: normalizeSenders(source.senders) });
72
+ }
73
+
74
+ export function normalizeGroupTriggers(value) {
75
+ const source = isRecord(value) ? value : {};
76
+ const groups = {};
77
+ const rawGroups = isRecord(source.groups) ? source.groups : {};
78
+ for (const [chatId, scope] of Object.entries(rawGroups)) {
79
+ const id = cleanIdentifier(chatId);
80
+ if (!id) continue;
81
+ groups[id] = normalizeGroupTriggerScope(scope);
82
+ }
83
+ const hidden = [];
84
+ if (Array.isArray(source.hiddenGroupIds)) {
85
+ for (const entry of source.hiddenGroupIds) {
86
+ const id = cleanIdentifier(entry);
87
+ if (id && !hidden.includes(id)) hidden.push(id);
88
+ }
89
+ }
90
+ return Object.freeze({
91
+ version: GROUP_TRIGGER_VERSION,
92
+ defaults: normalizeGroupTriggerScope(source.defaults),
93
+ groups: Object.freeze(groups),
94
+ // Chats the owner hid in the settings panel. They stay in the group
95
+ // history; the panel simply stops offering them.
96
+ hiddenGroupIds: Object.freeze(hidden),
97
+ });
98
+ }
99
+
100
+ /** The rule that applies to a chat: its own entry, otherwise the defaults. */
101
+ export function groupTriggerScopeFor(config, chatId) {
102
+ const normalized = config?.version === GROUP_TRIGGER_VERSION && config.defaults
103
+ ? config : normalizeGroupTriggers(config);
104
+ const id = cleanIdentifier(chatId);
105
+ return (id && Object.hasOwn(normalized.groups, id) ? normalized.groups[id] : normalized.defaults);
106
+ }
107
+
108
+ export function groupTriggerModeFor(config, chatId) {
109
+ return groupTriggerScopeFor(config, chatId).mode;
110
+ }
111
+
112
+ /**
113
+ * Whether a group message should wake the model.
114
+ *
115
+ * `tagged` is the legacy signal: an @username mention or a reply to the bot.
116
+ * Direct chats never reach this function — they are always addressed.
117
+ */
118
+ export function groupTriggerAddressed(config, { chatId, senderId, tagged = false } = {}) {
119
+ const scope = groupTriggerScopeFor(config, chatId);
120
+ const member = scope.senders.includes(typeof senderId === 'string' ? senderId : String(senderId ?? ''));
121
+ if (scope.mode === 'mention') return tagged === true;
122
+ if (scope.mode === 'all') return true;
123
+ if (scope.mode === 'mention-list') return tagged === true && member;
124
+ if (scope.mode === 'all-list') return member;
125
+ return false;
126
+ }
127
+
128
+ /** Chat IDs hidden in the settings panel. */
129
+ export function hiddenGroupIds(value) {
130
+ const normalized = value?.version === GROUP_TRIGGER_VERSION ? value : normalizeGroupTriggers(value);
131
+ return normalized.hiddenGroupIds;
132
+ }
133
+
134
+ /**
135
+ * Split whatever the owner pasted into a Telegram chat reference.
136
+ *
137
+ * Numeric IDs and `t.me/c/<internal>/...` links already determine the chat id;
138
+ * usernames and invite links only resolve through the Bot API.
139
+ */
140
+ export function parseGroupReference(value) {
141
+ const text = typeof value === 'string' ? value.replace(/[\s\u00a0]+/g, '') : '';
142
+ if (!text) throw invalidGroupTriggers('Enter a group ID, @username or a t.me link.');
143
+ if (NUMERIC_CHAT_ID.test(text)) return { chatId: text, query: text, numeric: true };
144
+ const internal = text.match(TELEGRAM_INTERNAL_MESSAGE_LINK);
145
+ if (internal) {
146
+ const chatId = `-100${internal[1]}`;
147
+ return { chatId, query: chatId, numeric: true };
148
+ }
149
+ // `getChat` accepts a numeric id or a supergroup/channel @username only, so an
150
+ // invite link can never be resolved by the Bot API; reject it explicitly
151
+ // instead of forwarding a URL the platform would refuse.
152
+ if (TELEGRAM_INVITE_LINK.test(text)) {
153
+ throw invalidGroupTriggers('Invite links cannot be resolved through the Bot API. Use the group @username or its numeric ID.');
154
+ }
155
+ const named = text.match(TELEGRAM_PUBLIC_LINK);
156
+ if (named) return { chatId: null, query: `@${named[1]}`, numeric: false };
157
+ const handle = text.match(TELEGRAM_HANDLE);
158
+ if (handle) return { chatId: null, query: `@${handle[1]}`, numeric: false };
159
+ throw invalidGroupTriggers('Unrecognized group reference; use a numeric ID, @username or a t.me link.');
160
+ }
161
+
162
+ /**
163
+ * Resolve a pasted reference into the real chat id.
164
+ *
165
+ * `getChat` is injected so the caller owns the Bot API token and tests can run
166
+ * without a network. Numeric references still succeed when the API is down;
167
+ * usernames and invites cannot, and the error tells the owner what to do.
168
+ */
169
+ export async function resolveGroupReference(value, { getChat } = {}) {
170
+ const reference = parseGroupReference(value);
171
+ if (!reference.chatId && typeof getChat !== 'function') {
172
+ throw invalidGroupTriggers('Could not resolve this reference through Telegram (Bot API is unavailable). Retry later or enter the numeric group ID.');
173
+ }
174
+ let chat = null;
175
+ let failure = null;
176
+ if (typeof getChat === 'function') {
177
+ try {
178
+ chat = await getChat(reference.query);
179
+ } catch (error) {
180
+ failure = error;
181
+ }
182
+ }
183
+ if (!chat && reference.numeric && /^\d{6,20}$/.test(reference.chatId)) {
184
+ try {
185
+ chat = await getChat(`-100${reference.chatId}`);
186
+ } catch {
187
+ // The first attempt already recorded the failure worth reporting.
188
+ }
189
+ }
190
+ const chatId = chat?.id === undefined || chat?.id === null ? reference.chatId : String(chat.id);
191
+ if (!chatId) {
192
+ const reason = failure && typeof failure.message === 'string' && failure.message
193
+ ? failure.message : 'Bot API is unavailable';
194
+ throw invalidGroupTriggers(`Could not resolve this reference through Telegram (${reason}). Retry later or enter the numeric group ID.`);
195
+ }
196
+ if (chat?.type === 'private') {
197
+ throw invalidGroupTriggers('This reference points to a private chat, not a group.');
198
+ }
199
+ return Object.freeze({
200
+ chatId,
201
+ title: typeof chat?.title === 'string' && chat.title.trim() ? chat.title.trim() : null,
202
+ type: typeof chat?.type === 'string' ? chat.type : null,
203
+ verified: Boolean(chat),
204
+ });
205
+ }
206
+
207
+ /** Panel view: the stored rules plus the groups the bot has actually seen. */
208
+ export function groupTriggersSettings(config, seenGroups = []) {
209
+ const normalized = config?.version === GROUP_TRIGGER_VERSION ? config : normalizeGroupTriggers(config);
210
+ const hidden = new Set(normalized.hiddenGroupIds);
211
+ const groups = {};
212
+ for (const [chatId, scope] of Object.entries(normalized.groups)) {
213
+ if (hidden.has(chatId)) continue;
214
+ groups[chatId] = { mode: scope.mode, senders: [...scope.senders] };
215
+ }
216
+ const seen = [];
217
+ for (const entry of Array.isArray(seenGroups) ? seenGroups : []) {
218
+ const chatId = cleanIdentifier(entry?.chatId);
219
+ if (!chatId || hidden.has(chatId) || seen.some((item) => item.chatId === chatId)) continue;
220
+ seen.push({
221
+ chatId,
222
+ title: typeof entry.title === 'string' && entry.title.trim() ? entry.title.trim() : null,
223
+ type: typeof entry.type === 'string' ? entry.type : null,
224
+ lastSeenAt: typeof entry.lastSeenAt === 'string' ? entry.lastSeenAt : null,
225
+ lastSenderName: typeof entry.lastSenderName === 'string' ? entry.lastSenderName : null,
226
+ });
227
+ }
228
+ return { defaults: { mode: normalized.defaults.mode, senders: [...normalized.defaults.senders] }, groups, seen };
229
+ }
@@ -178,6 +178,18 @@ export class TelegramApi {
178
178
  return this.#call('getWebhookInfo', {}, options);
179
179
  }
180
180
 
181
+ /**
182
+ * Look a chat up by numeric id, `@username` or an invite link.
183
+ *
184
+ * The settings page uses this to turn a pasted group reference into a chat
185
+ * id; the bot must already be able to see the chat for the lookup to work.
186
+ */
187
+ async getChat({ chatId, signal } = {}) {
188
+ const id = cleanString(chatId);
189
+ if (!id || id.length > 512) throw new TypeError('Telegram chat id is invalid');
190
+ return this.#call('getChat', { chat_id: id }, { signal });
191
+ }
192
+
181
193
  async getUpdates({ offset, timeout = 25, signal } = {}) {
182
194
  const payload = {
183
195
  timeout,
@@ -4,12 +4,28 @@ import {
4
4
  maskTelegramBotId,
5
5
  normalizeTelegramAccessPolicy,
6
6
  } from './config-store.mjs';
7
- import { inspectTelegramToken } from './telegram-api.mjs';
7
+ import {
8
+ GROUP_TRIGGER_VERSION,
9
+ groupTriggersSettings,
10
+ normalizeGroupTriggers,
11
+ parseGroupReference,
12
+ resolveGroupReference,
13
+ } from './group-triggers.mjs';
14
+ import { inspectTelegramToken, TelegramApi } from './telegram-api.mjs';
15
+ import { createTelegramHttpTransport } from './telegram-http.mjs';
8
16
  import { TELEGRAM_DESCRIPTOR } from './telegram-bridge.mjs';
9
17
 
10
18
  export class TelegramController extends TokenBotController {
11
19
  #configStore;
12
20
 
21
+ #credentials;
22
+
23
+ #groupHistory;
24
+
25
+ #createApi;
26
+
27
+ #createHttpTransport;
28
+
13
29
  constructor(options) {
14
30
  super({
15
31
  ...options,
@@ -19,6 +35,11 @@ export class TelegramController extends TokenBotController {
19
35
  maskPlatformId: maskTelegramBotId,
20
36
  });
21
37
  this.#configStore = options.configStore;
38
+ this.#credentials = options.credentials ?? null;
39
+ this.#groupHistory = options.groupHistory ?? null;
40
+ this.#createApi = options.createApi ?? ((apiOptions) => new TelegramApi(apiOptions));
41
+ // Lookup must go through the same proxy-aware transport as the runtime.
42
+ this.#createHttpTransport = options.createHttpTransport ?? createTelegramHttpTransport;
22
43
  }
23
44
 
24
45
  status() {
@@ -33,6 +54,7 @@ export class TelegramController extends TokenBotController {
33
54
  accessPolicy,
34
55
  // Default ON; only an explicit false in the config opts out.
35
56
  thinkingTraces: config?.thinkingTraces !== false,
57
+ groupTriggers: normalizeGroupTriggers(config?.groupTriggers),
36
58
  };
37
59
  }),
38
60
  };
@@ -49,4 +71,91 @@ export class TelegramController extends TokenBotController {
49
71
  thinkingTraces: value === true,
50
72
  }));
51
73
  }
74
+
75
+ /** Channels the bot has actually received messages from. */
76
+ async knownGroups() {
77
+ if (typeof this.#groupHistory?.listGroups !== 'function') return [];
78
+ try {
79
+ return await this.#groupHistory.listGroups({ channel: 'telegram' });
80
+ } catch {
81
+ // History only feeds the settings panel: a broken archive must not take
82
+ // the settings page down with it.
83
+ return [];
84
+ }
85
+ }
86
+
87
+ async groupTriggersPanel(botId) {
88
+ const config = this.#configStore.get(botId);
89
+ if (!config) throw new Error('Unknown Telegram bot');
90
+ return groupTriggersSettings(config.groupTriggers, await this.knownGroups());
91
+ }
92
+
93
+ /**
94
+ * Persist the per-group reply rules.
95
+ *
96
+ * `removed` lists the chats the owner deleted in the panel: they keep their
97
+ * archived history but stop being offered in the settings page.
98
+ */
99
+ async updateGroupTriggers(botId, { config: value, removed = [] } = {}) {
100
+ const stored = this.#configStore.get(botId);
101
+ if (!stored) throw new Error('Unknown Telegram bot');
102
+ const normalized = normalizeGroupTriggers(value);
103
+ const groups = { ...normalized.groups };
104
+ // The panel never echoes `hiddenGroupIds`, so they are merged with what the
105
+ // store already holds; otherwise a second save would resurrect every group
106
+ // removed by the first one.
107
+ const hidden = new Set(normalizeGroupTriggers(stored.groupTriggers).hiddenGroupIds);
108
+ for (const chatId of Array.isArray(removed) ? removed : []) {
109
+ const id = typeof chatId === 'string' ? chatId.trim() : '';
110
+ if (!id) continue;
111
+ delete groups[id];
112
+ hidden.add(id);
113
+ }
114
+ // An explicit rule means the owner brought the chat back into the panel.
115
+ for (const chatId of Object.keys(groups)) hidden.delete(chatId);
116
+ const next = {
117
+ version: GROUP_TRIGGER_VERSION,
118
+ defaults: normalized.defaults,
119
+ groups,
120
+ hiddenGroupIds: [...hidden],
121
+ };
122
+ await this.updateBotConfig(botId, (config) => ({ ...config, groupTriggers: next }));
123
+ return groupTriggersSettings(next, await this.knownGroups());
124
+ }
125
+
126
+ /**
127
+ * Turn a pasted group reference into a chat id.
128
+ *
129
+ * Numeric IDs resolve locally; usernames and invite links need the Bot API,
130
+ * so the call borrows the bot's own token instead of asking the owner for it.
131
+ */
132
+ async resolveGroupTrigger(botId, input) {
133
+ const config = this.#configStore.get(botId);
134
+ if (!config) throw new Error('Unknown Telegram bot');
135
+ let token = '';
136
+ if (this.#credentials && typeof this.#credentials.resolve === 'function') {
137
+ const resolved = await this.#credentials.resolve(config.tokenRef);
138
+ token = typeof resolved?.value === 'string' ? resolved.value.trim() : '';
139
+ }
140
+ // Numeric ids and message links resolve offline; only a username or an
141
+ // invite link needs the Bot API (and therefore a transport).
142
+ const reference = parseGroupReference(input);
143
+ if (reference.chatId) {
144
+ return Object.freeze({ chatId: reference.chatId, title: null, type: null, verified: false });
145
+ }
146
+ if (!token) return resolveGroupReference(input, {});
147
+ const transport = this.#createHttpTransport();
148
+ try {
149
+ const api = this.#createApi({
150
+ token,
151
+ fetchImpl: transport.fetchImpl,
152
+ FormDataImpl: transport.FormDataImpl,
153
+ });
154
+ return await resolveGroupReference(input, {
155
+ getChat: (chatId) => api.getChat({ chatId }),
156
+ });
157
+ } finally {
158
+ await transport.destroy?.();
159
+ }
160
+ }
52
161
  }
@@ -4,6 +4,7 @@ import { extractConnectionEvidence, createConnectionDiagnostics, atConnectionSta
4
4
  import { createEditableMessageStream } from '../shared/editable-message-stream.mjs';
5
5
  import { createTextDeliveryBlock } from '../shared/semantic/delivery.mjs';
6
6
  import { t } from '../shared/i18n.mjs';
7
+ import { groupTriggerAddressed, normalizeGroupTriggers } from './group-triggers.mjs';
7
8
  import { captureContextEnhancement } from '../shared/context-enhancement.mjs';
8
9
  import { recoverAssistantTextByTimestamp } from '../shared/session-reply-recovery.mjs';
9
10
  import { SHARED_COMMAND_CATALOG, commandsForChannel } from '../shared/command-catalog.mjs';
@@ -278,6 +279,7 @@ export function normalizeTelegramCallback(update, { botId } = {}) {
278
279
  export function normalizeTelegramUpdate(update, {
279
280
  botId,
280
281
  username,
282
+ groupTriggers,
281
283
  loadFile = async () => { throw new Error('Telegram file downloader is unavailable'); },
282
284
  loadFileStream = loadFile,
283
285
  loadReplyContent,
@@ -290,9 +292,15 @@ export function normalizeTelegramUpdate(update, {
290
292
  || !Number.isSafeInteger(messageId)) return null;
291
293
  if (!['private', 'group', 'supergroup'].includes(message.chat?.type)) return null;
292
294
  const direct = message.chat.type === 'private';
293
- const addressed = direct
294
- || String(message.reply_to_message?.from?.id ?? '') === String(botId)
295
+ // A reply to the bot or an @username mention is the legacy "tagged" signal;
296
+ // the per-group rule decides whether it is enough (or unnecessary).
297
+ const tagged = String(message.reply_to_message?.from?.id ?? '') === String(botId)
295
298
  || mentionedUsername(message, username);
299
+ const addressed = direct || groupTriggerAddressed(groupTriggers, {
300
+ chatId: String(chatId),
301
+ senderId: String(senderId),
302
+ tagged,
303
+ });
296
304
  const messageThreadId = Number.isSafeInteger(message.message_thread_id)
297
305
  ? message.message_thread_id : undefined;
298
306
  const image = telegramImageSource(message, loadFile);
@@ -1109,6 +1117,7 @@ export class TelegramRuntime {
1109
1117
  #state;
1110
1118
  #contextEnhancement;
1111
1119
  #groupHistory;
1120
+ #groupTriggers;
1112
1121
  #accessPolicy;
1113
1122
  #logger;
1114
1123
  #diagnostics;
@@ -1155,6 +1164,9 @@ export class TelegramRuntime {
1155
1164
  this.#state = state;
1156
1165
  this.#contextEnhancement = contextEnhancement;
1157
1166
  this.#groupHistory = groupHistory;
1167
+ // Rules change through the controller, which restarts the runtime, so the
1168
+ // normalized snapshot is read once per start.
1169
+ this.#groupTriggers = normalizeGroupTriggers(config.groupTriggers);
1158
1170
  this.#accessPolicy = accessPolicy;
1159
1171
  this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'telegram', logger });
1160
1172
  this.#replyTimeoutMs = replyTimeoutMs;
@@ -1423,6 +1435,7 @@ export class TelegramRuntime {
1423
1435
  const message = normalizeTelegramUpdate(update, {
1424
1436
  botId: this.#config.platformId,
1425
1437
  username: this.#config.username,
1438
+ groupTriggers: this.#groupTriggers,
1426
1439
  loadFile: (fileId, options) => this.#api.downloadFile({ fileId, ...options }),
1427
1440
  loadFileStream: (fileId, options) => this.#api.downloadFileStream({ fileId, ...options }),
1428
1441
  loadReplyContent: (reference, options) => this.#loadReplyContent(reference, options),
@@ -0,0 +1,184 @@
1
+ import { t } from '../shared/i18n.mjs';
2
+
3
+ // WeCom closes a streaming card 10 minutes after its FIRST frame; refreshes do
4
+ // not extend the window (verified against the provider: errcode 846608
5
+ // "stream message update expired (>10 minutes), cannot update"). A long or
6
+ // silent turn therefore outlives its card, and every later frame plus the
7
+ // final finish are rejected — the reply is lost.
8
+ //
9
+ // The supervisor keeps a turn deliverable by rotating cards before the wall:
10
+ // each rotation finishes the current card with a pointer note and opens a
11
+ // fresh stream that carries the same preview content. It also probes silent
12
+ // stretches (no frames to send) so the card stays informative, and rebuilds
13
+ // immediately after back-to-back rejected updates in case a card dies early.
14
+ //
15
+ // Concurrency rules:
16
+ // - Every send (rotation, probe, progress, finalization) runs on one serial
17
+ // queue, so a rotation already in flight completes — and publishes its new
18
+ // card — before the final finish is sent. The final answer always targets
19
+ // the newest live card.
20
+ // - stop() forbids opening further cards: an interrupted rotation closes its
21
+ // old card but never leaves an unfinished "continuing" orphan behind.
22
+ // - Finalization is terminal: once finishStream is called the timer stops and
23
+ // probes/rotations are suppressed, so slow follow-up delivery (remaining
24
+ // text chunks, attachments) can never touch or replace the finished card.
25
+ // A failed finish still falls through to the caller's active-message path.
26
+ export function createWecomStreamSupervisor({
27
+ client,
28
+ frame,
29
+ chatId,
30
+ generateStreamId,
31
+ previewText = () => '',
32
+ logger = console,
33
+ rotateAfterMs = 8 * 60 * 1000 + 30 * 1000,
34
+ silentProbeMs = 2 * 60 * 1000,
35
+ tickMs = 60 * 1000,
36
+ }) {
37
+ if (!client || typeof client.replyStream !== 'function') {
38
+ throw new TypeError('createWecomStreamSupervisor requires a client with replyStream');
39
+ }
40
+ if (typeof generateStreamId !== 'function') {
41
+ throw new TypeError('createWecomStreamSupervisor requires a generateStreamId function');
42
+ }
43
+ let currentStreamId = null;
44
+ let cardStartedAt = Date.now();
45
+ let lastFrameAt = Date.now();
46
+ let segmentNo = 1;
47
+ let alive = true;
48
+ let rejects = 0;
49
+ let stopped = false;
50
+ let delivering = false;
51
+ let timer = null;
52
+
53
+ // One serial queue for every provider interaction; a failed operation never
54
+ // blocks the next one.
55
+ let chain = Promise.resolve();
56
+ const enqueue = (operation) => {
57
+ const run = chain.then(operation, operation);
58
+ chain = run.catch(() => undefined);
59
+ return run;
60
+ };
61
+
62
+ // The SDK rejects send promises with the raw ack frame, which carries
63
+ // errcode/errmsg but no .message; wrap it so every caller sees an Error.
64
+ const normalize = (error) => {
65
+ if (error instanceof Error) return error;
66
+ const errcode = error?.errcode ?? error?.body?.errcode ?? error?.header?.errcode;
67
+ const wrapped = new Error(
68
+ `${error?.errmsg ?? error?.body?.errmsg ?? 'wecom stream update rejected'} (errcode=${errcode ?? 'unknown'})`,
69
+ );
70
+ if (errcode !== undefined) wrapped.errcode = Number(errcode);
71
+ if (typeof error?.errmsg === 'string') wrapped.errmsg = error.errmsg;
72
+ return wrapped;
73
+ };
74
+
75
+ const reply = (streamId, text, finish) => client.replyStream(frame, streamId, text, finish);
76
+
77
+ // Runs on the serial queue. Closes the current card, then — unless the
78
+ // supervisor was stopped or finalization began meanwhile — opens a fresh
79
+ // card seeded with the pending preview.
80
+ const rotateCore = async (headText) => {
81
+ const closedSegment = segmentNo;
82
+ segmentNo += 1;
83
+ if (currentStreamId) {
84
+ await reply(
85
+ currentStreamId,
86
+ t('▣ 第 {segment} 段 · 任务仍在进行,继续见下一条 ↓', { segment: closedSegment }),
87
+ true,
88
+ ).catch(() => undefined);
89
+ }
90
+ if (stopped) {
91
+ // Shutdown raced the rotation: closing the old card is still correct,
92
+ // but a new "continuing" card must never appear after stop(). A queued
93
+ // finalization is NOT a reason to abort — it runs after this rotation
94
+ // on the serial queue and needs the fresh card this rotation opens.
95
+ alive = false;
96
+ logger.warn?.('[dsh-im:wecom] stream rotation skipped after shutdown');
97
+ return currentStreamId;
98
+ }
99
+ const nextId = generateStreamId();
100
+ try {
101
+ await reply(nextId, headText || t('继续执行中…'), false);
102
+ currentStreamId = nextId;
103
+ cardStartedAt = Date.now();
104
+ lastFrameAt = Date.now();
105
+ rejects = 0;
106
+ alive = true;
107
+ logger.warn?.(`[dsh-im:wecom] stream card rotated to segment ${segmentNo} for chat ${chatId}`);
108
+ } catch (error) {
109
+ // Without a live card the final reply must go through an active message
110
+ // instead; keep alive=false so callers skip the stream.
111
+ alive = false;
112
+ logger.warn?.(
113
+ '[dsh-im:wecom] stream rotation failed; final delivery will use an active message:',
114
+ normalize(error),
115
+ );
116
+ }
117
+ return currentStreamId;
118
+ };
119
+
120
+ const sendCore = async (preview) => {
121
+ if (!alive || !currentStreamId) return;
122
+ try {
123
+ await client.replyStreamNonBlocking(frame, currentStreamId, preview, false);
124
+ rejects = 0;
125
+ lastFrameAt = Date.now();
126
+ } catch (error) {
127
+ const normalized = normalize(error);
128
+ if (Number.isFinite(normalized.errcode) && normalized.errcode !== 0) {
129
+ rejects += 1;
130
+ logger.warn?.(`[dsh-im:wecom] stream update rejected (${rejects}x): ${normalized.message}`);
131
+ if (rejects >= 2) {
132
+ alive = false;
133
+ await rotateCore(preview);
134
+ }
135
+ } else {
136
+ logger.warn?.('[dsh-im:wecom] stream update failed:', normalized.message);
137
+ }
138
+ }
139
+ };
140
+
141
+ const backgroundAction = () => {
142
+ if (delivering || stopped || !alive || !currentStreamId) return;
143
+ if (Date.now() - cardStartedAt >= rotateAfterMs) {
144
+ return enqueue(() => (delivering || stopped ? undefined : rotateCore(previewText())));
145
+ }
146
+ if (Date.now() - lastFrameAt >= silentProbeMs) {
147
+ return enqueue(() => (delivering || stopped ? undefined : sendCore(previewText() || t('仍在执行中…'))));
148
+ }
149
+ return undefined;
150
+ };
151
+
152
+ if (tickMs > 0) {
153
+ timer = setInterval(() => {
154
+ Promise.resolve(backgroundAction()).catch(() => undefined);
155
+ }, tickMs);
156
+ }
157
+
158
+ return {
159
+ start(streamId) { currentStreamId = streamId; },
160
+ currentId: () => currentStreamId,
161
+ isAlive: () => alive,
162
+ progress(preview) {
163
+ if (delivering || stopped || !alive || !currentStreamId || !preview) return Promise.resolve();
164
+ if (Date.now() - cardStartedAt >= rotateAfterMs) {
165
+ return enqueue(() => (delivering || stopped ? undefined : rotateCore(preview)));
166
+ }
167
+ return enqueue(() => (delivering || stopped ? undefined : sendCore(preview)));
168
+ },
169
+ finishStream(text) {
170
+ delivering = true;
171
+ if (timer) clearInterval(timer);
172
+ return enqueue(async () => {
173
+ if (!alive || !currentStreamId) throw new Error('wecom stream unavailable');
174
+ return reply(currentStreamId, text, true);
175
+ });
176
+ },
177
+ stop() {
178
+ stopped = true;
179
+ if (timer) clearInterval(timer);
180
+ },
181
+ // Exposed for tests and diagnostics: is a finalization in progress?
182
+ isDelivering: () => delivering,
183
+ };
184
+ }