@xmanrui/dsh-im 5.3.0 → 5.5.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 (112) hide show
  1. package/PROACTIVE_DELIVERY.en.md +15 -0
  2. package/PROACTIVE_DELIVERY.md +15 -0
  3. package/README.en.md +44 -3
  4. package/README.md +44 -3
  5. package/THIRD_PARTY_NOTICES.md +209 -0
  6. package/docs/client-integration.md +2 -2
  7. package/lib/client.js +3737 -433
  8. package/lib/index.js +415 -344
  9. package/package.json +1 -1
  10. package/plugin-src/client/channel-card-meta.js +6 -2
  11. package/plugin-src/client/channels/shared/token-api.js +13 -0
  12. package/plugin-src/client/channels/telegram/group-triggers-settings.js +393 -0
  13. package/plugin-src/client/channels/telegram/styles.js +4 -0
  14. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  15. package/plugin-src/client/delivery-settings.js +23 -3
  16. package/plugin-src/client/ds-bot-avatar-data.js +537 -0
  17. package/plugin-src/client/ds-bot-avatar.js +55 -0
  18. package/plugin-src/client/ds-bot-session-avatars.js +77 -0
  19. package/plugin-src/client/ds-bot-settings.js +194 -0
  20. package/plugin-src/client/i18n-ru.js +1615 -0
  21. package/plugin-src/client/i18n.js +130 -1
  22. package/plugin-src/client/index.js +20 -2
  23. package/plugin-src/client/plugin-page.js +3 -8
  24. package/plugin-src/client/styles.js +25 -5
  25. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  26. package/plugin-src/host/channels/feishu/production.mjs +13 -5
  27. package/plugin-src/host/channels/qq/production.mjs +2 -1
  28. package/plugin-src/host/channels/shared/group-triggers-rpc.mjs +110 -0
  29. package/plugin-src/host/channels/shared/production.mjs +12 -1
  30. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  31. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  32. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  33. package/plugin-src/host/channels/slack/production.mjs +2 -1
  34. package/plugin-src/host/channels/telegram/index.mjs +1 -0
  35. package/plugin-src/host/channels/telegram/production.mjs +9 -0
  36. package/plugin-src/host/channels/telegram/rpc.mjs +17 -2
  37. package/plugin-src/host/channels/wecom/production.mjs +4 -1
  38. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  39. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  40. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  41. package/plugin-src/host/delivery-adapter.mjs +129 -41
  42. package/plugin-src/host/delivery-rpc.mjs +33 -1
  43. package/plugin-src/host/delivery-service.mjs +112 -1
  44. package/plugin-src/host/delivery-suggestions.mjs +11 -0
  45. package/plugin-src/host/ds-bot-client.mjs +87 -0
  46. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  47. package/plugin-src/host/index.mjs +8 -1
  48. package/plugin-src/host/modern-harness-api.mjs +53 -8
  49. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  50. package/scripts/verify-package.mjs +17 -5
  51. package/src/channels/feishu/bridge.mjs +83 -5
  52. package/src/channels/feishu/feishu-cards.mjs +11 -7
  53. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  54. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  55. package/src/channels/shared/AGENTS.md +19 -0
  56. package/src/channels/shared/bot-workspace-store.mjs +136 -7
  57. package/src/channels/shared/clear-command.mjs +2 -1
  58. package/src/channels/shared/compact-command.mjs +2 -1
  59. package/src/channels/shared/conversation-queue.mjs +49 -0
  60. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  61. package/src/channels/shared/group-history-store.mjs +26 -0
  62. package/src/channels/shared/harness-client.mjs +5 -4
  63. package/src/channels/shared/history-command.mjs +2 -1
  64. package/src/channels/shared/i18n-en/feishu.mjs +1 -0
  65. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  66. package/src/channels/shared/i18n-en/shared-b.mjs +2 -2
  67. package/src/channels/shared/i18n-en/shared-c.mjs +3 -2
  68. package/src/channels/shared/i18n-en/wecom.mjs +4 -0
  69. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  70. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  71. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  72. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  73. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  74. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  75. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  76. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  77. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  78. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  79. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  80. package/src/channels/shared/i18n-ru/shared-b.mjs +257 -0
  81. package/src/channels/shared/i18n-ru/shared-c.mjs +173 -0
  82. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  83. package/src/channels/shared/i18n-ru/telegram.mjs +25 -0
  84. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  85. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  86. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  87. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  88. package/src/channels/shared/i18n-ru.mjs +48 -0
  89. package/src/channels/shared/i18n.mjs +47 -12
  90. package/src/channels/shared/inbound-access.mjs +1 -1
  91. package/src/channels/shared/interface-language.mjs +3 -3
  92. package/src/channels/shared/message-failure.mjs +3 -2
  93. package/src/channels/shared/model-command.mjs +2 -1
  94. package/src/channels/shared/permission-command.mjs +2 -1
  95. package/src/channels/shared/send-limit.mjs +38 -0
  96. package/src/channels/shared/session-binding-lock.mjs +2 -0
  97. package/src/channels/shared/session-error.mjs +3 -0
  98. package/src/channels/shared/status-reaction.mjs +2 -0
  99. package/src/channels/shared/text-harness-bridge.mjs +4 -0
  100. package/src/channels/shared/thinking-cadence.mjs +36 -0
  101. package/src/channels/shared/workspace-command.mjs +2 -1
  102. package/src/channels/shared/workspace-session.mjs +5 -1
  103. package/src/channels/telegram/config-store.mjs +38 -1
  104. package/src/channels/telegram/group-triggers.mjs +229 -0
  105. package/src/channels/telegram/telegram-api.mjs +223 -32
  106. package/src/channels/telegram/telegram-bridge.mjs +4 -1
  107. package/src/channels/telegram/telegram-controller.mjs +139 -1
  108. package/src/channels/telegram/telegram-runtime.mjs +522 -178
  109. package/src/channels/telegram/voice.mjs +250 -0
  110. package/src/channels/wecom/stream-supervisor.mjs +184 -0
  111. package/src/channels/wecom/wecom-bridge.mjs +25 -11
  112. package/src/channels/wecom/wecom-runtime.mjs +12 -1
