Commit Graph

358 Commits

Author SHA1 Message Date
kshitijk4poor
ab3e4affd6 fix(config): meet the code-health ratchet and keep pm's runtime tree off the YAML stack
CI on the salvage was red on the code-health ratchet (over-cap facades grew; two blind excepts)
and on the pm observer fixture, whose isolated source tree carries pm/ + hermes_cli/ but no utils.

- config_backend imports become module-level in the facades (it imports only stdlib); gateway,
  auth and telegram take config_exists through the hermes_cli.config import they already have.
- Pure helpers move to topical siblings, offsetting the growth: _csv_or_list_to_set ->
  gateway/run_common.py, the dotted config-path pair -> hermes_cli/backup_restore.py, the
  voice/timezone/web-backend checks -> hermes_cli/config_value_checks.py, _load_config_dict ->
  hermes_cli/profile_memory_config.py (both callers are memory-provider code).
- _load_config_dict catches YAMLError/OSError/UnicodeError instead of Exception.
- _load_config_cache_hit probes readability with config_backend.probe_config_readable (a 1-byte
  read through the backend's open) instead of a full parse plus a blind except.
- pm/plugins_state.read_home_selection checks config_exists before importing the YAML stack, so
  a home with no config never needs utils.
- developer-guide/config-backend.md describes this build (file backend only).

Same approach as @benbarclay's 74421be709 in #122509, which does not cherry-pick onto current main.
2026-10-25 18:54:09 -07:00
Ben Barclay
871900df63 feat(config): route every user config.yaml read and write through a ConfigBackend seam
Add hermes_cli/config_backend.py (config-config design §4.1, D10/D11): a
ConfigBackend protocol, the FileBackend (today's behaviour), selection by
HERMES_CONFIG_BACKEND only (default file; 'remote' and unknown values fail
closed with ConfigBackendUnavailable), and path-level helpers
(read_config_doc, read_config_doc_readonly, config_version, config_exists,
write_config_key, write_config_document, supports_file_tooling).

Migrate every direct reader/stat/exists/bypass writer of a user config.yaml
to the helpers (config.py loaders + caches, config_effective, env_loader,
gateway, TUI, CLI watchers, cron, tools, profiles, logging, time). File
tooling (config edit, backups, xAI migration rewrite, raw dashboard editor)
checks supports_file_tooling() first; migrations skip write-back without it.

Add scripts/check_config_yaml_readers.py (CI lint next to the writers gate)
that rejects a direct read of a config path outside the backend.
2026-10-25 18:54:09 -07:00
rob-maron
83c5737be2 merge main in 2026-10-20 21:19:31 -04:00
rob-maron
15307dece7 Usage-window plan support 2026-10-20 21:04:30 -04:00
Teknium
84b480d38e fix(telegram): two edits in one second are two inputs
The edit revision was edit_date, whole seconds, so a second edit of the
same message within that second reused the first edit's request id with
different text and still replied admission_conflict (#140845).

Key the edit on its update_id, which Telegram assigns once per edit and
keeps on redelivery; with no update id, edit_date plus a digest of the
edited text. A replayed edit still admits once.
2026-10-20 03:17:18 -07:00
Teknium
6483c39f84 fix(gateway): editing a sent message no longer replies admission_conflict (#140845)
Native admission keyed every message by its platform message_id. A Telegram
edit re-sends that same id with new text, so the ledger saw a changed replay
of the original send and refused it with admission_conflict, which reached the
user as "Sorry, I encountered an error (RuntimeStoreError)".

Edits stay turns, as they were before the unified runtime (pinned by
test_replay_is_admitted_once_before_dispatch[text-edit]). The adapter now stamps
MessageEvent.edit_revision from the edit's edit_date, it rides in the native
envelope, and _admit_native keys the edit as <message_id>:edit:<revision>. A
redelivered edit is still an exact replay of that edit; a second edit is its
own input.
2026-10-20 03:17:18 -07:00
Teknium
ae596f49a0 fix(telegram): an edit of an older lobby message keeps its room (#136567)
Message.date of an edit is the ORIGINAL send time, so an edit of a root-DM
message sent before the topic creation passed the send-time window (negative
gap) and was adopted into the new topic, consuming the record the real opener
needed. A message dated before the creation is now left alone and the record
stays for the opener.

Found by Greptile on #141751.

Live (real gateway + Telegram stand-in): edit an old lobby message right after
creating a topic, then send the opener. At 5e0eb93 the edit went to the new
topic; now the edit stays in the previous topic and the opener lands in the
new one. Slow-photo, split, interleaved-DM and late-lobby cases unchanged.
2026-10-19 21:47:53 -07:00
Teknium
406580697a fix(telegram): time the new-topic follow on send time, not handler time (#136567)
The 5 s follow window was read from time.monotonic() when each handler ran.
PerChatUpdateProcessor holds a chat's next update until the previous handler
returns, so a thread-less photo whose download (or STT, or a document's
caching) outlasted the window pushed the text sent right after it out of the
new topic, into the previous topic or the root DM.

The window now compares Telegram's Message.date stamps (set when the user
sent the message, untouched by queueing). A creation without a date is not
recorded. The local clock only bounds memory (records older than 600 s are
pruned; the oldest is evicted at the 256 cap).

Found by Greptile on #141751; root-caused and fixed in a proposed diff by
@PRELVAS94, adapted here.

Live (real gateway + Telegram stand-in, photo download held 7 s, text sent
right after): before, the text went to the old topic; after, both land in the
new topic. Split opener, interleaved DM and late-lobby cases unchanged.

Co-authored-by: PRELVAS94 <86016656+PRELVAS94@users.noreply.github.com>
2026-10-19 21:47:53 -07:00
Teknium
bda200183d fix(telegram): follow a new DM topic by time, not message-id adjacency (#136567)
The adoption of a client-created topic's thread-less opener required
message_id == creation + 1. Private-chat message ids come from ONE sequence
shared by every private chat of the bot account (bot replies included,
core.telegram.org/api/updates "Common message ID sequence"), so any message
in another DM, or a bot reply, between the creation and the opener broke
adjacency and the opener misrouted to the previous topic again. One-shot
adoption also split a long opener the client sends as several messages:
chunk 1 went to the new topic, chunk 2 back to the old one.

Now a thread-less message from the creator adopts the new topic while it
arrives within 5 s of the creation or of the previous adopted message; a
stamped message or a longer gap ends the follow. Per-chat FIFO update
processing (PerChatUpdateProcessor) means nothing from this chat lands in
between, so adjacency bought no safety.

Also drops the duplicated identity helpers the mixin redefined from the
adapter and restores the unrelated _cache_dm_topic_from_message move.

Live (real gateway + Telegram stand-in, DM topic mode, production batching):
main misroutes all four cases; the pairing as proposed misroutes the
interleaved-DM and split-opener cases; this lands every case in the new topic,
and a lobby message 7 s later still recovers to the bound topic.
2026-10-19 21:47:53 -07:00
sharpnotebot
7cfafba18e fix(telegram): 建立 topic 時不再快取名稱,恢復自動改名 (Refs #136567)
The forum_topic_created handler cached the user-chosen topic name (e.g.
"New Chat") in _dm_topics. _get_dm_topic_info treats any _dm_topics hit
as an operator-declared topic, so _rename_telegram_topic_for_session_title
silently skipped every dynamically created topic and session-title
auto-rename stopped working.

Keep only the pending-creation record (opener adoption is unchanged) and
leave _dm_topics to operator config. Topics declared in extra.dm_topics
stay protected from auto-rename.

Tests: real PTB creation -> thread-less opener -> runner rename path
renames once; a config-fixed topic is not renamed; a creation stays
pending without populating _dm_topics. The opener test that pinned the
cache side effect now asserts its absence.
2026-10-19 21:47:53 -07:00
sharpnotebot
37ec498ea7 fix(telegram): record topic creations only from authorized humans and consume them once (Refs #136567)
Builds on the salvaged #137348 commits above. The pairing store accepted
any private-chat forum_topic_created service message and kept records
whose opener arrived already threaded until the TTL ran out.

- Record a creation (and cache its topic name) only when the service
  Message carries message_thread_id, has a non-bot sender, and passes
  the existing intake prefilter _is_user_authorized_from_message, so a
  rejected user cannot populate adapter state.
- Cap the store at _NEW_TOPIC_OPENER_MAX_PENDING (256), evicting the
  oldest stamp after the TTL prune.
- The first later message from the same chat and sender consumes the
  record whether it is adopted, already threaded, non-adjacent or
  expired; adoption still requires a thread-less, adjacent, fresh
  opener. Other chats and senders neither adopt nor consume it.

Tests: adds real PTB Update.de_json -> connect() -> process_update
cases for unauthorized, bot, missing thread/sender, healthy consume,
non-adjacent consume, other chat/sender, expiry and the cap. Phase 1
of test_pending_created_topics_stays_bounded now expects the five
healthy records to be consumed (it previously pinned the leak), and an
unused unpacked `delivered` is renamed to satisfy RUF059.

Adapted from a local field-tested patch; the PTB service+opener
pairing design is from #137348 (PRELVAS94), and reading the topic id
from Message.message_thread_id rather than ForumTopicCreated follows
e756b3b in #136581 (liuhao1024).
2026-10-19 21:47:53 -07:00
Pedro Relvas
328b64a9a7 fix(telegram): bound the pending-created-topics cache (Refs #136567)
The _pending_created_topics map grows unboundedly: records whose opener
arrives already threaded (the healthy path) return early before any pop,
and records that simply never get claimed are never revisited. Prune
expired records at record time inside _pending_created_topics_store.

Adds a regression test that demonstrates the leak (10 distinct keys all
survive), the prune (negative TTL evicts all), and the routing contract
(fresh record still claims its opener).

Also cleans stale update receipts in the test's connected() fixture so
the admission controller doesn't drop updates across test runs.
2026-10-19 21:47:53 -07:00
PRELVAS94
3687ef0bf4 fix(telegram): route a new DM topic's thread-less opening message into that topic
Telegram normally stamps a new private-chat topic's opening message with the new
message_thread_id, but it sometimes delivers that opener with no thread id at all.
A forum_topic_created service message carries no text, so no core handler matched it and
the new topic id was never learned: the opener arrived lobby-shaped and gateway topic
recovery (gateway/run_topics.py) pinned it to the most recently bound topic, leaving the
new topic with no session, binding or auto-rename.

- telegram_topic_routing.py: narrow handler for filters.StatusUpdate.FORUM_TOPIC_CREATED
  records (chat_id, sender_id) -> (new thread id, creation message id, stamp) for private
  chats and caches the topic name; the opener adopts that thread id in _build_message_event
  (one-shot, only for the message immediately after the creation, inside a 120s window).
- adapter.py: wire the handler + mixin in, and drop the now-unreachable
  forum_topic_created branch in _resolve_topic_binding.
- tests/plugins/test_telegram_forum_topic_created_opener.py: real PTB dispatch coverage.

Fixes #136567
2026-10-19 21:47:53 -07:00
Teknium
fbd482d5c5 fix(telegram): a newer chunk no longer cancels a committed batch flush
_enqueue_text_event cancels the key's previous flush task on every new chunk,
even after that task has popped its batch and is dispatching it. With
dm_topic_auto_transfer on, a second root-DM message arriving while
createForumTopic for the first was in flight cancelled the dispatch: Telegram
had already created the topic, Hermes lost its ID, and the hold-queue replay of
the still-root message created a second topic, leaving the first empty.

_flush_buffered now leaves the per-key task slot once it pops the batch, so a
newer chunk re-arms a fresh flush instead of cancelling it. Committed flushes
are tracked per (family, key): a later flush for the same key waits for the
earlier one to settle, keeping order. Disconnect teardown still cancels them
(and the cancel path still holds the popped event).

Test: a fake Bot pauses createForumTopic while a second root message arrives;
no event is held, the first keeps topic 777, and every created topic gets its
message.
2026-10-19 01:15:18 -07:00
Teknium
407303dfdc fix(telegram): move dm_topic_auto_transfer to adapter ingress so the reply lands in the new topic
Builds on the salvaged #139188 (@KoNit-K). The salvaged commit ran the transfer in the runner's
_hmwa_resolve_session, which is too late through the real adapter. By then the adapter has keyed
the session on the root-DM source, and _handle_message has already answered with the lobby
reminder. So with the key on, no topic was ever created, and every root-DM message got the
"main chat is reserved" notice.

- The transfer now runs in TelegramAdapter.handle_message before session keying
  (telegram_topic_transfer.py), through a runner hook (_transfer_telegram_root_dm) wired in
  _wire_adapter_handlers next to topic recovery.
- If topic creation fails, the hook returns the lobby-recovery topic (fallback). Commands,
  internal wakes, routed events and unauthorized senders are never moved.
- The first reply in the new topic carries no reply anchor (the root message lives outside the
  topic), via reply_anchor_override="". This replaces the base.py metadata flag.
- With the key unset (default), behaviour is unchanged and the v0.22 lobby recovery stays
  (#136567).
- The top-level `telegram: dm_topic_auto_transfer` YAML key is bridged into extra, like
  disable_topic_auto_rename.
- Documented in the Telegram multi-session docs.

Refs #139136
Refs #134889 (MSG-15)
Refs #141321
2026-10-18 19:27:36 -07:00
Teknium
914737a811 feat(gateway): public SSRF-safe HTTP client helper for platform plugins
Every bundled adapter built its client from three private pieces:
gateway.platforms.base._ssrf_redirect_guard, tools.url_safety's
create_ssrf_safe_async_client and _http_client_limits.platform_httpx_limits.
The redirect guard becomes public (ssrf_redirect_guard; callers renamed, no
alias) and gateway.platforms.helpers.platform_http_client(**kw) composes all
three, with the guard ahead of any caller response hooks. QQ Bot and WeCom
move to it.
2026-10-17 14:51:46 -07:00
Teknium
53de7ff326 feat(clarify): public get_pending() query replaces _lock/_entries reads
Adapters rendering native clarify buttons (core Discord/Telegram, base
send_clarify, the community QQ plugin) read tools.clarify_gateway._entries
under _lock to learn whether a request is still pending and its choices.
get_pending(clarify_id) returns the entry while it awaits an answer, else
None; internal readers move to it.
2026-10-17 14:51:46 -07:00
Teknium
47d9efe490 feat(gateway): plugin platforms declare group-chat allowlist and pairing suppression
Two authz behaviours were hard-coded on Platform.QQBOT/TELEGRAM/... in
gateway/authz_mixin.py (_GROUP_CHAT_ENV, _ALLOWLIST_SUPPRESSES_PAIRING), so a
plugin-registered platform could not get them and removing the bundled QQ
adapter would silently drop QQ_GROUP_ALLOWED_USERS gating and change pairing.

PlatformEntry gains group_allowed_chats_env and allowlist_suppresses_pairing;
authz_mixin reads them through authz_field (live entry, else the bundled
gateway_env.AUTHZ). Every bundled platform that was in the old tables declares
them in its AUTHZ, so behaviour is unchanged.
2026-10-17 14:51:46 -07:00
Teknium
c05c476f14 refactor(telegram): move the reply-anchor normaliser into telegram_ids
The salvaged #139642 normaliser grew adapter.py past its code-health
cap. It is a pure id helper, so it lives beside normalize_telegram_chat_id
as parse_telegram_message_id; behaviour is unchanged.

Refs #139611
Refs #134889 (MSG-17)
Refs #140138
2026-10-16 20:25:09 -07:00
PRATHAMESH75
29cda7a5ef fix(telegram): send unanchored when a reply anchor is not a message id (#139611)
Route wakes (kanban-wake, loop-tick) are admitted with a synthetic JSON
identity (session_automation.admit_route_wake), and
_reply_anchor_for_event passes it to the send as the reply anchor. The
Telegram adapter ran raw int() on that anchor in
_metadata_reply_to_message_id, _reply_to_message_id_for_send and
_chunk_reply_routing, so every reply into the session failed with
"invalid literal for int() with base 10: '["kanban-wake",...]'" and
the poisoned anchor was retried.

All three sites now go through _telegram_message_id(): a non-numeric
anchor is not a Telegram message id, so the reply is sent unanchored,
or on the DM topic's own metadata anchor when there is one. The
normaliser follows luyifan's approach in #72937, which no longer applies
after the adapter refactor.

Co-authored-by: luyifan <al3060388206@gmail.com>
(cherry picked from commit 5b9f0d6cea2896c82e882297a0cd5e92571fdbb8)
2026-10-16 20:24:24 -07:00
Teknium
b95c4861b2 fix(platforms): bundled authorization env names hold when the live entry lacks them
Independent review found the allowlist, the open-policy startup refusal, the pairing-noise
rule and `hermes pairing revoke` reading only the live PlatformEntry: a user plugin overriding a
bundled platform without the fields, safe mode or a disabled plugin then gated on nothing
(looser than main, whose core tables always applied).

Each bundled plugin now declares them once as `gateway_env.AUTHZ` (passed to register() with
**), and `gateway.platform_env.authz_field` answers from the entry, else from that file (read
without the plugin package). Probed main vs head: 208/208 authz decisions identical in normal,
safe-mode, plugin-disabled and user-override modes; revoke drops the user in all four.

The terminal secret blocklist and config_env_table_keys() read the same files, which removes the
three hand-listed plugin secrets in local_env_policy.
2026-10-16 19:42:34 -07:00
Teknium
2f4b42191e fix(platforms): import new plugin siblings relatively (no second adapter copy)
The plugin loader runs a bundled platform package as hermes_plugins.platforms__<name>.
An absolute `from plugins.platforms.<name>.<sibling> import ...` inside register() imports
the canonical package too, whose __init__ loads a second copy of the adapter. The prompt-hint
and send-target siblings added on this branch did that for buzz, feishu and slack (three new
double-loaded adapters vs main). Relative imports, as the dashboard_card / gateway_env siblings
already use; after every plugin registers, the double-loaded set is back to main's five.
2026-10-16 19:42:34 -07:00
Teknium
3c3f85a0d0 refactor(gateway): plugin platforms declare their env->config rows on PlatformEntry
Move the per-platform `_Cred` rows of `_ENV_STEPS`, their helper steps and the
`_ENV_ENABLE_CREDENTIALS` rows for every plugin-backed platform (telegram, discord,
slack, whatsapp, whatsapp_cloud, signal, mattermost, matrix, email, sms, dingtalk,
feishu, wecom, wecom_callback, weixin, bluebubbles, qqbot, yuanbao) out of
gateway/config_env.py into each plugin's `gateway_env.py`, attached via two new
PlatformEntry fields: `env_overrides` (ordered steps) and `env_enable_credentials`.

`gateway/platform_env.py` holds the declarative `EnvCred` row and shared parsers.
`_apply_env_overrides` runs the rows of entries with activation evidence (same gate
as the plugin enable pass, computed once). Core-only rows (api_server, webhook,
msgraph_webhook, relay) stay in config_env. profile_channels reads the rows from
registry entries; the import-time terminal secret blocklist lists the three secrets
only those rows read, pinned by a new invariant test.

Resulting GatewayConfig and explicit-disable warnings are identical (differential
oracle, 100 fixtures); only env-created insertion order of api_server/webhook/
msgraph_webhook relative to plugin platforms changes.
2026-10-16 19:42:34 -07:00
Teknium
28e4da48fe refactor(dashboard): channel cards and env-value checks read the plugin's PlatformEntry
The Channels page catalog (_PLATFORM_OVERRIDES) and the PUT env-value validators
(_ENV_VALUE_RULES) duplicated per-platform data the bundled platform plugins can
declare. Each plugin now declares its card on its PlatformEntry (new dashboard
block: dashboard_label, dashboard_description, docs_url, dashboard_env_vars,
dashboard_required_env, env_value_rules); core keeps static rows only for the
core-only platforms (api_server, webhook, msgraph_webhook, relay).

Telegram/Slack validators move into their plugins. The PUT route resolves the
rules right after _require_platform (catalog build already materialized every
entry, so nothing extra is imported) and before entering _profile_scope, where
the registry's profile overlay may not hold the entry.

Adapters over their size cap (discord, feishu, matrix, slack, telegram) keep the
card in a sibling dashboard_card.py, imported relatively so no second canonical
copy of the adapter module loads; surplus blank lines offset the two added lines.

Behaviour identity: differential oracle over the real route handlers (GET
/api/messaging/platforms root + profile, PUT valid/invalid per rule root +
profile) is byte-identical to base.
2026-10-16 19:42:34 -07:00
Teknium
e24f12c69f refactor(send): read send_message target syntax and standalone routing from the plugin registry
Delete the per-platform tables in tools/send_message_targets.py (_PLATFORM_PARSERS, 14 rows) and
tools/send_message_tool.py (_PLUGIN_STANDALONE_MEDIA, _TEXT_SENDERS, plus the discord-always and
whatsapp-mentions ladders). Each bundled plugin now declares them on its PlatformEntry:

- target_ref_syntax_fn: the old parser, body unchanged. A new field rather than parse_target_ref_fn
  because that field is an authority (strict under pass_unresolved_references, no "not explicit"
  sentinel, not re-applied to channel-directory hits) and reusing it would change react/cron
  behaviour for ntfy/buzz/photon.
- standalone_send: StandaloneSendPolicy (label, media, all_sends, captionable,
  empty_list_between_chunks, forward_force_document, mentions, text_direct).

Shared builders and the NOT_EXPLICIT sentinel live in gateway/platforms/send_targets.py so plugins
import no core-private helpers. Lookups discover plugins first when the name is not registered yet
(fresh CLI/cron process). Differential oracle (33 platforms x 48 refs, 10 send cases each): base and
head output identical.
2026-10-16 19:42:34 -07:00
Teknium
3d21ec1294 refactor(platforms): plugin PlatformEntry carries its prompt hint and display defaults
PLATFORM_HINTS (agent/prompt_builder.py) and _PLATFORM_DEFAULTS (gateway/display_config.py)
duplicated per-platform data for every bundled messaging plugin. Both consumers already fell
back to the registry (PlatformEntry.platform_hint / display_tier), so the plugin rows move onto
each plugin's register() call and the core tables keep only core surfaces (cron, cli, tui,
desktop, api_server hints; webhook, api_server display rows).

New PlatformEntry field display_overrides: per-key defaults layered over display_tier (telegram,
discord, slack, wecom had tier + tweaks). Hint text is copied byte-for-byte (the shared
_MEDIA_NATIVE fragment is inlined); a base-vs-head oracle of platform_hint() and
resolve_display_setting()/resolve_tool_progress() for every platform, with and without user
display overrides, is byte-identical. Oversize adapters keep the hint in adapter_hint.py.
2026-10-16 19:42:34 -07:00
Teknium
2ab1a408d0 refactor(gateway): bot-bypass and own-policy startup gates read the PlatformEntry
_ALLOW_BOTS_ENV (authz_mixin) and _OWN_POLICY_OPEN_ENV (run) duplicated data the
platform plugins own. PlatformEntry gains allow_bots_env and own_policy_env; the
discord/feishu/telegram/slack and wecom/weixin/yuanbao/qqbot/whatsapp plugins
declare them and both tables are deleted.

Both consumers run an idempotent discover_plugins() first so a hand-built config
or bare runner still sees the entries. The bot bypass fails closed with no entry.
The open-policy startup check fails closed for a bundled platform whose plugin is
disabled or failed to load (conventional <NAME>_* names, manifest-declared
allow-all): config can still enable such a platform, and a later plugin enable
re-wires its adapter without re-running the startup check.

_own_policy_envs lives in run_startup.py to keep run.py under its line cap;
small offsets in the discord/slack/feishu/telegram plugin files for the same reason.
2026-10-16 19:42:34 -07:00
Maciej Lisiewski
c57fbf4584 ci: fix remaining ASYNCXXX linter errors 2026-10-10 15:20:14 +02:00
Maciej Lisiewski
0006a5e229 ci: fix PLW1509, PLW1510, PLW2101 linter errors 2026-10-10 15:20:13 +02:00
Teknium
a274d3388f fix: core modules import again on Python 3.11-3.13 (re-quote eager forward references)
#135348 ran ruff's UP037 autofix with ruff.strict.toml's target-version = "py314". On 3.14
annotations are lazy (PEP 649), so stripping quotes is safe there; on 3.11-3.13 a function or
variable annotation is evaluated when the def or statement runs. Every unquoted annotation that
names the enclosing class (`def clone_for_agent(self) -> ContextEngine`), a class bound later in
the module, or a TYPE_CHECKING-only import now raises NameError on import: 300 modules on main
(gateway.config, run_agent, hermes_state, cron.jobs, the Telegram adapter, ...) fail to import
under 3.11, the update path crashes mid-`hermes update` on any install whose interpreter is
older than 3.14, and the e2e-upgrade suite's retry leg fails with
`NameError: name 'ContextEngine' is not defined`.

- Re-quote exactly the 79 annotations (36 files) that name something unbound when they are
  evaluated (including tui_gateway/server.py's `_TurnScopes`, which only reaches that module's
  globals through register() after import); no other text changes.
- agent/turn_scripted_prelude.py: `Generator[...]` gets its third argument back. d76cce4f11
  applied UP043 (default type args, valid only from 3.13) to a module-level alias, so
  `Generator[Y, S]` raises TypeError on 3.11/3.12 and takes gateway.run, agent.conversation_loop
  and tui_gateway.{server,ws,entry} down with it.
- ruff.strict.toml target-version = "py311", the requires-python floor. With it UP037 leaves
  these quotes alone and only strips the two that are genuinely redundant, which this commit
  strips; any future version-gated fix stays valid on every supported Python.
- tests/ci/test_strict_ruff_target.py pins the target to the requires-python floor (red on main).
2026-10-09 14:25:07 -07:00
Maciej Lisiewski
2ff58849f4 ci: ruff UP037 fixes 2026-10-09 17:34:38 +02:00
Maciej Lisiewski
9eab688b42 ci: ruff UP017 fixes 2026-10-09 17:34:36 +02:00
Maciej Lisiewski
aff64c3eeb ci: UP007, UP022, UP028, UP031, UP041 linter fixes 2026-10-09 17:31:52 +02:00
Maciej Lisiewski
b4e436c115 ci: don't cast int to int 2026-10-08 19:28:23 +02:00
Maciej Lisiewski
aa2d120cba ci: prefix unused variables with underscore (RUF059) 2026-10-08 19:22:03 +02:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
beardthelion
8e85a0fd8c fix(plugins/telegram): clamp negative inline-query offsets to page zero
Telegram echoes back the client-controlled inline_query.offset string on
every inline query. build_inline_results passed it through int() and
used it directly as a slice start, so a negative offset indexed the
catalog from the tail: small catalogs served their last few entries with
negative-prefixed result ids, and larger catalogs could return an empty
page with a misleading next_offset that skipped most of the catalog.

Clamp the parsed offset to >= 0. Malformed offsets still fall back to
page zero via the existing except path, and valid pagination is
unchanged.
2026-10-06 22:52:16 -05:00
alt-glitch
1b8bd66b7f fix(lint): stdin guard catches calls whose arguments start on the next line (review)
Greptile 4198572811: the guard now finds subprocess/os/asyncio calls as ast.Call nodes, so multi-line calls are checked, and the 27 calls it newly flagged (pixel-art ffmpeg and 26 others) pass stdin=DEVNULL.
2026-10-07 01:03:03 +05:30
kshitijk4poor
3c5c402de1 refactor(telegram): import platform_ssl_context at module top in telegram_network
Gate finding C02-2 (Low): the function-local import in
discover_fallback_ips did not match the adapter, which already imports it
at module top. agent.ssl_verify imports only stdlib at module level, so
there is no cycle or import cost.
2026-10-06 12:25:01 +05:30
kshitijk4poor
cdd58da229 refactor(telegram): import platform_ssl_context at module top in the adapter
adapter.py is over the 2000-line target and frozen at its main size by the
code-health ratchet; the local import + named context variable grew it by 3
lines. A module-level import and calling the cached accessor at each use site
(it returns the same identity) keeps the change net-zero, and the test now
patches the name where production reads it.

Co-authored-by: luwen <142317085+LuwenOosten@users.noreply.github.com>
2026-10-06 12:25:01 +05:30
luwen
785cf8a3de fix(telegram): reuse the shared platform TLS context for every Telegram client
Every Telegram httpx client (DoH fallback discovery, both PTB HTTPXRequest
pools, and each lazily rebuilt TelegramFallbackTransport pool) was built with
verify=True, so httpx ran ssl.create_default_context() and a full CA load on
the gateway event loop per client, per reconnect. A slow trust store stalled
the loop for most of the connect deadline on every attempt.

agent.ssl_verify already caches one platform-trust client context
(_shared_context(None)); expose it as platform_ssl_context() and pass it as
verify= to every Telegram client and transport. Verification is unchanged
(CERT_REQUIRED + check_hostname via the truststore-injected context), proxies
still flow through httpx's proxy/env handling, and the first build is ~3 ms
because the platform verifier loads no CA file.

This is the minimal slice of #133340: the PR's single-flight Future, worker
thread and to_thread client construction are unnecessary once the context is
cached and shared.

Fixes #133339
Salvaged from #133340.
2026-10-06 12:25:01 +05:30
kshitijk4poor
7748c7f484 fix(gateway): do not hand an installed reconnect adapter's hold queue back to its predecessor
Gate finding C01.r1.2c [High]: the hand-back added for failed candidates
also ran in the post-install exception/cancel branches. After a successful
secondary install (or a primary publish) the predecessor already forwards
to the new adapter; if the task was cancelled during redelivery (gateway
teardown cancels secondary reconnect tasks) the hand-back linked the new
adapter back to the predecessor, and any hold - e.g. the disconnect()
teardown salvage - ping-ponged between the two until RecursionError.

Break the cycle at both ends: adopt_held_inbound clears the adopter's own
successor link (it owns the queue again), and the runner skips the
hand-back when the adapter is the one installed in its slot. Covered by a
cancel-after-install row on the secondary hand-back test.
2026-10-06 11:24:04 +05:30
kshitijk4poor
27855e7586 refactor(telegram): plain MessageEvent annotations in the held-inbound mixin
MessageEvent is imported at runtime in the new module, so the quoted forward references carried over from adapter.py are unnecessary. Final-head gate (quality Low).
2026-10-05 20:04:04 +05:30
kshitijk4poor
d169a2f3a9 refactor(telegram): move the held-inbound queue into telegram_held_inbound to keep adapter.py under its size cap
Code-health ratchet: plugins/platforms/telegram/adapter.py was 7446 lines > its 7422 cap after the
held-inbound hand-over (#132829) added adopt_held_inbound/_adopt_held_event. The whole hold queue
(_schedule_held_inbound_redispatch, _hold_inbound_event, adopt_held_inbound, _adopt_held_event,
_rehold_from, _redispatch_held_inbound) moves verbatim into TelegramHeldInboundMixin; TelegramAdapter
inherits it, so call sites and instance-level patches are unchanged. The sibling logs under the
adapter's logger name so existing log filters still match.
2026-10-05 20:04:04 +05:30
kshitijk4poor
6964477d80 refactor(telegram): drop the unreachable guard in adopt_held_inbound
Gate finding B05-2: adopt_held_inbound is only reached through
hand_over_held_inbound, which skips a None predecessor, and both runner
callers pass a candidate freshly built by _create_adapter for the same
platform as the replaced instance. So predecessor is never self and is
always a TelegramAdapter; the guard was dead code. Also use the file's
own `events = list(held); held.clear()` idiom.
2026-10-05 20:04:04 +05:30
kshitijk4poor
d87a031fe1 fix(telegram): accept the update claim when a retired adapter forwards a hold
Gate finding B05-1: the successor-forward branch of _hold_inbound_event
returned before self._accept_update(). The admission ContextVar is per
adapter instance, so the successor's own _accept_update() in its hold
path reads its own (empty) var and the predecessor's in-flight claim
stays unaccepted. _release_claim then skips _record_receipt, and the
update can be replayed after a restart even though it was handed off.

Accept on the retired adapter before forwarding, and deref the successor
weakref once.
2026-10-05 20:04:04 +05:30
kshitijk4poor
7ef5aca075 fix(gateway): hand Telegram held inbound to the rebuilt adapter
Telegram holds inbound events that PTB has already acked (offset advanced),
so dropping them means losing the message for good. The hold queue lives on
the adapter instance and drains only on that instance's _mark_connected. When
a retryable fatal (network error, polling/ingress stall) makes the runner
build a NEW adapter, that drain never runs: the reconnect path carried the
inbound dedup caches across but not the queue. Held events, plus anything
teardown salvaged onto the retired instance later, were silently stranded.

The reconnect queue entry (primary) and the secondary reconnect task now
keep the replaced adapter as "predecessor". The existing carry_inbound_dedup
seam reads its dedup caches from it before connect. A new
hand_over_held_inbound seam moves its held events at publish time
(_install_reconnected_adapter / secondary profile_map install). A candidate
that fails to connect never owns the queue, so no hand-back is needed, and
delivery waits until the replacement is registered. TelegramAdapter.
adopt_held_inbound rebinds only source._transport_adapter_ref (profile and
role authorization stay as resolved) and leaves a successor weakref on the
predecessor. Late _hold_inbound_event calls there (teardown salvage after the
replacement drained) forward to the replacement.

Reported-by: j2h4u (Maxim Brashenko)
Fixes #132829
2026-10-05 20:04:04 +05:30
kshitijk4poor
943d4caa47 fix(gateway): keep approval prompts interim instead of tagging them notify
The salvaged change also put notify=True on both approval sends.
On A2A, `notify` marks the turn-final reply, and A2A has no native
approval renderer. A prompt that needs a human decision would therefore
complete the caller's task with the prompt text while the turn is still
waiting (@ehz0ah's review on #132527). Telegram already pushes the
prompt through the approval-aware _notification_kwargs, so only the
is_approval_prompt marker is needed. The card send goes back to the
verbatim thread metadata: Telegram's control-message path never silences
cards.

Tests: the runner test pins that the fallback metadata stays interim and
does not carry notify. The adapter tests become a single parametrize.

Fold the _notification_kwargs change back into the original one-line
shape, so adapter.py grows by one line instead of six.
2026-10-04 11:58:00 +05:30
liuhao1024
e26d4cb3e3 fix(telegram): push approval prompts instead of silently delivering them
In the default Telegram notification mode ("important") the plain-text
approval fallback marked only is_approval_prompt, which no notification
decision consults, so _notification_kwargs sent the prompt with
disable_notification=True: the phone got no push, the user never learned
a dangerous command was waiting, and the tool sat the full approvals.timeout
(default 300s) before failing closed (#132516).

Mirror the cron-delivery convention on both approval sends in
_approval_notify_sync: notify=True on the button card and the text
fallback, and make _notification_kwargs itself approval-aware
(is_approval_prompt defeats disable_notification) so every surface that
marks the prompt is covered in one place. Loosens no guard and
auto-approves nothing.

(cherry picked from commit 576fec2ab6a6cdca08f96968574ba741c47568c0)
2026-10-04 11:58:00 +05:30
kshitijk4poor
c03cca2763 refactor(telegram): parse max_concurrent_updates with coerce_port
Gate BR3 r1 reuse (Low): build_update_processor hand-rolled the int-or-
default parse that gateway.platforms._shared.coerce_port already does.
Neither caught OverflowError, so `max_concurrent_updates: .inf` in YAML
aborted connect(). coerce_port now treats non-finite values as unparseable
(as gateway.config._coerce_num already does), which also hardens its other
port/int callers; the telegram setting warns and falls back to 32.
2026-10-03 20:50:15 +05:30