SilverElixir commited on
Commit
2d2dd2c
·
1 Parent(s): cd9b496

feat: в группах «Люмен, …» работает как упоминание — только в начале, с делимитером и просьбой

Browse files
README.md CHANGED
@@ -96,6 +96,8 @@ CLOUDFLARE_AI_BASE_URL=https://<proxy-domain>/fetch/api.cloudflare.com/client/v4
96
  LUMEN_PROXY_SECRET=<случайная строка от 32 символов: без неё прокси отвечает 503, а бот падает на старте>
97
  ```
98
 
 
 
99
  The proxy only forwards to an explicit host allowlist (`api.telegram.org`, `www.tikwm.com`, `tikwm.com`, and `api.cloudflare.com` — the latter restricted to `/client/v4/accounts/<id>/ai/...`, because the image API token rides along in `Authorization`). `api.cloudflare.com` is here for the same reason as TikWM: Hugging Face egress to it silently hangs (prod 09.11.2026). See `proxy/proxy.ts` for the implementation and `proxy/proxy_test.ts` for its tests; a green CI run on `main` ships it through `.github/workflows/deploy-proxy.yml`, and since 16.11.2026 that job deploys on every green run (the older diff-only rule missed a change once, prod 09.11.2026): after editing the allowlist, confirm both deploy steps finished as success, otherwise rerun the workflow or ship it by hand (see [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#deploy-paths)).
100
 
101
  ## Diagnostics
 
96
  LUMEN_PROXY_SECRET=<случайная строка от 32 символов: без неё прокси отвечает 503, а бот падает на старте>
97
  ```
98
 