@@ -1,3 +1,4 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
1
2
  import { createCommandListSnapshots } from './command-list-snapshots.mjs';
2
3
  import { t } from './i18n.mjs';
3
4
  import { withSessionBindingLock } from './session-binding-lock.mjs';
@@ -50,7 +51,7 @@ function errorMessage(error, writing) {
50
51
  if (code === WORKSPACE_SESSION_STALE || code === 'workspace-bot-not-found') {
51
52
  return t('工作区或机器人状态已发生变化,请重试。');
52
53
  }
53
- if (['session-not-found', 'session/not-found', 'agent-not-found'].includes(code)) {
54
+ if (isSessionNotFound(code) || code === 'agent-not-found') {
54
55
  return t('当前聊天绑定的会话已不存在,请先绑定或建立会话。');
55
56
  }
56
57
  if (['commands-unavailable', 'permissions-unavailable', 'harness-api-not-found',
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Per-chat send limit for Telegram.
3
+ *
4
+ * Telegram counts the messages a bot creates per chat and answers 429 once the
5
+ * budget for a chat is gone. The bot therefore paces its own new messages and
6
+ * waits for the next free slot instead of dropping them. The value lives in the
7
+ * bot config, is editable from the settings page, and is clamped on both sides:
8
+ * an unparseable form entry must never leave a bot unable to send.
9
+ *
10
+ * Kept free of Node imports so the Web client can share the same rules.
11
+ */
12
+
13
+ export const SET_SEND_LIMIT_ENDPOINT = 'bot.send-limit.set';
14
+ export const DEFAULT_SEND_LIMIT_PER_MINUTE = 15;
15
+ export const SEND_LIMIT_MIN_PER_MINUTE = 1;
16
+ /** Above this the bot would only wait for a budget Telegram never grants. */
17
+ export const SEND_LIMIT_MAX_PER_MINUTE = 30;
18
+
19
+ function clampSendLimit(value) {
20
+ return Math.min(
21
+ SEND_LIMIT_MAX_PER_MINUTE,
22
+ Math.max(SEND_LIMIT_MIN_PER_MINUTE, Math.round(value)),
23
+ );
24
+ }
25
+
26
+ /**
27
+ * A usable limit per minute: 1..30, default 15.
28
+ *
29
+ * Numeric strings from the form are accepted; anything else — missing, NaN,
30
+ * booleans, objects, garbage text — falls back to the default.
31
+ */
32
+ export function normalizeSendLimitPerMinute(value) {
33
+ const numeric = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
34
+ if (typeof numeric !== 'number' || !Number.isFinite(numeric)) {
35
+ return DEFAULT_SEND_LIMIT_PER_MINUTE;
36
+ }
37
+ return clampSendLimit(numeric);
38
+ }
@@ -1,4 +1,5 @@
1
1
  const bindingLocks = new WeakMap();
2
+ export const SESSION_BINDING_STATE_IDENTITY = Symbol('session-binding-state-identity');
2
3
 
3
4
  function stateLocks(state) {
4
5
  let locks = bindingLocks.get(state);
@@ -21,6 +22,7 @@ export async function withSessionBindingLock(state, key, operation) {
21
22
  if (typeof key !== 'string' || !key) throw new TypeError('conversation key is required');
22
23
  if (typeof operation !== 'function') throw new TypeError('operation is required');
23
24
 
25
+ state = state[SESSION_BINDING_STATE_IDENTITY] ?? state;
24
26
  const locks = stateLocks(state);
25
27
  const previous = locks.get(key) ?? Promise.resolve();
26
28
  let release;
@@ -0,0 +1,3 @@
1
+ export function isSessionNotFound(code) {
2
+ return code === 'session-not-found' || code === 'session/not-found';
3
+ }
@@ -66,6 +66,8 @@ export function beginStatusReaction({
66
66
  }
67
67
  };
68
68
 
69
+ // `emoji` may be null: the transition then only removes the previous
70
+ // reaction, which is how a channel asks for a clean message at the end.
69
71
  const transition = async (emoji) => {
70
72
  if (currentReaction !== null) {
71
73
  const previous = currentReaction;
@@ -1308,6 +1308,10 @@ export class TextHarnessBridge {
1308
1308
  return;
1309
1309
  }
1310
1310
  if (update.type === 'reasoning') return;
1311
+ // A carrier that delivers the answer as its own message must not
1312
+ // stream that answer into itself first: the reader would see the
1313
+ // reply twice, and every preview costs an edit.
1314
+ if (update.type === 'text' && stream.previewAnswer === false) return;
1311
1315
  const progress = update.type === 'text' ? update.text
1312
1316
  : update.type === 'tool' ? t('正在使用{name}…', { name: update.name }) : update.text;
1313
1317
  if (progress) {
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Pacing and numbering for Telegram "thinking trace" frames.
3
+ *
4
+ * A busy turn emits dozens of 💭/🔧 messages, so the owner can pace them to at
5
+ * most one frame per N seconds and prefix each frame with its number in the
6
+ * turn. Both values live in the bot config and are clamped here, once, so a
7
+ * half-typed form entry can never reach the runtime.
8
+ *
9
+ * Kept free of Node imports so the Web client can share the same rules.
10
+ */
11
+
12
+ export const SET_THINKING_CADENCE_ENDPOINT = 'bot.thinking-cadence.set';
13
+ /** 0 means "no pacing": every frame goes out as it arrives. */
14
+ export const DEFAULT_THINKING_INTERVAL_SECONDS = 0;
15
+ /** A longer window stops being a trace: the answer would overtake it. */
16
+ export const THINKING_INTERVAL_MAX_SECONDS = 60;
17
+
18
+ /**
19
+ * A usable interval in whole seconds, 0..60.
20
+ *
21
+ * Numeric strings from the form are accepted; anything else — missing, NaN,
22
+ * booleans, objects, fractional or garbage text — becomes 0, because a wrong
23
+ * number must not silently slow the trace down.
24
+ */
25
+ export function normalizeThinkingIntervalSeconds(value) {
26
+ const numeric = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
27
+ if (typeof numeric !== 'number' || !Number.isFinite(numeric) || !Number.isInteger(numeric)) {
28
+ return DEFAULT_THINKING_INTERVAL_SECONDS;
29
+ }
30
+ return Math.min(THINKING_INTERVAL_MAX_SECONDS, Math.max(0, numeric));
31
+ }
32
+
33
+ /** Numbering is off unless the config says otherwise. */
34
+ export function normalizeThinkingNumbering(value) {
35
+ return value === true;
36
+ }
@@ -1,3 +1,4 @@
1
+ import { isSessionNotFound } from './session-error.mjs';
1
2
  import { realpath, stat } from 'node:fs/promises';
2
3
  import { isAbsolute, resolve } from 'node:path';
3
4
 
@@ -317,7 +318,7 @@ function sessionBindErrorMessage(error) {
317
318
  return t(`Session ID 格式无效。
318
319
  {usage}`, { usage: t(SESSION_BIND_USAGE) });
319
320
  }
320
- if (['session-not-registered', 'session-not-found'].includes(error?.code)) {
321
+ if (error?.code === 'session-not-registered' || isSessionNotFound(error?.code)) {
321
322
  return t('未找到该会话,请先执行 /sessionlist 确认 Session ID。');
322
323
  }
323
324
  if (error?.code === 'session-subagent-unsupported') {
@@ -119,10 +119,14 @@ export async function askInWorkspaceSession({
119
119
  try {
120
120
  const binding = await withSessionBindingLock(state, key, async () => {
121
121
  await awaitPendingConversationSwitch(harness, key);
122
- let sessionId = state.sessionFor(key);
122
+ const dsBotSessionId = await harness.resolveDsBotSession?.(key);
123
+ let sessionId = dsBotSessionId || state.sessionFor(key);
123
124
  diagnostic.sessionId = sessionId;
124
125
  let session = sessionId ? workspaceSession(harness, sessionId, key) : null;
125
126
  if (!session || !(await sessionExists(session, existsOptions))) {
127
+ if (dsBotSessionId) {
128
+ throw Object.assign(new Error('DS Bot 的当前会话不可用。'), { code: 'ds-bot-unavailable' });
129
+ }
126
130
  sessionId = await createSession(harness, {
127
131
  conversationKey: key,
128
132
  ...(createOptions ?? {}),
@@ -4,6 +4,28 @@ import {
4
4
  maskPlatformId,
5
5
  TokenBotConfigStore,
6
6
  } from '../shared/token-config-store.mjs';
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';
7
29
 
8
30
  const IDENTITY_OPTIONS = Object.freeze({
9
31
  botPrefix: 'telegram',
@@ -51,7 +73,12 @@ function normalizeTelegramBotExtension(value) {
51
73
  const hasAccessMode = Object.hasOwn(value, 'accessMode');
52
74
  const hasAllowedUsers = Object.hasOwn(value, 'allowedUsers');
53
75
  const hasThinkingTraces = Object.hasOwn(value, 'thinkingTraces');
54
- if (!hasAccessMode && !hasAllowedUsers && !hasThinkingTraces) return {};
76
+ const hasGroupTriggers = Object.hasOwn(value, 'groupTriggers');
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 {};
55
82
  try {
56
83
  const policy = normalizeTelegramAccessPolicy(value);
57
84
  return {
@@ -59,6 +86,16 @@ function normalizeTelegramBotExtension(value) {
59
86
  ...(hasAllowedUsers || hasAccessMode ? { allowedUsers: policy.allowedUsers } : {}),
60
87
  // Explicit field is kept; an absent field stays absent.
61
88
  ...(hasThinkingTraces ? { thinkingTraces: value.thinkingTraces === true } : {}),
89
+ // Per-group reply triggers; absent means "no rule configured".
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) } : {}),
62
99
  };
63
100
  } catch {
64
101
  return null;
@@ -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
+ }