99
+ In groups the bot can be addressed not only by @mention but also by a wake word at the start of a message: “Lumen, …” or “Люмен, …” (list in `GROUP_WAKE_WORDS`, kill switch `GROUP_WAKE_ENABLED`). Forwards and third-person talk about the bot do not trigger.
100
+
101
  The proxy only forwards to an explicit host allowlist (`api.telegram.org`, `www.tikwm.com`, `tikwm.com`, and `api.cloudflare.com` — the latter restricted to `/client/v4/accounts/<id>/ai/...`, because the image API token rides along in `Authorization`). `api.cloudflare.com` is here for the same reason as TikWM: Hugging Face egress to it silently hangs (prod 09.11.2026). See `proxy/proxy.ts` for the implementation and `proxy/proxy_test.ts` for its tests; a green CI run on `main` ships it through `.github/workflows/deploy-proxy.yml`, and since 16.11.2026 that job deploys on every green run (the older diff-only rule missed a change once, prod 09.11.2026): after editing the allowlist, confirm both deploy steps finished as success, otherwise rerun the workflow or ship it by hand (see [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#deploy-paths)).
102
 
103
  ## Diagnostics
README.ru.md CHANGED
@@ -77,6 +77,8 @@ CLOUDFLARE_AI_BASE_URL=https://<proxy-domain>/fetch/api.cloudflare.com/client/v4
77
  LUMEN_PROXY_SECRET=<случайная строка от 32 символов: без неё прокси отвечает 503, а бот падает на старте>
78
  ```
79
 
 
 
80
  Прокси пропускает запросы только к явному списку хостов (`api.telegram.org`, `www.tikwm.com`, `tikwm.com` и `api.cloudflare.com` — последнему только путь `/client/v4/accounts/<id>/ai/...`, потому что токен генерации едет в `Authorization`). Cloudflare здесь по той же причине, что и TikWM: исходящие с Hugging Face к этому хосту молча виснут (прод 09.11.2026). Реализация — в `proxy/proxy.ts`, тесты — в `proxy/proxy_test.ts`; зелёный CI в `main` выкатывает его через `.github/workflows/deploy-proxy.yml`, и с 16.11.2026 этот шаг выкатывает прокси на каждом зелёном прогоне (прежнее правило «только при диффе `proxy/`» один раз промахнулось, прод 09.11.2026). После правки списка хостов убедись, что оба шага деплоя завершились success, иначе перезапусти workflow или выкати вручную (см. `docs/ARCHITECTURE.md`, раздел "Deploy paths").
81
 
82
  ## Диагностика
 
77
  LUMEN_PROXY_SECRET=<случайная строка от 32 символов: без неё прокси отвечает 503, а бот падает на старте>
78
  ```
79
 
80
+ В группах бота можно позвать не только через @упоминание, но и словом в начале сообщения: «Люмен, …» или «Lumen, …» (список слов — `GROUP_WAKE_WORDS`, выключатель — `GROUP_WAKE_ENABLED`). Пересланные сообщения и разговоры о боте в третьем лице не срабатывают.
81
+
82
  Прокси пропускает запросы только к явному списку хостов (`api.telegram.org`, `www.tikwm.com`, `tikwm.com` и `api.cloudflare.com` — последнему только путь `/client/v4/accounts/<id>/ai/...`, потому что токен генерации едет в `Authorization`). Cloudflare здесь по той же причине, что и TikWM: исходящие с Hugging Face к этому хосту молча виснут (прод 09.11.2026). Реализация — в `proxy/proxy.ts`, тесты — в `proxy/proxy_test.ts`; зелёный CI в `main` выкатывает его через `.github/workflows/deploy-proxy.yml`, и с 16.11.2026 этот шаг выкатывает прокси на каждом зелёном прогоне (прежнее правило «только при диффе `proxy/`» один раз промахнулось, прод 09.11.2026). После правки списка хостов убедись, что оба шага деплоя завершились success, иначе перезапусти workflow или выкати вручную (см. `docs/ARCHITECTURE.md`, раздел "Deploy paths").
83
 
84
  ## Диагностика
bot.py CHANGED
@@ -314,6 +314,13 @@ _TELEGRAM_PROXY_FALLBACKS = [
314
  _normalize_telegram_base_url(u) for u in os.getenv("TELEGRAM_API_BASE_URL_FALLBACKS", "").split(",") if u.strip()
315
  ]
316
  _TELEGRAM_PROXY_CANDIDATES: list[str] = [TELEGRAM_API_BASE_URL] + [u for u in _TELEGRAM_PROXY_FALLBACKS if u != TELEGRAM_API_BASE_URL]
 
 
 
 
 
 
 
317
  _telegram_proxy_idx = 0 # индекс текущего активного прокси в _TELEGRAM_PROXY_CANDIDATES
318
  # Ротация мутирует два глобала сразу — под локом, иначе два concurrent-сбоя
319
  # уводят индекс на два шага и пропускают кандидата (AUD-E-004).
 
314
  _normalize_telegram_base_url(u) for u in os.getenv("TELEGRAM_API_BASE_URL_FALLBACKS", "").split(",") if u.strip()
315
  ]
316
  _TELEGRAM_PROXY_CANDIDATES: list[str] = [TELEGRAM_API_BASE_URL] + [u for u in _TELEGRAM_PROXY_FALLBACKS if u != TELEGRAM_API_BASE_URL]
317
+ # Wake-word в группах: «Люмен, ...» работает как упоминание. Выключение одной
318
+ # переменной, слова-синонимы — списком (прод 18.11.2026 по просьбе владельца).
319
+ GROUP_WAKE_ENABLED = os.getenv("GROUP_WAKE_ENABLED", "1").strip().lower() not in {"0", "false", "no", "off"}
320
+ GROUP_WAKE_WORDS = tuple(
321
+ w.strip() for w in os.getenv("GROUP_WAKE_WORDS", "люмен,lumen").split(",") if w.strip()
322
+ ) or ("люмен", "lumen")
323
+
324
  _telegram_proxy_idx = 0 # индекс текущего активного прокси в _TELEGRAM_PROXY_CANDIDATES
325
  # Ротация мутирует два глобала сразу — под локом, иначе два concurrent-сбоя
326
  # уводят индекс на два шага и пропускают кандидата (AUD-E-004).
docs/ENVIRONMENT.md CHANGED
@@ -65,6 +65,8 @@ Before publishing, configure the same `LUMEN_PROXY_SECRET` on HF and every Deno
65
  | `POLLINATIONS_IMAGE_MODEL` | `sana` | Reserve provider model. Measured 09.11.2026 the free endpoint ignores this parameter entirely and always serves `sana` (`GET /models` returns `["sana"]`); the value is still sent so a future catalog change is visible in `/diag`. The old five-model catalog and the prompt-based style picker were deleted the same day: they selected nothing. sana mangles Cyrillic to `?` while the URL is parsed, so a prompt that is still non-ASCII when it reaches this provider is refused instead of drawing unrelated junk (review 10.11.2026). |
66
  | `IMAGE_APP_REFERRER` | `lumen-telegram-bot` | Sent as `referrer` to Pollinations, which logs the calling app name for keyless traffic. |
67
  | `VOICE_TRANSCRIBE_MAX_BYTES` | `10485760` (10 MB) | Voice/audio attachments larger than this skip Whisper transcription and go straight to Gemini audio, as before. |
 
 
68
  | `STOP_BUTTON_ENABLED` | `0` | Adds an inline "Stop" button under the streaming bubble (localized in 25 packs, callback `stop:<chat>`). Off by default on purpose: the button costs two extra message edits per answer and the per-chat edit budget is shared, so enable it only after the live smoke test (audit 16.11.2026). Permissions are the same as `/stop`: the question author or `OWNER_ID`. The owner set it to `1` on the Space on 16.11.2026 after the parity decision. |
69
  | `STOP_COMMAND_ENABLED` | `1` | Enables the `/stop` command (audit 16.11.2026). The command sets a per-chat flag; the streaming loop checks it before and after every piece, keeps the partial answer (it is written to history with `state.interrupted`), appends the localized stopped note and does not trigger auto-continue. Only the question's author or `OWNER_ID` can stop; a foreign `/stop` is ignored silently. The command is not in the `/` menu, like `/help`. |
70
  | `WEB_SEARCH_ENABLED` | `1` | Free external snippets for every fresh-info request, regardless of whether the route contains a grounded Gemini model. News queries merge DuckDuckGo with Google News (freshness-filtered, publication dates included). Set to `0` (plus restart) to answer from knowledge with an honest "without live search" note instead. |
 
65
  | `POLLINATIONS_IMAGE_MODEL` | `sana` | Reserve provider model. Measured 09.11.2026 the free endpoint ignores this parameter entirely and always serves `sana` (`GET /models` returns `["sana"]`); the value is still sent so a future catalog change is visible in `/diag`. The old five-model catalog and the prompt-based style picker were deleted the same day: they selected nothing. sana mangles Cyrillic to `?` while the URL is parsed, so a prompt that is still non-ASCII when it reaches this provider is refused instead of drawing unrelated junk (review 10.11.2026). |
66
  | `IMAGE_APP_REFERRER` | `lumen-telegram-bot` | Sent as `referrer` to Pollinations, which logs the calling app name for keyless traffic. |
67
  | `VOICE_TRANSCRIBE_MAX_BYTES` | `10485760` (10 MB) | Voice/audio attachments larger than this skip Whisper transcription and go straight to Gemini audio, as before. |
68
+ | `GROUP_WAKE_ENABLED` | `1` | Adds word-based invocation in groups: a message starting with a wake word («Люмен, …», «Lumen, …») is treated like a mention. Set `0` to require @mention only. Forwards are ignored, third-person mentions do not trigger. |
69
+ | `GROUP_WAKE_WORDS` | `люмен,lumen` | Comma-separated wake words for groups (case-insensitive, start of message only, delimiter required). |
70
  | `STOP_BUTTON_ENABLED` | `0` | Adds an inline "Stop" button under the streaming bubble (localized in 25 packs, callback `stop:<chat>`). Off by default on purpose: the button costs two extra message edits per answer and the per-chat edit budget is shared, so enable it only after the live smoke test (audit 16.11.2026). Permissions are the same as `/stop`: the question author or `OWNER_ID`. The owner set it to `1` on the Space on 16.11.2026 after the parity decision. |
71
  | `STOP_COMMAND_ENABLED` | `1` | Enables the `/stop` command (audit 16.11.2026). The command sets a per-chat flag; the streaming loop checks it before and after every piece, keeps the partial answer (it is written to history with `state.interrupted`), appends the localized stopped note and does not trigger auto-continue. Only the question's author or `OWNER_ID` can stop; a foreign `/stop` is ignored silently. The command is not in the `/` menu, like `/help`. |
72
  | `WEB_SEARCH_ENABLED` | `1` | Free external snippets for every fresh-info request, regardless of whether the route contains a grounded Gemini model. News queries merge DuckDuckGo with Google News (freshness-filtered, publication dates included). Set to `0` (plus restart) to answer from knowledge with an honest "without live search" note instead. |
lumen_message_core.py CHANGED
@@ -36,6 +36,7 @@ from lumen_message_parse import (
36
  _draw_trigger_is_visual,
37
  _tts_trigger_is_speech,
38
  _split_image_variants,
 
39
  _strip_variants_phrase,
40
  _wants_style_reference,
41
  _NO_MEDIA_NOTE,
@@ -940,6 +941,18 @@ async def _handle_message_core(
940
  is_private = message.chat.type == ChatType.PRIVATE
941
  is_guest = bot.is_guest_message(message)
942
  mentioned = bot.message_mentions_bot(message)
 
 
 
 
 
 
 
 
 
 
 
 
943
  # Старт для замера задержки ответа в след.
944
  _trace_start = time.monotonic()
945
 
@@ -998,7 +1011,7 @@ async def _handle_message_core(
998
  # (свои загрузки — только через _download_url_bin с гардом схемы).
999
  needs_website = True
1000
 
1001
- clean_prompt = bot.clean_mention(t).strip()
1002
 
1003
  if clean_prompt and _looks_like_injection_probe(clean_prompt):
1004
  # Инъекция: отвечаем без LLM. Текст в лог не пишем, только длину (аудит M5, 10.2026).
 
36
  _draw_trigger_is_visual,
37
  _tts_trigger_is_speech,
38
  _split_image_variants,
39
+ strip_group_wake_word,
40
  _strip_variants_phrase,
41
  _wants_style_reference,
42
  _NO_MEDIA_NOTE,
 
941
  is_private = message.chat.type == ChatType.PRIVATE
942
  is_guest = bot.is_guest_message(message)
943
  mentioned = bot.message_mentions_bot(message)
944
+ # Wake-word («Люмен, ...») в группах: пересланное и обсуждения в третьем лице
945
+ # не считаем обращением (просьба владельца 18.11.2026).
946
+ _wake_rest = ""
947
+ if (
948
+ not mentioned and not is_private and not is_guest
949
+ and not getattr(message, "forward_origin", None)
950
+ and getattr(bot, "GROUP_WAKE_ENABLED", False)
951
+ ):
952
+ _wake_hit, _wake_rest_new = strip_group_wake_word(t, getattr(bot, "GROUP_WAKE_WORDS", ("люмен", "lumen")))
953
+ if _wake_hit:
954
+ mentioned = True
955
+ _wake_rest = _wake_rest_new
956
  # Старт для замера задержки ответа в след.
957
  _trace_start = time.monotonic()
958
 
 
1011
  # (свои загрузки — только через _download_url_bin с гардом схемы).
1012
  needs_website = True
1013
 
1014
+ clean_prompt = bot.clean_mention(_wake_rest or t).strip()
1015
 
1016
  if clean_prompt and _looks_like_injection_probe(clean_prompt):
1017
  # Инъекция: отвечаем без LLM. Текст в лог не пишем, только длину (аудит M5, 10.2026).
lumen_message_parse.py CHANGED
@@ -148,6 +148,54 @@ def _strip_variants_phrase(text: str) -> str:
148
  return re.sub(r"\s{2,}", " ", cleaned).strip(" ,.-")
149
 
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  def _detect_image_variants(text: str) -> int:
152
  """Сколько вариантов просили: 1 — обычная генерация, 2-4 — несколько."""
153
  return _split_image_variants(text)[0]
 
148
  return re.sub(r"\s{2,}", " ", cleaned).strip(" ,.-")
149
 
150
 
151
+ # ── Wake-word в группах: «Люмен, ...» вместо @упоминания ──
152
+ # Триггер только в начале сообщения (после частиц-обращений) и только с
153
+ # разделителем: «люменальный», «я люблю люмен», обсуждения в третьем лице
154
+ # («люмен — это бот») не срабатывают. Голое имя без просьбы — тоже нет.
155
+ _WAKE_PARTICLE_RE = re.compile(
156
+ r"^(?:эй|слушай|окей|okay|hey|а|ну|ладно)\s*[,.!—–-]?\s+", re.IGNORECASE,
157
+ )
158
+ _WAKE_COPULA_RE = re.compile(
159
+ r"^(?:это|is|является|был|была|было|были)(?![А-Яа-яA-Za-z])", re.IGNORECASE,
160
+ )
161
+
162
+
163
+ def strip_group_wake_word(text: str, words: tuple[str, ...] = ("люмен", "lumen")) -> tuple[bool, str]:
164
+ """(сработал ли wake-word, текст без него). Безопасен к обсуждениям:
165
+ имя в середине фразы, часть слова, URL или @упоминание не трогаем."""
166
+ src = (text or "").strip()
167
+ if not src or src.startswith("/"):
168
+ return False, text
169
+ rest = src
170
+ for _ in range(2):
171
+ m = _WAKE_PARTICLE_RE.match(rest)
172
+ if not m:
173
+ break
174
+ rest = rest[m.end():]
175
+ rest = rest.lstrip("\"'«“(")
176
+ low = rest.lower()
177
+ for word in words:
178
+ w = (word or "").strip().lower()
179
+ if not w or not low.startswith(w):
180
+ continue
181
+ after = rest[len(w):]
182
+ if after[:1] and (after[0].isalnum() or after[0] in "_@"):
183
+ continue
184
+ after = after.lstrip().lstrip("\"'»”)")
185
+ if after[:1] in ("—", "–", "-"):
186
+ after = after[1:].lstrip()
187
+ elif after[:1] in (",", ":", ";", "!", "?", "."):
188
+ after = after[1:].lstrip()
189
+ if not after:
190
+ continue
191
+ if _WAKE_COPULA_RE.match(after):
192
+ return False, text
193
+ if not re.search(r"[0-9A-Za-zА-Яа-яЁё]", after):
194
+ continue
195
+ return True, after
196
+ return False, text
197
+
198
+
199
  def _detect_image_variants(text: str) -> int:
200
  """Сколько вариантов просили: 1 — обычная генерация, 2-4 — несколько."""
201
  return _split_image_variants(text)[0]
tests/test_audit_fixes_17_11.py CHANGED
@@ -1616,3 +1616,26 @@ def test_media_relay_prefers_big_and_skips_small_body_host():
1616
  assert bot._pick_media_candidate(candidates, {small: True, big: False}, {"small.example"}) == small
1617
  assert bot._pick_media_candidate(candidates, {small: False, big: False}, {"small.example"}) is None
1618
  assert bot._proxy_host("https://lumen-vercel-relay.vercel.app/fetch/api.telegram.org") == "lumen-vercel-relay.vercel.app"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1616
  assert bot._pick_media_candidate(candidates, {small: True, big: False}, {"small.example"}) == small
1617
  assert bot._pick_media_candidate(candidates, {small: False, big: False}, {"small.example"}) is None
1618
  assert bot._proxy_host("https://lumen-vercel-relay.vercel.app/fetch/api.telegram.org") == "lumen-vercel-relay.vercel.app"
1619
+
1620
+
1621
+ def test_group_wake_word_matrix():
1622
+ # Позитивы: имя в начале, делимитер, просьба после. Негативы: часть слова,
1623
+ # середина фразы, третье лицо, голое имя, упоминание, URL.
1624
+ from lumen_message_parse import strip_group_wake_word as wake
1625
+ for q in (
1626
+ "Люмен, сколько будет 2+2?",
1627
+ "люмен: привет",
1628
+ "ЛЮМЕН — что такое фотосинтез",
1629
+ "эй, люмен, как дела",
1630
+ "слушай люмен, расскажи",
1631
+ "lumen, hi",
1632
+ "люмен запрос погоды",
1633
+ "«Люмен», привет",
1634
+ ):
1635
+ assert wake(q)[0] is True, q
1636
+ for q in (
1637
+ "Люмен!", "люмен,", "люмен:", "люмен это бот", "люмен — это бот",
1638
+ "я люблю люмен", "в люмене баг", "люменальный", "люминесцентный",
1639
+ "@LumenAI_bot привет", "https://lumen.example", "обычный разговор",
1640
+ ):
1641
+ assert wake(q)[0] is False, q
tests/test_bot_state.py CHANGED
@@ -2881,6 +2881,50 @@ def test_passive_group_message_does_not_consume_quota(rate_guard_setup, monkeypa
2881
  bot._tg_call.assert_not_awaited()
2882
 
2883
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2884
  def test_log_queue_handler_masks_secrets_in_args_and_traceback(monkeypatch):
2885
  monkeypatch.setattr(bot, "LUMEN_PROXY_SECRET", "fake-proxy-secret-123", raising=False)
2886
  try:
 
2881
  bot._tg_call.assert_not_awaited()
2882
 
2883
 
2884
+ def test_group_wake_word_activates_like_a_mention(rate_guard_setup, monkeypatch):
2885
+ # Просьба владельца 18.11.2026: в группах «Люмен, ...» работает как @упоминание,
2886
+ # но только в начале фразы и с просьбой после имени.
2887
+ message = rate_guard_setup()
2888
+ message.chat.type = bot.ChatType.GROUP
2889
+ message.text = "Люмен, сколько будет 2+2?"
2890
+ record = AsyncMock()
2891
+ run_route = AsyncMock(return_value=("ok", False))
2892
+ monkeypatch.setattr(bot, "_record_passive_group_context", record)
2893
+ monkeypatch.setattr(bot, "_run_route", run_route)
2894
+ asyncio.run(bot._handle_message_core(message))
2895
+ record.assert_not_awaited()
2896
+ assert run_route.await_count >= 1
2897
+ prompt = run_route.await_args.args[1]
2898
+ assert "Люмен," not in prompt and "2+2" in prompt
2899
+
2900
+
2901
+ def test_group_talking_about_lumen_stays_passive(rate_guard_setup, monkeypatch):
2902
+ message = rate_guard_setup()
2903
+ message.chat.type = bot.ChatType.GROUP
2904
+ message.text = "люмен это бот, он живёт в телеграме"
2905
+ record = AsyncMock()
2906
+ run_route = AsyncMock(return_value=("ok", False))
2907
+ monkeypatch.setattr(bot, "_record_passive_group_context", record)
2908
+ monkeypatch.setattr(bot, "_run_route", run_route)
2909
+ asyncio.run(bot._handle_message_core(message))
2910
+ record.assert_awaited_once()
2911
+ run_route.assert_not_awaited()
2912
+
2913
+
2914
+ def test_group_forwarded_wake_word_does_not_trigger(rate_guard_setup, monkeypatch):
2915
+ message = rate_guard_setup()
2916
+ message.chat.type = bot.ChatType.GROUP
2917
+ message.text = "Люмен, привет"
2918
+ message.forward_origin = object()
2919
+ record = AsyncMock()
2920
+ run_route = AsyncMock(return_value=("ok", False))
2921
+ monkeypatch.setattr(bot, "_record_passive_group_context", record)
2922
+ monkeypatch.setattr(bot, "_run_route", run_route)
2923
+ asyncio.run(bot._handle_message_core(message))
2924
+ record.assert_awaited_once()
2925
+ run_route.assert_not_awaited()
2926
+
2927
+
2928
  def test_log_queue_handler_masks_secrets_in_args_and_traceback(monkeypatch):
2929
  monkeypatch.setattr(bot, "LUMEN_PROXY_SECRET", "fake-proxy-secret-123", raising=False)
2930
  try: