
    Jj%0                       d Z ddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZmZ ddlmZmZmZmZmZ  ej        e          ZdedefdZdej        ddfd	Zdd
defdZdAdZdAdZ	 ddlm a m!a!m"a"m#a#m$a$ 	 ddlm%a% n# e&$ r da%Y nw xY wddl'm(a(m)a)m*a*m+a,m-a-m.a. ddl/m0a0m1a1 ddl2m3a3 da4n8# e&$ r0 da4ea ea!ea"ea#ea$da%ea(ea)ea*ea,ea3da.da0da1 G d d          Z5e5a-Y nw xY wddl6Z6ddl7m8Z9 e6j:        ;                    d e e9e<          =                                j>        d                              ddl?m@Z@mAZA ddlBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZR ddlSmTZT ddlUmVZVmWZWmXZX ddlYmZZZm[Z[m\Z\ h dZ]d d!d!d"d#d$Z^d%d&d&d'd(d)Z_de`fd*Za e	jb        d+          Zcd,edefd-Zdd,edefd.Ze e	jb        d/          Zfd,edefd0Zgdd1lhmiZjmkZl  e	jb        d2e	jm                  Znd,edefd3Zod4Zp G d5 d6eC          Zqdefd7Zrd8 Zsde`fd9Ztdddd:d;ZudAd<Zvd=ewd>ewdewdz  fd?ZxdAd@ZydS )Bz
Telegram platform adapter.

Uses python-telegram-bot library for:
- Receiving messages from users/groups
- Sending responses back
- Handling media and commands
    N)datetimetimezone)DictListOptionalSetAnyerrorreturnc                 z    | dnt          |           }|s|S 	 ddlm}  ||d          S # t          $ r Y dS w xY w)zORedact secrets from Telegram transport errors before logging or returning them.N r   )redact_sensitive_textT)forcez<telegram error redacted>)stragent.redactr   	Exception)r
   textr   s      H/home/rurouni/.hermes/hermes-agent/plugins/platforms/telegram/adapter.py_redact_telegram_error_textr      ss    22CJJD +666666$$T6666 + + +***+s   , 
::taskc                     	 |                                   dS # t          j        $ r Y dS t          $ r  t                              dd           Y dS w xY w)zFObserve a detached task's terminal exception to avoid noisy loop logs.z1Abandoned Telegram init task failed after timeoutTexc_infoN)	exceptionasyncioCancelledErrorr   loggerdebug)r   s    r   _consume_abandoned_taskr   &   sz    Y!    Y Y YHSWXXXXXXYs    A%AA)
on_abandontimeoutc                0  	
K   t          j        |           }t          j                                                    
d
fd	d	fd}t	          j        t          |d          |          }d|_        |                                 	 t          j	        |
ht           j
                   d{V \  }}||v rE
                                s
                                 | d{V 	 |                                 S |                                 |                    t                     |;t          j        t          |                    }|                    t                     t          j                    # |                                 w xY w)	a*  Await with a wall-clock deadline that does not depend on loop timers.

    ``asyncio.wait_for`` schedules its timeout on the event loop and then waits
    for cancellation to propagate.  PTB/httpcore initialization can sit inside
    cancellation-shielded anyio scopes, so a timed-out initialize() may never
    hand control back to the retry ladder under some supervisors.  This helper
    lets a daemon ``threading.Timer`` wake the loop and, on timeout, abandons
    the shielded task instead of awaiting cancellation completion.

    ``on_abandon`` (optional) is a zero-arg callable returning an awaitable that
    is scheduled as a detached best-effort cleanup when the task is abandoned on
    timeout.  The abandoned initialize() may leave a half-built httpx client /
    connection pool open (it never completed and we do not await its
    cancellation), so the caller uses this to shut that state down and avoid
    leaking a pool per retry attempt.  Cleanup runs detached and its own errors
    are swallowed, so it can never re-block the retry ladder.
    r   Nc                  ^                                      s                     d            d S d S N)done
set_result)deadlines   r   _mark_expiredz2_await_with_thread_deadline.<locals>._mark_expiredF   s7    }} 	&%%%%%	& 	&    c                  2                                     d S r$   )call_soon_threadsafe)r(   loops   r   _expire_from_threadz8_await_with_thread_deadline.<locals>._expire_from_threadJ   s    !!-00000r)           T)return_whenr   N)r   ensure_futureget_running_loopcreate_future	threadingTimermaxdaemonstartwaitFIRST_COMPLETEDr%   canceladd_done_callbackr   _run_abandon_cleanupTimeoutError)	awaitabler!   r    r   r-   timerr%   _cleanupr(   r'   r,   s            @@@r   _await_with_thread_deadlinerC   0   s     $  ++D#%%D!!##H& & & & & &1 1 1 1 1 1 1 OC--/BCCEEL	KKMMM8/
 
 
 
 
 
 
 
 
a 4<<==?? "!!!:::::: 	 	6777!
 +,@,L,LMMG%%&=>>>"$$$s   AE? A>E? ?Fc                    K   	  |             }t          j        |          st          j        |          r
| d{V  dS dS # t          $ r  t                              dd           Y dS w xY w)u   Run the abandonment cleanup coroutine, swallowing any failure.

    Wrapped so a cleanup that itself hangs or raises cannot surface as an
    unhandled task error or block anything — it is fully fire-and-forget.
    Nz&Abandoned Telegram init cleanup failedTr   )r   iscoroutineisfuturer   r   r   )r    results     r   r=   r=   h   s      Nv&& 	'*:6*B*B 	LLLLLLLLL	 	 N N N=MMMMMMNs   :A &A,+A,c                   K   | dS 	 |                                   d{V  n,# t          $ r t                              dd           Y nw xY wt	          | dd          }|t	          |dd          nd}|sdS |D ]}}t	          |dd          }|	  |            }t          j        |          st          j        |          r| d{V  R# t          $ r t                              dd           Y zw xY wdS )	u  Release a half-built PTB app's httpx transports after init was abandoned.

    ``Application.shutdown()`` / ``Bot.shutdown()`` are gated on the app's
    ``_initialized`` / ``_requests_initialized`` flags, which a wedged
    ``initialize()`` (the case this whole path exists for) may never have set —
    so calling only ``app.shutdown()`` no-ops and leaks the connection pool it
    was meant to close.  ``HTTPXRequest`` builds its ``httpx.AsyncClient``
    eagerly in its constructor and its ``shutdown()`` gates only on
    ``client.is_closed``, so closing the request transports directly releases
    the pool regardless of PTB init state.  We try the clean path first, then
    fall back to the transports.  All best-effort and swallowed.
    Nz(Abandoned Telegram app.shutdown() failedTr   bot_requestshutdownz*Abandoned Telegram request shutdown failed)rK   r   r   r   getattrr   rE   rF   )apprI   requestsrequestrK   rG   s         r   _shutdown_abandoned_apprP   v   sm      {Pllnn P P P?$OOOOOP
 #ud
#
#C14wsJ---dH  	V 	V7J55	VXZZF"6** g.>v.F.F  	V 	V 	VLLEPTLUUUUU	V	V 	Vs!   # &AA:C&C65C6)UpdateBotMessageInlineKeyboardButtonInlineKeyboardMarkupLinkPreviewOptionsApplicationCommandHandlerCallbackQueryHandlerMessageHandlerContextTypesfilters	ParseModeChatTypeHTTPXRequestTFc                       e Zd ZeZdS )_MockContextTypesN)__name__
__module____qualname__r	   DEFAULT_TYPE r)   r   re   re      s        r)   re   )Path   )PlatformPlatformConfig)BasePlatformAdapterMessageEventMessageTypeProcessingOutcome
SendResultclassify_send_errorcache_image_from_bytescache_audio_from_bytescache_video_from_bytescache_document_from_bytesresolve_proxy_urlSUPPORTED_VIDEO_TYPESSUPPORTED_DOCUMENT_TYPESSUPPORTED_IMAGE_DOCUMENT_TYPES_TEXT_INJECT_EXTENSIONS	utf16_len)normalize_telegram_chat_id)TelegramFallbackTransportdiscover_fallback_ipsparse_fallback_ip_env)atomic_replace	env_floatenv_int>   .gif.jpg.png.jpeg.webpr   r   r   r   )	image/png
image/jpegz	image/jpg
image/webp	image/gifr   r   r   r   )r   r   r   r   r   c                  ^   t           rdS 	 ddlm}   | dd           n# t          $ r Y dS w xY w	 ddlm}m}m} ddlm}m	} 	 dd	lm
} n# t          $ r d
}Y nw xY wddlm}m}m}	m}
m}m} ddlm}m} ddlm} n# t          $ r Y dS w xY w|a|a|a|a|a	|a
|a|a|	a|
a|a|a|a|a|ada dS )aF  Check if Telegram dependencies are available.

    If python-telegram-bot is missing, attempts to lazy-install it via
    ``tools.lazy_deps.ensure("platform.telegram")``. After a successful
    install, re-imports the SDK and flips ``TELEGRAM_AVAILABLE`` to True
    so the adapter's class-level type aliases get rebound.
    Tr   )ensurezplatform.telegramF)prompt)rQ   rR   rS   )rT   rU   rV   NrX   r_   rb   )TELEGRAM_AVAILABLEtools.lazy_depsr   r   telegramrQ   rR   rS   rT   rU   rW   ImportErrortelegram.extrY   rZ   r[   r\   r]   r^   telegram.constantsr`   ra   telegram.requestrc   TelegramMessageHandler)_lazy_ensure_Update_Bot_Message_IKB_IKM_LPO_App_CH_CQH_MH_CT_filters_PM_CtT_HRs                   r   check_telegram_requirementsr      s     t::::::(77777   uuPPPPPPPPPPWWWWWWWW	;;;;;;; 	 	 	DDD		
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	JIIIIIII8888888   uuF
CGKN LGIHL4sA    
--A< A 
A< AA< A!A< <
B
	B
z([_*\[\]()~`>#\+\-=|{}.!\\])r   c                 8    t                               d|           S )zIEscape Telegram MarkdownV2 special characters with a preceding backslash.z\\\1)_MDV2_ESCAPE_REsubr   s    r   _escape_mdv2r   1  s    w---r)   c                    t          j        dd|           }t          j        dd|          }t          j        dd|          }t          j        dd|          }t          j        dd|          }t          j        dd|          }|S )zStrip MarkdownV2 escape backslashes to produce clean plain text.

    Also removes MarkdownV2 formatting markers so the fallback
    doesn't show stray syntax characters from format_message conversion.
    z\\([_*\[\]()~`>#\+\-=|{}.!\\])\1z\*\*([^*]+)\*\*z\*([^*]+)\*z(?<!\w)_([^_]+)_(?!\w)z	~([^~]+)~z\|\|([^|]+)\|\|rer   )r   cleaneds     r   _strip_mdv2r   6  s     f6tDDGf'88Gf^UG44G f.w??Gf\5'22Gf'88GNr)   z2(?m)^``` (?P<indicator>(?:\\)?\(\d+/\d+(?:\\)?\))$c                 8    t                               d|           S )a  Move ``(N/M)`` chunk markers off Telegram code-fence lines.

    ``truncate_message()`` appends chunk indicators to the end of a chunk. When
    the chunk had to close an in-progress fenced code block, that creates a
    line like ````` \(1/2\)`` after MarkdownV2 escaping. Telegram does not
    treat that as a clean closing fence, so it can reject MarkdownV2 and fall
    back to plain text. Put the indicator on its own line immediately after the
    closing fence.
    z```\n\g<indicator>)_CHUNK_INDICATOR_ON_FENCE_REr   r   s    r   $_separate_chunk_indicator_from_fencer   Q  s     (++,A4HHHr)   )TABLE_SEPARATOR_REconvert_table_to_bulletsz(?:```[^\n]*\n[\s\S]*?```)|(?:^[^\n]*\|[^\n]*\n[ \t]*\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)+\|?[ \t]*(?:\n[^\n]*\|[^\n]*)*)c                    | rd| vr| S g }d}t                               |           D ]}| ||                                         }|                    t	          j        dd|                     |                    |                    d                     |                                }| |d         }|                    t	          j        dd|                     d                    |          S )u  Convert single ``\n`` to Markdown hard breaks for the rich-message path.

    Standard Markdown treats a lone ``\n`` as whitespace (soft break), so
    Bot API 10.1 ``sendRichMessage`` collapses multi-line content — e.g.
    slash-command lists joined with ``"\n".join(lines)`` — into a single
    paragraph.  Adding two trailing spaces before each single newline
    forces a hard line break (``<br>``) in the rendered output.

    Paragraph breaks (``\n\n``), fenced code blocks, and GFM pipe-table
    blocks are left untouched: tables render natively in the rich path and a
    hard break injected into a row separator would corrupt the table.
    
r   z(?<!\n)\n(?!\n)z  
Nr   )	_RICH_PROTECTED_REGION_REfinditerr8   appendr   r   groupendjoin)r   outposmprosetails         r   _rich_normalize_linebreaksr   ~  s      4t##C C&//55  S]#

26,fe<<===

1771::eegg:DJJrv(&$77888773<<r)   g      .@c                   P    e Zd ZU dZdZdZdZdZeZdZ	dZ
dZdZeed<   d	Zd
ZdZdZeddddededee         dee         def
d            Zed             Zdef fdZd? fdZd? fdZdedededdf fdZdefdZdee ee!f                  de ee!f         fd Z"ddddd!d"ed#ee         d$ee         d%ee         d&ee         defd'Z#de$fd(Z%defd)Z&de$defd*Z'e(dee ee!f                  dee         fd+            Z)e(dee ee!f                  dee         fd,            Z*e(dee ee!f                  dee+         fd-            Z,ed#edefd.            Z-e(d#ed%ee         dee ee!f                  defd/            Z.edefd0            Z/e(	 	 d@d1ee         dee ee!f                  d2ee         dee+         fd3            Z0e(	 	 	 dAd#ed%ee         dee ee!f                  d4ee+         d2ee         de ee!f         fd5            Z1e(d%ee         dee+         fd6            Z2e(d%ee         dee+         fd7            Z3ed8e4defd9            Z5d#e!d%e!ddfd:Z6ed8e4defd;            Z7e(d8e4dee ee!f                  d4ee+         defd<            Z8	 dBd=e!d>e ee!f         dee ee!f                  d4ee+         d?ed@ee!         de!fdAZ9de:e         fdBZ;ed8e4defdC            Z<ed8e4defdD            Z=ed8e4defdE            Z>ed8e4defdF            Z?dCdHededefdIZ@de ee!f         fdJZAdKedefdLZBdefdMZC eDjE        dNeDjF        eDjG        z            ZH eDjE        dOeDjF        eDjG        z            ZI eDjE        dP          ZJdKedefdQZKdKedefdRZLdKedefdSZMdKedefdTZNdKedefdUZOdKedefdVZP	 dBdKedee ee!f                  defdWZQ	 dBdKedee ee!f                  defdXZRdee+         fdYZSdGdZdKed[ede ee!f         fd\ZTd]e4defd^ZUd]e4defd_ZVd#ed1ee         dee ee!f                  d%ee         deeW         f
d`ZXd#edKed1ee         dee ee!f                  deeY         f
daZZ	 dBd#edbedKedee ee!f                  deeY         f
dcZ[dKedefddZ\d#edee+dKedee ee!f                  def
dfZ]d?dgZ^de_j`        fdhZad?diZbd8e4djeddfdkZcdefdlZddmedefdnZed8e4ddfdoZfd?dpZgdqeddfdrZhd?dsZid?dtZjd8e4ddfduZk	 	 d@d#e+dedvee+         dwee         dee+         f
dxZldyededee         fdzZmdCd#ed{ed|edee         fd}Znd#e+d%e+deddfd~Zo	 dCd#e+d{ed%e+deddf
dZpd?dZqd?dZrd?dZsdGddedefdZtdeddfdZud?dZvd?dZwd1ee         de+defdZx	 	 d@d#edKed1ee         dee ee!f                  deYf
dZyddd#ededKedee ee!f                  deYf
dZzdGddd#edbedKededee ee!f                  deYfdZ{dKedefdZ|ddd#edbedKededee ee!f                  deYfdZ}d#edbedefdZ~	 	 d@d$ee         dee ee!f                  defdZ	 dBd#edee+dKedee ee!f                  deYf
dZd Z	 	 	 dDd#ededededee ee!f                  deYfdZ	 	 dEd#ededededee ee!f                  deYfdZ	 dBd#edededededee ee!f                  deYfdZ	 dBd#ededee:         dededee ee!f                  deYfdZ	 dBd#ede:dedededee ee!f                  deYfdZdZdZdFde:de+deWfdZde:de+deWfdZded#eddfdZdeddfdZ	 	 	 	 	 	 dGdZdg ddGfdg ddGfdg ddGfdg ddGfddgddfddgddfddgddfddgddfddgddfddgddfdМ
ZdeddfdфZdededefdԄZdede!de+defdׄZde!dedeWeee         f         fdلZ	 	 	 dAd#ededee         d1ee         dee ee!f                  deYf fd܄Z	 	 dHd#edeeW         dee ee!f                  deddf
 fdZ	 	 	 dAd#ededee         d1ee         dee ee!f                  deYf fdZ	 	 	 	 dId#ededee         dee         d1ee         dee ee!f                  deYf fdZ	 	 	 dAd#ededee         d1ee         dee ee!f                  deYf fdZ	 	 	 dAd#ededee         d1ee         dee ee!f                  deYf fdZ	 	 	 dAd#ededee         d1ee         dee ee!f                  deYfdZdBd#edee ee!f                  ddfdZd#ede ee!f         fdZdKedefdZdefdZdefdZdefdZdefdZdee         fdZdee         fdZdee         fdZdee         fdZdee         fdZdee+         fdZdeeDj                 fdZde$defdZe(de$dee         fd            Zde$defdZede$dee         fd            Zde$defdZde$defdZde$defd Zde$defdZdee         dee         fdZde$defdZd ZdedefdZdefdZdedefd	Zd
e$defdZd
e$deddfdZd
e!deddfdZd
e$fdZedee         dedefd            Z	 dBd
e$deded]e4dee         ddfdZ	 	 d@de$dedee+         dee         ddf
dZde$defdZdGdde$dedefdZÐd?dZdedee$         fdZdedej        ddfdZdedej        ddfdZdedej        ddfd Zːdedefd!Z̐deddfd"ZdHeddfd#Zΐded
e$defd$Zϐd%eddfd&ZАd%ededdfd'Zdedej        ddfd(ZҐd)ededdfd*ZӐd)eddfd+ZԐd
e$dd,ddfd-ZՐd?d.Zd#ed%ee         dee ee!f                  fd/Zd#ed%ed{eddfd0Ze(d1e!defd2            Ze(d3e!defd4            Ze(d5e!dee         fd6            Z	 dBde$dedee+         defd7Zdefd8Zd#edbed9edefd:Zd#edbedefd;Zߐdeddfd<Zded=eddfd>Z xZS (J  TelegramAdapterz
    Telegram bot adapter.

    Handles:
    - Receiving messages from users and groups
    - Sending responses with Telegram markdown
    - Forum topics (thread_id support)
    - Media messages
       Ti   i  皙?1REQUIRES_EDIT_FINALIZEi@  g
ףp=
?   gQ?N	min_value	max_valuenamedefaultr   r   r   c                V   ddl }t          j        |           }	 |t          |          nt          |          }n&# t          t
          f$ r t          |          }Y nw xY w|                    |          st          |          }|t          ||          }|t          ||          }|S )zRead a float env var, reject non-finite values, and clamp to bounds.

        Guarantees the returned value is a finite number usable directly in
        ``asyncio.sleep()`` and similar APIs that reject NaN / Inf.
        r   N)	mathosgetenvfloat	TypeError
ValueErrorisfiniter6   min)r   r   r   r   r   rawvalues          r   _env_float_clampedz"TelegramAdapter._env_float_clamped  s     	ioo	#"%/E#JJJuW~~EE:& 	# 	# 	#'NNEEE	#}}U## 	#'NNE y))E y))Es    ;  AAc                     t           S )z6Telegram measures message length in UTF-16 code units.)r~   selfs    r   message_len_fnzTelegramAdapter.message_len_fn  s
     r)   configc                    t                                          |t          j                   d | _        d | _        d| _        |                                 | _        t          |dd          pd| _
        |                     dd          | _        |                     dd          | _        |                     dd          | _        d| _        d| _        t#          dd          | _        i | _        i | _        i | _        i | _        |                     d	d
dd          | _        |                     dd| j        d          | _        i | _        i | _        d| _        d | _        d| _        d| _        d | _         d | _!        d| _"        d| _#        d| _$        tK          j&                    | _'        i | _(        tS                      | _*        tK          j&                    | _+        tY          | j-        j.        /                    dd                    | _0        tc          | j-        j.        /                    dd                    | _2        tc          | j-        j.        /                    dd                    | _3        | j-        j.        /                    dg           | _4        d | j4        D             | _5        | j-        j.        /                    d          rdnd| _6        i | _7        i | _8        i | _9        i | _:        d| _;        i | _<        i | _=        d | _>        d S )NFreply_to_modefirstdisable_link_previewsrich_messagesrich_drafts)HERMES_TELEGRAM_MEDIA_BATCH_DELAY_SECONDSr   (HERMES_TELEGRAM_TEXT_BATCH_DELAY_SECONDSg333333?g{Gz?g       @r   .HERMES_TELEGRAM_TEXT_BATCH_SPLIT_DELAY_SECONDS      ?g      @r   status_indicatorstatus_onlineOnlinestatus_offlineOffline	dm_topicsc                 @    h | ]}d |v t          |d                    S chat_idr   ).0es     r   	<setcomp>z+TelegramAdapter.__init__.<locals>.<setcomp>`  s0     -
 -
 -
"#aC)r)   base_urll          @	important)?super__init__rm   TELEGRAM_app_bot_webhook_mode_compile_mention_patterns_mention_patternsrL   _reply_to_mode_coerce_bool_extra_disable_link_previews_rich_messages_enabled_rich_drafts_enabled_rich_send_disabled_rich_draft_disabledr   _media_batch_delay_seconds_pending_photo_batches_pending_photo_batch_tasks_media_group_events_media_group_tasksr   _text_batch_delay_seconds_text_batch_split_delay_seconds_pending_text_batches_pending_text_batch_tasks_drop_delayed_deliveries_polling_error_task_polling_conflict_count_polling_network_error_count_polling_error_callback_ref_polling_heartbeat_task_polling_pending_stuck_count_polling_not_running_count_send_path_degradedr   Lock_general_request_drain_lock
_dm_topicsset_forum_command_registered_forum_lockboolr   extraget_status_indicator_enabledr   _status_online_text_status_offline_text_dm_topics_config_dm_topic_chat_ids_max_doc_bytes_model_picker_state_approval_state_slash_confirm_state_clarify_state_notifications_mode_status_message_ids_last_overflow_preview_post_connect_task)r   r   	__class__s     r   r  zTelegramAdapter.__init__  s3   !2333+/	#'	#(!%!?!?!A!A#*6?G#L#L#WPW,0,C,CD[]b,c,c# -1,C,COUZ,[,[# +/*A*A-QV*W*W! */ */! +44_ad*e*e'?A#CE'<> ;= *.)@)@6	 *A *
 *
& 04/F/F<4	 0G 0
 0
, ?A"BD&(-%;? ,-$12)+/(?C$ 23) 01' */ +2<>>(*,3655&"<>> 04K!!"4e<<0
 0
& ),K!!/8<<)
 )
  *-K!!"2I>>*
 *
! 8<{7H7L7L[Z\7]7]-
 -
'+'=-
 -
 -
 { $$Z00"""! 	 57 /1 57! /1 )4  68  9;#
 ;?r)   c                 V    d| _         t                                                       d S )NF)r  r   _mark_connectedr   r8  s    r   r:  zTelegramAdapter._mark_connected  s'    (-%!!!!!r)   c                 V    d| _         t                                                       d S )NT)r  r   _mark_disconnectedr;  s    r   r=  z"TelegramAdapter._mark_disconnected  s'    (,%""$$$$$r)   codemessage	retryablec                ^    d| _         t                                          |||           d S )NTr@  )r  r   _set_fatal_error)r   r>  r?  r@  r8  s       r   rC  z TelegramAdapter._set_fatal_error  s0    (,%  w) DDDDDr)   c                 >    t          t          | dd                    S )u*  True once teardown/fatal-error started — delayed flushes must drop.

        Buffered text/photo/media-group flushes sit behind an asyncio.sleep().
        If disconnect wins the race, dispatching them spawns an agent on a
        torn-down session, producing stale/duplicate deliveries.
        r  F)r'  rL   r   s    r   _should_drop_delayed_deliveryz-TelegramAdapter._should_drop_delayed_delivery  s     GD"<eDDEEEr)   metadatac                 j    t          | dd          dk    ri S |pi                     d          ri S ddiS )a!  Return disable_notification kwargs when the adapter is in silent mode.

        In "important" mode, all message sends are silently delivered
        (disable_notification=True) unless the caller explicitly requests a
        notification by setting ``metadata["notify"] = True``.
        r4  r   notifydisable_notificationT)rL   r)  )r   rF  s     r   _notification_kwargsz$TelegramAdapter._notification_kwargs  sK     4.<<KKIN)) 	I&--r)   r   	chat_type	thread_id	user_nameuser_idr   rL  rM  rN  c          
         t          |pd                                          }|sdS t          t          | dd          dd          }t          |dd          }t          |          r	 ddlm}	 t          |pd	                                                                          pd	}
|
d
k    rd	}
n|
dk    r|dnd}
 |	t          j        t          |p|          |
||r!t          |                                          nd|t          |          nd          }t           ||                    S # t          $ r  t                              d|d           Y nw xY wt          j        dd                                          }|s)t          j        dd                                          dv S d |                    d          D             }d|v p||v S )zIReturn whether a Telegram inline-button caller may perform gated actions.r   F_message_handlerN__self___is_user_authorizedr   SessionSourcedmprivate
supergroupforumr   platformr   rL  rO  rN  rM  z=[Telegram] Falling back to env-only callback auth for user %sTr   TELEGRAM_ALLOWED_USERSGATEWAY_ALLOW_ALL_USERS>   r   yestruec                 ^    h | ]*}|                                 |                                 +S rj   stripr   uids     r   r   z?TelegramAdapter._is_callback_user_authorized.<locals>.<setcomp>  -    TTTs		Tsyy{{TTTr)   ,*)r   rb  rL   callablegateway.sessionrU  lowerrm   r  r'  r   r   r   r   r   split)r   rO  r   rL  rM  rN  normalized_user_idrunnerauth_fnrU  normalized_chat_typesourceallowed_csvallowed_idss                 r   _is_callback_user_authorizedz,TelegramAdapter._is_callback_user_authorized  s2    !B//5577! 	5'94@@*dSS&"7>>G 	999999'*9+<'='='C'C'E'E'K'K'M'M'UQU$'944+/(()\996?6K77QX(&%. =+=>>2.8AKc)nn22444t090Ec)nnn4   GGFOO,,,   S&!       i 8"==CCEE 	\
 96;;AACCG[[[TTk.?.?.D.DTTTk!F%7;%FFs   )CD1 1'EEc                    ddl m} t          |dd          }t          |dd          }t          t          |dd                                                    pd}t          t          |dd          pt          |d	d          pd                                          pd}|s{t          |d
d          }|ht          t          |dd                                                    pd}|s4t          t          |dd          pd                                          pd}t          t          |dd                                                    p|}t          t          |dd                                                                                    pd}	|	dk    rd}	nR|	dk    rLt          |dd          }
t          t          |dd                    }t          |dd          du }|
|s|rdnd}	d}t          |dd          }
|
bt          t          |dd                    }t          |dd          du }|	dk    r|s|rt          |
          }n|	dk    r|rt          |
          } |t          j        |pd|	|||          S )a`  Build the same Telegram source shape the gateway auth path expects.

        Resolves the identity to authorize from ``from_user`` for normal
        messages, falling back to ``sender_chat`` for channel posts (which
        carry no ``from_user``) so a removed/unauthorized channel cannot
        inject content via the broadcast path either.
        r   rT  	from_userNchatidr   username	full_namesender_chattitletyperV  rW  rX  message_thread_idis_topic_messageFis_forumTrY  r   rZ  )	ri  rU  rL   r   rb  rj  r'  rm   r  )r   r?  rU  userrv  rO  rN  rz  r   rL  thread_id_rawr~  is_forum_grouprM  s                 r   _source_from_message_for_authz-TelegramAdapter._source_from_message_for_auth  s    	211111wT22w--gdD"--..4466>$j"--U{B1O1OUSUVV\\^^  	
  	!'=$??K&gk4<<==CCEEM  GK"==CDDJJLLTPT  gdD"--..4466A'fd3344::<<BBDDL		!!II,&&#G-@$GGM#GG5G$O$OPP$T:u==EN !,2B,n,   	)<dCC$#GG5G$O$OPP$T:u==ENG##)9#^#..		d""'7"..	}&Mr
 
 
 	
r)   c                 8    d}t          d |D                       S )zDReturn True when Telegram auth env vars make an early decision safe.)r\  TELEGRAM_GROUP_ALLOWED_USERSTELEGRAM_GROUP_ALLOWED_CHATSTELEGRAM_ALLOW_ALL_USERSGATEWAY_ALLOWED_USERSr]  c              3   d   K   | ]+}t          j        |d                                           V  ,dS )r   N)r   r   rb  )r   keys     r   	<genexpr>z@TelegramAdapter._telegram_auth_env_configured.<locals>.<genexpr>.  s:      >>#29S"%%++-->>>>>>r)   )any)r   keyss     r   _telegram_auth_env_configuredz-TelegramAdapter._telegram_auth_env_configured$  s(    
 >>>>>>>>r)   c           	      ^   |                      |          }|j        }|sdS | j        j                            d          }|d |D             }||v pd|v S | j                            d          }t          |          rB	 t           |||j        |j	        |j
        |j                            S # t          $ r Y nw xY wt          t          | dd          d	d          }t          |d
d          }t          |          r\|                                 sdS 	 t           ||                    S # t          $ r  t                              d|d           Y nw xY wt#          j        dd                                          }	|	sdS d |	                    d          D             }
d|
v p||
v S )a  Check if the sender of a Telegram message is authorized.

        Intake prefilter that runs BEFORE text batching, event construction,
        and unmentioned-group observation, so a removed/unauthorized user
        cannot inject prompt content into the agent path or the observed
        transcript (fixes #40863). It only rejects when it can make the same
        context-aware decision the runner would make. Unknown DMs with no
        allowlist still pass through so the normal pairing flow can run.
        T
allow_fromNc                     h | ]D}t          |                                          #t          |                                          ES rj   r   rb  )r   us     r   r   zCTelegramAdapter._is_user_authorized_from_message.<locals>.<setcomp>G  s9    TTT!SVV\\^^Ts1vv||~~TTTr)   rg  rs  rK  rQ  rR  rS  z4[Telegram] Falling back to env-only auth for user %sr   r\  r   c                 ^    h | ]*}|                                 |                                 +S rj   ra  rc  s     r   r   zCTelegramAdapter._is_user_authorized_from_message.<locals>.<setcomp>q  re  r)   rf  )r  rO  r   r(  r)  __dict__rh  r'  r   rL  rM  rN  r   rL   r  r   r   r   r   rb  rk  )r   r?  rp  rO  adapter_allow_fromallowedcallback_authrm  rn  rq  rr  s              r    _is_user_authorized_from_messagez0TelegramAdapter._is_user_authorized_from_message0  s)    33G<<.  	4 "[.22<@@)TT/ATTTGg%77 ))*HIIM"" 	!M &"("2"("2"("2         '94@@*dSS&"7>>G 	 5577 tGGFOO,,,   J!       i 8"==CCEE 	4TTk.?.?.D.DTTTk!;W%;;s$    0B1 1
B>=B>D0 0'EEc                     |sd S |                     d          p|                     d          }|t          |          nd S )NrM  r}  r)  r   )clsrF  rM  s      r   _metadata_thread_idz#TelegramAdapter._metadata_thread_idt  sG     	4LL--R>Q1R1R	!*!6s9~~~D@r)   c                     |sd S |                     d          p|                     d          }|t          |          nd S )Ndirect_messages_topic_id!telegram_direct_messages_topic_idr  )r  rF  topic_ids      r   "_metadata_direct_messages_topic_idz2TelegramAdapter._metadata_direct_messages_topic_id{  sH     	4<< :;;px||Lo?p?p ( 4s8}}}$>r)   c                 Z    |sd S |                     d          }|t          |          nd S )Ntelegram_reply_to_message_id)r)  int)r  rF  reply_tos      r   _metadata_reply_to_message_idz-TelegramAdapter._metadata_reply_to_message_id  s6     	4<< >?? ( 4s8}}}$>r)   c                 Z    	 t          |           dk    S # t          t          f$ r Y dS w xY w)Nr   F)r  r   r   r   s    r   _looks_like_private_chat_idz+TelegramAdapter._looks_like_private_chat_id  s?    	w<<!##:& 	 	 	55	s    **c                 J   |                      |          ;t          |o+|                    d          o|                     |          d u          S |r|                    d          rdS t          |o+|r|                    d          p|                     |                    S )N telegram_dm_topic_reply_fallback"telegram_dm_topic_created_for_sendF)r  r'  r)  r  r  )r  r   rM  rF  s       r   _is_private_dm_topic_sendz)TelegramAdapter._is_private_dm_topic_send  s     11(;;G LLL!CDDL55h??tK  
  	%IJJ 	5 MX\\*LMM <227;;	
 
 	
r)   c                      dS )Nz`Telegram DM topic delivery requires a reply anchor; refusing to send outside the requested topicrj   rj   r)   r   _dm_topic_missing_anchor_errorz.TelegramAdapter._dm_topic_missing_anchor_error  s    qqr)   r  r   c                     |rt          |          S |r2|                    d          r|dk    rd S |                     |          S d S )Nr  off)r  r)  r  )r  r  rF  r   s       r   _reply_to_message_id_for_sendz-TelegramAdapter._reply_to_message_id_for_send  s]      	!x==  	?%GHH 	?%%t44X>>>tr)   reply_to_message_idc                    |r|                     d          rx|dk    rd|                     |          iS ||                     |          }|+|                     |          }|dt	          |          dS i S d|                     |          iS |                     |          }|dt	          |          dS d|                     |          iS )aA  Return Telegram send kwargs for forum and direct-message topic routing.

        Supergroup/forum topics use ``message_thread_id``. True Bot API Direct
        Messages topics can opt in with explicit ``direct_messages_topic_id``
        metadata. Hermes-created private-chat topic lanes are marked with
        ``telegram_dm_topic_reply_fallback``. Live replies send the private
        topic thread id together with a reply anchor; synthetic/resumed sends
        without an anchor use ``direct_messages_topic_id`` when metadata has it.
        ``message_thread_id`` alone can render outside the visible lane.

        When ``reply_to_mode`` is ``"off"``, the reply anchor is suppressed for
        DM topic fallback sends while preserving the ``message_thread_id`` so
        the message still lands in the correct topic.
        r  r  r}  N)r}  r  )r)  _message_thread_id_for_sendr  r  r  )r  r   rM  rF  r  r   direct_topic_ids          r   _thread_kwargs_for_sendz'TelegramAdapter._thread_kwargs_for_send  s   .  	U%GHH 	U%%+S-L-LY-W-WXX"*&)&G&G&Q&Q#"*"%"H"H"R"R".-1474H4H   	')H)H)S)STT@@JJ&%),/,@,@   $S%D%DY%O%OPPr)   c                 X    |rt          |          | j        k    rd S t          |          S r$   )r   _GENERAL_TOPIC_THREAD_IDr  r  rM  s     r   r  z+TelegramAdapter._message_thread_id_for_send  s.     	C	NNc.JJJ49~~r)   c                 (    |sd S t          |          S r$   )r  r  s     r   _message_thread_id_for_typingz-TelegramAdapter._message_thread_id_for_typing  s      	49~~r)   r
   c                 H    dt          |                                           v S )Nthread not found)r   rj  )r
   s    r   _is_thread_not_found_errorz*TelegramAdapter._is_thread_not_found_error  s    !SZZ%5%5%7%777r)   c                    ||dS t          | dd          }|dS t          |dd          }|t          |d          sdS 	 |                    t          |          t          |                    }n5# t          $ r( t
                              d| j        ||d           Y dS w xY w|r$t
                              d	| j        ||           dS dS )
uN  Drop the stale ``telegram_dm_topic_bindings`` row for a
        topic Telegram has confirmed deleted.

        Without this prune the recovery logic in
        ``gateway.run._recover_telegram_topic_thread_id`` keeps
        steering future inbound messages to the dead thread (the
        bug behind #31501 — tool progress, approvals, replies all
        end up in the wrong place even though the user has moved
        on to a fresh topic).  Best-effort: we never raise from a
        send-fallback path — a failed cleanup must not turn into a
        failed user-facing send.
        N_session_store_dbdelete_telegram_topic_binding)r   rM  uR   [%s] delete_telegram_topic_binding failed for chat=%s thread=%s — skipping pruneTr   zY[%s] Pruned stale Telegram DM topic binding chat=%s thread=%s (Bot API: thread not found))	rL   hasattrr  r   r   r   r   r   info)r   r   rM  storedbremoveds         r   _prune_stale_dm_topic_bindingz-TelegramAdapter._prune_stale_dm_topic_binding  s    ?i/F.55=FUE4((:WR)HII:F
	66GI 7  GG  	 	 	LL7	7I    
 FF	  	KK@	7I    	 	s   1A4 4.B&%B&c                     | j         j                                        }|dk    s|                    d          rdS 	 ddlm} t          | |          S # t          $ r Y dS w xY w)N
badrequestTr   
BadRequestF)r8  rf   rj  endswithtelegram.errorr  
isinstancer   )r
   r   r  s      r   _is_bad_request_errorz%TelegramAdapter._is_bad_request_error'  s    '--//<4==#>#>4	111111eZ000 	 	 	55	s   A 
A! A!c                 "   |r|                     d          sdS |                     |          sdS t          |                                          |dv rdS |                     d          rd}t	          fd|D                       rdS dS )	u  True when a DM-topic send should be retried with routing stripped.

        Two cases trigger the retry:

        1. The original anchor-stale case — the reply target was deleted, so
           Bot API returns "message to be replied not found". The retry drops
           the reply anchor and the topic id together.

        2. The synthetic-event case (added when #27937 introduced
           ``direct_messages_topic_id`` fallback for sends without an anchor):
           if Bot API rejects the topic id itself with any BadRequest that
           mentions topic/thread routing, we retry without routing rather
           than dropping the message.
        r  FNmessage to be replied not foundTr  )direct_messages_topiczmessage thread not foundr  topic_closedtopic_deletedztopic not foundc              3       K   | ]}|v V  	d S r$   rj   )r   marker	err_lowers     r   r  zNTelegramAdapter._should_retry_without_dm_topic_reply_anchor.<locals>.<genexpr>Z  s(      CC66Y&CCCCCCr)   )r)  r  r   rj  r  )r  r
   rF  r  topic_markersr  s        @r   +_should_retry_without_dm_topic_reply_anchorz;TelegramAdapter._should_retry_without_dm_topic_reply_anchor2  s    *  	X\\*LMM 	5((// 	5JJ$$&&	*/PT]/]/]4 <<233 
	M CCCC]CCCCC tur)   send_fnsend_kwargsmedia_labelreset_mediac                 z  K   	  |di | d{V S # t           $ r}|                     |||          s t                              d| j        ||           |
 |             t          |          }d|d<   |                    dd           |                    dd            |di | d{V cY d}~S d}~ww xY w)zFRetry stale private-topic media replies once without the topic anchor.NzR[%s] Reply target deleted for Telegram %s, retrying without reply/topic anchor: %sr  r}  r  rj   )r   r  r   warningr   dictpop)	r   r  r  rF  r  r  r  send_errretry_kwargss	            r   &_send_with_dm_topic_reply_anchor_retryz6TelegramAdapter._send_with_dm_topic_reply_anchor_retry^  s.     	1 //;///////// 	1 	1 	1CC#  
 NN:	   &,,L26L./0$7777>>> 00<00000000000000)	1s    
B:BB5/B:5B:c                 &   t          | j        dd          r | j        j                            dg           ng }t	          |t
                    r|                    d          }t          |rd                    d |D                       nd          S )zNReturn validated fallback IPs from config (populated by _apply_env_overrides).r(  Nfallback_ipsrf  c              3   4   K   | ]}t          |          V  d S r$   r   r   vs     r   r  z0TelegramAdapter._fallback_ips.<locals>.<genexpr>  s(      -I-Ic!ff-I-I-I-I-I-Ir)   )	rL   r   r(  r)  r  r   rk  r   r   r   
configureds     r   _fallback_ipszTelegramAdapter._fallback_ips  s    BI$+W^`dBeBemT[&**>2>>>km
j#&& 	/#))#..J$Z%aSXX-I-Ij-I-I-I%I%I%I]abbbr)   c                     t          |                                           }| j        j                                        dk    pd|v pd|v S )Nconflictz&terminated by other getupdates requestzanother bot instance is running)r   rj  r8  rf   )r
   r   s     r   _looks_like_polling_conflictz,TelegramAdapter._looks_like_polling_conflict  sQ    5zz!!O$**,,
: 974?90D8	
r)   c                     | j         j                                        }|dv rdS 	 ddlm}m} t          | ||f          rdS n# t          $ r Y nw xY wt          | t                    S )zJReturn True for transient network errors that warrant a reconnect attempt.>   timedoutnetworkerrorconnectionerrorTr   NetworkErrorTimedOut)	r8  rf   rj  r  r  r  r  r   OSError)r
   r   r  r  s       r   _looks_like_network_errorz)TelegramAdapter._looks_like_network_error  s     '--//BBB4	========%,!9:: t 	 	 	D	%)))s   A 
AAc                    t                      }| g}|r|                                }t          |          }||v r*|                    |           |j        j                                        }t          |                                          }d|v sd|v sd|v rdS t          |dd          }t          |dd          }||	                    |           ||	                    |           |dS )	a*  Return True when a Telegram TimedOut wraps a connect-timeout.

        A plain Telegram TimedOut may mean the request reached Telegram and
        should not be re-sent. A ConnectTimeout means the TCP connection was
        never established, so retrying is safe and prevents silent drops.
        connecttimeoutzconnect timeoutzconnect timed outT	__cause__N__context__F
r$  r  rw  addr8  rf   rj  r   rL   r   	r
   seenstackcuridentr   r   causecontexts	            r   _looks_like_connect_timeoutz+TelegramAdapter._looks_like_connect_timeout  s    &+W 	&))++CsGGE}}HHUOOO=)//11Ds88>>##D4''+<+D+DH[_cHcHctCd33Ec=$77G U###"W%%%  	&  ur)   c                    t                      }| g}|r|                                }t          |          }||v r*|                    |           |j        j                                        }t          |                                          }d|v sd|v sd|v rd|v rdS t          |dd          }t          |dd          }||	                    |           ||	                    |           |d	S )
a  Return True when a Telegram TimedOut wraps an httpx pool timeout.

        PTB converts ``httpx.PoolTimeout`` into ``telegram.error.TimedOut`` with
        a message that explicitly states the request was *not* sent
        (``"Pool timeout: All connections in the connection pool are occupied.
        Request was *not* sent to Telegram."``). Because the request never left
        the process, re-sending is safe and cannot duplicate -- the opposite of
        a generic TimedOut, which may have reached Telegram. We match the
        wrapped ``httpx.PoolTimeout`` class as well as the message string so the
        check survives PTB message-wording changes.
        pooltimeoutzpool timeoutzconnection pooloccupiedTr  Nr  Fr  r  s	            r   _looks_like_pool_timeoutz(TelegramAdapter._looks_like_pool_timeout  s    &+W 	&))++CsGGE}}HHUOOO=)//11Ds88>>##D$$$(>(>!T))jD.@.@tCd33Ec=$77G U###"W%%%#  	&$ ur)   Fr  c                 (   t          | j        dd           r| j        j                            |          nd }||S t	          |t
                    r4|                                                                }|dv rdS |dv rdS |S t          |          S )Nr(  >   r   onr^  r_  T>   0nor  falseF)	rL   r   r(  r)  r  r   rb  rj  r'  )r   r  r   r   lowereds        r   r	  z"TelegramAdapter._coerce_bool_extra  s    .5dk7D.Q.Q[!%%c***W[=NeS!! 	kkmm))++G444t555uNE{{r)   c                 b    t          | dd          si S t          dt          d          iS ddiS )Nr
  Flink_preview_optionsT)is_disableddisable_web_page_preview)rL   rW   r   s    r   _link_preview_kwargsz$TelegramAdapter._link_preview_kwargs  sD    t5u== 	I)*,>4,P,P,PQQ*D11r)   contentc                 2    t          |          | j        k    S )a  Cheap pre-check for the one hard rich limit we can count locally.

        Only the 32,768 UTF-8 character text cap is enforced here. Other Bot API
        rich limits (500 blocks, 16 nesting levels, 20 table columns, ...) are
        not pre-counted; if exceeded Telegram returns a BadRequest, which
        :meth:`_is_rich_fallback_error` classifies as permanent so the send
        degrades to the legacy chunking path.
        )lenRICH_MESSAGE_MAX_CHARSr   r  s     r   _content_fits_rich_limitsz)TelegramAdapter._content_fits_rich_limits  s     7||t:::r)   c                 R    t          j        t          | j        dd                    S )u  True when the bound bot can issue raw ``sendRichMessage`` calls.

        Gates on ``do_api_request`` being an *async* callable. The real
        ``telegram.Bot.do_api_request`` is a coroutine function; test doubles
        that opt into rich set it to an ``AsyncMock`` (also a coroutine
        function). Plain ``MagicMock`` bots expose a *sync* auto-child and
        ``SimpleNamespace`` bots lack the attribute entirely — both resolve to
        ``False`` here, so the legacy path is used unchanged.
        do_api_requestN)inspectiscoroutinefunctionrL   r  r   s    r   _bot_supports_richz"TelegramAdapter._bot_supports_rich  s%     *749>NPT+U+UVVVr)   z<details\b[^>]*>.*?</details>z(\$\$.*?\$\$|\\\[.*?\\\]|\\\(.*?\\\)|\\(?:sum|frac|alpha|beta|gamma|delta|theta|lambda|mu|pi|sigma|int|prod|sqrt|lim|infty|begin\{(?:equation|align|matrix|cases)\}))u.   [぀-ヿ㐀-䶿一-鿿가-힯豈-﫿𠀀-𲎯]c                     |sdS | j                             |          D ]}| j                            |          r dS  dS )a  Return True for rich-message details+math content that crashes TDesktop.

        Telegram Desktop 6.9.1 can crash while rendering Bot API 10.1 rich
        messages containing math inside a collapsible details block
        (telegramdesktop/tdesktop#30808). The Bot API accepts the payload, so
        Hermes must skip rich delivery up front and use the legacy MarkdownV2
        path until affected Desktop clients age out.
        FT)_RICH_DETAILS_REfindall_RICH_MATH_IN_DETAILS_REsearch)r   r  details_blocks      r   ._has_telegram_desktop_details_math_crash_shapez>TelegramAdapter._has_telegram_desktop_details_math_crash_shape'  s[      	5!2::7CC 	 	M,33MBB ttur)   c                 T    t          |o| j                            |                    S )as  Return True for CJK content that current TDesktop rich drafts garble.

        Telegram Mac/Desktop Bot API 10.1 rich-message rendering currently
        leaves overlapping draft/overlay glyph artifacts for CJK text (#47653).
        The legacy MarkdownV2 path renders the same text cleanly, so skip rich
        delivery up front until affected clients age out.
        )r'  _RICH_CJK_REr'  r  s     r   +_has_telegram_desktop_cjk_rich_garble_shapez;TelegramAdapter._has_telegram_desktop_cjk_rich_garble_shape7  s(     GA 1 8 8 A ABBBr)   c                     |sdS t          d |                                D                       rdS t          j        d|          rdS t          j        d|          rdS d|v rdS dS )a  Return True for markdown constructs that the legacy path degrades.

        Keep ordinary replies on the pre-rich MarkdownV2 path so Telegram
        clients render a consistent font weight/spacing. The rich endpoint is
        reserved for constructs where raw markdown materially improves output:
        pipe tables (MarkdownV2 has no table syntax and rewrites them into
        bullet lists), GFM task lists, collapsible ``<details>`` blocks, and
        block math.  Adapted from #45995 (@YonganZhang).
        Fc              3   >   K   | ]}t          j        |          V  d S r$   _TABLE_SEPARATOR_REmatchr   lines     r   r  z8TelegramAdapter._needs_rich_rendering.<locals>.<genexpr>M  s.      PP4"(..PPPPPPr)   T(?m)^\s*[-*]\s+\[[ xX]\]\s+3(?m)^<details\b|^</details>|^<summary\b|^</summary>$$r  
splitlinesr   r'  r  s     r   _needs_rich_renderingz%TelegramAdapter._needs_rich_renderingA  s      	5PP7;M;M;O;OPPPPP 	493W== 	49KWUU 	47??4ur)   c                     |r+t          d |                                D                       sdS t          j        d|          rdS t          j        d|          rdS d|v rdS dS )u  True when pipe tables are the only rich construct in *content*.

        Tables are auto-routed to ``sendRichMessage`` even when the full
        ``rich_messages`` opt-in is off — MarkdownV2 has no table syntax and
        the legacy path rewrites them into bullet lists, which reads like a
        regression when users enable Telegram Topics and expect native tables.
        Task lists, ``<details>``, and block math still require the full opt-in.
        c              3   >   K   | ]}t          j        |          V  d S r$   r/  r2  s     r   r  zATelegramAdapter._content_is_pipe_table_primary.<locals>.<genexpr>`  s?       "
 "
04%d++"
 "
 "
 "
 "
 "
r)   Fr4  r5  r6  Tr7  r  s     r   _content_is_pipe_table_primaryz.TelegramAdapter._content_is_pipe_table_primaryW  s      	c "
 "
8?8J8J8L8L"
 "
 "
 
 
 	 593W== 	59KWUU 	57??5tr)   c                 h    t          t          | dd          p|                     |                    S )z2Whether rich delivery is allowed for this payload.r  T)r'  rL   r<  r  s     r   _rich_delivery_enabledz&TelegramAdapter._rich_delivery_enabledl  s:    D2D99 <227;;
 
 	
r)   c                 j   t          |                     |          ot          | dd           o|o}|                                oi|                     |          oT|                     |           o>|                     |           o(|                     |          o|                                           S )a  Capability/content eligibility for rich, ignoring ``expect_edits``.

        Shared core of :meth:`_should_attempt_rich` minus the per-call
        ``expect_edits`` metadata gate.  The rich EDIT-finalize path
        (:meth:`_try_edit_rich`) needs this: a streamed preview is sent with
        ``expect_edits=True`` to stay on the editable path mid-stream, but the
        FINAL edit should still upgrade to rich when the content warrants it.
        r  F)	r'  r>  rL   rb  r9  r)  r,  r  r"  r  s     r   _rich_eligiblezTelegramAdapter._rich_eligibles  s     ''00 *D"7???** * **733	*
 GGPPP* DDWMMM* ..w77* ''))

 

 
	
r)   c                 v    t          |pi                     d           o|                     |                    S )Nexpect_edits)r'  r)  r@  r   r  rF  s      r   _should_attempt_richz$TelegramAdapter._should_attempt_rich  sD     R$$^444 -##G,,
 
 	
r)   c                     dS )uU  Whether to replace a streamed preview with a fresh rich final.

        Disabled for Telegram. The fresh-final path briefly shows two copies of
        the final answer, then deletes the streaming preview after the rich send
        succeeds — it looks like duplicate delivery at the end of every streamed
        turn (the reason #46206 reverted it).  Rich finalize is instead handled
        by editing the existing preview in place via Bot API 10.1's
        ``editMessageText`` ``rich_message`` parameter (see
        :meth:`_try_edit_rich`), so no fresh re-send / delete is needed.
        Frj   rC  s      r   prefers_fresh_final_streamingz-TelegramAdapter.prefers_fresh_final_streaming  s	     ur)   c                     t          | dd          r,t          | dd          s|                                 r| j        S dS )uD  Allow the stream consumer to accumulate up to the rich-message cap
        before splitting, so a reply that fits one ``sendRichMessage`` /
        ``sendRichMessageDraft`` isn't fragmented at the 4,096 MarkdownV2 limit.

        Gated on the same rich capability as the send path (minus the
        content-length check — raising that cap is the whole point): rich not
        latched off and the bot exposes an async ``do_api_request``.  Returns
        ``None`` (→ legacy 4,096 limit) when rich isn't available, so non-rich
        streams split exactly as before.
        r  Tr  FN)rL   r"  r  r   s    r   streaming_overflow_limitz(TelegramAdapter.streaming_overflow_limit  sT     D2D99	/D"7??	/ ''))	/
 ..tr)   )skip_entity_detectionrI  c                6    dt          |          i}|rd|d<   |S )u  Build the ``InputRichMessage`` object from RAW markdown.

        Never pass ``format_message(content)`` here — that converts to
        MarkdownV2 and would escape/destroy rich syntax like table pipes.

        Single newlines are normalized to Markdown hard breaks so that
        multi-line content (slash-command lists, etc.) renders correctly
        in the rich-message path.  See ``_rich_normalize_linebreaks``.
        markdownTrI  )r   )r   r  rI  payloads       r   _rich_message_payloadz%TelegramAdapter._rich_message_payload  s/     $./I'/R/R"S  	4/3G+,r)   excc                 .   |j         j                                        }|dv rdS t          |t          t
          t          f          rdS t          |dd          dk    rdS t          |                                          }d|v sd|v r
d|v sd	|v rdS d
|v S )uf  True ⇒ the rich endpoint itself is unavailable (old PTB/server).

        These latch rich off for the rest of the adapter's life — retrying is
        pointless and would cost a failed roundtrip on every send. Per-message
        rejections (BadRequest from a parser/limit issue) are NOT capability
        errors: the next message may be fine.
        >   invalidtokenendpointnotfoundT
error_codeNi  methodendpointz	not foundzdoes not existzno such method)	r8  rf   rj  r  AttributeErrorr   NotImplementedErrorrL   r   )r   rN  r   ss       r   _is_rich_capability_errorz)TelegramAdapter._is_rich_capability_error  s     }%++--7774cNI7JKLL 	43d++s224HHNNMMZ1__1 0A 5 541$$r)   c                     |                      |          rdS |                     |          rdS t          |                                          }d|v pd|v S )uy  True ⇒ permanent/capability error ⇒ safe to fall back to legacy.

        Conservative on purpose: only clearly-permanent failures (BadRequest,
        capability errors, unknown/unsupported endpoint) qualify. Everything
        else is treated as transient — the rich request may have reached
        Telegram, so we must NOT legacy-resend and risk a duplicate.
        Tunsupportedznot implemented)r  rX  r   rj  )r   rN  rW  s      r   _is_rich_fallback_errorz'TelegramAdapter._is_rich_fallback_error  se     %%c** 	4))#.. 	4HHNN!;%6!%;;r)   c                    |                      |          }|                     |||          }|o.| j        dk    o#t          |o|                    d                    }|p|r|t          |          nd}|r|duo
| j        dk    }	n|                     |d          }	|	r|rt          |          nd}
|                     ||||
| j                  }|r|
|s|                    d          sdS |
|fS )u;  Routing for a single (rich) send — mirrors send()'s index-0 block.

        Returns ``(reply_to_id, thread_kwargs)``, or ``None`` to signal "skip
        rich, let the legacy path handle it" — used for the DM-topic fail-loud
        case so the legacy path stays the single source of the refuse result.
        r  r  Nr   r  r   r  )	r  r  r  r'  r)  r   _should_thread_replyr  r  )r   r   r  rF  rM  metadata_reply_toprivate_dm_topic_senddm_topic_reply_to_offreply_to_sourceshould_threadreply_to_idthread_kwargss               r   _compute_single_send_routingz,TelegramAdapter._compute_single_send_routing  s_    !>>xHH $ > >w	S[ \ \! T#u,TXR(,,/Q"R"RSS 	
 # 
$):)F !""" 	
 ! 	J+47XD<OSX<XMM 55oqIIM.;YYc/***UY44 +- 5 
 
 ! 	[%8AV%8
 !$$%?@@ tM))r)   c                   K   |                      |          }|                     ||||          }|dS |\  }}t          |          |                     |          d}	|	                    d |                                D                        |	                    |                     |                     t          | dd          rddi|	d<   |d	|i|	d
<   	 | j        	                    d|	           d{V }
nz# t          $ rl}|                     |          rC|                     |          rd| _        t                              d| j        |           Y d}~dS t#          |                                          }	 ddlm} n# t*          t,          f$ r d}Y nw xY w|rt/          ||          pd|v }|                     |          }t          |dd          }|Dddl}|                    d||j                  }|r"t9          |                    d                    }t=          |          }t                              d| j        |           tA          d||p| |          cY d}~S d}~ww xY wd}t/          |
tB                    rB|
"                    d	          }|*|
"                    d          pi "                    d	          }nt          |
d	d          }|I	 ddl#m$} |%                    t#          |          t#          |          |           n# t          $ r Y nw xY wtA          d|t#          |          nd          S )a#  Attempt a single ``sendRichMessage`` send.

        Returns a :class:`SendResult` (success, or a transient failure that the
        caller must NOT legacy-resend), or ``None`` to signal "fall back to the
        legacy MarkdownV2 path" (permanent/capability error or DM-topic skip).
        N)r   rich_messagec                     i | ]
\  }}|||S r$   rj   r   kr  s      r   
<dictcomp>z2TelegramAdapter._try_send_rich.<locals>.<dictcomp>0      PPPA!-1---r)   r
  Fr  Tr  
message_idreply_parameterssendRichMessage
api_kwargsuA   [%s] sendRichMessage rejected (%s) — falling back to MarkdownV2r   r  	timed outretry_afterzretry\s+(?:in\s+)?(\d+)   z=[%s] sendRichMessage transient failure (no legacy resend): %s)successr
   r@  ru  rG   rich_sent_storerw  rn  )&r  rf  r   rM  updateitemsrJ  rL   r  r  r   r[  rX  r  r   r   r   r   rj  r  r  r   rU  r  r  r   r'  
IGNORECASEr   r   r   r  rs   r  r)  gatewayry  record)r   r   r  r  rF  rM  routingrd  re  rL  msgrN  err_str	_TimedOut
is_timeoutis_connect_timeout_retry_after_re_m
safe_errorrn  ry  s                         r   _try_send_richzTelegramAdapter._try_send_rich  s!      ,,X66	33GXxQZ[[?4%,"] 2':: 66w??#
 #
 	PP)<)<)>)>PPPQQQt00::;;;41599 	D/<d.CG*+"
 ,8*EG&'0	
 	00!g 1        CC  (	 (	 (	++C00 	11#66 4 04D,WIs   ttttt #hhnn&&G!@@@@@@@0 ! ! ! 			!#B
3	(B(B]{V]G]J!%!A!A#!F!F #3t<<L#    ZZ :GS^TT 6#(!#5#5L4S99JNNO	:    -?Z(	        G(	T 
c4   	:..J!!ggh//52::<HH
 lD99J!333333&&s7||S__gNNNN   *4*@s:d
 
 
 	
s\   "C= =I4AI/ !I/F	I/	FI/FC
I/)I4/I4$7L 
L)(L)rn  c                   K   t          |          t          |          |                     |          d}|                     |          }|                     |||d| j                  }|                    d |                                D                        t          | dd          rddi|d	<   	 | j	        
                    d
|           d{V  n# t          $ r}|                     |          r||                     |          rd| _        dt          |                                          v rt#          d|          cY d}~S t$                              d| j        |           Y d}~dS dt          |                                          v rt#          d|          cY d}~S t          |                                          }		 ddlm}
 n# t.          t0          f$ r d}
Y nw xY w|
rt3          ||
          pd|	v }|                     |          }t7          |          }t$                              d| j        |           t#          d||p|           cY d}~S d}~ww xY w	 ddlm} |                    t          |          t          |          |           n# t          $ r Y nw xY wt#          d|          S )u  Edit an existing message in place as a rich message (Bot API 10.1).

        Uses ``editMessageText`` with the ``rich_message`` parameter so a
        streamed preview can finalize as rich (tables/task lists/details/math)
        WITHOUT a fresh send + delete — no duplicate preview.  Mirrors
        :meth:`_try_send_rich`'s error contract:

        - success → ``SendResult(success=True, message_id=...)``
        - permanent / capability error → ``None`` (caller falls back to the
          legacy MarkdownV2 edit; capability errors latch rich off)
        - transient / unknown → ``SendResult(success=False)`` with retry
          semantics (the message may already be edited; do NOT legacy-resend)
        )r   rn  rh  Nr]  c                     i | ]
\  }}|||S r$   rj   rj  s      r   rl  z2TelegramAdapter._try_edit_rich.<locals>.<dictcomp>  rm  r)   r
  Fr  Tr  editMessageTextrq  not modifiedrz  uK   [%s] rich editMessageText rejected (%s) — falling back to MarkdownV2 editr   rs  rt  zB[%s] rich editMessageText transient failure (no legacy resend): %srw  r
   r@  rx  ) r   r  rM  r  r  r  r{  r|  rL   r  r  r   r[  rX  r  r   rj  rs   r   r   r   r  r  r   rU  r  r  r   r  r~  ry  r  )r   r   rn  r  rF  rL  rM  re  rN  r  r  r  r  r  ry  s                  r   _try_edit_richzTelegramAdapter._try_edit_rich  sq     * 2'::j// 66w??#
 #

 ,,X66	44 $- 5 
 
 	PP)<)<)>)>PPPQQQ41599 	D/<d.CG*+%	 )**+<*QQQQQQQQQQ  	  	  	++C00 11#66 4/3D, "SXX^^%5%555%dzJJJJJJJJJaIs   tttttS!1!111!$:FFFFFFFFF#hhnn&&G!@@@@@@@0 ! ! ! 			!#B
3	(B(B]{V]G]J!%!A!A#!F!F4S99JNNT	:    -?Z        9 	J	//////""3w<<Z'JJJJ 	 	 	D	$:>>>>st   4"C I)#A$I$I)!I$43I$'I)-!I$GI$G,)I$+G,,A2I$I)$I)-7J% %
J21J2c                 ~   t          t          | dd          ot          | dd          ot          | dd           o|t          | dd           oj|oh|                                oT|                     |           o>|                     |           o(|                     |          o|                                           S )Nr  Tr  Fr  r  )r'  rL   rb  r)  r,  r  r"  r  s     r   _should_attempt_rich_draftz*TelegramAdapter._should_attempt_rich_draft  s    D2D99 	*4e<<	*D"7???	* D"8%@@@	* 		*
 	* GGPPP	* DDWMMM	* ..w77	* ''))
 
 	
r)   draft_idc                   K   t          |          t          |          |                     |          d}|                     |          }|t          |          |d<   	 | j                            d|           d{V }t          |          S # t          $ rj}|                     |          r)d| _	        t                              d| j        |           n!t                              d| j        |           Y d}~d	S d}~ww xY w)
u  Emit one ``sendRichMessageDraft`` preview frame; True on success.

        Draft frames are ephemeral and overwritten by the next frame / the
        final ``sendRichMessage``, so a duplicate or lost rich draft is
        harmless — any failure simply returns False and the caller renders the
        legacy plain-text draft. A permanent/capability failure additionally
        latches ``_rich_draft_disabled`` so later frames skip the rich attempt.
        )r   r  rh  Nr}  sendRichMessageDraftrq  TuB   [%s] sendRichMessageDraft unsupported (%s) — using legacy draftsuL   [%s] sendRichMessageDraft transient failure (%s) — legacy draft this frameF)r   r  rM  r  r  r  r'  r   rX  r  r   r   r   )	r   r   r  r  rF  rL  rM  okrN  s	            r   _try_send_rich_draftz$TelegramAdapter._try_send_rich_draft  s6       2'::H 66w??#
 #

 ,,X66	 +.y>>G'(	y//0FSZ/[[[[[[[[B88O 	 	 	--c22 
,0)XIs   
 bIs   55555	s    0B 
DAD  Dc                    K   | j         r| j         j        sdS 	 | j         j        j        d         }n# t          $ r Y dS w xY w	 |                                 d{V  n2# t          $ r% t
                              d| j        d           Y nw xY w	 |                                 d{V  t
                              d| j                   dS # t          $ r& t
                              d| j        d           Y dS w xY w)ur  Reset the httpx connection pool used for getUpdates polling.

        Network errors (especially through proxies like sing-box) can leave
        httpx connections in a half-closed state that still occupy pool slots.
        After enough reconnect cycles the pool fills up entirely, causing
        ``Pool timeout: All connections in the connection pool are occupied.``

        We reset ONLY ``_request[0]`` (the getUpdates request) — the general
        request (``_request[1]``) is left untouched so concurrent
        ``send_message`` / ``edit_message`` calls are never interrupted.

        Implementation note: accesses ``Bot._request[0]`` which is the
        get-updates ``BaseRequest`` in the PTB 22.x internal tuple
        ``(get_updates_request, general_request)``.  There is no public
        accessor for the polling request; review if upgrading to PTB 23+.
        Nr   z0[%s] Polling request shutdown failed (non-fatal)Tr   z2[%s] Polling request pool drained before reconnectz5[%s] Polling request re-initialize failed (non-fatal))	r  rI   rJ   r   rK   r   r   r   
initialize)r   polling_reqs     r   _drain_polling_connectionsz*TelegramAdapter._drain_polling_connections  su     " 	 	dim 	F	 )-03KK 	 	 	FF		&&(((((((((( 	 	 	LLB	D      	
		((*********LLDdi      	 	 	LLG	D       	s0   1 
??A ,BB:C ,C=<C=c                 `    t          | dd           }|t          j                    }|| _        |S )Nr"  )rL   r   r!  r"  )r   locks     r   _get_general_request_drain_lockz/TelegramAdapter._get_general_request_drain_lock7  s1    t:DAA<<>>D/3D,r)   c                   K   t          t          | dd          dd          }|t          | dd          }|dS 	 |j        d         }n# t          $ r Y dS w xY w|                                 4 d{V  	 |                                 d{V  n2# t          $ r% t
                              d| j        d           Y nw xY w	 |                                 d{V  t
          	                    d	| j                   n2# t          $ r% t
                              d
| j        d           Y nw xY wddd          d{V  dS # 1 d{V swxY w Y   dS )a4  Reset the Bot API request pool after a confirmed send pool timeout.

        ``send_message`` uses PTB's general request pool (``_request[1]``).
        When httpx reports that this pool is exhausted, PTB says the request
        was not sent, so it is safe to reset the wedged pool before retrying.
        r  NrI   r  rv  zC[%s] General request shutdown failed after pool timeout (non-fatal)Tr   z=[%s] General request pool drained after Telegram pool timeoutzH[%s] General request re-initialize failed after pool timeout (non-fatal))
rL   rJ   r   r  rK   r   r   r   r  r  )r   rI   general_reqs      r   -_drain_general_connections_after_pool_timeoutz=TelegramAdapter._drain_general_connections_after_pool_timeout>  sW      gdFD115$??;$--C;F	,q/KK 	 	 	FF	7799 	 	 	 	 	 	 	 	!**,,,,,,,,,,   YI      

!,,.........SI       ^I      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	sk   A	 	
AA4E6BE,C =E?C  E:C?>E?,D.+E-D..E
EEreasonc                   | j         rdS | j        r=| j                                        s$t                              d| j        ||           dS d| _        t                              d| j        ||           t          j	                    }|
                    |                     |                    | _        | j                            | j                   | j                            | j        j                   dS )ay  Schedule polling recovery without failing gateway startup.

        A Telegram bootstrap failure (deleteWebhook / initial start_polling)
        caused by a transient network error should degrade only the Telegram
        adapter: the gateway process stays alive and the existing reconnect
        ladder (``_handle_polling_network_error``) recovers in the background.
        NzA[%s] Telegram polling recovery already scheduled; ignoring %s: %sTzR[%s] Telegram polling degraded (%s); gateway stays alive and will retry. Error: %s)has_fatal_errorr  r%   r   r   r   r   r  r   r2   create_task_handle_polling_network_error_background_tasksr   r<   discard)r   r
   r  r,   s       r   _schedule_polling_recoveryz*TelegramAdapter._schedule_polling_recoveryc  s      	F# 	D,D,I,I,K,K 	LLS	65   F#' `Ivu	
 	
 	
 '))#'#3#3D4V4VW\4]4]#^#^ ""4#;<<< 2243I3QRRRRRr)   c                 <  K   | j         sdS t          | j         dd          }t          |          sdS 	  |d           d{V  dS # t          $ rI}|                     |          r.t
                              d| j        |           d| _        Y d}~dS  d}~ww xY w)a3  Clear any stale webhook, but never fail polling on a network error.

        Returns True when the webhook was cleared (or there was nothing to do)
        and False when a transient network error was swallowed so bootstrap can
        continue to polling; the reconnect ladder recovers from there.
        Fdelete_webhookNT)drop_pending_updateszu[%s] deleteWebhook failed with a recoverable network error; continuing to polling so getUpdates/retry can recover: %s)	r  rL   rh  r   r  r   r  r   r   )r   r  errs      r   _delete_webhook_best_effortz+TelegramAdapter._delete_webhook_best_effort}  s       y 	5 ,<dCC'' 	4	 .e<<<<<<<<<<4 		 		 		--c22 PIs  
 ,0(uuuuu		s   A 
B=BBBr  c                  K   | j         r| j         j        st          d          	 | j         j                            t          j        ||           d{V  dS # t          $ r}|                     |          rt          	                    d| j
        |           t          j                    }|                    |                     |                    | _        | j                            | j                   | j                            | j        j                   Y d}~dS |                     |          r|                     |d           Y d}~dS  d}~ww xY w)	a  Start PTB polling; on a transient bootstrap failure, recover in background.

        Returns True when polling started, False when a transient conflict or
        network error was scheduled for background recovery instead of raising
        (keeping the gateway process alive).
        z,Telegram application/updater not initializedallowed_updatesr  error_callbackNTz[[%s] Telegram polling bootstrap conflict; gateway stays alive while conflict retry runs: %sFzpolling bootstrap)r  )r  updaterRuntimeErrorstart_pollingrQ   	ALL_TYPESr   r  r   r  r   r   r2   r  _handle_polling_conflictr  r  r   r<   r  r  r  )r   r  r  r  r,   s        r   _start_polling_resilientz(TelegramAdapter._start_polling_resilient  s      	 	Odi/ 	OMNNN	)#11 & 0%9- 2         
 4 	 	 	0055 
4Is  
 /11+/+;+;D<Y<YZ]<^<^+_+_(&**4+CDDD(::4;Q;YZZZuuuuu--c22 //<O/PPPuuuuu	s$   2A 
E$B9E#,EEEc                   K   | j         rdS d}d}d}| xj        dz  c_        d| _        | j        }||k    rhd|z  }t                              d| j        |t          |                     |                     d	|d
           |                                  d{V  dS t          |d|dz
  z  z  |          }t          |          }t          
                    d| j        ||||           t          j        |           d{V  | j        }		 |	r|	j        r{|	j        j        ro	 t          j        |	j                                        t$                     d{V  n5# t          j        $ r# t          
                    d| j                   Y nw xY wn# t(          $ r Y nw xY w|                                  d{V  	 |	st-          d          |	j                            t0          j        d| j                   d{V  t                              d| j        |           d| _        d| _        | j         sat          j        |                                           }
| j                            |
           |
                     | j        j!                   dS dS # t(          $ r}t          |          }t          
                    d| j        |           | j         smt          j        | "                    |                    }| j                            |           |                     | j        j!                   || _#        Y d}~dS Y d}~dS d}~ww xY w)aK  Reconnect polling after a transient network interruption.

        Triggered by NetworkError/TimedOut in the polling error callback, which
        happen when the host loses connectivity (Mac sleep, WiFi switch, VPN
        reconnect, etc.).  The gateway process stays alive but the long-poll
        connection silently dies; without this handler the bot never recovers.

        Strategy: exponential back-off (5s, 10s, 20s, 40s, 60s cap) up to
        MAX_NETWORK_RETRIES attempts, then mark the adapter retryable-fatal so
        the supervisor restarts the gateway process.
        N
      <   rv  TzXTelegram polling could not reconnect after %d network error retries. Restarting gateway.z[%s] %s Last error: %stelegram_network_errorrB     zK[%s] Telegram network error (attempt %d/%d), reconnecting in %ds. Error: %sr!   z[%s] updater.stop() timed out during network-error reconnect (likely CLOSE-WAIT socket); forcing drain and restart without clean stopz3Telegram application was torn down during reconnectFr  z>[%s] Telegram polling resumed after network error (attempt %d)r   z*[%s] Telegram polling reconnect failed: %s)$r  r  r   r   r
   r   r   rC  _notify_fatal_errorr   r  r   sleepr  r  runningwait_forstop_UPDATER_STOP_TIMEOUTr>   r   r  r  r  rQ   r  r  r  r1   _verify_polling_after_reconnectr  r   r<   r  r  r  )r   r
   MAX_NETWORK_RETRIES
BASE_DELAY	MAX_DELAYattemptr?  delayr  rM   probe	retry_errsafe_retry_errorr   s                 r   r  z-TelegramAdapter._handle_polling_network_error  s<       	F 
	))Q.))#' 3(((&(;<  LL149gGbchGiGijjj!!":Gt!TTT**,,,,,,,,,FJ!!"45yAA077
YIw 3UJ	
 	
 	
 mE""""""""" i	 s{ s{':  "*3;+;+;+=+=G\]]]]]]]]]]]+   NN9 		      	 	 	D	 --/////////3	0 Z"#XYYY+++ & 0%*#? ,         
 KKP	7   12D- (-D$ ' H-d.R.R.T.TUU&**5111''(>(FGGGGGH H  	0 	0 	0:9EENNGTdeee ' 0,66yAA  &**4000&&t'='EFFF ,0(((((((0 0 0 0 0 0	0sP   F "8E F /F
F FF 
FF<CJ 
M"BMMc                   K   d}d}	 	 t          j        |           d{V  | j        rdS | j        r| j        j        nd}|=t          t          |dd                    sdS t          j        |                                |           d{V  | 	                    ||           d{V  n# t           j
        $ r Y dS t           j        t          f$ r}t                              d| j        |           | j        r| j                                        sY d}~t          j                    }|                    |                     |                    | _        Y d}~nd}~wt*          $ r Y nw xY wn)u  Detect dead Telegram TCP sockets (CLOSE-WAIT) by periodic probing.

        PTB's long-poll task blocks on epoll waiting for Telegram to push an
        update.  When the underlying TCP connection enters CLOSE-WAIT (the remote
        sent a FIN but the httpx pool has not yet noticed), epoll still reports
        the socket as readable and no exception is raised — so PTB's
        ``error_callback`` never fires and the gateway silently stops receiving
        messages.

        This loop probes ``get_me()`` every ``HEARTBEAT_INTERVAL`` seconds on the
        *general* request path (not the getUpdates pool), so a healthy long-poll
        waiting for the 30-second Telegram window is never interrupted.  On any
        connect-level failure the loop hands off to
        ``_handle_polling_network_error`` — the same path triggered by PTB's own
        ``error_callback`` — which drains the dead pool and restarts polling.

        Unlike ``_verify_polling_after_reconnect`` (a one-shot probe scheduled
        only after an explicit reconnect), this loop runs for the full lifetime
        of the polling connection, so it catches a socket that wedges during
        steady-state operation without any prior error event.
        Z      TNget_mez>[%s] Polling heartbeat probe failed (%s); triggering reconnect)r   r  r  r  rI   rh  rL   r  r  _probe_pending_updatesr   r>   r  r   r  r   r  r%   r2   r  r  r   )r   HEARTBEAT_INTERVALPROBE_TIMEOUTrI   	probe_errr,   s         r   _polling_heartbeat_loopz'TelegramAdapter._polling_heartbeat_loop6  s     ,  (	'm$6777777777' F'+y:dimmd;  Xt < <== F&szz||]CCCCCCCCC 11#}EEEEEEEEEE)   ('2 
 
 
TIy   + D4L4Q4Q4S4S HHHH/11+/+;+;66yAA, ,((((((     K(	s=   !B. B. B. $A	B. .E1 E1AE!A E!!E10E1probe_timeoutc                   K   | j         rdS | j        r"| j                                        s	d| _        dS | j        rt          | j        dd          nd}|	d| _        dS t          |dd          sd| _        | xj        dz  c_        t                              d| j	        | j                   | j        dk    rtd| _        t                              d	| j	                   t          j                    }|                    |                     t          d
                              | _        dS d| _        t          |dd          }t          |          sdS 	 t          j         |            |           d{V }n# t          j        t$          f$ r Y dS w xY wt'          t          |dd          pd          }|dk    r	d| _        dS | xj        dz  c_        t                              d| j	        || j                   | j        dk    rvd| _        t                              d| j	                   t          j                    }|                    |                     t          d                              | _        dS dS )u  Detect a wedged getUpdates consumer via pending_update_count.

        PTB can report ``updater.running == True`` while its long-poll task is
        silently stuck (e.g. a socket that epoll keeps reporting readable on
        WSL2). ``get_me()`` stays healthy because it uses the general request
        path, so the CLOSE-WAIT heartbeat never fires — yet DMs queue in the
        Bot API and never reach handlers (#42909).

        ``get_webhook_info().pending_update_count`` is the one signal that
        exposes this: a growing/stuck queue while we believe we're polling means
        the consumer is dead. We only escalate after two consecutive stuck
        probes so a single update that's simply in-flight between probes does
        not trip a needless recovery. Recovery reuses
        ``_handle_polling_network_error`` — the same ladder PTB's own
        ``error_callback`` feeds — so no new restart machinery is introduced.

        This also covers the harsher case where the updater has stopped
        entirely (``running=False``) with no reconnect in flight: the long-poll
        task is gone rather than wedged, so even ``get_webhook_info`` can't
        report a queue against a live consumer. We detect the stopped updater
        directly and feed the same ladder (#55769).
        Nr   r  r  Frv  zY[%s] Telegram polling heartbeat: updater stopped while in polling mode (stuck probe %d/2)r  zV[%s] Telegram updater is not running (long-poll task gone); triggering polling restartz.Telegram updater stopped while in polling modeget_webhook_infopending_update_countzX[%s] Telegram polling heartbeat: %d update(s) queued but not consumed (stuck probe %d/2)zX[%s] getUpdates consumer appears wedged (queue not draining); triggering polling restartz8getUpdates consumer wedged: pending updates not draining)r  r  r%   r  r  rL   r  r   r  r   r   r2   r  r  r  rh  r  r>   r  r  )r   rI   r  r  r,   r  r  pendings           r   r  z&TelegramAdapter._probe_pending_updatesy  s     2  	F # 	D,D,I,I,K,K 	./D+F9=L'$)Y555?01D-Fw	511 	 12D-++q0++NN2	4:  
 .!3323/8I  
 /11+/+;+;66$%UVV , ,(
 F*+'"3(:DAA()) 	F	 )*:*:*<*<mLLLLLLLLDD$g. 	 	 	 FF	 gd$:A>>C!DDa<<01D-F))Q.))*Iw A	
 	
 	

 ,1101D-NN-	  
 +--D'+'7'722 ![\\ ( (D$$$ 21s   #E< <FFc                 ^  K   d}d}t          j        |           d{V  | j        rdS | j        r| j        j        r| j        j        j        sKt                              d| j        |           | 	                    t          d                     d{V  dS 	 t          j        | j        j                                        |           d{V  d| _        dS # t          $ rH}t                              d| j        ||           | 	                    |           d{V  Y d}~dS d}~ww xY w)a(  Heartbeat probe scheduled after a successful reconnect.

        PTB's Updater can survive a botched stop()+start_polling() cycle
        with `running=True` but a wedged consumer task. No error callback
        fires, so the reconnect ladder doesn't advance on its own. This
        probe detects the wedge by:

        1. Sleeping HEARTBEAT_PROBE_DELAY so a healthy long-poll has time
           to complete at least one cycle.
        2. Verifying `Updater.running` is still True.
        3. Probing the bot endpoint with a tight asyncio timeout. A
           wedged httpx pool fails this probe; a healthy one returns
           well under the timeout.

        On any failure, re-enter the reconnect ladder so the existing
        MAX_NETWORK_RETRIES path can ultimately escalate to fatal-error.
        r  r  NuC   [%s] Updater not running %ds after reconnect — treating as wedgedz-Updater not running after reconnect heartbeatFz;[%s] Polling heartbeat probe failed %ds after reconnect: %s)r   r  r  r  r  r  r   r  r   r  r  r  rI   r  r   r   )r   HEARTBEAT_PROBE_DELAYr  r  s       r   r  z/TelegramAdapter._verify_polling_after_reconnect  s     $ !#m1222222222 	F	 	di/ 	DI4E4M 	NNU	0   44LMM         F	@"49=#7#7#9#9=IIIIIIIII',D$$$ 	@ 	@ 	@NNM	0)   44Y???????????????	@s   >C 
D,$=D''D,c                    | j         rt          | j         dd          nd}|dS dD ]y}t          ||d          }t          |t          j                  rL|                                s5|                                 t                              d| j	        |            dS zt                              d| j	                   dS )u  Synchronously stop PTB's internal polling retry loop.

        PTB wraps ``getUpdates`` in ``network_retry_loop`` with
        ``max_retries=-1`` (retry forever).  When a ``TelegramError`` (including
        a 409 ``Conflict``) fires, that loop calls our ``error_callback``
        *synchronously*, then sleeps and re-checks ``while is_running()`` before
        polling again.  Our ``error_callback`` only schedules an async recovery
        task (``loop.create_task(...)``) and returns immediately, so PTB's loop
        keeps polling while our handler concurrently runs
        ``stop -> sleep -> start_polling``.  The two polling sessions overlap and
        Telegram returns a fresh 409 — a self-inflicted conflict loop on a
        ~31s cadence.

        The loop is wired with ``is_running=lambda: updater.running`` and a
        private ``stop_event`` (``do_action`` races that event and returns the
        moment it is set).  Setting that event *synchronously inside the
        callback* — before it returns — makes PTB's loop exit on its own next
        tick instead of racing our recovery.  Our async handler then performs
        the real ``await updater.stop()`` (idempotent) followed by
        drain + ``start_polling()``, which builds a fresh ``stop_event`` so the
        restart is not poisoned.

        Best-effort and defensive: PTB names the attribute differently across
        versions (``_Updater__polling_task_stop_event`` via name-mangling), so
        we probe for both spellings.  If neither is found we do nothing and
        fall back to the prior behaviour (async ``updater.stop()`` racing PTB) —
        i.e. we never make things worse than before.

        We deliberately do NOT fall back to flipping ``updater._running``:
        ``stop()`` raises ``RuntimeError`` when ``running`` is already False and
        our recovery handler guards its ``stop()`` call on ``running``, so
        clearing the flag here would skip the real teardown and leave PTB's
        stop_event uncleared — poisoning the subsequent ``start_polling()``.
        The stop_event lever leaves ``_running`` True, so the handler's
        ``await updater.stop()`` still runs, drains the polling task, and clears
        the event for a clean restart.
        r  N)!_Updater__polling_task_stop_event_polling_task_stop_eventz+[%s] Disarmed PTB polling retry loop via %szu[%s] Could not disarm PTB polling retry loop (stop_event not found on this PTB version); falling back to async stop())
r  rL   r  r   Eventis_setr$  r   r   r   )r   r  attr
stop_events       r   _disarm_ptb_retry_loopz&TelegramAdapter._disarm_ptb_retry_loop	  s    L :>L'$)Y555?F
 	 	D !$55J*gm44 !((** NN$$$LLE	4    	+ I		
 	
 	
 	
 	
r)   c           
      V  K   | j         r| j        dk    rd S | xj        dz  c_        d}d| j        dz  z   }| j        |k    rt                              d| j        | j        |||           	 | j        r| j        j        r| j        j        j        rt	 t          j
        | j        j                                        t                     d {V  n5# t          j        $ r# t                              d| j                   Y nw xY wn# t          $ r Y nw xY wt          j        |           d {V  |                                  d {V  | j        }	 |st#          d          |j                            t&          j        d	| j        
           d {V  t                              d| j        | j        |           d| _        d S # t          $ r}t                              d| j        | j        ||           | j        |k     rFt          j                    }|                    |                     |                    | _        Y d }~d S Y d }~nd }~ww xY wd|t7          d t9          d|dz             D                       fz  }t                              d| j        ||           | j         o
| j        dk    }|                     d|d	           	 | j        rI| j        j        r=t          j
        | j        j                                        t                     d {V  nj# t          j        $ r# t                              d| j                   Y n9t          $ r-}	t                              d| j        |	d           Y d }	~	nd }	~	ww xY w|s|                                  d {V  d S d S )Ntelegram_polling_conflictrv  r  r  u   [%s] Telegram polling conflict (%d/%d) — previous session still held open on Telegram's servers. Waiting %ds for it to expire. Error: %sr  zZ[%s] updater.stop() timed out during conflict retry (likely CLOSE-WAIT socket); continuingz<Telegram application was torn down during conflict reconnectFr  z8[%s] Telegram polling resumed after conflict retry %d/%dr   zF[%s] Telegram polling retry %d/%d failed: %s. Scheduling next attempt.aH  Telegram polling could not recover after %d retries (%ds total wait). The previous gateway session is still held open on Telegram's servers, or another process is using the same bot token. To recover: ensure no other Hermes or OpenClaw instance is running with this token, then restart the gateway with 'hermes gateway restart'.c              3   &   K   | ]}d |d z  z   V  dS )r  Nrj   )r   is     r   r  z;TelegramAdapter._handle_polling_conflict.<locals>.<genexpr>	  s*      (a(aa"f(a(a(a(a(a(ar)   z[%s] %s Original error: %srB  zv[%s] updater.stop() timed out after exhausting conflict retries (likely CLOSE-WAIT socket); proceeding to fatal notifyzK[%s] Failed stopping Telegram updater after exhausting conflict retries: %sTr   ) r  fatal_error_coder  r   r  r   r  r  r  r   r  r  r  r>   r   r  r  r  r  rQ   r  r  r  r2   r  r  r  sumranger
   rC  r  )
r   r
   MAX_CONFLICT_RETRIESRETRY_DELAYrM   r  r,   r?  _already_fatal
stop_errors
             r   r  z(TelegramAdapter._handle_polling_conflictK	  s      	D$9=X$X$XF$ 	$$)$$ 
 D82=>'+???NN 	479MU  9 !2 ty7H7P %.ty/@/E/E/G/GQfggggggggggg"/   K I         -,,,,,,,,,11333333333 )C% g&'efffk//$*$4).#'#C 0         
 NIt;=Q   01,   /It;=Q	   /2FFF #355D/3/?/?55i@@0 0D, FFFFF GFFFF:W
 $S(a(aeAG[^_G_>`>`(a(a(a%a%abc 	 	(Iw	
 	
 	
   E%)DD 	 	97eTTT	y `TY. `&ty'8'='='?'?I^__________# 	 	 	NNQ	    
  	 	 	NN]	:         	
  	-**,,,,,,,,,,,	- 	-so   ,$D =C D /D>D  DD 
DDA1G 
IA3IIAL! !/N	N#NN
icon_coloricon_custom_emoji_idc                 ,  K   | j         sdS 	 ||d}|||d<   |r||d<    | j         j        di | d{V }|j        }t                              d| j        |||           |S # t          $ r}t          |                                          }	d|	v sd|	v r#t                              d| j        ||           nNd	|	v sd
|	v r#t          	                    d| j        ||           n#t          	                    d| j        |||           Y d}~dS d}~ww xY w)zCreate a forum topic in a private (DM) chat.

        Uses Bot API 9.4's createForumTopic which now works for 1-on-1 chats.
        Returns the message_thread_id on success, None on failure.
        N)r   r   r  r  z5[%s] Created DM topic '%s' in chat %s -> thread_id=%stopic_name_duplicatealreadyzT[%s] DM topic '%s' already exists in chat %s (will be mapped from incoming messages)znot a forumforums_disabledz[%s] Cannot create DM topic '%s' in chat %s: Topics mode is not enabled. The user must open the DM with this bot in Telegram, tap the bot name at the top, and enable 'Topics' in chat settings before topics can be created.z2[%s] Failed to create DM topic '%s' in chat %s: %srj   )
r  create_forum_topicr}  r   r  r   r   r   rj  r  )
r   r   r   r  r  kwargstopicrM  r   
error_texts
             r   _create_dm_topicz TelegramAdapter._create_dm_topic	  s      y 	4#	18$%G%GF%'1|$# F1E-.6$)6@@@@@@@@@@E/IKKG	4)    	 	 	QJ &33yJ7N7NjItW    *,,0AZ0O0Oe ItW	    HItWa   44444+	s   AA$ $
D.BDDparent_chat_idc                    K   	 t          |          }n# t          t          f$ r Y dS w xY w|                     ||           d{V }|rt	          |          ndS )a	  Create a forum topic for a session handoff.

        Works for DM topics (Bot API 9.4+, requires user to enable Topics
        in their chat with the bot) and forum supergroups. Returns the
        ``message_thread_id`` as a string, or ``None`` on failure.
        N)r   )r  r   r   r  r   )r   r  r   chat_id_intrM  s        r   create_handoff_threadz%TelegramAdapter.create_handoff_thread
  s      	n--KK:& 	 	 	44	//$/GGGGGGGG	!*4s9~~~4s    ))
topic_nameforce_createc                 d  K   t          |pd                                          }|sdS 	 t          |          }n# t          t          f$ r Y dS w xY w| d| }| j                            |          }|r|st          |          S d}d}	| j        D ]n}
t          |
                    d                    t          |          k    r6|
}	|
                    dg           D ]}|                    d          |k    r|} n  |rE|                    d          r0|s.t          |d                   }|| j        |<   t          |          S |	|g d}	| j                            |	           |-d|i}|		                    dg                               |           | 
                    |||                    d	          |                    d
                     d{V }|sdS ||d<   t          |          | j        |<   |                     ||t          |          |           t          |          S )zJReturn a private DM topic thread id, creating and persisting it if needed.r   N:r   topicsr   rM  r   r  r  r  )r   r  r  )replace_existing)r   rb  r  r   r   r#  r)  r-  r   
setdefaultr  _persist_dm_topic_thread_id)r   r   r  r  r   r  	cache_keycached
topic_conf
chat_entryentry	candidaterM  s                r   ensure_dm_topiczTelegramAdapter.ensure_dm_topic#
  s     :#$$**,, 	4	g,,KK:& 	 	 	44	 #++T++	$$Y// 	, 	v;;/3
/3
+ 	 	E599Y''((C,<,<<<J"YYx44  	==((D00!*JE 1  	"*..55 	"l 	"J{344I)2DOI&y>>!%0B??J"))*555 $J!!(B//66zBBB//!~~l33!+0F!G!G	 0 
 
 
 
 
 
 
 
	  	4"+
;%(^^	"((dC	NN]i(jjj9~~s   ; AAc                   K   | j         sdS 	 t          |          }n# t          t          f$ r |}Y nw xY w| j                             |t          |          |           d{V  t
                              d| j        |||           dS )z,Rename a forum topic in a private (DM) chat.N)r   r}  r   z5[%s] Renamed DM topic in chat %s thread_id=%s -> '%s')r  r  r   r   edit_forum_topicr   r  r   )r   r   rM  r   chat_id_args        r   rename_dm_topiczTelegramAdapter.rename_dm_topicX
  s       y 	F	"g,,KK:& 	" 	" 	"!KKK	"i((!)nn ) 
 
 	
 	
 	
 	
 	
 	
 	

 	CIw	4	
 	
 	
 	
 	
s    33r  c                    	 ddl m}  |            dz  }|                                s#t                              d| j        |           dS ddl}t          |dd          5 }|                    |          pi }	ddd           n# 1 swxY w Y   |		                    d	i           }
|
	                    d
i           }|	                    di           }|	                    dg           }d}d}|D ]}	 t          |                    dd                    t          |          k    }n# t          t          f$ r d}Y nw xY w|sT|}|	                    dg           D ]T}|                    d          |k    r9|s|                    d          s |                    d          |k    r||d<   d} n/U|	                    dg                               ||d           d} ||                    |||dgd           d}|r9ddlm}  |||	dd           t                              d| j        ||           dS dS # t$          $ r.}t                              d| j        |d           Y d}~dS d}~ww xY w)zTSave a newly created thread_id back into config.yaml so it persists across restarts.r   get_hermes_homeconfig.yamlz:[%s] Config file not found at %s, cannot persist thread_idNrutf-8encoding	platformsr   r(  r   Fr   r  r   rM  T)r   rM  r  )atomic_config_write)default_flow_style	sort_keysz9[%s] Persisted thread_id=%s for topic '%s' in config.yamlz.[%s] Failed to persist thread_id to config: %sr   )hermes_constantsr  existsr   r  r   yamlopen	safe_loadr  r  r)  r   r   r   hermes_cli.configr  r  r   )r   r   r  rM  r  r  config_path_yamlfr   r  telegram_configr(  r   changedmatching_chat_entryr  chat_matchestr  r   s                        r   r	  z+TelegramAdapter._persist_dm_topic_thread_ido
  s   @	j888888)/++m;K%%'' []a]fhsttt    k3999 2Q++1r2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ))+r::I'22:rBBO#..w;;E((b99IG"&'  
)#&z~~i'C'C#D#DG#TLL!:. ) ) )#(LLL)# &0##..x<< # #AuuV}}
22+ /1553E3E / uu[11Y>>1:+*. 3 ))(B77>>!+)DD   #G"*  &(2KKL" "     AAAAAA##',#	    OIy*       	j 	j 	jNNKTYXYdhNiiiiiiiii	jsh   AH< H< "B:H< B

H< B
A#H< 24D'&H< 'D=:H< <D==C;H< <
I4#I//I4c           	        K   | j         sdS | j         D ]}|                    d          }|                    dg           }|r|s3t                              d| j        t          |          |           |D ]}|                    d          }|s| d| }|                    d          }|r:t          |          | j        |<   t                              d| j        ||           s|                    d	          }|                    d
          }	|                     t          |          |||	           d{V }
|
r|
| j        |<   t                              d| j        ||
           | 
                    t          |          ||
           	 | j                            t          |          |
d|            d{V  Q# t          $ r-}t                              d| j        ||           Y d}~d}~ww xY wdS )u  Load or create configured DM topics for specified chats.

        Reads config.extra['dm_topics'] — a list of dicts:
        [
            {
                "chat_id": 123456789,
                "topics": [
                    {"name": "General", "icon_color": 7322096, "thread_id": 100},
                    {"name": "Accessibility Auditor", "icon_color": 9367192, "skill": "accessibility-auditor"}
                ]
            }
        ]

        If a topic already has a thread_id in the config (persisted from a previous
        creation), it is loaded into the cache without calling createForumTopic.
        Only topics without a thread_id are created via the API, and their thread_id
        is then saved back to config.yaml for future restarts.
        Nr   r  z*[%s] Setting up %d DM topic(s) for chat %sr   r  rM  z4[%s] DM topic loaded from config: %s -> thread_id=%sr  r  )r   r   r  r  z([%s] DM topic cached: %s -> thread_id=%su   📌 )r   r}  r   z2[%s] Could not send seed message to topic '%s': %s)r-  r)  r   r  r   r  r  r#  r  r   r	  r  send_messager   r   )r   r  r   r  r  r  r
  existing_thread_idr  
icon_emojirM  seed_errs               r   _setup_dm_topicsz TelegramAdapter._setup_dm_topics
  s     & % 	F0 <	 <	J nnY//G^^Hb11F & KK<	3v;;  
 % 1 1
'^^F33
! &5555	 &0^^K%@%@"% 145G1H1HDOI.KKN	9.@    (^^L99
'^^,BCC
"&"7"76w??#))3	 #8 # #      	  1:DOI.KKB	9i  
 44S\\:yYYY
"i44$>w$G$G.7!;z!;!; 5          
 %   P Iz8       #91<	 <	s   3G
G?"G::G?c                     | j         }|r|                                sdS t          j        |                                           | _         dS )zKick off deferred post-connect housekeeping in the background.

        Idempotent: if a previous housekeeping task is still running (e.g. a
        rapid reconnect), it is left in place rather than double-scheduled.
        N)r7  r%   r   r1   _run_post_connect_housekeeping)r   r   s     r    _start_post_connect_housekeepingz0TelegramAdapter._start_post_connect_housekeeping  sR     & 			 	F")"7//11#
 #
r)   c           	        K   	 	 ddl mm}m}m} ddlm}m} | j        s&	 | j	        t          j                    u r	d| _	        dS dS  |            } ||          \  }}fd|D             }	|||fD ]}
t          |
dt          |
                    }	 | j                            |	 |
                       d{V  t                              d	| j        |t%          |	                     {# t&          $ r,}t                              d
| j        ||           Y d}~d}~ww xY w|r0t                              d| j        t%          |          ||           n:# t&          $ r-}t                              d| j        |d           Y d}~nd}~ww xY w	 |                     d           d{V  n# t&          $ r Y nw xY w	 |                                  d{V  n:# t&          $ r-}t                              d| j        |d           Y d}~nd}~ww xY wn# t          j        $ r  w xY w| j	        t          j                    u r	d| _	        dS dS # | j	        t          j                    u rd| _	        w xY w)u   Register the command menu, surface the status indicator, and set up
        DM topics — all off the connect path so a slow Bot API call cannot blow
        the gateway connect timeout (#46298). Every step is non-fatal.r   )
BotCommandBotCommandScopeAllPrivateChatsBotCommandScopeAllGroupChatsBotCommandScopeDefaulttelegram_menu_commandstelegram_menu_max_commandsNmax_commandsc                 .    g | ]\  }} ||          S rj   rj   r   r   descr9  s      r   
<listcomp>zBTelegramAdapter._run_post_connect_housekeeping.<locals>.<listcomp>3  )    WWW:4

4 6 6WWWr)   rf   scopez.[%s] set_my_commands OK for scope %s (%d cmds)z,[%s] set_my_commands FAILED for scope %s: %szc[%s] Telegram menu: %d commands registered, %d hidden (over %d limit). Use /commands for full list.z1[%s] Could not register Telegram command menu: %sTr   onlinez+[%s] DM topics setup failed (non-fatal): %s)r   r9  r:  r;  r<  hermes_cli.commandsr>  r?  r  r7  r   current_taskrL   r   set_my_commandsr   r  r   r  r   r  _set_status_indicatorr4  r   )r   r:  r;  r<  r>  r?  rA  menu_commandshidden_countbot_commands	scope_cls
scope_name	scope_errr   
topics_errr9  s                  @r   r6  z.TelegramAdapter._run_post_connect_housekeeping  s     F	/+            cbbbbbbby p &'*>*@*@@@*.''' A@e  :9;;.D.DR^._._._+|WWWWWWW #9:XZv!w y yI!(JI!O!OJy"i77IIKK7XXXXXXXXX$TVZV_akmpq}m~m~$ y y y'UW[W`blnwxxxxxxxxy   KK}	3}#5#5|\      GI!	         000==========   ++----------   AIzD         
 % 	 	 		 &'*>*@*@@@*.''' A@t&'*>*@*@@@*.'....s   E AE AC.-E .
D$8"DE D$$5E H 
F$#FH FH F2 1H 2
F?<H >F??H G H 
H(#HH HH I H**I #I5)is_reconnectrV  c                   $%K   t           s"t                              d j                   dS  j        j        s"t                              d j                   dS 	                      d j        j        d          sdS t          j                                         j        j                  } j        j	        
                    d          }|ri|                    |          }|                     j        j	        
                    d|                    }t                              d j        |            j        j	        
                    d	          r5|                    d
          }t                              d j                   dt          dt           dt           fd}dt          dt"          dt"          fd} |dd           |dd           |dd           |dd           |dd          d}ddlm}  |            }|-ddl}	|	                    |d         |j        |j                  $nd$dWd t0          t2                   dt2          f$fd!}
t5          j        d"d#                                                                          d$v }                                 }|sht                              d% j                   tA                       d{V }t                              d& j        d'!                    |                     d(g|}tE          d)|*          }|r||sz|sxt                              d+ j        d'!                    |                     i }$$|d,<   tG          dXi |d d-tI          |fi |ii}tG          dXi |d d-tI          |fi |ii}n|rTt                              d. j        |           tG          dXi || |
            d/}tG          dXi || |
            d/}nR|r t                              d0 j                   tG          dXi |d  |
            i}tG          dXi |d  |
            i}|%                    |          &                    |          }|'                                 _(         j(        j)         _*         j(        +                    tY          tZ          j.        tZ          j/         z   j0                              j(        +                    tY          tZ          j/         j1                              j(        +                    tY          tZ          j2        tg          tZ          d1tZ          j2                  z   j4                              j(        +                    tY          tZ          j5        tZ          j6        z  tZ          j7        z  tZ          j8        z  tZ          j9        j:        z  tZ          j;        j:        z   j<                              j(        +                    t{           j>                             	 dd2l?m@}mA} n# t          $ r t          x}}Y nw xY wd3} |d4d5          }t          |          D ]_}	 t                              d6 j        |d7z   |           t           j(        F                                | j(        fd89           d{V   n# t          jH        $ rx ||d7z
  k     rUt          d:|z  d;          }t                              d< j        |d7z   |||           t          jJ        |           d{V  nt          d=| d>|d?d@          Y ||t          f$ rj}||d7z
  k     rUt          d:|z  d;          }t                              dA j        |d7z   |||           t          jJ        |           d{V  n Y d}~Yd}~ww xY w j(        K                                 d{V  t5          j        dBd#                                          }|rt          dCdD          }t5          j        dEd#                                          }|st          dF          ddGlNmO}  ||          jP        pdH} j(        jQ        R                    dI||||t          jT        | J           d{V  d
 _U        t                              dK j        ||           n V                                 d{V  t          jW                    %dLt          ddf% fdM}| _Y         Z                    | |N           d{V }|s t                              dO j                    [                                  jU        rdPndQ} t                              dR j        |             jU        sd j\        r2 j\        ]                                s j\        ^                                 t          j_         `                                           _\         a                                 d
S # t          $ rl}! b                                 t          |!          }"dS|" }# d                    dT|#d
U           t                              dV j        |"           Y d}!~!dS d}!~!ww xY w)Yu`  Connect to Telegram via polling or webhook.

        By default, uses long polling (outbound connection to Telegram).
        If ``TELEGRAM_WEBHOOK_URL`` is set, starts an HTTP webhook server
        instead.  Webhook mode is useful for cloud deployments (Fly.io,
        Railway) where inbound HTTP can wake a suspended machine.

        ``is_reconnect`` distinguishes a cold first boot (False — drop any
        stale Bot API queue) from a watcher reconnect after a prolonged
        outage (True — preserve the updates Telegram queued while the bot
        was offline, otherwise every message sent during the outage is
        silently lost). The in-process network-error ladder and the
        409-conflict handler already pass ``drop_pending_updates=False``
        for the same reason; bootstrap follows suit on the reconnect path.

        Env vars for webhook mode::

            TELEGRAM_WEBHOOK_URL    Public HTTPS URL (e.g. https://app.fly.dev/telegram)
            TELEGRAM_WEBHOOK_PORT   Local listen port (default 8443)
            TELEGRAM_WEBHOOK_SECRET Secret token for update verification
        zL[%s] python-telegram-bot not installed. Run: pip install python-telegram-botFz[%s] No bot token configuredztelegram-bot-tokenzTelegram bot tokenr   base_file_urlz'[%s] Using custom Telegram base_url: %s
local_modeTz5[%s] Using Telegram local_mode (read files from disk)r   r   r   c                     	 t          t          j        | t          |                              S # t          t
          f$ r |cY S w xY wr$   )r  r   r   r   r   r   r   r   s     r   _env_intz)TelegramAdapter.connect.<locals>._env_int  sP    #rys7||<<===!:. # # #"NNN#   .1 AAc                     	 t          t          j        | t          |                              S # t          t
          f$ r |cY S w xY wr$   )r   r   r   r   r   r   r[  s     r   
_env_floatz+TelegramAdapter.connect.<locals>._env_float  sP    # 4W!>!>???!:. # # #"NNN#r]  HERMES_TELEGRAM_HTTP_POOL_SIZEi   !HERMES_TELEGRAM_HTTP_POOL_TIMEOUTg       @$HERMES_TELEGRAM_HTTP_CONNECT_TIMEOUTg      $@!HERMES_TELEGRAM_HTTP_READ_TIMEOUTg      4@"HERMES_TELEGRAM_HTTP_WRITE_TIMEOUT)connection_pool_sizepool_timeoutconnect_timeoutread_timeoutwrite_timeoutr   )platform_httpx_limitsNre  )max_connectionsmax_keepalive_connectionskeepalive_expiryhttpx_kwargsc                 @    t          | pi           }	d|vr|d<   |S )u  Merge tuned keepalive limits into httpx client kwargs.

                Used by the proxy and direct-DNS branches, where httpx honours
                the client-level ``limits`` kwarg. A caller-supplied ``limits``
                is left untouched; otherwise the CLOSE_WAIT-safe limits are
                injected. The fallback-IP branch does NOT use this helper — see
                the ``_transport_kwargs`` note below for why.
                Nlimits)r  )rn  r  _pool_limitss     r   _with_limitsz-TelegramAdapter.connect.<locals>._with_limits  s6     l0b11+0F0F'3F8$r)   $HERMES_TELEGRAM_DISABLE_FALLBACK_IPSr   >   r   r  r^  r_  u@   [%s] Discovering Telegram API fallback IPs via DNS-over-HTTPS…z.[%s] Auto-discovered Telegram fallback IPs: %sz, zapi.telegram.orgTELEGRAM_PROXY)target_hostsz%[%s] Telegram fallback IPs active: %srp  	transportz;[%s] Proxy detected; passing explicitly to HTTPXRequest: %s)proxyrn  z4[%s] Telegram fallback-IP transport disabled via envVENUEr     HERMES_TELEGRAM_INIT_TIMEOUT      >@u.   [%s] Connecting to Telegram (attempt %d/%d)…rv  c                      t          |           S r$   )rP   )rM   s    r   <lambda>z)TelegramAdapter.connect.<locals>.<lambda>N  s    9PQT9U9U r)   )r!   r    r  r  uD   [%s] Connect attempt %d/%d timed out after %.0fs — retrying in %dsz(Telegram initialization timed out after z attempts (z.0fzus each). Check network connectivity to api.telegram.org or set HERMES_TELEGRAM_HTTP_CONNECT_TIMEOUT to a lower value.u9   [%s] Connect attempt %d/%d failed: %s — retrying in %dsTELEGRAM_WEBHOOK_URLTELEGRAM_WEBHOOK_PORTi   TELEGRAM_WEBHOOK_SECRETu  TELEGRAM_WEBHOOK_SECRET is required when TELEGRAM_WEBHOOK_URL is set. Without it, the webhook endpoint accepts forged updates from anyone who can reach it — see https://github.com/NousResearch/hermes-agent/security/advisories/GHSA-3vpc-7q5r-276h.

Generate a secret and set it in your .env:
  export TELEGRAM_WEBHOOK_SECRET="$(openssl rand -hex 32)"

Then register it with Telegram when setting the webhook via setWebhook's secret_token parameter.)urlparsez	/telegramz0.0.0.0)listenporturl_pathwebhook_urlsecret_tokenr  r  z-[%s] Webhook server listening on 0.0.0.0:%d%sr
   c                    j         rj                                         sd S                     |           r                                                                         |                     _         j                            j                    j                             j        j	                   d S 
                    |           rt                              dj        |                                                    |                     _         j                            j                    j                             j        j	                   d S t                              dj        | d           d S )Nz5[%s] Telegram network error, scheduling reconnect: %sz[%s] Telegram polling error: %sTr   )r  r%   r  r  r  r  r  r   r<   r  r  r   r  r   r  r
   )r
   r,   r   s    r   _polling_error_callbackz8TelegramAdapter.connect.<locals>._polling_error_callback  sp   / 8P8U8U8W8W 88?? i 33555373C3CDDaDabgDhDh3i3i0.2243KLLL0BB4CYCabbbbb77>> i'^`d`ikpqqq373C3CDDfDfglDmDm3n3n0.2243KLLL0BB4CYCabbbbb%F	SXcghhhhhr)   )r  r  ze[%s] Connected in degraded Telegram mode: gateway is alive, polling will be retried in the backgroundwebhookpollingz$[%s] Connected to Telegram (%s mode)zTelegram startup failed: telegram_connect_errorrB  z&[%s] Failed to connect to Telegram: %sr$   rj   )er   r   r
   r   r   token_acquire_platform_lockrY   builderr(  r)  r   rX  r  rY  r   r  r   %gateway.platforms._http_client_limitsrj  httpxLimitsrl  rm  r   r  r   r   rb  rj  r  r  r   r   ry   rc   r   rO   get_updates_requestbuildr  rI   r  add_handlerr   r^   TEXTCOMMAND_handle_text_message_handle_commandLOCATIONrL   _handle_location_messagePHOTOVIDEOAUDIOVOICEDocumentALLSticker_handle_media_messager[   _handle_callback_queryr  r  r  r   r  r  rC   r  r   r>   r   r  r8   r   r  urllib.parser  pathr  start_webhookrQ   r  r  r  r2   r   r  r  r:  r  r%   r;   r1   r  r7  _release_platform_lockr   rC  )&r   rV  r  custom_base_urlr\  r_  request_kwargsrj  _base_limits_httpxrr  disable_fallbackr  proxy_targets	proxy_url_transport_kwargsrO   r  r  r  _max_connect_init_timeout_attemptr9   init_errr  webhook_portwebhook_secretr  webhook_pathr  polling_startedmoder   r  r?  rq  r,   s&   `                                   @@r   connectzTelegramAdapter.connectf  sQ     , " 	LL^	   5{  	LL7CCC5j	../CT[EVXlmm u ")++11$+2CDDG"k/33J??O !**?;;!//K%))/?KK  =I   { $$\22 `!,,T22SUYU^___
#s #S #S # # # ## #u # # # # # )11QSV(W(W *
+NPS T T#-:.TVZ#[#[ *
+NPT U U!+,PRV!W!W N( TSSSSS0022L'&&&&%}}$23I$J.:.T%1%B  -      $ 8D> T       !#	*PRT U U [ [ ] ] c c e e  jD  !D--//L acgclmmm%:%<%<<<<<<<DIIIl++   0?,?M)*:WWWI 0I 06F 0;IIIl++   +-!+2>%h/&  $  $%>(& &,=& &"   '3 ' '$' ' $%>(& &,=& &"' ' '##  Y[_[dfoppp&  $,5LLNN    '3 ' '$',5LLNN' ' ' '## $ cKK VX\Xabbb&UUUUllnnUUU&2 ' '$' '3?<>>' ' '# oog..BBCVWWGDI	DI I!!"8//)# #    I!!"8$# #    I!!"8 77GW=M#N#NN-# #    I!!"8-=MPWP`Pddgngvgzz*# #   
 I!!"6t7R"S"STTT
2AAAAAAAAA 2 2 2*11xxx2L&J'EtLLM!,// ) )(NNH	8a<   6	,,.. - /3i#U#U#U
 
 
 
 
 
 
 
 
 
 E+   ,"222"1="55b Ix!|\=RV   &mD1111111111%]| ] ] -k] ] ]   21 %h8 	 	 	,"222"1="55W Ix!|\8T   &mD1111111111 21111	 )//######### )$:B??EEGGK a  ''>EE!#+Db!I!I!O!O!Q!Q% &	K   211111'x449H[i'55$%) +!/$*$4
 .:)9 6          &*"CI|\    66888888888/11i9 i i i i i i i i0 4K0(,(E(E .:)9#: )F ) ) # # # # # # ' NND	     """ $ 2A99	DKK>	4PPP
 % / :8T8Y8Y8[8[ :077999/6/D00220 0, 113334 	 	 	'')))4Q77J>*>>G!!":Gt!TTTLLA49jYYY55555	s~   !h V$h &X/ .h /Yh Y#h )A[h B_h _A^>8h >_Ih 
j
A!jj
rJ  c                 j  K   t          | dd          sdS | j        }|dS |r| j        n| j        }|dd         }	 |                    |           d{V  t
                              d| j        |           dS # t          $ r-}t
          	                    d| j        ||           Y d}~dS d}~ww xY w)u]  Set the bot's short description to the online/offline status text.

        The short description is the line shown under the bot's name in its
        profile. It is the closest Bot API surface to a presence indicator —
        bots have no real online/offline dot (that's a user-account feature).

        No-op unless ``extra.status_indicator`` is enabled. Best-effort: any
        failure is logged at debug and swallowed so it never blocks connect or
        disconnect. The default (no language_code) description applies to every
        user who doesn't have a language-specific one set.
        r*  FNx   )short_descriptionz#[%s] Set bot status indicator to %rz1[%s] Failed to set bot status indicator to %r: %s)
rL   r  r+  r,  set_my_short_descriptionr   r  r   r   r   )r   rJ  rI   r   r   s        r   rN  z%TelegramAdapter._set_status_indicator  s      t8%@@ 	Fi;F+1Pt''t7PDSDz	...FFFFFFFFFKK=ty$OOOOO 	 	 	LLC	4        	s   =A; ;
B2"B--B2c                   K   t          j                    g g t                      dt          t           j                 ddffd}t          | j                                                  D ]} ||           t          | j                                                  D ]} ||           t          | j	                                                  D ]} ||            || j
                   D ]}|                                 rt          j        ddi d{V  | j                                         | j                                         | j                                         | j                                         | j	                                         | j                                         | j
        ur	d| _
        dS dS )a  Cancel every delayed-delivery task family before disconnect completes.

        Covers media-group, photo-batch and text-batch flush tasks plus the
        polling-error recovery task. Each sits behind an ``asyncio.sleep()``;
        if teardown leaves them running they dispatch ``handle_message`` into a
        torn-down session. Skips the current task so the coroutine driving
        teardown does not cancel itself.
        r   r   Nc                 <   | r|                                  s| u rd S t          |           }|v rd S                     |                               |            t	          j        |           st	          j        |           r                    |            d S d S r$   )r%   rw  r   r   r   rF   rE   )r   r  awaitable_tasksrL  pending_tasksr  s     r   collectz?TelegramAdapter._cancel_pending_delivery_tasks.<locals>.collect  s     499;; $,*>*>XXF~~HHV  &&&%% -)<T)B)B -&&t,,,,,- -r)   return_exceptionsT)r   rL  r$  r   Tasklistr  valuesr  r  r  r;   gatherclearr  r  r  )r   r  r   r  rL  r  r  s      @@@@r   _cancel_pending_delivery_tasksz.TelegramAdapter._cancel_pending_delivery_tasks  s      +--,..0		-(7<0 		-T 		- 		- 		- 		- 		- 		- 		- 		- 		- 07799:: 	 	DGDMMMM8??AABB 	 	DGDMMMM7>>@@AA 	 	DGDMMMM()))! 	 	DKKMMMM 	K./JTJJJJJJJJJ%%''' &&((('--///#))+++&,,..."((***#<77'+D$$$ 87r)   c                   K   |                                   t          | dd          }|rD|                                s0|                                 t	          j        |d           d{V  d| _        | j        rV| j                                        s=| j                                         	 | j         d{V  n# t          j        $ r Y nw xY wd| _        	 | 	                    d           d{V  n# t          $ r Y nw xY w|                                  d{V  | j        r"	 | j        j        r| j        j        j        rt	 t	          j        | j        j                                        t"                     d{V  n5# t          j        $ r# t&                              d| j                   Y nw xY w| j        j        r| j                                         d{V  | j                                         d{V  nE# t          $ r8}t&                              d	| j        t/          |                     Y d}~nd}~ww xY w|                                  d| _        d| _        t&                              d
| j                   dS )zHStop polling/webhook, cancel pending delayed deliveries, and disconnect.r7  NT)r  FrI  r  z`[%s] updater.stop() timed out during disconnect (likely CLOSE-WAIT socket); forcing app shutdownz)[%s] Error during Telegram disconnect: %sz[%s] Disconnected from Telegram)r=  rL   r%   r;   r   r  r7  r  r   rN  r   r  r  r  r  r  r  r  r>   r   r  r   rK   r   r  r  r  )r   post_connect_taskr   s      r   
disconnectzTelegramAdapter.disconnect?  s@     
 	!!! $D*>EE 	L%6%;%;%=%= 	L$$&&&.!2dKKKKKKKKKK"& ' 	0L0Q0Q0S0S 	(//111222222222)   '+$	,,E,:::::::::: 	 	 	D	 113333333339 	 9$ ):)B %.ty/@/E/E/G/GQfggggggggggg"/   O I     9$ +)..*********i((**********   ?I:1==       
 	##%%%		5tyAAAAAsa   /B= =CCC7 7
DD*H =F H /F85H 7F88AH 
I.IIchunk_indexc                 D    |sdS | j         }|dk    rdS |dk    rdS |dk    S )a3  Determine if this message chunk should thread to the original message.

        Args:
            reply_to: The original message ID to reply to
            chunk_index: Index of this chunk (0 = first chunk)

        Returns:
            True if this chunk should be threaded to the original message
        Fr  allTr   )r  )r   r  r  r  s       r   r^  z$TelegramAdapter._should_thread_reply  s@      	5"5==5U]]4!##r)   c                   K   | j         st          dd          S t          | dd          rt          ddd          S |r|                                st          dd	          S 	 |                     ||
          ro|                     ||||           d{V }|O|j        rF|pi                     d          s/	 |                     ||
           d{V  n# t          $ r Y nw xY w|S | 
                    |          }|                     || j        t                    }t          |          dk    rd |D             }g }|                     |          }	|                     |	          }
d}	 ddlm} n# t&          $ r
 t(          }Y nw xY w	 ddlm} n# t&          $ r d}Y nw xY w	 ddlm} n# t&          t.          f$ r d}Y nw xY wt1          |          D ]\  }}d}|                     |          }|                     ||	|          }|o.| j        dk    o#t9          |o|                    d                    }|p|r|t;          |          nd}|r|duo
| j        dk    }n|                     ||          }|r|rt?          |          nd}|r*|(|s&t          d|                                  d          c S | !                    ||	||| j                  }|r)|                    d          tE          |          }d|d<   |                    d          }d}tG          d          D ]{}	 	  | j         j$        d2tK          |          |tL          j'        |d|| (                                | )                    |           d{V }n# t          $ r}dt;          |          *                                v s#dt;          |          *                                v rtV          ,                    d| j-        |           t]          |          } | j         j$        d2tK          |          |d|d|| (                                | )                    |           d{V }n Y d}~nd}~ww xY w n5# |$ rz}|rt_          ||          r| 0                    |          r||s|r=|                    d          r(t          dt;          |          d          cY d}~c c S |s)d}tV          ,                    d| j-        |           Y d}~tV          ,                    d| j-        |           | 1                    ||           d}d}ddi}Y d}~*t;          |          *                                }d|v r||r*te          |          } t          d| d          cY d}~c c S te          |          } tV          ,                    d | j-        |            d}|r|                    d          ri }d}n4| !                    ||	||| j                  }|                    d          }Y d}~ | 3                    |          }!|r(t_          ||          r| 4                    |          s|!s |!r| 5                                 d{V  |d!k     rUd!|z  }"te          |          } tV          ,                    d"| j-        |dz   |"|            tm          j7        |"           d{V  n Y d}~d}~wt          $ r}t          |d#d          }#|##d$t;          |          *                                v rn|d!k     rh|#tq          |#          nd%}"te          |          } tV          ,                    d&| j-        |dz   |"|            tm          j7        |"           d{V  Y d}~t d}~ww xY w|9                    t;          |j:                             |pi                     d          s/	 |                     ||
           d{V  n# t          $ r Y nw xY wt          d|r|d         nd||
|d'(          S # t          $ r"}$te          |$          }%tV          ;                    d)| j-        |%           t;          |$          *                                }&ty          |$          }'d*|&v sd+|&v r7tV          =                    d,| j-                   t          dd*d-.          cY d}$~$S t}                                          d/          }(|(rt_          |$|(          pd0|&v })| 4                    |$          }*| 3                    |$          }!t          d|%|*p|!p|) |'1          cY d}$~$S d}$~$ww xY w)3z"Send a message to a Telegram chat.FNot connectedrw  r
   r   send_path_degradedTr  Nrz  rF  rH  len_fnrv  c           	      T    g | ]%}t          t          j        d d|                    &S )z \((\d+)/(\d+)\)$z \\(\1/\2\\))r   r   r   )r   chunks     r   rE  z(TelegramAdapter.send.<locals>.<listcomp>  sF         93_eLL   r)   r   )r  r  rs  r  r  r]  r}  rl   r   r   
parse_moder  parserK  z<[%s] MarkdownV2 parse failed, falling back to plain text: %sr  z;[%s] Thread %s not found, retrying once with same thread_idz<[%s] Thread %s not found, retrying without message_thread_idr  z8[%s] Reply target deleted, retrying without reply_to: %sr  z>[%s] Network error on send (attempt %d/3), retrying in %ds: %sru  retry afterr   zI[%s] Telegram flood control on send (attempt %d/3), retrying in %.1fs: %s)message_idsrequested_thread_idthread_fallback)rw  rn  raw_responsez([%s] Failed to send Telegram message: %smessage_too_longtoo longzF[%s] send() content too long, falling back to new-message continuationtoo_long)rw  r
   
error_kindr  rt  )rw  r
   r@  r  rj   )?r  rs   rL   rb  rD  r  rw  r)  send_typingr   format_messagetruncate_messageMAX_MESSAGE_LENGTHr~   r  r  r  r  r  r   r  r  r  rU  	enumerater  r  r  r'  r   r^  r  r  r  r  r  r0  r   r`   MARKDOWN_V2r  rJ  rj  r   r  r   r   r  r  r  r   r  r  r  r   r  r   r   rn  r
   rt   r   locals)+r   r   r  r  rF  rich_result	formattedchunksr  rM  r  used_thread_fallback_NetErr_BadReqr  r  r  retried_thread_not_foundr_  r`  ra  rb  rc  rd  re  effective_thread_idr  _send_attemptmd_errorplain_chunkr  r  safe_send_erroris_pool_timeoutr9   ru  r   r  r  r  _tor  r  s+                                              r   sendzTelegramAdapter.send  sS      y 	De?CCCC 4.66 	Ye3GSWXXXX  	=gmmoo 	=dt<<<<r	 ((8(DD '$($7$7(T\$]$]]]]]]]*"* % !)B33H== %%&*&6&6w&6&R&R R R R R R R R R#, % % % $%&& ++G44I**429 +  F 6{{Q  "(	   K00::I"&"B"B9"M"M#( "BBBBBBB " " "!"@@@@@@@   !@@@@@@@0 ! ! ! 			! &f-- @8 @85+0($($F$Fx$P$P!(,(F(FwPY[c(d(d% * \+u4\XZ(,,7Y*Z*Z[[ &
 #+ #.CoHYHeC)***ko   ) R't3 9 /58 "M
 %)$=$=oq$Q$QM6Caac/222]a( [-@I^-@% %"AACC"'     
 !% < <(3"&"5 != ! ! ( >M,=,=>Q,R,R,^$($7$7M9=M"56&3&7&78K&L&L#%*1XX S SMR&(>	(> )(B7(K(K%*+4+@4?	) )
 #0) #'";";"="=) #'";";H"E"E) ) # # # # # #CC  ) & & &&#h--*=*=*?*???:QTU]Q^Q^QdQdQfQfCfCf &/mosox  {C  !D  !D  !D.9%.@.@,BDI,B -",Fw,O,O)4/38C	-" -"
 '4-" '+&?&?&A&A-" '+&?&?&I&I-" -" '" '" '" '" '" '" !& !$&  " e" e" e"
 # G"z(G'D'D G"#>>xHH $)M`Ml#8 !&X !&(,,W{J|J| !&+505.1(mm27,& ,& ,& %& %& %& %& %& %& %& %& %& %& (@ !-?C$<$*NN(e(,	3F%& %& %& %-HHHH !'$b$(I/B!" !" !" !% B B$+-@!" !" !" 8< 46: 31Dd0K ((+H(;(;(=(=I@IMMR]Ri#8 !&6QRZ6[6[O+505.=27,& ,& ,& %& %& %& %& %& %& %& %& %& %& 3Nh2W2W &$^$(I!" !" !" /3#+ !a=_0`0` !a46M:>$7$7484P4P(/(1(0<G6:6I 5Q 5& 5&M ;H:K:KL_:`:`$7 (! +/*G*G*Q*Q%" *8Y ? ?" %)$D$DX$N$N" %4	" "* W"&"T"T"V"VVVVVVVV(1,,#$#5D.I(.S.SO"NN+k+/9ma6G` ` `")-"5"555555555! 65555 %   &-ht&L&L&2ms8}}GZGZG\G\6\6\,q00=H=Tu['9'9'9Z]2Mh2W2W &$o$(I$1A$5$($3!" !" !" '.mD&9&9 9 9 9 9 9 9 9 (  ""3s~#6#67777 N''11 **7X*FFFFFFFFFF    D -8B;q>>d#.+>';      	 	 	4Q77JLLCTYPZ[[[!ffllnnG,Q//J "W,,
g0E0E\I   "%7IV`aaaaaaaaa ((,,{++C4*Q"4"4O9OJ!%!A!A!!D!D";;A>>O -RR
N%	        -	s  &A`: <C `: 
C'$`: &C''`: ,B`: 1E8 7`: 8F	`: F`: F `: F&#`: %F&&`: *F1 0`: 1G`: GC6`: >A3`: 3ANQ6
Q0CQ+&Q6+Q00Q63`: 6^(<A"[1^(`: (%[1`: ?[1`: A	[1!^("`: +B[1-`: 3B8[1+`: 1^(>B^#`: "^##^((A`: ,`
 	`: 

``: `"`: :e'Be"e'$A8e"e'"e'r  
status_keyc                  K   t          |          t          |          f}| j                            |          }|g|                     |||d|           d{V }|j        r%|j        rt          |j                  | j        |<   |S | j                            |d           |                     |||           d{V }|j        r#|j        rt          |j                  | j        |<   |S )a  Send a status message, or edit the previous one with the same key.

        Issue #30045: progress/status callbacks (context-pressure, lifecycle,
        compression, etc.) used to append a fresh bubble on every call. With
        this method, the first call sends and the message id is remembered;
        subsequent calls with the same (chat_id, status_key) edit that same
        message in place. If the edit fails (message deleted, too old, etc.)
        we drop the cached id and send fresh.
        NTfinalizerF  r  )r   r5  r)  edit_messagerw  rn  r  r  )r   r   r  r  rF  r  	cached_idrG   s           r   send_or_update_statusz%TelegramAdapter.send_or_update_status  s'     " 7||S__-,0055	 ,,GdX -        F ~ $ K478I4J4JD,S1$((d333yy'HyEEEEEEEE> 	Cf/ 	C,/0A,B,BD$S)r)   r  r  c                  K   | j         st          dd          S |r8|                     |          r#|                     ||||           d{V }||S t	          |          t	          |          f}d}|r| j                            |d           t          |          | j        k    ri|r | 	                    |||||           d{V S | 
                    |          }d}| j                            |          |k    rt          d|          S n|s| j                            |d           	 |sZ| j                             t          |          t          |          |	           d{V  |r
|| j        |<   t          d|          S |                     |          }		 | j                             t          |          t          |          |	t           j        
           d{V  n# t$          $ r}
dt	          |
                                          v rt          d|          cY d}
~
S t)          |
          }t*                              d| j        |           |rt1          |          n|}| j                             t          |          t          |          |	           d{V  Y d}
~
nd}
~
ww xY wt          d|          S # t$          $ r!}t	          |                                          dv rt          d|          cY d}~S dv sdv rt*                              d| j        t          |          | j                   |r%| 	                    |||||           d{V cY d}~S | 
                    |          }| j                            |          |k    rt          d|          cY d}~S | j                             t          |          t          |          |	           d{V  || j        |<   t          d|          cY d}~S t5          |dd          }|dv r|r|nd}t*                              d| j        |           |dk    rt          dd|           cY d}~S t7          j        |           d{V  	 | j                             t          |          t          |          |	           d{V  t          d|          cY d}~S # t$          $ rP}t)          |          }t*                              d| j        |           t          d|          cY d}~cY d}~S d}~ww xY wd}t=          fd|D                       }|rHt)          |          }t*                              d| j        ||           t          d|d          cY d}~S t)          |          }t*                              d| j        ||           t          d|          cY d}~S d}~ww xY w)a"  Edit a previously sent Telegram message.

        Telegram caps single-message text at 4096 UTF-16 codeunits.  Streaming
        replies that grow past this limit must NOT be silently truncated and
        must NOT return failure (the consumer would re-send and create a
        duplicate).  Instead this method split-and-delivers: edit the
        existing message with the first chunk and send the rest as
        continuation messages, returning the final chunk's id so subsequent
        edits target the most recent visible message.
        Fr  r  r  Nr  Trz  r   rn  r   r   rn  r   r  r  z;[%s] MarkdownV2 edit failed, falling back to plain text: %sr  r  z6[%s] edit_message overflow (%d UTF-16 > %d), splittingru  r  r   z*[%s] Telegram flood control, waiting %.1fsg      @zflood_control:z+[%s] Edit retry failed after flood wait: %s)connecterrorzconnect errorzconnection errorr  znetwork errorrt  readtimeoutwritetimeoutzserver disconnectedztemporarily unavailableztemporary failurer  c              3       K   | ]}|v V  	d S r$   rj   )r   r   r  s     r   r  z/TelegramAdapter.edit_message.<locals>.<genexpr>  s'      IIWIIIIIIr)   z@[%s] Transient network error editing message %s (will retry): %sr  z+[%s] Failed to edit Telegram message %s: %s)r  rs   r@  r  r   r6  r  r~   r  _edit_overflow_split!_truncate_stream_overflow_previewr)  edit_message_textr   r  r  r`   r  r   rj  r   r   r  r   r   r   rL   r   r  r
   r  )r   r   rn  r  r  rF  r  _preview_key_saturated_previewr  fmt_errsafe_format_error_plainr   	truncatedru  r9   r  r  _transient_markers_is_transientr  r  s                         @r   r  zTelegramAdapter.edit_message  sZ     & y 	De?CCCC  	#++G44 	# $ 3 3Wx !4 ! !      K &"" Gc*oo6" 	@ '++L$???W 777 !66Z8h 7          <<WEEG!% *..|<<GG!$:FFFF H 	@ '++L$???@	? Gi116w??":  2         
 & H@GD/=!$:FFFF++G44Ii116w??":"(4	 2              !S\\%7%7%9%999%dzJJJJJJJJJ$?$H$H!QI%  
 29EW---gi116w??": 2              " dzBBBB [	? [	? [	?!ffllnnG((!$:FFFFFFFFF "W,,
g0E0ELIy1143J    !%!:!:WxRZ "; " "             !BB7KK	.22<@@IMM%dzJJJJJJJJJi116w??":" 2         
 =F+L9!$:FFFFFFFFF "!]D99K&-7*B*B&1:{{s@It   #::%e;RD;R;RSSSSSSSSSmD)))))))))M)55 :7 C C#&z??$ 6         
 &dzJJJJJJJJJ  M M M'B9'M'M$LLE	#3   &e;KLLLLLLLLLLLLLLM"  IIII6HIIIIIM S8;;
VI	   "%zTRRRRRRRRR4Q77JLL=		   e:>>>>>>>>>w[	?s   2AK K $AG- ,K -
J:73J5*J:+K 0B J50K 5J::K W:5W5W:AW52W:8AW5;W:AW5W:AW56W:<W5AS*$W:*
U4A T?4U5W59W:?UA$W5(W:.AW5/W:5W:c                 R    |                      || j        t                    d         S )a  Return a one-message preview for oversized streaming edits.

        Streaming edits must keep targeting the original message. Splitting a
        mid-stream preview creates continuation messages and moves the active
        message id, so the next accumulated-token edit repeats the overflow
        cycle (#48648). Final edits still use ``_edit_overflow_split`` to
        deliver the complete response.
        r  r   )r  r  r~   r  s     r   r
  z1TelegramAdapter._truncate_stream_overflow_preview  s7     $$# % 
 
 	 	r)   c                n  K   |                      || j        t                    }t          |          dk    r|g}|d         }	 |rt	          |                     |                    }	 | j                            t          |          t          |          |t          j                   d{V  n# t          $ r}	dt          |	                                          vrkt                              d| j        |	           | j                            t          |          t          |          t%          |                     d{V  Y d}	~	nEd}	~	ww xY w| j                            t          |          t          |          |           d{V  n# t          $ rv}
t          |
                                          }d|v rnFt                              d	| j        |
d
           t)          dt          |
                    cY d}
~
S Y d}
~
nd}
~
ww xY wg }|g}|}|                     |          }|dd         D ]}d}|rt          |          nd}|                     ||||          }|rdndD ]}	 |r#t	          |                     |                    }n|rt%          |          n|} | j        j        d!t          |          ||rt          j        nd|d||                                 |                     |           d{V } nA# t          $ r3}dt          |                                          v r|r|                    d          ri n|                     |||d          }	  | j        j        d!t          |          |rt%          |          n|d||                                 |                     |           d{V }Y d}~ nx# t          $ r2}t                              d| j        |           d}Y d}~Y d}~ nAd}~ww xY w|rY d}~t                              d| j        |           d}Y d}~ nd}~ww xY w|t                              d| j        dt          |          z   t          |                     d                    d |D                       }t)          d|dd
d
dt          |          z   t          |          ||t9          |          dt9          |                    c S t          t;          |dd                    p|}|                    |           |                    |           |}|r|d         n|}t                              d| j        dt          |          z   |           t)          d
|t9          |                     S )"u  Split an oversized edit across the existing message + continuations.

        Edit the original ``message_id`` with chunk 1 (with the platform's
        usual ``(1/N)`` suffix preserved), then send the remaining chunks as
        new messages threaded as replies to the previous chunk so the user
        sees them grouped.  Returns ``SendResult(success=True,
        message_id=<last-chunk-id>, continuation_message_ids=(...))`` so the
        stream consumer can keep editing the most recent visible message
        and the gateway has full visibility into every message id we put on
        screen.

        Falls back to ``SendResult(success=False)`` only if even the first-
        chunk edit fails — that's a real adapter problem, not an overflow.
        r  rv  r   r  Nr  zW[%s] Overflow split: MarkdownV2 first-chunk edit failed, falling back to plain text: %sr  z0[%s] Overflow split: first-chunk edit failed: %sTr   Fr  r  TFFr  zreply message not foundr  )r   r   z4[%s] Overflow continuation no-reply retry failed: %sz*[%s] Overflow continuation send failed: %sz6[%s] Overflow split: stopped at %d/%d chunks deliveredr   c              3   B   K   | ]}t          j        d d|          V  dS )z \(\d+/\d+\)$r   Nr   )r   	delivereds     r   r  z7TelegramAdapter._edit_overflow_split.<locals>.<genexpr>  sE       + +! F+R;;+ + + + + +r)   overflow_continuation_failed)partial_overflowdelivered_chunkstotal_chunkslast_message_iddelivered_prefixcontinuation_message_ids)rw  rn  r
   r@  r  r!  rn  z3[%s] Overflow split delivered %d chunks; last_id=%s)rw  rn  r!  rj   ) r  r  r~   r  r   r  r  r  r   r  r`   r  r   r   rj  r   r  r   r   r
   rs   r  r  r0  r  rJ  r)  r   tuplerL   r   r   )r   r   rn  r  r  rF  r  first_chunkr  r  r   r  continuation_idsr  prev_idrM  r  sent_msgrd  re  use_markdownr   r  retry_thread_kwargs
_retry_errr   new_idlast_ids                               r   r	  z$TelegramAdapter._edit_overflow_split  s     . &&T,Y ' 
 
 v;;! YF Qi+	?  A''44 	)55 :7 C C#&z??&#,#8	 6           !   %S\\-?-?-A-AAAE Iw  
 #i99$>w$G$G'*:!,[!9!9 :          i116w??":$ 2         
  	? 	? 	?!ffllnnG(( FIq4     "%s1vv>>>>>>>>> 	?& ')'=,,X66	ABBZ e	 e	EH*1;#g,,,tK 88$/	 9  M 2: Gx : :9# 	IC //66    6>H{51115%;TY%; & :7 C C!<H#R9#8#8d,7	& &
 (& 3355& 33H==& &            H E  $ $ $0CMM4G4G4I4III  (,4LL9[,\,\BB!%!=!= 'HRV "> " " ,"-CTY-C .(B7(K(K;C%N[%7%7%7. . #6. #'";";"="=	.
 #'";";H"E"E. . ( ( ( ( ( (H "EEEEE( " " ""NN V $	:   (,H!EEEEEEEEE" $ ! NND	8    $HEEEEEI$J  LIq3'7#8#88#f++   $&77 + +%5+ + + $ $  "!&8",0,-4D0E0E,E(+F+2,<49:J4K4K" " .33C-D-D      <<<==HF##F+++##E***GG*:J"2&&
AIq3/000'	
 	
 	
 %*+;%<%<
 
 
 	
s   %F *AB3 2F 3
E=BEF EA F 
H A&HHH:BLQ!AQ7A"O
P	)#P	QP	Q&#QQc                 
  K   | j         sdS 	 | j                             t          |          t          |                     d{V  dS # t          $ r-}t
                              d| j        ||           Y d}~dS d}~ww xY w)u  Delete a previously sent Telegram message.

        Used by the stream consumer's fresh-final cleanup path (ported
        from openclaw/openclaw#72038) to remove long-lived preview
        messages after sending the completed reply as a fresh message.
        Telegram's Bot API ``deleteMessage`` works for bot-posted
        messages in the last 48 hours.  Failures are non-fatal — the
        caller leaves the preview in place and logs at debug level.
        F)r   rn  NTz-[%s] Failed to delete Telegram message %s: %s)r  delete_messager   r  r   r   r   r   r   r   rn  r   s       r   r.  zTelegramAdapter.delete_message  s       y 	5	)**27;;z?? +          4 	 	 	LL?	:q   55555	s   <A 
B"A==Bc                 n    | j         rt          | j         d          sdS |pd                                dv S )a  Telegram supports sendMessageDraft for private chats only.

        Bot API 9.5 (March 2026) opened ``sendMessageDraft`` to all bots
        unconditionally for private (DM) chats.  Groups, supergroups, and
        channels still rely on the edit-based path.

        We additionally require ``self._bot`` to expose ``send_message_draft``
        (added to python-telegram-bot in 22.6); older PTB installs gracefully
        fall back to the edit path even on DMs.
        send_message_draftFr   >   rV  rW  )r  r  rj  )r   rL  rF  s      r   supports_draft_streamingz(TelegramAdapter.supports_draft_streaming  sC     y 		3G H H 	5R&&((,===r)   c           	      6  K   | j         st          dd          S |                     |          r/|                     ||||           d{V rt          dd          S t	          | j         d          st          dd          S t          |          | j        k    r|n'|                     || j        t          	          d
         }| 	                    |          }dD ]*}t          |          t          |          |r|                     |          n|d}|rt          j        |d<   |||d<   	  | j         j        di | d{V }	|	rt          dd          c S t          dd          c S # t           $ r}
|r=|                     |
          r(t$                              d| j        |||
           Y d}
~
t$                              d| j        |||
           t          dt+          |
                    cY d}
~
c S d}
~
ww xY wt          dd          S )u  Stream a partial message via Telegram's native draft API.

        Uses ``sendRichMessageDraft`` (Bot API 10.1) with the raw markdown when
        rich messages are enabled and supported, otherwise the plain-text
        ``sendMessageDraft``. The Bot API animates the preview when the same
        ``draft_id`` is reused across consecutive calls in the same chat.  When
        the response finishes, the caller sends the final text via the normal
        ``send`` path; the draft preview clears naturally on the client
        (Telegram has no Bot API to "promote" a draft to a real message — the
        final ``sendMessage``/``sendRichMessage`` is what the user receives in
        their history).
        Fnot_connectedr  NTrz  r1  api_unavailabler  r   r  )r   r  r   r  r}  draft_rejectedz[[%s] sendMessageDraft MarkdownV2 rejected, retrying as plain text (chat=%s draft_id=%s): %sz6[%s] sendMessageDraft failed (chat=%s draft_id=%s): %srj   )r  rs   r  r  r  r  r  r  r~   r  r   r  r  r`   r  r1  r   r  r   r   r   r   )r   r   r  r  rF  r   rM  r(  r  r  r   s              r   
send_draftzTelegramAdapter.send_draft  s     & y 	De?CCCC **733 	A..w'8TTTTTTTT A!$4@@@@ty"677 	Fe3DEEEE g,,$*AAAww!!'4+B9!UUVWX 	 ,,X66	 * #	? #	?L5g>>MM5AK++D111t& &F
  ='0'<|$$.7*+?7497AA&AAAAAAAA E &dtDDDDDD!%7GHHHHHH ? ? ?   D$>$>q$A$A LLB	7Ha  
 HHHHLIw!   "%s1vv>>>>>>>>>>>#?& %/?@@@@s+   1*E1E11
H;:H:A H:HHc                 $  K   | j         st          d          |                    d          }	  | j         j        di | d{V S # t          $ r}||                     |          r|                     |          rt                              d| j	        |           | 
                    |                    d          |           t          |          }|                    dd            | j         j        di | d{V cY d}~S  d}~ww xY w)a  Send a Telegram message, retrying once without message_thread_id
        if Telegram returns 'Message thread not found'.

        Used for control-style sends (approval prompts, model picker,
        update prompts) that can carry a stale thread_id from a DM
        reply chain.  The streaming send loop has its own equivalent
        (PR #3390) at the body of ``send``; this helper applies the
        same retry pattern to the non-streaming control paths.
        r  r}  NzP[%s] Thread %s not found for control message, retrying without message_thread_idr   rj   )r  r  r)  r0  r   r  r  r   r  r   r  r  r  )r   r  r}  r  r  s        r   "_send_message_with_thread_fallbackz2TelegramAdapter._send_message_with_thread_fallback*  sh      y 	0///"JJ':;;	//99&999999999 	 	 	!-..x88 .33H== . fI%   22JJy))+<    $F||  !4d;;;3TY3CClCCCCCCCCCCCCCC+	s$   A 
DB2D
D	D

Dr   r   session_keyc                   K   | j         st          dd          S 	 |rd| dnd}|                     d| |           }t          t	          dd	
          t	          dd
          gg          }|                     |          }	|                     d|| j                  }
 | j        dt          |          |t          j        ||
d|                     ||	||
| j                  |                                  d{V }t          dt          |j                            S # t           $ rI}t"                              d| j        |           t          dt          |                    cY d}~S d}~ww xY w)zSend an inline-keyboard update prompt (Yes / No buttons).

        Used by the gateway ``/update`` watcher when ``hermes update --gateway``
        needs user input (stash restore, config migration).
        Fr  r  z (default: )r   u    ⚕ *Update needs your input:*

u   ✓ Yeszupdate_prompt:ycallback_datau   ✗ Nozupdate_prompt:nNr   r   r   r  reply_markupr  r]  Trz  z"[%s] send_update_prompt failed: %srj   )r  rs   r  rU   rT   r  r  r  r9  r   r`   r  r  r  r   rn  r   r   r  r   )r   r   r   r   r:  rF  default_hintr   keyboardrM  rd  r  r   s                r   send_update_promptz"TelegramAdapter.send_update_promptQ  s      y 	De?CCCC	;7>F33333BL&&'bF'bT`'b'bccD+(BSTTT(ARSSS-  H 00::I<<T8[_[n<ooK?? 27;;$0%$/  ..(3"&"5 /   ++--       C ds3>7J7JKKKK 	; 	; 	;NN?ANNNe3q66:::::::::	;s   D	D& &
E90>E4.E94E9dangerous commandcommanddescriptionc           	      t  K   | j         st          dd          S 	 t          |          dk    r|dd         dz   n|}dt          j        |           dt          j        |           }|                     |          }d	dl}	t          | d
          s|	                    d          | _	        t          | j	                  }
t          t          dd|
           t          dd|
           gt          dd|
           t          dd|
           gg          }t          |          |t          j        |d|                                 }|                     d|| j                  }||d<   |                    |                     ||||| j                              | j        di | d{V }|| j        |
<   t          dt/          |j                            S # t2          $ rI}t4                              d| j        |           t          dt/          |                    cY d}~S d}~ww xY w)u   Send an inline-keyboard approval prompt with interactive buttons.

        The buttons call ``resolve_gateway_approval()`` to unblock the waiting
        agent thread — same mechanism as the text ``/approve`` flow.
        Fr  r    N...u.   ⚠️ <b>Command Approval Required</b>

<pre>z</pre>

Reason: r   _approval_counterrv  u   ✅ Allow Oncezea:once:r=  u   ✅ Sessionzea:session:u
   ✅ Alwaysz
ea:always:u   ❌ Denyzea:deny:r   r   r  rA  r?  r  r]  Trz  z"[%s] send_exec_approval failed: %srj   )r  rs   r  _htmlescaper  	itertoolsr  countrK  nextrU   rT   r   r`   HTMLr  r  r  r{  r  r9  r1  r   rn  r   r   r  r   )r   r   rF  r:  rG  rF  cmd_previewr   rM  rO  approval_idrC  r  rd  r  r   s                   r   send_exec_approvalz"TelegramAdapter.send_exec_approval|  s      y 	De?CCCC9	;47LL44G4G'%4%.500WK7[117 7 <447 7  00::I
 4!455 <)2););&t566K+()9IaT_IaIabbb(FaT_FaFabbb
 )E_R]E_E_```(C[kC[C[\\\	- 	 	H 6g>>'n (	& &
 ++--&F <<T8[_[n<ooK,7F()MM,,(3"&"5 -     @?II&IIIIIIIIC 1<D -ds3>7J7JKKKK 	; 	; 	;NN?ANNNe3q66:::::::::	;s   GG$ $
H7.>H2,H72H7r{  
confirm_idc           	        K   | j         st          dd          S 	 |                     t          |          dk    r|n|dd         dz             }t	          t          dd| 	          t          d
d| 	          gt          dd| 	          gg          }|                     |          }	t          |          |t          j	        |d| 
                                }
|                     d|| j                  }||
d<   |
                    |                     ||	||| j                              | j        di |
 d{V }|| j        |<   t          dt#          |j                            S # t&          $ rI}t(                              d| j        |           t          dt#          |                    cY d}~S d}~ww xY w)z8Render a three-button slash-command confirmation prompt.Fr  r  rI  NrJ  u   ✅ Approve Oncezsc:once:r=  u   🔒 Always Approvez
sc:always:u
   ❌ Cancelz
sc:cancel:rL  r?  r  r]  Trz  z"[%s] send_slash_confirm failed: %srj   )r  rs   r  r  rU   rT   r  r   r`   r  r  r  r  r{  r  r9  r2  r   rn  r   r   r  r   )r   r   r{  r?  r:  rV  rF  previewrC  rM  r  rd  r  r   s                 r   send_slash_confirmz"TelegramAdapter.send_slash_confirm  sC     
 y 	De?CCCC&	;))S\\T5I5I''wW\X\W\~`eOeffG+();KbV`KbKbccc()>Ng[eNgNghhh
 )E^R\E^E^___-  H 00::I5g>>'3 (	& &
 ++--&F <<T8[_[n<ooK,7F()MM,,(3"&"5 -     @?II&IIIIIIIIC4?D%j1ds3>7J7JKKKK 	; 	; 	;NN?ANNNe3q66:::::::::	;s   EE6 6
G	 >G>G	G	questionchoices
clarify_idc           
      J  K   | j         st          dd          S 	 dt          j        |           }|                     |          }|r4d                    d t          |          D                       }	|d|	 z  }t          |          |t          j	        d| 
                                }
|rg }t          t          |                    D ]=}|                    t          t          |d	z             d
| d|           g           >|                    t          dd
| d          g           t!          |          |
d<   |                     d|          }||
d<   |
                    |                     ||||                      | j        di |
 d{V }|| j        |<   t          dt          |j                            S # t.          $ rI}t0                              d| j        |           t          dt          |                    cY d}~S d}~ww xY w)u$  Render a clarify prompt with one inline button per choice.

        Multi-choice mode (``choices`` non-empty): renders one button per
        option plus a final "✏️ Other (type answer)" button.  Picking the
        "Other" button flips the entry into text-capture mode so the next
        message becomes the response.

        Open-ended mode (``choices`` empty): renders the question as plain
        text — no buttons.  The next message in the session is captured by
        the gateway's text-intercept and resolves the clarify.
        Fr  r     ❓ r   c              3   n   K   | ]0\  }}|d z    dt          j        t          |                     V  1dS )rv  z. N)rM  rN  r   )r   r  cs      r   r  z/TelegramAdapter.send_clarify.<locals>.<genexpr>  s\       ) )1 1u66SVV 4 466) ) ) ) ) )r)   

r   r   r  rv  cl:r  r=  u   ✏️ Other (type answer)z:otherrA  Nr  r  Trz  z[%s] send_clarify failed: %srj   )r  rs   rM  rN  r  r   r  r   r`   rR  r  r  r  r   rT   r   rU   r  r{  r  r9  r3  rn  r   r   r  r   )r   r   rZ  r[  r\  r:  rF  r   rM  option_linesr  rowsidxrd  r  r   s                   r   send_clarifyzTelegramAdapter.send_clarify  s     ( y 	De?CCCC9	;2%,x0022D00::I 	.
  $yy ) ) )' 2 2) ) )     -|--- 6g>>'n& & ++--	&F  D  W..  CKK,aLL*B
*B*BS*B*B  !     (4&>J&>&>&>      *>d)C)C~&<<T8LLK,7F()MM,,(3	 -     @?II&IIIIIIIIC.9D
+ds3>7J7JKKKK 	; 	; 	;NN949aHHHe3q66:::::::::	;s   F2G 
H">HH"H"	providerscurrent_modelcurrent_providerc                 ^  K   | j         st          dd          S 	 ddlm} n# t          $ r d }Y nw xY w	 |                     |d          \  }	}
 ||          }|                     d|pd d	| d
|
           }|r|                    d          nd}|                     d|| j	                  } | j
        dt          |          |t          j        |	|d|                     ||||| j	                  |                                  d{V }|j        |||||dd| j        t%          |          <   t          dt%          |j                            S # t&          $ rI}t(                              d| j        |           t          dt%          |                    cY d}~S d}~ww xY w)u   Send an interactive inline-keyboard model picker.

        Two-step drill-down: provider selection → model selection.
        Edits the same message in-place as the user navigates.
        Fr  r  r   	get_labelc                     | S r$   rj   slugs    r   rm  z4TelegramAdapter.send_model_picker.<locals>.get_label[      r)   +   ⚙ *Model Configuration*

Current model: `unknown`
Provider: 

Select a provider:rM  Nr?  r@  r]  )msg_idrh  r:  on_model_selectedri  rj  provider_pageTrz  z![%s] send_model_picker failed: %srj   )r  rs   hermes_cli.providersrm  r   _build_provider_keyboardr  r)  r  r  r9  r   r`   r  r  r  rn  r0  r   r   r   r  r   )r   r   rh  ri  rj  r:  rw  rF  rm  rC  provider_page_infoprovider_labelr   rM  rd  r  r   s                    r   send_model_pickerz!TelegramAdapter.send_model_pickerF  sw      y 	De?CCCC	6666666 	 	 	    	.	;+/+H+HTU+V+V(H(&Y'788N&&>'4'A	> >!/> > *<> > D 6>G[1114I<<T8[_[n<ooK?? 27;;$0%$/  ..(3"&"5 /   ++--       C$ .&*%6!.$4!"6 6D$S\\2 ds3>7J7JKKKK 	; 	; 	;NN>	1MMMe3q66:::::::::	;s*   # 33D!E 
F,#>F'!F,'F,r  ry  r   pagec           	         	 ddl m} n# t          $ r d}Y nw xY wd |D             d }g }| |d |D                       D ]}|d         dk    rfd	|d
         D             }t          d |D                       }|d          d| d}	t	          d |D                       rd|	 }	|                    t          |	d|d                                                   |d                   }
|
|                     ||
                     n#|D ] }
|                     ||
                     !| j        }t          |          }t          d||z   dz
  |z            }t          dt          ||dz
                      }||z  }t          ||z   |          }|||         fdt          dt                    d          D             }|dk    rg }|dk    r*|                    t          dd|dz
                        |                    t          |dz    d| d                     ||dz
  k     r*|                    t          dd|dz                         |                    |           |                    t          dd          g           |dk    rd|dz    d | d!| dnd"}t          |          |fS )#a  Build the paginated top-level provider keyboard, folding groups.

        Provider families (Kimi/Moonshot, MiniMax, xAI Grok, ...) collapse to
        a single ``mpg:<gid>`` button; tapping it drills into a member
        sub-keyboard. Single providers (and groups with only one authenticated
        member) render as direct ``mp:<slug>`` buttons. Grouping mirrors the
        CLI ``hermes model`` picker via the shared ``group_providers`` fold,
        so all surfaces stay consistent.
        r   )group_providersNc                 :    i | ]}|                     d           |S ro  r)  r   ps     r   rl  z<TelegramAdapter._build_provider_keyboard.<locals>.<dictcomp>  s$    777155==!777r)   c           	          |                      dt          |                      dg                               }| d          d| d}|                      d          rd| }t          |d| d	          
          S )Ntotal_modelsmodelsr    (r<  
is_current   ✓ mp:rp  r=  )r)  r  rT   )r  rP  labels      r   _provider_buttonzBTelegramAdapter._build_provider_keyboard.<locals>._provider_button  s    EE.#aeeHb.A.A*B*BCCEy,,E,,,Euu\"" '&u'=N1V9=N=NOOOOr)   c                 8    g | ]}|                     d           S ro  r  r  s     r   rE  z<TelegramAdapter._build_provider_keyboard.<locals>.<listcomp>  s"    'I'I'I!f'I'I'Ir)   kindr   c                 (    g | ]}|v |         S rj   rj   r   r   by_slugs     r   rE  z<TelegramAdapter._build_provider_keyboard.<locals>.<listcomp>  s"    RRRaQ'\\wqz\\\r)   membersc           
   3      K   | ];}|                     d t          |                     dg                               V  <dS )r  r  N)r)  r  r   r   s     r   r  z;TelegramAdapter._build_provider_keyboard.<locals>.<genexpr>  sW          LMnc!%%"2E2E.F.FGG           r)   r  u    ▸ (r<  c              3   @   K   | ]}|                     d           V  dS )r  Nr  r  s     r   r  z;TelegramAdapter._build_provider_keyboard.<locals>.<genexpr>  s.      @@1155..@@@@@@r)   r  mpg:group_idr=  rp  rv  c                 *    g | ]}||d z            S r  rj   )r   r  page_buttonss     r   rE  z<TelegramAdapter._build_provider_keyboard.<locals>.<listcomp>  s&    PPPAQQY'PPPr)   r     ◀ Prevmpv:/mx:noop   Next ▶
   ✗ Cancelmxr     – of r   )hermes_cli.modelsr  r   r  r  r   rT   r)  _PROVIDER_PAGE_SIZEr  r6   r   r  rU   )r   rh  r~  r  r  buttonsrowr  rP  r  r  	page_sizetotaltotal_pagesr8   r   re  nav	page_infor  r  s                      @@r   rz  z(TelegramAdapter._build_provider_keyboard  s   	#9999999 	# 	# 	#"OOO	# 87Y777	P 	P 	P &&'I'Iy'I'I'IJJ < <v;'))RRRR3y>RRRG    QX       E  #7|;;5;;;E@@@@@@@ / .uNN,UBZZBZBZ[[[     CK00A}'7'7':':;;;<"  4 4//223333,	G!ei/!3	ABB1c$a0011y %)#U++uSy)PPPPq#l:K:KQ1O1OPPP??Caxx

/
J[QUXYQYJ[J[\\\]]]JJ+tax,G,G+,G,GW`aaabbbkAo%%

/
J[QUXYQYJ[J[\\\]]]KK),dKKKLMMM<G!OO888s888888QS	#D))944s    r  c                 V   | j         }t          |          }t          d||z   dz
  |z            }t          dt          ||dz
                      }||z  }t          ||z   |          }|||         }g t	          |          D ]r\  }	}
||	z   }d|
v r|
                    d          d         n|
}t          |          dk    r|dd         dz   }                    t          |d	| 
                     sfdt          dt                    d          D             }|dk    rg }|dk    r*|                    t          dd|dz
   
                     |                    t          |dz    d| d
                     ||dz
  k     r*|                    t          dd|dz    
                     |                    |           |                    t          dd
          t          dd
          g           |dk    rd|dz    d| d| dnd}t          |          |fS )zBBuild paginated model buttons. Returns (keyboard, page_info_text).rv  r   r  r"  &   N#   rJ  mm:r=  c                 *    g | ]}||d z            S r  rj   r   r  r  s     r   rE  z9TelegramAdapter._build_model_keyboard.<locals>.<listcomp>  s&    FFFqAE	"FFFr)   r  r  mg:r  r     ◀ Backmbr  r  r  r  r  r<  r   )
_MODEL_PAGE_SIZEr  r6   r   r  rk  r   rT   r  rU   )r   r  r~  r  r  r  r8   r   page_modelsr  model_idabs_idxshortre  r  r  r  s                   @r   _build_model_keyboardz%TelegramAdapter._build_model_keyboard  s   )	F!ei/!3	ABB1c$a0011y %)#U++U3Y'$[11 	 	KAxaiG/2hHNN3''++HE5zzBcrc
U*NN$U///JJJ    GFFFE!S\\1,E,EFFF ??Caxx

/
JZPTWXPXJZJZ[[[\\\JJ+tax,G,G+,G,GW`aaabbbkAo%%

/
JZPTWXPXJZJZ[[[\\\KK 4@@@ TBBB
 	 	 	
 =H!OO888s888888QS	#D))944r)   datac           
      J  $%&K   | j                             |          }|s|                    d           d{V  dS 	 ddlm} n# t
          $ r d }Y nw xY w|                    d          r\|dd         &t          &fd	|d
         D             d          }|s|                    d           d{V  dS |                    dg           }&|d<   |                    d&          |d<   ||d<   d|d<   |                     |d          \  }}	|                    d&          }
|                    dt          |                    }t          |          }||k    r	d||z
   dnd}|
                    |                     d|
 d|	 d|           t          j        |           d{V  |                                 d{V  dS |                    d          r|	 t          |dd                   }n-# t          $ r  |                    d           d{V  Y dS w xY w|                    dg           }||d<   |                     ||          \  }}	|                    dd          }
|                    dd          &t          &fd|d
         D             d          }|r#|                    dt          |                    nt          |          }t          |          }||k    r	d||z
   dnd}|
                    |                     d|
 d|	 d|           t          j        |           d{V  |                                 d{V  dS |                    d          r	 t          |dd                   }n-# t          $ r  |                    d           d{V  Y dS w xY w||d<   |                     |d
         |          \  }}	  ||d                    }n# t"          $ r |d          }Y nw xY w|
                    |                     d!|d"         pd# d$| d%|           t          j        |           d{V  |                                 d{V  dS |                    d&          r	 t          |dd                   }n-# t          $ r  |                    d'           d{V  Y dS w xY w|                    dg           }|dk     s|t          |          k    r|                    d(           d{V  dS ||         }|                    dd          &|                    d)          }|s|                    d*           d{V  dS d+}	  |||&           d{V }n9# t"          $ r,}t$                              d,|           d-| }d.}Y d}~nd}~ww xY w	 |
                    |                     |          t          j        d           d{V  n@# t"          $ r3 	 |
                    |dd           d{V  n# t"          $ r Y nw xY wY nw xY w|                    |rd/nd0           d{V  | j                             |d           dS |                    d1          r	 t          |dd                   }n-# t          $ r  |                    d'           d{V  Y dS w xY w|                    dg           }|dk     s|t          |          k    r|                    d(           d{V  dS ||         }|                    dd          &|                    d)          }|s|                    d*           d{V  dS 	 dd2lm} t/          j        ||&3           d{V }n# t"          $ r d}Y nw xY w|t3          t5          d4d&| 5          gt5          d6d75          t5          d8d95          gg          }|
                    |                     d:|j                   t          j        |           d{V  |                    d;           d{V  dS d+}	  |||&           d{V }n9# t"          $ r,}t$                              d,|           d-| }d.}Y d}~nd}~ww xY w	 |
                    |                     |          t          j        d           d{V  n@# t"          $ r3 	 |
                    |dd           d{V  n# t"          $ r Y nw xY wY nw xY w|                    |rd/nd0           d{V  | j                             |d           dS |                    d<          r|dd         }	 dd=lm} |                    |ddg f          \  }}}n# t"          $ r dg }}Y nw xY wd> |d
         D             %%fd?|D             }|s|                    d@           d{V  dS g $|D ]} |                     dt          |                     dg                               }!| d          dA|! dB}"|                     dC          rdD|" }"$                    t5          |"d| dE          5                     $fdFt?          dt          $          dG          D             }#|#                    t5          d6d75          t5          d8d95          g           t3          |#          }|
                    |                     dH|p| dI          t          j        |           d{V  |                                 d{V  dS |d7k    rt          |                    dd          pd          }|                     |d
         |          \  }}	  ||d                    }n# t"          $ r |d          }Y nw xY w|
                    |                     d!|d"         pd# d$| d%|           t          j        |           d{V  |                                 d{V  dS |d9k    rT| j                             |d           |
                    dJdK           d{V  |                                 d{V  dS |                                 d{V  dS )LzHHandle model picker inline keyboard callbacks (mp:/mm:/mc:/mb:/mx:/mg:).u$   Picker expired — use /model again.r   Nr   rl  c                     | S r$   rj   ro  s    r   rm  z@TelegramAdapter._handle_model_picker_callback.<locals>.get_label  rq  r)   r  rl   c              3   4   K   | ]}|d          k    |V  dS rp  Nrj   r   r  provider_slugs     r   r  z@TelegramAdapter._handle_model_picker_callback.<locals>.<genexpr>  1      MMq!F)}2L2L2L2L2L2LMMr)   rh  zProvider not found.r  selected_providerr   selected_provider_name
model_list
model_pager  z
_u2    more available — type `/model <name>` directly_r   u&   ⚙ *Model Configuration*

Provider: *rg  z
Select a model:r   r  rA  r  zInvalid page.c              3   4   K   | ]}|d          k    |V  dS r  rj   r  s     r   r  z@TelegramAdapter._handle_model_picker_callback.<locals>.<genexpr>E  r  r)   r     rx  rj  rr  ri  rs  rt  ru  mc:zInvalid selection.zInvalid model index.rw  zPicker expired.FzModel picker switch failed: %szError switching model: TzSwitch failed.zModel switched!r  )expensive_model_warning)providerzSwitch anywayr=  r  r  r  r  u   ⚠ *Expensive Model Warning*

zConfirm expensive modelr  )PROVIDER_GROUPSc                      i | ]}|d          |S ro  rj   r  s     r   rl  zATelegramAdapter._handle_model_picker_callback.<locals>.<dictcomp>  s    @@@qy!@@@r)   c                 (    g | ]}|v |         S rj   rj   r  s     r   rE  zATelegramAdapter._handle_model_picker_callback.<locals>.<listcomp>  s"    HHHa1<<wqz<<<r)   zGroup not found.r  r<  r  r  rp  c                 *    g | ]}||d z            S r  rj   r  s     r   rE  zATelegramAdapter._handle_model_picker_callback.<locals>.<listcomp>  s&    JJJ1GAAI&JJJr)   r  u-   ⚙ *Model Configuration*

Provider family: *z*

Select a provider:zModel selection cancelled.r   rA  ) r0  r)  answerry  rm  r   
startswithrQ  r  r  r  r  r`   r  r  r   rz  r   r   r
   r  hermes_cli.model_cost_guardr  r   	to_threadrU   rT   r?  r  r  r   r  )'r   queryr  r   staterm  r  r  rC  r  pnamer  shownr(  r~  r{  r|  rf  r  r  callbackswitch_failedresult_textrN  r  r  r  r  _label_descmember_slugsr  r  rP  r  re  r  r  r  s'                                       @@@r   _handle_model_picker_callbackz-TelegramAdapter._handle_model_picker_callback  s      (,,W55 	,,$J,KKKKKKKKKF	6666666 	 	 	    	 ??5!! ~	! HMMMMME+.MMM H  ll(=l>>>>>>>>>\\(B//F)6E%&.6ll6=.Q.QE*+"(E,"#E,"&"<"<VQ"G"GHiLL77ELLV==EKKE_dgl_l_l[%%-[[[[rtE))((2&+2 2.72 2*/2 2  %0% * 
 
 
 
 
 
 
 
 
 ,,..         __U## Y	!48}}   lll888888888 YY|R00F"&E,"&"<"<VT"J"JHiII6;;E!II&92>>MMMMME+.MMM H BJZHLLV===sSY{{EKKE_dgl_l_l[%%-[[[[rtE))((2&+2 2.72 2*/2 2  %0% * 
 
 
 
 
 
 
 
 
 ,,..         __V$$ u	!48}}   lll888888888 &*E/"+/+H+Hk"D, ,(H(;!*51C+D!E!E ; ; ;!&'9!:; ))((B+0+A+NYB B%3B B .@B B  %0% *          ,,..         __U## U	!$qrr(mm   ll(<l========= <44JQww#Z00ll(>l?????????!#H!II&92>>Myy!455H ll(9l:::::::::!M%$,HWh$N$NNNNNNN % % %=sCCC=== $%
--,,[99(4!% .          
    11(#'%) 2          
 !   D ,,)6M%%<M           $(($77777__U## d	!$qrr(mm   ll(<l========= <44JQww#Z00ll(>l?????????!#H!II&92>>Myy!455H ll(9l:::::::::OOOOOO !( 1+*! ! !      
    "/)/sUUUV,ZtLLL,\NNN1   --,,MGOMM   )4!) .          ll(AlBBBBBBBBB!M%$,HWh$N$NNNNNNN % % %=sCCC=== $%--,,[99(4!% .          
  	 	 	11(#'%) 2          
 !   D	 ,,)6M%%<M          
 $(($77777__V$$ Q	!ABBxH.======.=.A.A(RQSUWL.Y.Y+|| . . .')2. A@U;-?@@@GHHHH<HHHG ll(:l;;;;;;;;;G  nc!%%"2E2E.F.FGGV90000055&& +*5NNE(>OAfI>O>OPPP    KJJJaWq0I0IJJJDKK$ZtDDD$\FFF    ,D11H))((.-3-?x. . .  %0% * 
 
 
 
 
 
 
 
 
 ,,..         T\\uyy!449::D+/+H+Hk"D, ,(H(;!*51C+D!E!E ; ; ;!&'9!:; ))((B+0+A+NYB B%3B B .@B B  %0% *          ,,..         T\\$(($777))1! *          ,,..          ,,..         s>  A AA$G< <&H&%H&5N &N76N7O1 1PPR   &S
	S
0V 
V:"V55V:>;W: :
X7X$#X7$
X1.X70X11X76X7Z& &&[[4#^ ^'&^'a( (
b2"bb";c 
d)dd
ddddd<#f   f10f1n/ /oouser_displayc                   K   	 |                     d           d{V  n# t          $ r Y nw xY w	 |                    dt          j        |j        j        pd           dt          j        d           d{V  dS # t          $ r Y dS w xY w)u  Tell the user a clarify tap arrived too late to be delivered.

        Fires when the clarify entry was evicted by ``clarify_timeout`` or the
        gateway restarted between asking and the tap. In both cases the agent
        thread is no longer waiting, so the tap would otherwise leave a
        misleading ✓ (or an "awaiting typed response" prompt) on a button the
        agent never receives.
        u-   ⚠️ This prompt expired — please /retry.r   Nr^  r   uM   

<i>⚠️ This question expired or the session reset — please /retry.</i>r  )	r  r   r  rM  rN  r?  r   r`   rR  )r   r  r  s      r   _notify_clarify_expiredz'TelegramAdapter._notify_clarify_expiredP  s      	,,$S,TTTTTTTTTT 	 	 	D	
	))b5<(:(@bAA b b b %>! *             	 	 	DD	s   ! 
..A
A> >
BBr{  rQ   r  ContextTypes.DEFAULT_TYPEc           
      ,  K   |j         }|r|j        sdS |j        }t          |dd          }t          |dd          }t          |dd          }t          |dd          }t          |dd          }	t          |j        dd          }
|                    d          rC|j        rt          |j        j                  nd}|r|                     |||           d{V  dS |                    d	          r#| 	                    |||||	|

           d{V  dS |                    d          rd|
                    dd          }t          |          dk    r8|d         }	 t          |d                   }n4# t          t          f$ r  |                    d           d{V  Y dS w xY wt          t          |j        dd                    }|                     |||t          |          nd|	t          |	          nd|
          s|                    d           d{V  dS | j                            |d          }|s|                    d           d{V  dS ddddd}t          |j        dd          }|                    |d          }|                    |           d{V  	 |                    |                     | d|           t,          j        d           d{V  n# t0          $ r Y nw xY w	 d d!lm}  |||          }t6                              d"||||           n4# t0          $ r'}t6                              d#|           d }Y d}~nd}~ww xY w|r$|"|                     t          |                     dS |                    d$          r;|
                    dd          }t          |          dk    r|d         }|d         }t          t          |j        dd                    }|                     |||t          |          nd|	t          |	          nd|
          s|                    d%           d{V  dS | j                            |d          }|s|                    d&           d{V  dS dd'd(d)}t          |j        dd          }|                    |d          }|                    |           d{V  	 |                    |                     | d|           t,          j        d           d{V  n# t0          $ r Y nw xY w	 d d*l m!} |"                    |||           d{V }|rE|j        r=t          |j        dd          }t          |j        dd          }t          |dd          }t          |j        d+d          }t          |j        j                  |                     |          t,          j        d,| #                                }t          |d-|          }t          |          $                                d.t          tJ          j&                  $                                t          t          tJ          j&        d-tJ          j&                            $                                hv } || r}|{t          |          }!|!|d/<   |'                    | (                    t          |j        j                  t          |          t          |          d0d1|!| j)        2                     nf|d|'                    | (                    t          |j        j                  t          |          d3t          |          i| j)        4                      | j*        dZi | d{V  n:# t0          $ r-}t6                              d5| j+        |d06           Y d}~nd}~ww xY wdS |                    d7          r9|
                    dd          }t          |          dk    r|d         }"|d         }#t          t          |j        dd                    }|                     |||t          |          nd|	t          |	          nd|
          s|                    d%           d{V  dS | j,                            |"          }|s|                    d&           d{V  dS t          |j        dd          }|#d8k    rd9}$	 d d:l-m.}%  |%|"          }$n8# t0          $ r+}t6          /                    d;| j+        |           Y d}~nd}~ww xY w|$s9| j,                            |"d           | 0                    ||           d{V  dS |                    d<           d{V  	 |                    d=|j        j1        pd d>te          j3        |           d?t,          j4        d           d{V  n# t0          $ r Y nw xY wdS 	 t          |#          }&n4# t          tj          f$ r  |                    d@           d{V  Y dS w xY wd}'	 d dAl-m6}( |(                    |"          })|)r6|)j7        r/d |&cxk    rt          |)j7                  k     rn n|)j7        |&         }'n# t0          $ r d}'Y nw xY w|'dB|&dz    }'| j,                            |"d           	 d dCl-m8}*  |*|"|'          }+n:# t0          $ r-}t6                              dD| j+        |           d9}+Y d}~nd}~ww xY w|+r|                    dE|'ddF                     d{V  	 |                    d=te          j3        |j        j1        pd           dGte          j3        |           dHte          j3        |'           t,          j4        d           d{V  n# t0          $ r Y nw xY wt6                              dI|"|'|           n7| 0                    ||           d{V  t6          /                    dJ|"           dS |                    dK          sdS |
                    dd          d         },t          t          |j        dd                    }|                     |||t          |          nd|	t          |	          nd|
          s|                    dL           d{V  dS |                    dM|, dN           d{V  |,dOk    rdPndQ}	 |                    |                     dR| dS          t,          j        d           d{V  n# t0          $ r Y nw xY w	 d dTl9m:}-  |-            }.|.dUz  }/|/;                    dV          }0|0<                    |,           |0=                    |/           t6                              dW|,t          |j        ddX                     dS # t0          $ r&}t6                              dY|           Y d}~dS d}~ww xY w)[z%Handle inline keyboard button clicks.Nr?  r   rv  r|  r}  
first_name)r  r  r  r  r  r  r  r  zgt:)query_chat_idquery_chat_typequery_thread_idquery_user_namezea:r  r  rl   rv  zInvalid approval data.r   rw  r   rK  u/   ⛔ You are not authorized to approve commands.z(This approval has already been resolved.u   ✅ Approved onceu   ✅ Approved for sessionu   ✅ Approved permanentlyu
   ❌ Denied)oncesessionalwaysdenyUserResolved by r  r   )resolve_gateway_approvalzKTelegram button resolved %d approval(s) for session %s (choice=%s, user=%s)z;Failed to resolve gateway approval from Telegram button: %szsc:u1   ⛔ You are not authorized to answer this prompt.z&This prompt has already been resolved.u   🔒 Always approveu   ❌ Cancelled)r  r  r;   )slash_confirmrn  rb  r   rW  r  T)rM  r  r]  rM  r?  z&[%s] slash-confirm callback failed: %sr   rc  otherF)mark_awaiting_textz"[%s] mark_awaiting_text failed: %su$   ✏️ Type your answer in the chat.r^  z"

<i>Awaiting typed response from u   …</i>zInvalid choice.)_entrieszchoice )resolve_gateway_clarifyz'[%s] resolve_gateway_clarify failed: %sr  r  z

<b>z:</b> z<Telegram clarify button resolved (id=%s, choice=%r, user=%s)zGTelegram clarify button: resolve_gateway_clarify returned False (id=%s)zupdate_prompt:u4   ⛔ You are not authorized to answer update prompts.zSent 'z' to the update process.yYesNou   ⚕ Update prompt answered: *rg  r  z.update_responsez.tmpz/Telegram update prompt answered '%s' by user %srs  z1Failed to write update response from callback: %srj   )>callback_queryr  rL   ru  r  r?  r   r   r  _handle_gmail_triage_callbackrk  r  r  r   
IndexErrorr  rs  r1  r  r)  r  r  r`   r  r   tools.approvalr  r   r  r
   resume_typing_for_chatr2  toolsr  resolver  rj  ra   PRIVATEr{  r  r  r9  r   r3  tools.clarify_gatewayr  r  r  r   rM  rN  rR  r   r  r[  r  r!  r  with_suffix
write_textreplace)1r   r{  r  r  r  query_messager  
query_chatr  r  r  r   partschoicerT  	caller_idr:  	label_mapr  r  r  rP  rN  rV  _slash_confirm_modr  rM  rv  rL  prompt_message_idr  chat_type_valueis_private_chatrd  r\  choice_tokenflippedr  rf  resolved_text_clarify_entriesr  r  resolvedr  r  homeresponse_pathtmps1                                                    r   r  z&TelegramAdapter._handle_callback_queryi  s      % 	EJ 	Fzy$77y$??]FD99
!*fd;;!-1DdKK!%/<FF ??STT 	49MKc%-/000tG O88gNNNNNNNNNF ??5!! 		44+ / / / 5          F ??5!! D	JJsA&&E5zzQq"%eAh--KK"J/   ,,,D,EEEEEEEEEFF
  r B BCC	88)6E6Qc/222W[6E6Qc/222W[- 9     ,,,],^^^^^^^^^F"266{DII" ,,,V,WWWWWWWWWF 098(	 	  'ufMM!fj99lll.........11!00E1M1M|1M1MNN#,#8%) 2          
 !   D	GGGGGG44[&IIEKKe{FL    !   LL!^`cdddEEEEEE  D]6//M0B0BCCCF ??5!! a	JJsA&&E5zzQq"1X
r B BCC	88)6E6Qc/222W[6E6Qc/222W[- 9     ,,,_,`````````F"7;;JMM" ,,,T,UUUUUUUUUF 03- 	
  'ufMM!fj99lll.........11!00E1M1M|1M1MNN#,#8%) 2          
 !   D3jIIIIII(:(B(B#Z) ) # # # # # #K # ,Uu} ,U %,EM;NPT$U$U	&u}fdCC$+D&$$?$?	,3EM<QU,V,V)'*5=+@'A'A$($7$7$D$D*3*?7 7 #7799	7 +2)Wi*P*P*-o*>*>*D*D*F*F% 0117799(8'8CS T TUU[[]]K +
 %0_0IZIf*-.?*@*@KALK(=>'.. $ < <$'(=$>$>$'	NN58^^LP%& %& 9D262E != 	!" 	!"    '2'.. $ < <$'(=$>$>$'	NN%0#i..$A262E	 != !" !"   FdETTTTTTTTTTT  j j jLL!I49VYdhLiiiiiiiijF ??5!! q	JJsA&&E5zzQ"1X
$Qxr B BCC	88)6E6Qc/222W[6E6Qc/222W[- 9     ,,,_,`````````F"155jAA" ,,,T,UUUUUUUUUF&ufMM7** $G]LLLLLL"4"4Z"@"@$ ] ] ]'KTYX[\\\\\\\\] #  +//
DAAA"::5,OOOOOOOOO,,,R,SSSSSSSSS#55 "J(:(@b  "J  "Jfkfrs  gA  gA  "J  "J  "J'0~)- 6          
 %   Fl++CC"I.   ,,,=,>>>>>>>>>FF 04)RRRRRR,00<<E ; ;13P3P3P3Pc%->P>P3P3P3P3P3P(-c(:  ) ) )$(MMM) !( %8cAg$7$7M #''
D999%MMMMMM66z=QQHH  % % %LL!JDIWZ[[[$HHHHHH%  ,,,G="3E,G,G,HHHHHHHHH#55 "WU]5G5M2(N(N  "W  "WW\WcdpWqWq  "W  "Wy~  zF  GT  zU  zU  "W  "W'0~)- 6          
 %   KKV"M<    66ulKKKKKKKKKNNa"   F /00 	FC##A&r::;;	00!.=.Ic/***t.=.Ic/***t% 1 
 
 	 ,,$Z,[[[[[[[[[Fll I I I IlJJJJJJJJJ3D	))(()Q)Q)Q)QRR$0! *          
  	 	 	D	
	S888888"?$$D #55M++F33CNN6"""KK&&&KKIy I IK K K K K 	S 	S 	SLLLcRRRRRRRRR	Ss   E6 6-F'&F'2A K3 3
L ?L 0L5 5
M&?M!!M&(A T) )
T65T6:I+^& &
_0#__	d 
e%!ee+Ag9 9
hhh -iiAj' 'j65j6k2 2
l)<#l$$l)A3o
 

oo?u 
uuBw# #
x-xxzsend-draft.shu   ✓ sent draftz
archive.shu   ✓ archivedzdraft-blank.shu   ✓ drafted replyzspam.shu   ✓ marked spamzmute-add.shemailu	   ✓ muteddomainu   ✓ muted domainztrusted-ops-add.shu   ✓ trustedu   ✓ trusted domainz
vip-add.shu   ✓ marked VIPu   ✓ marked VIP domain)
r  archivedraftspammutezmute-domaintrustztrust-domainvipz
vip-domainc          	        K   |                     dd          }t          |          dk    r|                    d           d{V  dS |d         |d         }	}t          t	          |j        dd	                    }
|                     |
||t          |          nd|t          |          nd|
          s|                    d           d{V  dS | j                            |          }|s!|                    d|            d{V  dS |\  }}}}t          j
                    dz  dz  dz  |z  }|                                sC|                    d| d           d{V  t                              d| j        |           dS t          |          |	g|}d}	 t          j        |t          j        j        t          j        j        d d{V }t          j        |                                d           d{V \  }}|j        dk    r'|}d}t                              d| j        ||	           n|                    dd                                          }|r|                                d         n	d|j         }d| d|dd           }t                              d!| j        ||	|j        |           n|# t          j        $ r+ d| d"}t                              d#| j        ||	           Y nCt6          $ r7}d| d$| }t                              d%| j        ||	|d&           Y d}~nd}~ww xY w|                    |           d{V  |sdS t	          |j        d'd(          }|j        r|j        j        pd	nd	}| d)| d*| }	 |r|                    |           d{V  dS |                    |d+           d{V  dS # t6          $ r Y dS w xY w),z=Dispatch a gmail-triage inline-button callback (gt:verb:arg).r  r  rl   zInvalid gmail-triage data.r   Nrv  rw  r   rK  u0   ⛔ You are not authorized to act on this email.zUnknown verb: z.hermesscriptszgmail-triageu   ❌ z missingz$[%s] gmail-triage script missing: %sF)stdoutstderrr  r  r   Tz-[%s] gmail-triage callback ok: verb=%s arg=%sr  r  )errorsr"  zexit z	 failed: P   zA[%s] gmail-triage callback failed: verb=%s arg=%s rc=%s stderr=%sz
 timed outz4[%s] gmail-triage callback timed out: verb=%s arg=%sz error: z;[%s] gmail-triage callback exception: verb=%s arg=%s err=%sr   r  r  u   
— r  r  )rk  r  r  r   rL   ru  rs  _GT_VERB_DISPATCHr)  _Pathr  r"  r   r
   r   r   create_subprocess_exec
subprocessPIPEr  communicate
returncoder  decoderb  r8  r>   r   r?  r   r  )r   r  r  r  r  r  r  r  verbargr  r  script_name
extra_argssuccess_labelis_state_verbscript_pathcmdrw  proc_stdout_bytesstderr_bytesr  stderr_text	last_linerN  r  original_textappendeds                                r   r  z-TelegramAdapter._handle_gmail_triage_callback  sK      

3""u::??,,$@,AAAAAAAAAF!HeAhcr::;;	00!.=.Ic/***t.=.Ic/***t% 1 
 
 	 ,,$V,WWWWWWWWWF&**400 	,,$;T$;$;,<<<<<<<<<F@E=ZjllY.:^KkY!!## 	,,$@;$@$@$@,AAAAAAAAALL?KXXXF;2z2 	 7).).        D
 180@  ""B1 1 1 + + + + + +'M< !##%CItS   
 +11')1LLRRTT<GfK2244R88MfUYUdMfMf	>t>>in>>WItS$/;   # 	g 	g 	g+4+++ELLOQUQZ\`befffff 	 	 	.4....ELLM	4cD         	 lll&&&&&&&&& 	FufEE6;mK+1r#DD5DDlDD		 P --8-<<<<<<<<<<< --8$-OOOOOOOOOOO 	 	 	DD	s7   'D!K	 	7M	M-L==MO =O 
O*)O*r  r  c                 H    | d| }|                     d          r|dz  }|S )zBuild an actionable file-not-found error for gateway MEDIA delivery.

        Paths like /workspace/... or /output/... often only exist inside the
        Docker sandbox, while the gateway process runs on the host.
        z file not found: )z/workspace/z/output/z	/outputs/z (path may only exist inside the Docker sandbox. Bind-mount a host directory and emit the host-visible path in MEDIA: for gateway file delivery.))r  )r   r  r  r
   s       r   _missing_media_path_errorz)TelegramAdapter._missing_media_path_errorB  sB     11411??CDD 	=E
 r)   	file_size	max_bytesc                     t          d|dz            }	 t          |pd          dz  }|dd}n# t          t          f$ r d}Y nw xY wd| d| d	| d
S )Nrv     r   z.1fz MBzunknown sizez
[Telegram z skipped: file size z exceeds the z0 MB limit. Ask the user to send a smaller file.])r6   r  r   r   )r   r  rB  rC  limit_mbsize_mb	size_texts          r   _telegram_media_too_large_notez.TelegramAdapter._telegram_media_too_large_noteQ  s    q)455	').q))[9G"++++II:& 	' 	' 	'&III	'J J JI J JJ J J	
s   0 AArp  c                    t          t          | dd          pd          }t          |dd          }	 t          |pd          }n# t          t          f$ r d}Y nw xY w|dk    rdS ||k    rdS d|                     |||          fS )z<Validate Telegram media size before downloading into memory.r/  r   rB  Nr   )TNF)r  rL   r   r   rI  )r   rp  r  rC  rB  sizes         r   _telegram_media_size_allowedz,TelegramAdapter._telegram_media_size_allowed]  s    &68HII]M]^^	FK66		y~A&&DD:& 	 	 	DDD	199:9:d99%yQQQQs   A AA
audio_pathcaptionc           
        K   | j         st          dd          S 	 t          j                            |          s%t          d|                     d|                    S t          |d          5 t          j                            |          d                                         }|dv r| 	                    |          }| 
                    ||| j                  }	|                     ||||	| j        	          }
|                     | j         j        t          |          |r
|d
d         nd
|	d|
|                     |          ||	dfd           d
{V }n|dv r| 	                    |          }| 
                    ||| j                  }	|                     ||||	| j        	          }|                     | j         j        t          |          |r
|d
d         nd
|	d||                     |          ||	dfd           d
{V }n,|                     |||||           d
{V cd
d
d
           S d
d
d
           n# 1 swxY w Y   t          dt'          |j                            S # t*          $ rY}t,                              d| j        |d           t3                                          |||||           d
{V cY d
}~S d
}~ww xY w)z<Send audio as a native Telegram voice message or audio file.Fr  r  Audiorbrv  >   .opus.oggr?  r]  Nr   )r   voicerN  r  rT  c                  .                          d          S Nr   seek
audio_files   r   r}  z,TelegramAdapter.send_voice.<locals>.<lambda>      JOOA,>,> r)   r  >   .m4a.mp3)r   audiorN  r  r_  c                  .                          d          S rV  rW  rY  s   r   r}  z,TelegramAdapter.send_voice.<locals>.<lambda>  r[  r)   )r   	file_pathrN  r  rF  Trz  zJ[%s] Failed to send Telegram voice/audio, falling back to base adapter: %sr   r  )r  rs   r   r  r"  rA  r$  splitextrj  r  r  r  r  r  
send_voicer   rJ  
send_audiosend_documentr   rn  r   r   r
   r   r   )r   r   rM  rN  r  rF  r  ext_voice_threadrd  voice_thread_kwargsr  _audio_threadaudio_thread_kwargsr   rZ  r8  s                  @r   rc  zTelegramAdapter.send_voicek  sH      y 	De?CCCCL	g7>>*-- l!%t7U7UV]_i7j7jkkkkj$'' ?:g&&z2215;;==+++$($<$<X$F$FM"&"D"DXxgkgz"D"{"{K*.*F*F% ,7&*&9 +G + +' !% K K	,'A''J'J%/9@'Jwuu~~d3>	 
 2 #77AA !#$>$>$>$> !L ! !      CC ,,,$($<$<X$F$FM"&"D"DXxgkgz"D"{"{K*.*F*F% ,7&*&9 +G + +' !% K K	,'A''J'J%/9@'Jwuu~~d3>	 
 2 #77AA !#$>$>$>$> !L ! !      CC$ "&!3!3 '", '!)!) "4 " "      s? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?@ ds3>7J7JKKKK 	g 	g 	gLL\		     ++GZ(]e+ffffffffffffff	gsP   AJ "J 2G	I;J J IJ I%J 
K%AK K% K%r.   imageshuman_delayc           
        K   | j         sdS |sdS 	 ddlm} nc# t          $ rV}t                              d| j        |           t                                          ||||           d{V  Y d}~dS d}~ww xY wg }g |D ]^\  }}	|	                    d          s-| 
                    |          r|                    ||	f           G                    ||	f           _|r+t                                          ||||           d{V  sdS ddlm}
 |                     |          }dfd	t          dt!                              D             }t#          |          D ]\  }}|dk    r |dk    rt%          j        |           d{V  g }g 	 |D ]\  }}	|	r
|	dd
         nd}|	                    d          r |
|dd                   }t(          j                            |          s"t                              d| j        |           |t/          |d          }                    |           |                     |||                     |                     |||                     |s-	 D ]'}	 |                                 # t          $ r Y $w xY wEt                              d| j        t!          |          |dz   t!          |                     |                     d|| j                  }|                     ||||| j                  }dfd}|                     | j         j        t?          |          ||d||                      |          ||d|           d{V  nw# t          $ rj}t                              d| j        |dz   t!          |          |d           t                                          ||||           d{V  Y d}~nd}~ww xY wD ]'}	 |                                 # t          $ r Y $w xY w# D ]'}	 |                                 # t          $ r Y $w xY ww xY wdS )a)  Send a batch of images natively via Telegram's media group API.

        Telegram's ``send_media_group`` bundles up to 10 photos/videos into
        a single album. Larger batches are chunked. Animated GIFs cannot
        go into a media group (they require ``send_animation``), so they
        are peeled off and sent individually via the base default path.

        URL-based photos go into the group directly; local files are
        opened as byte streams. On failure the whole batch falls back to
        the base adapter's per-image loop.
        Nr   )InputMediaPhotozD[%s] InputMediaPhoto unavailable, falling back to per-image send: %szfile://)rl  )unquoter  c                 *    g | ]}||z            S rj   rj   )r   r  CHUNKphotoss     r   rE  z8TelegramAdapter.send_multiple_images.<locals>.<listcomp>  s&    LLL!&1u9%LLLr)   r      z.[%s] Skipping missing image in media group: %srQ  )mediarN  z5[%s] Sending media group of %d photo(s) (chunk %d/%d)rv  r?  r]  r   c                  ^    D ](} 	 |                      d           # t          $ r Y %w xY wd S rV  )rX  r   )fhopened_filess    r   _reset_opened_fileszATelegramAdapter.send_multiple_images.<locals>._reset_opened_files'  sR    * ! !!GGAJJJJ( ! ! ! D!! !s   
**)r   rt  r  zmedia groupr\  zI[%s] send_media_group failed (chunk %d/%d), falling back to per-image: %sTr   r0   )!r  r   rn  r   r   r  r   r   send_multiple_imagesr  _is_animation_urlr   r  ro  r  r  r  r  r   r  r   r  r"  r$  closer  r  r  r  r  send_media_groupr   rJ  )r   r   rk  rF  rl  rn  rN  
animations	image_urlalt_text_unquote_threadr  	chunk_idxr  rt  rN  
local_pathrv  rd  re  rx  r   rq  rw  rr  r8  s                          @@@r   ry  z$TelegramAdapter.send_multiple_images  sF     $ y 	F 	F	0000000 	 	 	NNV	3   ''..w+VVVVVVVVVFFFFF	 #%
 #) 	5 	5Ix''	22 5t7M7Mi7X7X 5!!9h"78888y(34444  	''..X; /           	F444444**844 LLLLLuQFU/K/KLLL )& 1 1 K	 K	IuQ9q==mK000000000!E&(LE+0 X X'Ix19ChuuootG ++I66 X%-Xim%<%<
!w~~j99 %"NN P $	:   %!*d33$++B///__2w%O%O%OPPPP__9g%V%V%VWWWW ^ '  B



$   [ KIs5zz9q=#f++   #@@x_c_r@ss $ < <(3"&"5 != ! !! ! ! ! ! ! AAI.#=g#F#F!&/:  (	
 33H== ! 3 B            	 	 	_Iy1}c&kk1!     gg22UH+ 3              	 '  B



$   ,  B



$   OK	 K	s    
A<AA77A<C'N
J
J,+J,1CNP*
O;A O61P*6O;;P*P
P%$P%*Q0QQ
QQQQ
image_pathc           
        K   | j         st          dd          S 	 t          j                            |          s%t          d|                     d|                    S |                     |          }|                     ||| j                  }| 	                    ||||| j                  }	t          |d          5 |                     | j         j        t          |          |r
|dd	         nd|d
|	|                     |          ||dfd           d{V }
ddd           n# 1 swxY w Y   t          dt          |
j                            S # t"          $ r}t          |          }d|v pd|v }|r"t$                              d| j        |           n#t$                              d| j        |d           	 |                     |||t          j                            |          ||           d{V cY d}~S # t"          $ r^}t$                              d| j        |d           t3                                          |||||           d{V cY d}~cY d}~S d}~ww xY wd}~ww xY w)z5Send a local image file natively as a Telegram photo.Fr  r  Imager?  r]  rQ  Nr   r   photorN  r  r  c                  .                          d          S rV  rW  )
image_files   r   r}  z1TelegramAdapter.send_image_file.<locals>.<lambda>u  s    
(:(: r)   r\  Trz  Photo_invalid_dimensionsPHOTO_INVALID_DIMENSIONSzK[%s] Image dimensions exceed Telegram photo limits, sending as document: %szO[%s] Failed to send Telegram local image as photo, trying document fallback: %sr   )r   ra  rN  	file_namer  rF  zV[%s] Failed to send Telegram local image as document, falling back to base adapter: %sr  )r  rs   r   r  r"  rA  r  r  r  r  r$  r  
send_photor   rJ  r   rn  r   r   r  r   r  re  basenamer
   r   send_image_file)r   r   r  rN  r  rF  r  r  rd  re  r  r   	error_stris_dim_errordoc_errr  r8  s                  @r   r  zTelegramAdapter.send_image_fileM  s      y 	De?CCCCN	p7>>*-- l!%t7U7UV]_i7j7jkkkk..x88G<<Xx_c_r<ssK 88$/"1 9  M j$'' : GGI(#=g#F#F!+5<#F75D5>>$/:	 
 ( 33H==  : : : : H                        ds3>7J7JKKKK 0	p 0	p 0	pAI +i7 ;-:   .I	    3I!    p!//#(# g..z::%% 0                p p p7I!     #WW44Wj'S[fn4ooooooooooooooooooopQ0	ps|   AE! "A!E! A$D3'E! 3D77E! :D7;%E! !I>,AI9=HI>
I6AI1&I6'I9+I>1I66I99I>ra  r  c           
        K   | j         st          dd          S 	 t          j                            |          s%t          d|                     d|                    S |pt          j                            |          }|                     |          }	|                     ||| j	                  }
| 
                    ||	||
| j	                  }t          |d          5 |                     | j         j        t          |          ||r
|dd	         nd|
d
||                     |          ||
dfd           d{V }ddd           n# 1 swxY w Y   t          dt!          |j                            S # t$          $ re}t&                              d| j        t-          |                     t/                                          ||||||           d{V cY d}~S d}~ww xY w)z<Send a document/file natively as a Telegram file attachment.Fr  r  Filer?  r]  rQ  Nr   )r   documentfilenamerN  r  r  c                  .                          d          S rV  rW  r)  s   r   r}  z/TelegramAdapter.send_document.<locals>.<lambda>      q		 r)   r\  Trz  z [%s] Failed to send document: %sr  )r  rs   r   r  r"  rA  r  r  r  r  r  r$  r  re  r   rJ  r   rn  r   r   r  r   r   r   )r   r   ra  rN  r  r  rF  r  display_namer  rd  re  r  r   r)  r8  s                 @r   re  zTelegramAdapter.send_document  s      y 	De?CCCC&	t7>>),, j!%t7U7UV\^g7h7hiiii$C(8(8(C(CL..x88G<<Xx_c_r<ssK 88$/"1 9  M i&& ! GGI+#=g#F#F$%$05<#F75D5>>$/:  ( 33H==  1 1 1 1 H                      " ds3>7J7JKKKK 	t 	t 	tNN2	6q99   ..w	7IW_jr.ssssssssssssss	tsK   AF "BF $A%E	F EF E%F 
G2AG-'G2-G2
video_pathc           
        K   | j         st          dd          S 	 t          j                            |          s%t          d|                     d|                    S |                     |          }|                     ||| j                  }| 	                    ||||| j                  }	t          |d          5 |                     | j         j        t          |          |r
|dd	         nd|d
|	|                     |          ||dfd           d{V }
ddd           n# 1 swxY w Y   t          dt          |
j                            S # t"          $ rd}t$                              d| j        t+          |                     t-                                          |||||           d{V cY d}~S d}~ww xY w)z2Send a video natively as a Telegram video message.Fr  r  Videor?  r]  rQ  Nr   )r   videorN  r  r  c                  .                          d          S rV  rW  r  s   r   r}  z,TelegramAdapter.send_video.<locals>.<lambda>  r  r)   r\  Trz  z[%s] Failed to send video: %sr  )r  rs   r   r  r"  rA  r  r  r  r  r$  r  
send_videor   rJ  r   rn  r   r   r  r   r   r   )r   r   r  rN  r  rF  r  r  rd  re  r  r   r)  r8  s               @r   r  zTelegramAdapter.send_video  s      y 	De?CCCC#	g7>>*-- l!%t7U7UV]_i7j7jkkkk..x88G<<Xx_c_r<ssK 88$/"1 9  M j$'' 1 GGI(#=g#F#F!"5<#F75D5>>$/:	 
 ( 33H==  1 1 1 1 H                        ds3>7J7JKKKK 	g 	g 	gNN/	6q99   ++GZ(]e+ffffffffffffff	gsK   AE! "A!E! A$D3'E! 3D77E! :D7;%E! !
G+AG
G
Gr~  c           	        K   | j         st          dd          S ddlm}  ||          sLt                              d| j                   t                                          |||||           d{V S 	 | 	                    |          }| 
                    ||| j        	          }|                     ||||| j        
          }	|                     | j         j        t          |          ||r
|dd         nd|d|	|                     |          ||d           d{V }
t          dt#          |
j                            S # t&          $ r}t                              d| j        |d           	 ddl}|                    d          4 d{V }|                    |           d{V }|                                 |j        }ddd          d{V  n# 1 d{V swxY w Y   |                     ||||| j        
          }|                     | j         j        t          |          ||r
|dd         nd|d||                     |          ||d           d{V }
t          dt#          |
j                            cY d}~S # t&          $ r^}t                              d| j        |d           t                                          |||||           d{V cY d}~cY d}~S d}~ww xY wd}~ww xY w)zSend an image natively as a Telegram photo.
        
        Tries URL-based send first (fast, works for <5MB images).
        Falls back to downloading and uploading as file (supports up to 10MB).
        Fr  r  r   )is_safe_urlz/[%s] Blocked unsafe image URL (SSRF protection)r  Nr?  r]  r   r  z	URL photoTrz  z8[%s] URL-based send_photo failed, trying file upload: %sr   r{  r  zuploaded photoz+[%s] File upload send_photo also failed: %s)r  rs   tools.url_safetyr  r   r  r   r   
send_imager  r  r  r  r  r  r   rJ  r   rn  r   r  AsyncClientr)  raise_for_statusr  r
   )r   r   r~  rN  r  rF  r  _photo_threadrd  photo_thread_kwargsr  r   r  clientresp
image_dataupload_thread_kwargse2r8  s                     r   r  zTelegramAdapter.send_image  s      y 	De?CCCC000000{9%% 	fNNLdiXXX++GY\d+eeeeeeeeeG	j 44X>>M<<Xx_c_r<ssK"&">">$/"1 #? # # CC	$9'BB&18Bwuu~~d+6	 
 * //99        C ds3>7J7JKKKK -	j -	j -	jNNJ		    %j ,,T,:: . . . . . . .f!'I!6!6666666D))+++!%J. . . . . . . . . . . . . . . . . . . . . . . . . . .
 (,'C'C!(3"&"5 (D ( ($ !GGI(#=g#F#F!+5<#F75D5>>$/:	 
 / 33H== $        "$3s~;N;NOOOOOOOOO j j jAI!	     #WW//GX`h/iiiiiiiiiiiiiiiiiiijK-	jsu   :CE L
#L; J7G$J$
G.	.J1G.	2B"JL

L$AK=2L3L7L
=LLL
animation_urlc                   K   | j         st          dd          S 	 |                     |          }|                     ||| j                  }|                     ||||| j                  }|                     | j         j        t          |          ||r
|dd         nd|d|| 	                    |          ||d	           d{V }	t          d
t          |	j                            S # t          $ rM}
t                              d| j        |
d
           |                     |||||           d{V cY d}
~
S d}
~
ww xY w)zJSend an animated GIF natively as a Telegram animation (auto-plays inline).Fr  r  r?  r]  Nr   )r   	animationrN  r  r  Trz  zA[%s] Failed to send Telegram animation, falling back to photo: %sr   r  )r  rs   r  r  r  r  r  send_animationr   rJ  r   rn  r   r   r
   r   r  )r   r   r  rN  r  rF  _anim_threadrd  animation_thread_kwargsr  r   s              r   r  zTelegramAdapter.send_animationp  s      y 	De?CCCC!	g33H==L<<Xx_c_r<ssK&*&B&B$/"1 'C ' '# CC	(9'BB!.18Bwuu~~d+6	 
 . //99        C ds3>7J7JKKKK 	g 	g 	gLLS		     -(]effffffffffffff	gs   CC. .
E8AE :E Ec                 .  K   | j         r
d}d}	 |                     |          }t          |o|                    d                    }|                     |          }| j                             t          |          d|           d{V  dS # t          $ rx}|rH|F	 | j                             t          |          d           d{V  Y d}~dS # t          $ r Y nw xY wt          	                    d| j
        |d	           Y d}~dS d}~ww xY wdS )
zSend typing indicator.FNr  typing)r   actionr}  )r   r  z1[%s] Failed to send Telegram typing indicator: %sTr   )r  r  r'  r)  r  send_chat_actionr   r   r   r   r   )r   r   rF  _is_dm_topicr}  _typing_threadr   s          r   r  zTelegramAdapter.send_typing  s     9 	!&L/3!%!9!9(!C!C#H$a>`1a1abb$($F$F~$V$V!i006w??#&7 1           
       $5$A"i88$>w$G$G#+ 9          $    GI!	          	 	s6   A>B 
DD/C
C!D C!!&DDc                 @  K   | j         sdddS 	 | j                             t          |                     d{V }d}|j        t          j        k    rd}n8|j        t          j        k    rd}|j        rd}n|j        t          j        k    rd}|j	        p|j
        pt          |          ||j        t          |dd	          d
S # t          $ rN}t                              d| j        ||d           t          |          dt          |          dcY d}~S d}~ww xY w)z&Get information about a Telegram chat.UnknownrV  )r   r|  Nr   rY  channelr  F)r   r|  rx  r  z0[%s] Failed to get Telegram chat info for %s: %sTr   )r   r|  r
   )r  get_chatr   r|  ra   GROUP
SUPERGROUPr  CHANNELr{  ry  r   rx  rL   r   r   r
   r   )r   r   rv  rL  r   s        r   get_chat_infozTelegramAdapter.get_chat_info  sf     y 	5%t444	I++,Fw,O,OPPPPPPPPDIyHN**#		h111#	= ( 'Ih...%	 
DdnDG! M#D*e<<	    	I 	I 	ILLB	      LL$QHHHHHHHH	Is   B4C 
DADDDc                 @   |s|S i dgdt           dt           ffd|}t          |          }fd}t          j        d||          }t          j        dfd|          }fd	}t          j        d
||          }fd}t          j        d||t          j                  }t          j        dfd|          }t          j        dfd|          }t          j        dfd|          }t          j        dfd|          }fd}t          j        d||t          j                  }t          |          }t          t                                                              D ]}|	                    ||                   }t          j
        d|          }g }	t          |          D ]R\  }
}|
dz  dk    r|	                    |           $|fd}|	                    t          j        d||                     Sd                    |	          }|S )af  
        Convert standard markdown to Telegram MarkdownV2 format.

        Protected regions (code blocks, inline code) are extracted first so
        their contents are never modified.  Standard markdown constructs
        (headers, bold, italic, links) are translated to MarkdownV2 syntax,
        and all remaining special characters are escaped.
        r   r   r   c                 J    dd          d}dxx         dz  cc<   | |<   |S )z@Stash *value* behind a placeholder token that survives escaping.z PHr    rv  rj   )r   r  counterplaceholderss     r   _phz+TelegramAdapter.format_message.<locals>._ph  s;    +71:+++CAJJJ!OJJJ %LJr)   c                 ,   |                      d          }d|dd          v r|                    d          dz   nd}|d |         }||d          }|d d         }|                    dd                              dd	          } ||z   d
z             S )Nr   r   rl   rv  \\\`z\`z```)r   indexr  )r   r   open_endopeningbody_and_closebodyr  s         r   _protect_fencedz7TelegramAdapter.format_message.<locals>._protect_fenced  s    ''!**C.2c!""goosyy**1H)8)nG ^N!#2#&D<<f--55c5AAD3w~-...r)   z(```(?:[^\n]*\n)?[\s\S]*?```)z	(`[^`]+`)c                 h     |                      d                              dd                    S )Nr   r  r  )r   r  r   r  s    r   r}  z0TelegramAdapter.format_message.<locals>.<lambda>  s+    cc!''!**,,T6::;; r)   c                     t          |                     d                    }|                     d                              dd                              dd          } d| d| d          S )	Nrv  r  r  r  r<  z\)[]()r   r   r  )r   displayurlr  s      r   _convert_linkz5TelegramAdapter.format_message.<locals>._convert_link  sm    "1771::..G''!**$$T622::3FFC3,7,,c,,,---r)   z-\[([^\]]+)\]\(([^()]*(?:\([^()]*\)[^()]*)*)\)c                     |                      d                                          }t          j        dd|          } dt	          |           d          S )Nrv  \*\*(.+?)\*\*r   rg  )r   rb  r   r   r   )r   innerr  s     r   _convert_headerz7TelegramAdapter.format_message.<locals>._convert_header$  sV    GGAJJ$$&&EF+UE::E31<..111222r)   z^#{1,6}\s+(.+)$)flagsr  c                 b     dt          |                     d                     d          S )Nrg  rv  r   r   r  s    r   r}  z0TelegramAdapter.format_message.<locals>.<lambda>1  /    cc9l1771::66999:: r)   z\*([^*\n]+)\*c                 b     dt          |                     d                     d          S )NrA   rv  r  r  s    r   r}  z0TelegramAdapter.format_message.<locals>.<lambda>:  r  r)   z	~~(.+?)~~c                 b     dt          |                     d                     d          S )N~rv  r  r  s    r   r}  z0TelegramAdapter.format_message.<locals>.<lambda>A  r  r)   z\|\|(.+?)\|\|c                 b     dt          |                     d                     d          S )N||rv  r  r  s    r   r}  z0TelegramAdapter.format_message.<locals>.<lambda>H  s/    cc;|AGGAJJ77;;;<< r)   c           	      2   |                      d          }|                      d          }|                    d          r;|                    d          r& | dt          |d d                    d          S  | dt          |                     S )Nrv  r  z**r   )r   r  r  r   )r   prefixr  r  s      r   _convert_blockquotez;TelegramAdapter.format_message.<locals>._convert_blockquoteO  s    WWQZZFggajjG   && G7+;+;D+A+A GsfEE|GCRCL'A'AEEEFFF3&::<#8#8::;;;r)   z^((?:\*\*)?>{1,3}) (.+)$z(```[\s\S]*?```|`[^`]+`)r  rv  c                    |                                  }|                     d          }|dk    r||dz
           dk    r|S |dk    r|dk    r||dz
           dk    r|S |dk    r|d |         }d|v sd|v rnd}t          |dz
  t          |d	z
  d
          d
          D ]F}||         dk    r'|dz  }|dk     r|dk    r||dz
           dk    r|c S  n5||         dk    r|dz  }Gd|z   S )Nr   rv  r  (]r<  z](httpr  i  r"  )r8   r   r  r6   )r   _segrW  chbeforedepthjs          r   	_esc_barez1TelegramAdapter.format_message.<locals>._esc_barer  s1   		AB1uua!e!4!4!	SyyQUUtAE{c/A/A!	Syy!%bqb#v--$%E%*1q5#a$h2C2CR%H%H / /#'7c>>$)QJE',qyy+,q55T!a%[C5G5G35III(- (1 &*!W^^$)QJE"9$r)   z[(){}]r   )r   _wrap_markdown_tablesr   r   	MULTILINEr   reversedr  r  r  rk  r  r   r   )r   r  r   r  r  r  r  r  _code_split_safe_parts_idxr  r  r  r  r  s                @@@r   r  zTelegramAdapter.format_message  s     	N#	s 	s 	 	 	 	 	 	 	  %T**	/ 	/ 	/ 	/ 	/ v,
 
 v;;;;
 
	. 	. 	. 	. 	.
 vFW[\\	3 	3 	3 	3 	3 vR\
 
 

 v::::
 
 v::::
 
 v::::
 
 v<<<<
 
	< 	< 	< 	< 	< v',	
 
 
 D!! D!2!2!4!45566 	8 	8C<<\#%677DD
 h:DAA#K00 	G 	GJD$ax1}}""4(((( '+ % % % %2 ""26)Y#E#EFFFFww{##r)   c                 
   | j         j                            d          }|:t          |t                    r|                                dv S t          |          S t          j        dd                                          dv S )zBReturn whether group chats should require an explicit bot trigger.require_mentionN>   r   r  r^  r_  TELEGRAM_REQUIRE_MENTIONr  	r   r(  r)  r  r   rj  r'  r   r   r  s     r   _telegram_require_mentionz)TelegramAdapter._telegram_require_mention  s    [&**+<==
!*c** H!''))-GGG
###y3W==CCEEIcccr)   c                 L   | j         j                            d          }|| j         j                            d          }|:t          |t                    r|                                dv S t          |          S t          j        dd                                          dv S )aM  Return whether skipped unmentioned group messages are stored as context.

        When enabled with ``require_mention``, Telegram matches the Yuanbao /
        OpenClaw-style group UX: observe ordinary group chatter in the session
        transcript, but only dispatch the agent when the bot is explicitly
        addressed.
        "observe_unmentioned_group_messagesN!ingest_unmentioned_group_messages>   r   r  r^  r_  +TELEGRAM_OBSERVE_UNMENTIONED_GROUP_MESSAGESr  r   r  s     r   ,_telegram_observe_unmentioned_group_messagesz<TelegramAdapter._telegram_observe_unmentioned_group_messages  s     [&**+OPP
*../RSSJ!*c** H!''))-GGG
###yFPPVVXX\vvvr)   c                 
   | j         j                            d          }|:t          |t                    r|                                dv S t          |          S t          j        dd                                          dv S )zFReturn whether non-allowlisted groups may trigger via direct @mention.
guest_modeN>   r   r  r^  r_  TELEGRAM_GUEST_MODEr  r   r  s     r   _telegram_guest_modez$TelegramAdapter._telegram_guest_mode  s~    [&**<88
!*c** H!''))-GGG
###y.88>>@@D^^^r)   c                 
   | j         j                            d          }|:t          |t                    r|                                dv S t          |          S t          j        dd                                          dv S )zJReturn whether explicit @...bot mentions exclusively route group messages.exclusive_bot_mentionsN>   r   r  r^  r_  TELEGRAM_EXCLUSIVE_BOT_MENTIONSr_  r   r  s     r    _telegram_exclusive_bot_mentionsz0TelegramAdapter._telegram_exclusive_bot_mentions  s    [&**+CDD
!*c** H!''))-GGG
###y:FCCIIKKOiiir)   c                    | j         j                            d          }|t          j        dd          }t          |t                    rd |D             S d t          |                              d          D             S )Nfree_response_chatsTELEGRAM_FREE_RESPONSE_CHATSr   c                     h | ]D}t          |                                          #t          |                                          ES rj   r  r   parts     r   r   z@TelegramAdapter._telegram_free_response_chats.<locals>.<setcomp>  =    KKK$T9J9JKCIIOO%%KKKr)   c                 ^    h | ]*}|                                 |                                 +S rj   ra  r  s     r   r   z@TelegramAdapter._telegram_free_response_chats.<locals>.<setcomp>  -    MMM

M

MMMr)   rf  	r   r(  r)  r   r   r  r  r   rk  r   r   s     r   _telegram_free_response_chatsz-TelegramAdapter._telegram_free_response_chats  s    k##$9::;):B??Cc4   	LKK#KKKKMMS)<)<MMMMr)   c                    | j         j                            d          }|t          j        dd          }t          |t                    rd |D             S d t          |                              d          D             S )a_  Return the whitelist of group/supergroup chat IDs the bot will respond in.

        When non-empty, group messages from chats NOT in this set are
        silently ignored unless ``guest_mode`` is enabled and the bot is
        explicitly @mentioned.  DMs are never filtered.
        Empty set means no restriction (fully backward compatible).
        allowed_chatsNTELEGRAM_ALLOWED_CHATSr   c                     h | ]D}t          |                                          #t          |                                          ES rj   r  r  s     r   r   z:TelegramAdapter._telegram_allowed_chats.<locals>.<setcomp>  r  r)   c                 ^    h | ]*}|                                 |                                 +S rj   ra  r  s     r   r   z:TelegramAdapter._telegram_allowed_chats.<locals>.<setcomp>  r  r)   rf  r  r  s     r   _telegram_allowed_chatsz'TelegramAdapter._telegram_allowed_chats  s     k##O44;)4b99Cc4   	LKK#KKKKMMS)<)<MMMMr)   c                    | j         j                            d          }|t          j        dd          }t          |t                    rd |D             S d t          |                              d          D             S )z0Return Telegram chats authorized at group scope.group_allowed_chatsNr  r   c                     h | ]D}t          |                                          #t          |                                          ES rj   r  r  s     r   r   z@TelegramAdapter._telegram_group_allowed_chats.<locals>.<setcomp>  r  r)   c                 ^    h | ]*}|                                 |                                 +S rj   ra  r  s     r   r   z@TelegramAdapter._telegram_group_allowed_chats.<locals>.<setcomp>  r  r)   rf  r  r  s     r   _telegram_group_allowed_chatsz-TelegramAdapter._telegram_group_allowed_chats  s    k##$9::;):B??Cc4   	LKK#KKKKMMS)<)<MMMMr)   c                     |                                  }|st                      S |                                 }|r||z  S |S )a#  Chats where observed group context may use a shared source.

        ``group_allowed_chats`` is the gateway authorization allowlist for
        user-less group sources.  ``allowed_chats`` remains an optional response
        gate; when set, observed context must satisfy both lists.
        )r%  r$  r   )r   group_allowedresponse_alloweds      r   _telegram_observe_allowed_chatsz/TelegramAdapter._telegram_observe_allowed_chats  sR     ::<< 	55L7799 	4 #333r)   c                    | j         j                            d          }|t          j        dd          }t          |t                    rd |D             S d t          |                              d          D             S )aa  Return the whitelist of Telegram forum topic IDs this bot handles.

        When non-empty, group/supergroup messages from other topics are
        silently ignored. DMs are never filtered by topic. Telegram may omit
        ``message_thread_id`` for the forum General topic, so ``None`` is
        treated as topic ``1`` for matching purposes.
        allowed_topicsNTELEGRAM_ALLOWED_TOPICSr   c                     h | ]D}t          |                                          #t          |                                          ES rj   r  r  s     r   r   z;TelegramAdapter._telegram_allowed_topics.<locals>.<setcomp>  r  r)   c                 ^    h | ]*}|                                 |                                 +S rj   ra  r  s     r   r   z;TelegramAdapter._telegram_allowed_topics.<locals>.<setcomp>  r  r)   rf  r  r  s     r   _telegram_allowed_topicsz(TelegramAdapter._telegram_allowed_topics  s     k##$455;)5r::Cc4   	LKK#KKKKMMS)<)<MMMMr)   c                 
   | j         j                            d          }|t          j        dd          }t          |t                    r|}n"t          |                              d          }t                      }|D ]}t          |          
                                }|s&	 |                    t          |                     J# t          t          f$ r$ t                              d| j        |           Y ~w xY w|S )Nignored_threadsTELEGRAM_IGNORED_THREADSr   rf  z,[%s] Ignoring invalid Telegram thread id: %r)r   r(  r)  r   r   r  r  r   rk  r$  rb  r   r  r   r   r   r  r   )r   r   r  ignoredr   r   s         r   _telegram_ignored_threadsz)TelegramAdapter._telegram_ignored_threads  s   k##$566;)6;;Cc4   	)FFXX^^C((FEE 	a 	aEu::##%%D aCII&&&&z* a a aMtyZ_`````as   ("C2D ?D c                    | j         j                            d          }|t          j        dd                                          }|rg	 t          j        |          }nO# t          $ rB d |	                                D             }|sd |
                    d          D             }Y nw xY w|}|g S t          |t                    r|g}t          |t                    s5t                              d| j        t#          |          j                   g S g }|D ]}t          |t                    r|                                s,	 |                    t)          j        |t(          j                             `# t(          j        $ r,}t                              d	| j        ||           Y d}~d}~ww xY w|r.t                              d
| j        t3          |                     |S )z=Compile optional regex wake-word patterns for group triggers.mention_patternsNTELEGRAM_MENTION_PATTERNSr   c                 ^    g | ]*}|                                 |                                 +S rj   ra  r  s     r   rE  z=TelegramAdapter._compile_mention_patterns.<locals>.<listcomp>  s-    XXXt4::<<XdjjllXXXr)   c                 ^    g | ]*}|                                 |                                 +S rj   ra  r  s     r   rE  z=TelegramAdapter._compile_mention_patterns.<locals>.<listcomp>  s-    !Z!Z!Z4TZZ\\!Z$**,,!Z!Z!Zr)   rf  z?[%s] telegram mention_patterns must be a list or string; got %sz,[%s] Invalid Telegram mention pattern %r: %sz*[%s] Loaded %d Telegram mention pattern(s))r   r(  r)  r   r   rb  jsonloadsr   r8  rk  r  r   r  r   r  r   r|  rf   r   r   compiler}  r
   r  r  )r   patternsr   loadedcompiledpatternrN  s          r   r  z)TelegramAdapter._compile_mention_patterns  s   ;$(();<<)7<<BBDDC "[!Z__FF  [ [ [XXs~~7G7GXXXF! [!Z!Z399S>>!Z!Z!Z[ "Ih$$ 	" zH(D)) 	NNQ	X'  
 I%' 	h 	hGgs++ 7==?? h
7BM B BCCCC8 h h hMtyZacfggggggggh 	`KKDdiQTU]Q^Q^___s+   A! !A	B-,B-	2E<<F7"F22F7c                     t          |dd           }|sdS t          t          |dd                                        d          d                                         }|dv S )Nrv  Fr|  r   .r"  >   r   rX  )rL   r   rk  rj  )r   r?  rv  rL  s       r   _is_group_chatzTelegramAdapter._is_group_chat7  sd    w-- 	5fb112288==bAGGII	333r)   c                    t          |dd          }|rIt          t          |dd                                        d          d                                         nd}t          |dd          }t	          t          |dd	                    }|d
v ot          |dd	          du }|0|s|d
v r|rt          |          S |dk    r|rt          |          S dS |r| j        S dS )aH  Return the routable thread id for a Telegram message.

        Forum supergroup messages posted in the General topic arrive with
        ``message_thread_id=None`` while Telegram itself addresses that topic
        as thread id ``1``.  Ordinary replies are the opposite footgun:
        Telegram populates ``message_thread_id`` with a reply-UI anchor id on
        plain group/DM replies, but those ids are not topic/session routing
        ids and must not be treated as such.  Gating, skill binding, and
        outbound routing must all agree on the same normalized value.
        rv  Nr|  r   rB  r"  r}  r~  F)r   rX  r  TrW  )rL   r   rk  rj  r'  r  )r  r?  rv  rL  r   r~  r  s          r   _effective_message_thread_idz,TelegramAdapter._effective_message_thread_id>  s	    w--MQYCfb112288==bAGGIIIWY	g2D991CU K KLL"&==j'$PZ\aBbBbfjBj?  )/F"F"FK["F3xxI%%*:%3xx4 	0//tr)   c                     | j         rt          |dd           sdS t          |j        dd           }t          |o(t          |dd           t          | j         dd           k              S )Nreply_to_messageFru  rw  )r  rL   rG  r'  )r   r?  
reply_users      r   _is_reply_to_botz TelegramAdapter._is_reply_to_botY  sm    y 	1CT J J 	5W5{DII
Jd7:tT#B#BgdiY]_cFdFd#deeer)   c           	      h    t                      } fd} |            D ]\  }}|D ]}t          t          |dd                                        d          d                                         }|dvrQt          t          |dd                    }t          t          |dd	                    }|d	k     s|d	k    r||||z                                            }	|d
k    r^|	                    d                                          }
t          j	        d|
t          j
                  r|                    |
           |	                    d          }|d	k     r:|	|dz   d                                                                         }t          j	        d|t          j
                  r|                    |            |            D ]\\  }}|r|r
t          j        d|          D ]<}|                    |                    d                                                     =]|S )a{  Extract explicit Telegram bot usernames mentioned in text/captions.

        Telegram bot usernames are 5-32 characters and must end in "bot".
        Entity mentions are authoritative. The raw-text fallback is intentionally narrow so
        entity-less mobile/client variants still work without treating email
        addresses or arbitrary substrings as bot mentions.
        c               3      K   t           dd           pdt           dd           pg fV  t           dd           pdt           dd           pg fV  d S Nr   r   entitiesrN  caption_entitiesrL   r?  s   r   _iter_sourceszETelegramAdapter._extract_bot_mention_usernames.<locals>._iter_sourcesj  x      '64006BUY8Z8Z8`^`````'9d339r77L^`d;e;e;kikkkkkkkr)   r|  r   rB  r"  >   mentionbot_commandoffsetlengthr   rS  @[a-z0-9_]{2,29}botrv  Nz1(?i)(?<![A-Za-z0-9_`/])@([A-Za-z0-9_]{2,29}bot)\b)r$  r   rL   rk  rj  r  rb  lstripr   	fullmatchr}  r   findr   r   )r?  mentioned_bot_usernamesrQ  source_textrM  entityentity_typerU  rV  entity_texthandleat_indexcommand_targetraw_textr1  s   `              r   _extract_bot_mention_usernamesz.TelegramAdapter._extract_bot_mention_usernames_  sl    -0EE	l 	l 	l 	l 	l &3]__ 	@ 	@!K" @ @!'&&""="=>>DDSII"MSSUU&@@@WVXr::;;WVXq99::A::1)&&*@AGGII)++(//44::<<F|$962=QQ </33F;;; '++C00a<<!,X\]]!;!A!A!C!C!I!I!K!K< 5~r}UU @+//???3@< #0-// 	D 	DHh x %Y[cdd D D'++EKKNN,@,@,B,BCCCCD '&r)   c           	         | j         sdS t          | j         dd           pd                    d                                          }t          | j         dd           }|rd| nd }fd} |            D ]\  }}|D ]}t	          t          |dd                                        d          d	                                         }	|	d
k    r|rt          t          |dd	                    }
t          t          |dd                    }|
dk     s|dk    r||
|
|z                                                                            |k    r  dS |	dk    r.t          |dd           }|rt          |dd           |k    r  dS |	dk    r|rt          t          |dd	                    }
t          t          |dd                    }|
dk     s|dk    r]||
|
|z            }|                    d          }|dk     r||d                                                                          |k    r  dS |r7t          j
        d|t          j                  r||                               v S dS )NFrx  r   rW  rw  c               3      K   t           dd           pdt           dd           pg fV  t           dd           pdt           dd           pg fV  d S rL  rO  rP  s   r   rQ  z<TelegramAdapter._message_mentions_bot.<locals>._iter_sources  rR  r)   r|  rB  r"  rS  rU  rV  r   Ttext_mentionr  rT  rX  )r  rL   rY  rj  r   rk  r  rb  r[  r   rZ  r}  re  )r   r?  bot_usernamebot_idexpectedrQ  r]  rM  r^  r_  rU  rV  r  command_textrb  s    `             r   _message_mentions_botz%TelegramAdapter._message_mentions_bot  s   y 	5	:t<<BJJ3OOUUWWD$//)5?%|%%%4	l 	l 	l 	l 	l &3]__ !	$ !	$!K"  $  $!'&&""="=>>DDSII"MSSUU)+++ 2!>!>??F 1!=!=>>FzzVq[[ "6&6/#9:@@BBHHJJhVV#ttt W N22"66488D $dD 9 9V C C#ttt M11h1 !2!>!>??F 1!=!=>>FzzVq[[ #.vfvo/E#FL+0055H!|| #HII.4466<<>>(JJ#tttA $B  	PBL)>bm\\ 	P4#F#Fw#O#OOOur)   c                     | j         sdS t          | j         dd          pd                    d                                          }|sdS |                     |          }t          |          o||vS )a  Return True when explicit bot handles target other bots, not this one.

        Telegram groups can contain several Hermes bot profiles. A message like
        ``@bot3 hi @bot4`` must not wake ``@bot1`` through reply/wake-word
        fallbacks. Treat explicit bot-handle mentions as an exclusive routing
        hint: if at least one @...bot username is present and none matches this
        adapter's own bot username, this adapter should ignore the message.

        MessageEntity values are preferred, but some Telegram clients expose
        selected bot handles as plain text in group messages. The raw-text
        fallback is intentionally limited to usernames ending in "bot", which
        Telegram requires for bot accounts.
        Frx  Nr   rW  )r  rL   rY  rj  re  r'  )r   r?  ri  r\  s       r   #_explicit_bot_mentions_exclude_selfz3TelegramAdapter._explicit_bot_mentions_exclude_self  s     y 	5	:t<<BJJ3OOUUWW 	5"&"E"Eg"N"N+,,\E\1\\r)   c                     | j         sdS t          |dd           t          |dd           fD ](}|s| j         D ]}|                    |          r  dS )dS )NFr   rN  T)r  rL   r'  )r   r?  r  r@  s       r   !_message_matches_mention_patternsz1TelegramAdapter._message_matches_mention_patterns  s    % 	5!'6488''9VZ:[:[\ 	  	 I 1    >>),,  444   ur)   c                 T    |                                  o|                     |          S )zReturn True for the narrow guest-mode bypass: explicit bot mention.

        The caller (:meth:`_should_process_message`) has already verified
        the message is a group chat, so that check is not repeated here.
        )r
  rm  )r   r?  s     r   _is_guest_mentionz!TelegramAdapter._is_guest_mention  s)     ((**Rt/I/I'/R/RRr)   r   c                     |r| j         rt          | j         dd           s|S t          j        | j         j                  }t          j        d| dd|                                          }|p|S )Nrx  z(?i)@z\b[,:\-]*\s*r   )r  rL   r   rN  rx  r   rb  )r   r   rx  r   s       r   _clean_bot_trigger_textz'TelegramAdapter._clean_bot_trigger_text  sv     	49 	GDIz4,P,P 	K9TY/00&8(888"dCCIIKK$r)   c           	      h   |                      |          rdS |                                 sdS |                     |          sdS t          |dd          }|                                 }|r|t          |          n| j        }||vrdS |?	 t          |          |                                 v rdS n# t          t          f$ r Y dS w xY wt          t          t          |dd          dd                    }|                                 r|                     |          rdS |                                 }|r||vrdS ||                                 v rdS |                                 sdS |                     |          rdS |                     |          rdS |                     |          rdS dS )zEReturn True when a group message should be stored but not dispatched.Fr}  Nrv  rw  r   T)_is_own_messager  rC  rL   r/  r   r  r  r4  r   r   r  ro  r)  r  r  rI  rm  rq  )r   r?  rM  r+  r  chat_id_strr  s          r   )_should_observe_unmentioned_group_messagez9TelegramAdapter._should_observe_unmentioned_group_message  s
   (( 	5@@BB 	5""7++ 	5G%8$??	6688 	)2)>s9~~~DDaH~--u y>>T%C%C%E%EEE 5 Fz*   uu '''64"@"@$KKLL0022 	t7_7_`g7h7h 	56688  	+W445
 $<<>>>>5--// 	5  )) 	5%%g.. 	511':: 	5ts   #B3 3CCc                 2    t          j        |ddd          S )zFReturn a chat/topic-scoped source for observed Telegram group context.N)rO  rN  user_id_alt)dataclassesr  )r   rp  s     r   %_telegram_group_observe_shared_sourcez5TelegramAdapter._telegram_group_observe_shared_source2  s    "644UYZZZZr)   eventc                 ^    |j         j        pd}|j         j        p|}d| d| d|j        pd S )Nrs  r  |z]
r   )rp  rO  rN  r   )r   r~  rO  senders       r   '_telegram_group_observe_attributed_textz7TelegramAdapter._telegram_group_observe_attributed_text6  sE    ,&3)'27:6::G::
(8b:::r)   c                     t          t          | dd           dd           pd}t          t          | dd           dd           pd}d| d| dS )Nr  rx  rs  rw  zIYou are handling a Telegram group chat message.
- Your identity: user_id=z , @-mention name in this group=@a)  
- observed Telegram group context may be provided in a separate context-only block before the current message; it is not necessarily addressed to you.
- Treat only the current new message as a request explicitly directed at you, and use observed context only when the current message asks for it.rO  )r   rx  rj  s      r   &_telegram_group_observe_channel_promptz6TelegramAdapter._telegram_group_observe_channel_prompt;  su    7466
DIIVYvt44dDAANYR(.R RPXR R R	
r)   c           	      H   |                                  s|S t          |dd          }|r|                     |          s|S t          t          t          |dd          dd                    }|                                 }|r||vr|S |                     |j                  }|                                 }|j        r|j         d| n|}|j	        t          j        k    rt          j        |||          S t          j        ||                     |          ||          S )	z>Align triggered group turns with observed-history attribution.raw_messageNrv  rw  r   ra  )rp  channel_prompt)r   rp  r  )r  rL   rC  r   r)  r}  rp  r  r  message_typerq   r  r|  r  r  )r   r~  r  rx  r  shared_sourceobserve_promptr  s           r   )_apply_telegram_group_observe_attributionz9TelegramAdapter._apply_telegram_group_observe_attributionG  sO   @@BB 	Le]D99 	$"5"5k"B"B 	L''+vt"D"DdBOOPP6688 	+W44LBB5<PPDDFFJOJ^rE0FFnFFFdr!444&$-   
 "==eDD )	
 
 
 	
r)   r  c                     |j         rt          j        S |j        rt          j        S |j        rt          j        S |j        rt          j        S |j	        rt          j
        S t          j        S )z5Classify a Telegram media message into a MessageType.)stickerrq   STICKERr  r  r  r  r_  r  rT  r  DOCUMENT)r   r  s     r   _media_message_typez#TelegramAdapter._media_message_typeb  sj    ; 	'&&9 	%$$9 	%$$9 	%$$9 	%$$##r)   c                   K   ddl m} |                     |          \  }}}}|dS t          | dd          }t          |dd          }		 t	          |	pd          }
n# t
          t          f$ r d}
Y nw xY wd|
cxk     r|k    sHn |dz  }|                     |j        d| d	          |_        t          
                    d
|	           dS 	 |                                 d{V }t          |                                 d{V           }|s0t          j                            t          |dd          pd          } |||||          }n5# t"          $ r(}t                              d|d           Y d}~dS d}~ww xY w|"|                     |j        d          |_        dS |j        g|_        |j        g|_        |j        dk    rt.          j        |_        n|j        dk    rt.          j        |_        |                     |j        |                                          |_        t          
                    d|j        |j                   dS )a2  Cache an unmentioned group attachment and annotate the observed text.

        Passive group traffic, so downloads are bounded by the same
        ``_max_doc_bytes`` limit as the addressed document path. Oversized or
        unsupported attachments are noted in the transcript without downloading.
        r   cache_media_bytesNr/  r   rB  rE  zB[Observed Telegram attachment too large or unverifiable. Maximum: z MB.]z6[Telegram] Observed group attachment skipped (size=%s)ra  r   r  	mime_typedefault_kindz3[Telegram] Failed to cache observed group media: %sTr   z=[Observed Telegram attachment could not be read, not cached.]imager  z)[Telegram] Cached observed group %s at %s)gateway.platforms.baser  _observed_media_sourcerL   r  r   r   _append_observed_noter   r   r  get_filebytesdownload_as_bytearrayr   r  r  r   r  
media_urls
media_typemedia_typesr  rq   r  r  r  context_note)r   r  r~  r  rp  r  mimer  rC  rB  rK  rF  file_objr  r  rN  s                   r   _cache_observed_mediaz%TelegramAdapter._cache_observed_mediap  s      	=<<<<<'+'B'B3'G'G$$>FD"24DEE	FK66		y~A&&DD:& 	 	 	DDD	D%%%%I%%%% [1H33
dU]ddd EJ KKPR[\\\F	#__........Hx==????????@@D V7++GHk2,N,N,TRTUU&&th$]abbbFF 	 	 	NNPRU`dNeeeFFFFF	 > 33
[ EJ F"K=#./;'!!!,!2E[G##!,!2E//
F<O<O<Q<QRR
?fkZZZZZs+   
A A21A2BE 
F E;;F c           
        K   ddl m} t          |dd          }|dS |                     |          \  }}}}|dS t          | dd          }	t          |dd          }
	 t	          |
pd          }n# t
          t          f$ r d}Y nw xY wd|cxk     r|	k    sn dS 	 |                                 d{V }t          |	                                 d{V           }|s0t          j                            t          |dd	          pd	          } |||||
          }n5# t          $ r(}t                              d|d           Y d}~dS d}~ww xY w|dS |j                            |j                   |j                            |j                   t)          |j                  dk    r9|j        dk    rt,          j        |_        n|j        dk    rt,          j        |_        |                     |j        d|j         d|j         d|j         d          |_        t                              d|j        |j                   dS )z:Cache media from the message this turn replies to, if any.r   r  rG  Nr/  r   rB  ra  r   r  z/[Telegram] Failed to cache replied-to media: %sTr   rv  r  r  z[Replied-to z 'z' saved at: r  z%[Telegram] Cached replied-to %s at %s)r  r  rL   r  r  r   r   r  r  r  r   r  r  r   r   r  r  r   r  r  r  r  rq   r  r  r  r  r   r  r  )r   r  r~  r  	reply_msgrp  r  r  r  rC  rB  rK  r  r  r  rN  s                   r   _cache_replied_mediaz$TelegramAdapter._cache_replied_media  s     <<<<<<C!3T::	F'+'B'B9'M'M$$>FD"24DEE	FK66		y~A&&DD:& 	 	 	DDD	D%%%%I%%%%F	#__........Hx==????????@@D V7++GHk2,N,N,TRTUU&&th$]abbbFF 	 	 	NNLc\`NaaaFFFFF	 >F,,,  !2333u  A%%{g%%%0%6""''%0%6"//JY6;YY&*=YY6;YYY
 

 	;V[&+VVVVVs+   A1 1BBBD 
E)EEc                 6   |j         r|j         d         dddfS |j        r|j        dddfS |j        r|j        dddfS |j        r!|j        t	          |j        d	d          pdddfS |j        r-|j        }||j        pd|j        pd                                d
fS dS )zEReturn (telegram_file_source, filename, mime, default_kind) or Nones.r"  r   r  	video/mp4r  z	voice.ogg	audio/oggr_  r  N)Nr   r   N)	r  r  rT  r_  rL   r  r  r  rj  )r   r  docs      r   r  z&TelegramAdapter._observed_media_source  s    9 	29R="b'119 	79b+w669 	@9k;??9 	U9gcibAAGRWTT< 	Q,C+cm.Ar-H-H-J-JDPP!!r)   existingnotec                 $    |s| pdS | s|S |  d| S )Nr   ra  rj   )r  r  s     r   r  z%TelegramAdapter._append_observed_note  s5     	">r! 	K&&&&&r)   r  r  c                 R  K   |rd| dnd}	 |                     d| | d|j        j         d           d{V  n5# t          $ r(}t                              d||d	           Y d}~nd}~ww xY wd
| | d|j        j         d}|                     |j        |          |_        dS )uK  Surface a failed media download/cache on BOTH ends instead of swallowing it.

        When download_as_bytearray()/cache_*_from_bytes() raises (typically a
        transient httpx.ConnectError to Telegram's CDN), the attachment never
        made it into event.media_urls. Without this, the handler falls through
        and dispatches an empty turn: the user thinks the file was delivered,
        the agent sees nothing, and the only record is a buried log warning.

        This (1) replies to the user in Telegram so they know to retry, and
        (2) appends an agent-visible notice to event.text via the existing
        observed-note channel so the agent knows an attachment was attempted
        and failed — never a silent empty turn. No new event fields (the
        structured-event refactor is out of scope per #23045).
        r  r<  r   u   ⚠️ Couldn't download your z). Please try sending it again.Nz;[Telegram] Failed to notify user about %s cache failure: %sTr   z[The user attempted to send a z! but it could not be downloaded (z"); they have been asked to retry.])
reply_textr8  rf   r   r   r  r  r   )	r   r  r~  r  rN  r  named	reply_err
agent_notes	            r   _surface_media_cache_failurez,TelegramAdapter._surface_media_cache_failure  sR     , )5<$\$$$$"	..Lt LU L LM*L L L           	 	 	NNM	         	VT V5 V V=1V V V 	 //
JGG


s   .= 
A/A**A/msg_type	update_idc                    t          | dd          }|sdS 	 |p|                     |||          }|                     |j                  }|                    |          }d|                     |          t          j        t          j	                  
                                dd}|j        rt          |j                  |d<   |                    |j        |           t          | d	d
          }	t                              d|	t          t          |dd          dd          |j        j        pd           dS # t$          $ r8}
t          | d	d
          }	t                              d|	|
           Y d}
~
dS d}
~
ww xY w)zGAppend skipped group chatter to the target session without dispatching.r  Nr  r  )tzT)roler  	timestampobservedrn  r   r   zF[%s] Telegram group message observed (no bot trigger): chat=%s from=%srv  rw  rs  z1[%s] Failed to observe Telegram group message: %s)rL   _build_message_eventr}  rp  get_or_create_sessionr  r   nowr   utc	isoformatrn  r   append_to_transcript
session_idr   r  rO  r   r  )r   r?  r  r  r~  r  r  session_entryr  adapter_namerN  s              r   "_observe_unmentioned_group_messagez2TelegramAdapter._observe_unmentioned_group_message  s    .55 	F	c^T66wT]6^^E FFu|TTM!77FFMGGNN%\X\:::DDFF 	 E  <&)%*:&;&;l#&&}'?GGG"4<<LKKX66iHH$1		      	c 	c 	c"4<<LNNNP\^abbbbbbbbb	cs   D#D< <
E>-E99E>c                     | j         sdS t          |dd          }|dS t          | j         dd          }t          |dd          }|duo	|duo||k    S )ac  Return True when the message was sent by this bot itself.

        In some Telegram environments (groups, supergroups where the bot can
        see its own messages), getUpdates returns the bot's own outgoing
        messages as updates.  These must be filtered out so they are not
        counted as incoming unread messages in the Hermes inbox.
        Fru  Nrw  )r  rL   )r   r?  ru  rj  rO  s        r   rw  zTelegramAdapter._is_own_message9  sr     y 	5G[$77	5D$//)T400T!OgT&9Of>OOr)   
is_commandr  c          	         |                      |          rdS |                     |          sdS |                     |          }|                                 }|r|t	          |          n| j        }||vrdS |_	 t          |          |                                 v rdS n8# t          t          f$ r$ t                              d| j        |           Y nw xY w|                     |          s^|Z| j        j                            dd          r:t	          t!          t!          |dd          dd                    }|s|| j        v rdS dS t	          t!          t!          |dd          dd                    }|                                 r|                     |          rdS |                     |          }|                                 }	|	r||	vr|S |rdS ||                                 v rdS |                                 sdS |                     |          rdS |                                 s|                     |          rdS |                     |          S )	u  Apply Telegram group trigger rules.

        DMs remain unrestricted. Group/supergroup messages are accepted when:
        - the chat passes the ``allowed_chats`` whitelist (when set), or
          ``guest_mode`` is enabled and the bot is explicitly mentioned
        - the chat is explicitly allowlisted in ``free_response_chats``
        - ``require_mention`` is disabled
        - the message replies to the bot
        - the bot is @mentioned
        - the text/caption matches a configured regex wake-word pattern

        When ``allowed_chats`` is non-empty, it remains a hard gate except for
        the narrow ``guest_mode`` bypass: group/supergroup messages that
        explicitly @mention this bot. Replies and regex wake words do not bypass
        ``allowed_chats``. When ``require_mention`` is enabled, slash commands are not given
        special treatment — they must pass the same mention/reply checks
        as any other group message.  Users can still trigger commands via
        the Telegram bot menu (``/command@botname``) or by explicitly
        mentioning the bot (``@botname /command``), both of which are
        recognised as mentions by :meth:`_message_mentions_bot`.
        FTNz8[%s] Ignoring non-numeric Telegram message_thread_id: %rignore_root_dmrv  rw  r   )rw  rC  rE  r/  r   r  r  r4  r   r   r   r  r   r   r(  r)  rL   r.  r  ro  rs  r   r  r  rI  r
  rm  rq  )
r   r?  r  rM  r+  r  r   rx  guest_mentionr  s
             r   _should_process_messagez'TelegramAdapter._should_process_messageJ  s   4 (( 	5""7++ 	455g>>	6688 	)2)>s9~~~DDaH~--u  qy>>T%C%C%E%EEE 5 Fz* q q qY[_[dfopppppq ""7++ 	 T[%6%:%:;KU%S%S gggvt&D&DdBOOPP! !g1H&H&H 54'''64"@"@$KKLL0022 	t7_7_`g7h7h 	5 ..w77
 ..00 	!{'11   	4$<<>>>>4--// 	4  )) 	4 ((** 	t/I/I'/R/R 	455g>>>s   ;#B! !2CCc                 
  K   | j         4 d{V  	 t          |dd          }|rt          |dd          s	 ddd          d{V  dS t          |j                  }|| j        v r	 ddd          d{V  dS ddlmm} ddlm	}m
}  | |                      \  }}fd	|D             }	| j                            |	 ||
                     d{V  | j                            |           t                              d| j        t#          |	          |           n8# t$          $ r+}
t                              d| j        |
           Y d}
~
nd}
~
ww xY wddd          d{V  dS # 1 d{V swxY w Y   dS )u   Lazy-register bot commands for forum supergroups.

        Forum topics don't inherit AllGroupChats scope — Telegram resolves
        via BotCommandScopeChat(chat_id).  Register on first message so the
        command menu works in topic views.
        Nrv  r  Fr   )r9  BotCommandScopeChatr=  r@  c                 .    g | ]\  }} ||          S rj   rj   rC  s      r   rE  z:TelegramAdapter._ensure_forum_commands.<locals>.<listcomp>  rF  r)   r   rG  z2[%s] Lazy-registered %d commands for forum chat %sz/[%s] Forum command lazy-registration failed: %s)r&  rL   r  rw  r%  r   r9  r  rK  r>  r?  r  rM  r   r   r  r   r  r   r  )r   r?  rv  r   r  r>  r?  rO  rA   rQ  r   r9  s              @r   _ensure_forum_commandsz&TelegramAdapter._ensure_forum_commands  s.      # 	` 	` 	` 	` 	` 	` 	` 	``w55 74U#C#C 		` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	`
 dg,,d<<<	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` EDDDDDDDbbbbbbbb#9#9GaGaGcGc#d#d#d qWWWWWWWi//DWDW`gDhDhDh/iiiiiiiii.227;;;PRVR[]`am]n]npwxxxx ` ` `PRVR[]^________`	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	` 	`sG   E2$D'D'<B*D'&E2'
E1!EE2EE22
E<?E<c                 F    t          |dd          pt          |dd          S )a|  Return the message-like payload for normal messages and channel posts.

        Telegram exposes channel broadcasts as ``update.channel_post`` rather
        than ``update.message``.  MessageHandler filters can still dispatch
        those updates, so handlers must use ``effective_message`` to avoid
        consuming channel posts without ever building a gateway event.
        effective_messageNr?  rO  )r   r{  s     r   _effective_update_messagez)TelegramAdapter._effective_update_message  s)     v2D99]WVYX\=]=]]r)   c                 &  K   |                      |          }|r|j        sdS |                     |          sZt                              dt          t          |dd          dd          t          t          |dd          dd                     dS |                     |          s>|                     |          r'|                     |t          j
        |j                   dS |                     |j                   d{V  |                     |t          j
        |j                  }|                     |j                  |_        |                     ||           d{V  |                     |          }|                     |           dS )zHandle incoming text messages.

        Telegram clients split long messages into multiple updates.  Buffer
        rapid successive text messages from the same user/chat and aggregate
        them into a single MessageEvent before dispatching.
        N2[Telegram] Blocked unauthorized user %s in chat %sru  rw  rv  r  )r  r   r  r   r  rL   r  ry  r  rq   r  r  r  r?  r  ru  r  r  _enqueue_text_eventr   r{  r  r  r~  s        r   r  z$TelegramAdapter._handle_text_message  s      ,,V44 	#( 	F
 44S99 	NND[$77tDDVT22D$??  
 F++C00 	==cBB k77[=MY_Yi7jjjF))&.999999999))#{/?6K[)\\11%*==
''U333333333>>uEE  '''''r)   c                   K   |                      |          }|r|j        sdS |                     |d          sdS |                     |          sZt                              dt          t          |dd          dd          t          t          |dd          dd                     dS |                     |           d{V  |                     |t          j
        |j                  }|                     |j                  |_        |                     ||           d{V  |                     |          }|                     |           d{V  dS )	z!Handle incoming command messages.NTr  r  ru  rw  rv  r  )r  r   r  r  r   r  rL   r  r  rq   r  r  ru  r  r  handle_messager  s        r   r  zTelegramAdapter._handle_command  s     ,,V44 	#( 	F++CD+AA 	F44S99 	NND[$77tDDVT22D$??  
 F))#.........))#{/BfN^)__11%*==
''U333333333>>uEE!!%(((((((((((r)   c                   K   |                      |          }|sdS |                     |          sZt                              dt	          t	          |dd          dd          t	          t	          |dd          dd                     dS |                     |          s>|                     |          r'|                     |t          j	        |j
                   dS t	          |dd          }|rt	          |dd          nt	          |dd          }|sdS t	          |d	d          }t	          |d
d          }||dS dg}|rVt	          |dd          }	t	          |dd          }
|	r|                    d|	            |
r|                    d|
            |                    d|            |                    d|            |                    d| d|            |                    d           |                     |t          j	        |j
                  }d                    |          |_        |                     |          }|                     |           d{V  dS )z,Handle incoming location/venue pin messages.Nr  ru  rw  rv  r  venuelocationlatitude	longitudez![The user shared a location pin.]r{  addresszVenue: z	Address: z
latitude: zlongitude: z5Map: https://www.google.com/maps/search/?api=1&query=rf  zSAsk what they'd like to find nearby (restaurants, cafes, etc.) and any preferences.r   )r  r  r   r  rL   r  ry  r  rq   r  r  r   r  r   r   r  r  )r   r{  r  r  r  r  latlonr  r{  r  r~  s               r   r  z(TelegramAdapter._handle_location_message  s     ,,V44 	F44S99 	NND[$77tDDVT22D$??  
 F++C00 	==cBB o77[=Q]c]m7nnnFWd++7<`75*d333'#z[_B`B` 	Fh
D11hT22;#+F 55 	4E7D11EeY55G 0.u../// 4222333'#''((((3(()))XSXXSVXXYYYjkkk))#{/CvO_)``YYu%%
>>uEE!!%(((((((((((r)   c                     ddl m} |                     |            ||j        | j        j                            dd          | j        j                            dd                    S )a  Session-scoped key for text message batching.

        Applies the installed topic-recovery hook first so DM-topic batches
        coalesce on (and dispatch to) the recovered lane rather than the
        raw inbound ``message_thread_id`` Telegram may have attached.
        r   build_session_keygroup_sessions_per_userTthread_sessions_per_userFr  r  )ri  r  _apply_topic_recoveryrp  r   r(  r)  )r   r~  r  s      r   _text_batch_keyzTelegramAdapter._text_batch_key,  s}     	655555""5)))  L$(K$5$9$9:SUY$Z$Z%)[%6%:%:;UW\%]%]
 
 
 	
r)   c                    |                                  rt                              d           dS |                     |          }| j                            |          }t          |j        pd          }|||_        || j        |<   nw|j        r$|j        r|j         d|j         n|j        |_        ||_        |j	        r>|j	        
                    |j	                   |j        
                    |j                   | j                            |          }|r(|                                s|                                 t          j        |                     |                    | j        |<   dS )a2  Buffer a text event and reset the flush timer.

        When Telegram splits a long user message into multiple updates,
        they arrive within a few hundred milliseconds.  This method
        concatenates them and waits for a short quiet period before
        dispatching the combined message.
        z?[Telegram] Dropping text batch enqueue after disconnect startedNr   r   )rE  r   r   r  r  r)  r  r   _last_chunk_lenr  extendr  r  r%   r;   r   r  _flush_text_batch)r   r~  r  r  	chunk_len
prior_tasks         r   r  z#TelegramAdapter._enqueue_text_event;  s|    --// 	LLZ[[[F""5))-11#66
(b))	$-E!.3D&s++ z bDLM a8= @ @EJ @ @ @W\Wa'0H$ ?#**5+;<<<$++E,=>>> 377<<
 	 joo// 	 .5.A""3''/
 /
&s+++r)   c                   K   t          j                    }	 | j                            |          }|rt	          |dd          nd}|r t          t	          |dd          pd          nd}|| j        k    r| j        }nS|| j        k    rt          | j
        | j                  }n-|| j        k    rt          | j
        | j                  }n| j
        }t          j        |           d{V  | j                            |d          }|s<	 | j                            |          |u r| j                            |d           dS dS |                                 rVt$                              d           	 | j                            |          |u r| j                            |d           dS dS t$                              d|t          |j        pd                     |                     |           d{V  | j                            |          |u r| j                            |d           dS dS # | j                            |          |u r| j                            |d           w w xY w)zWait for the quiet period then dispatch the aggregated text.

        Uses a longer delay when the latest chunk is near Telegram's 4096-char
        split point, since a continuation chunk is almost certain.
        r  r   r   r   Nz=[Telegram] Dropping text batch flush after disconnect startedz,[Telegram] Flushing text batch %s (%d chars))r   rL  r  r)  rL   r  _SPLIT_THRESHOLDr  _TEXT_BATCH_FAST_LENr   r  _TEXT_BATCH_FAST_DELAY_S_TEXT_BATCH_SHORT_LEN_TEXT_BATCH_SHORT_DELAY_Sr  r  r  rE  r   r   r  r   r  )r   r  rL  r  last_len	total_lenr  r~  s           r   r  z!TelegramAdapter._flush_text_batch_  s      +--&	> 044S99GAHOww(91===aHCJQGGVR88>B???PQI4000<d777D:D<YZZd888D:D<Z[[6-&&&&&&&&&.223==E  -11#66,FF.223===== GF 1133 \]]] -11#66,FF.223===== GF KK>S)r**   %%e,,,,,,,,,-11#66,FF.223===== GFt-11#66,FF.223==== Gs   C0H3 .H3 -AH3 3:I-c                     ddl m}  ||j        | j        j                            dd          | j        j                            dd                    }t          |dd	          }|r| d
| S | dS )z1Return a batching key for Telegram photos/albums.r   r  r  Tr  Fr  media_group_idNz:album:z:photo-burst)ri  r  rp  r   r(  r)  rL   )r   r~  r  r  r:  r  s         r   _photo_batch_keyz TelegramAdapter._photo_batch_key  s    555555''L$(K$5$9$9:SUY$Z$Z%)[%6%:%:;UW\%]%]
 
 

 !&6== 	;!::.:::++++r)   	batch_keyc                 t  K   t          j                    }	 t          j        | j                   d{V  | j                            |d          }|s<	 | j                            |          |u r| j                            |d           dS dS |                                 rVt          
                    d           	 | j                            |          |u r| j                            |d           dS dS t                              d|t          |j                             |                     |           d{V  | j                            |          |u r| j                            |d           dS dS # | j                            |          |u r| j                            |d           w w xY w)z;Send a buffered photo burst/album as a single MessageEvent.Nz>[Telegram] Dropping photo batch flush after disconnect startedz3[Telegram] Flushing photo batch %s with %d image(s))r   rL  r  r  r  r  r  r)  rE  r   r   r  r  r  r  )r   r  rL  r~  s       r   _flush_photo_batchz"TelegramAdapter._flush_photo_batch  s     +--	E- ?@@@@@@@@@/33ItDDE  .229==MM/33ItDDDDD NM 1133 ]^^^ .229==MM/33ItDDDDD NM KKMyZ]^c^nZoZoppp%%e,,,,,,,,,.229==MM/33ItDDDDD NMt.229==MM/33ItDDDD Ns   <E= .E= 9A	E= =:F7c                 n   |                                  rt                              d           dS | j                            |          }||| j        |<   nj|j                            |j                   |j                            |j                   |j        r%| 	                    |j        |j                  |_        | j
                            |          }|r(|                                s|                                 t          j        |                     |                    | j
        |<   dS )z;Merge photo events into a pending batch and schedule flush.z@[Telegram] Dropping photo batch enqueue after disconnect startedN)rE  r   r   r  r)  r  r  r  r   _merge_captionr  r%   r;   r   r  r  )r   r  r~  r  r  s        r   _enqueue_photo_eventz$TelegramAdapter._enqueue_photo_event  s"   --// 	LL[\\\F.229==5:D'	22&&u'7888 ''(9:::z O $ 3 3HM5: N N488CC
 	 joo// 	 5<5HI`I`ajIkIk5l5l'	222r)   c                   K   |j         sdS |                     |j                   sdt                              dt	          t	          |j         dd          dd          t	          t	          |j         dd          dd                     dS |                     |j                   s|                     |j                   r|j         }|                     |          }|                     |||j	                  }|j
        r|                     |j
                  |_        |                     ||           d{V  |                     ||j        |j	        |           dS |j         }|                     |          }|                     |||j	                  }|j
        r|                     |j
                  |_        |j        rN|                     ||           d{V  |                     |          }|                     |           d{V  dS |                     |          }|j        r	 |j        d         }	|	                                 d{V }
|
                                 d{V }d	}|
j        r5d
D ]2}|
j                                                            |          r|} n3t5          t7          |          |          }|g|_        d|                    d           g|_        t                              d|           t	          |dd          }|r*|                     tA          |          |           d{V  n,| !                    ||          }| "                    ||           dS # tF          $ rE}t          $                    d|d           | %                    ||d|           d{V  Y d}~nd}~ww xY w|j&        rf	 | '                    |j&        d          \  }}|sn| (                    |j        |pd          |_        t                              dt	          |j&        dd                     |                     |           d{V  dS |j&                                         d{V }
|
                                 d{V }tS          t7          |          d          }|g|_        dg|_        t                              d|           	n# tF          $ rF}t          $                    d|d           | %                    ||d|           d{V  Y d}~	nCd}~ww xY w|j*        rf	 | '                    |j*        d          \  }}|sn| (                    |j        |pd          |_        t                              dt	          |j*        dd                     |                     |           d{V  dS |j*                                         d{V }
|
                                 d{V }tS          t7          |          d          }|g|_        dg|_        t                              d |           n # tF          $ rF}t          $                    d!|d           | %                    ||d|           d{V  Y d}~nd}~ww xY w|j+        r	 | '                    |j+        d"          \  }}|sn| (                    |j        |pd          |_        t                              d#t	          |j+        dd                     |                     |           d{V  dS |j+                                         d{V }
|
                                 d{V }d$}t	          |
d%d          r:tX          D ]2}|
j                                                            |          r|} n3t[          t7          |          |          }|g|_        tY          j.        |d&          g|_        t                              d'|           nR# tF          $ rF}t          $                    d(|d           | %                    ||d"|           d{V  Y d}~nd}~ww xY w|j/        r|j/        }	 d}|j0        pd}|r6tb          j2        3                    |          \  }}|                                }|j4        pd                                }|sR|rPtj          .                    |d          }|s3d) tm          j7                    D             }|.                    |d          }|j8        r|j8        | j9        k    rR| j9        d*z  }d+| d,|_        t                              d-|j8                   |                     |           d{V  dS |tt          v s|;                    d          r|                                 d{V }
|
                                 d{V }|tt          v r|ntj          .                    |d	          }	 t5          t7          |          |          }na# tx          $ rT}t          $                    d.|d           d/|p|p|pd0 d1|_        |                     |           d{V  Y d}~dS d}~ww xY wtz          j>        |_        |g|_        |;                    d          r|nt~          .                    |d2          g|_        t                              d3|           t	          |dd          }|r*|                     tA          |          |           d{V  n,| !                    ||          }| "                    ||           dS |s?|j4        r8d4 tY          j7                    D             }|.                    |j4        d          }|sS|j4        rLi }t          j7                    D ]\  }} |A                    | |           |.                    |j4        d          }|tX          v r|                                 d{V }
|
                                 d{V }t[          t7          |          |          }|g|_        tX          |         g|_        tz          jB        |_        t                              d5|           |                     |           d{V  dS |                                 d{V }
|
                                 d{V }!t7          |!          }"t          |"|pd6|pd7           }tm          j.        |          p|j4        pd8}#|g|_        |#g|_        t                              d9||#           d:}$|t          v p|pd;                    d;          }%|%rt          |"          |$k    rn	 |"F                    d<          }&|pd6|pd= }'t          jH        d>d?|'          }'d@|' dA|& }(|j        r|( dB|j         |_        n|(|_        n# t          $ r Y nw xY wne# tF          $ rX}t          $                    dC|d           | %                    ||dD|t	          |dEd          pdF           d{V  Y d}~nd}~ww xY wt	          |dd          }|r+|                     tA          |          |           d{V  dS |                     |           d{V  dS )GzBHandle incoming media messages, downloading images to local cache.Nz=[Telegram] Blocked media from unauthorized user %s in chat %sru  rw  rv  r  )r  r~  r"  r   )r   r   r   r   r   rf  zimage/rB  z"[Telegram] Cached user photo at %sr  z$[Telegram] Failed to cache photo: %sTr   r  zvoice messager   z1[Telegram] Skipped oversized user voice (size=%s)rB  rS  r  z"[Telegram] Cached user voice at %sz$[Telegram] Failed to cache voice: %sz
audio filez1[Telegram] Skipped oversized user audio (size=%s)r^  z	audio/mp3z"[Telegram] Cached user audio at %sz$[Telegram] Failed to cache audio: %sz
video filez1[Telegram] Skipped oversized user video (size=%s)z.mp4ra  r  z"[Telegram] Cached user video at %sz$[Telegram] Failed to cache video: %sc                     i | ]\  }}||	S rj   rj   rj  s      r   rl  z9TelegramAdapter._handle_media_message.<locals>.<dictcomp>b  s    &Y&Y&Y1q!&Y&Y&Yr)   rE  zFThe document is too large or its size could not be verified. Maximum: z MB.z'[Telegram] Document too large: %s bytesz-[Telegram] Failed to cache image document: %szImage document 'rs  z ' could not be read as an image.r   z+[Telegram] Cached user image-document at %sc                     i | ]\  }}||	S rj   rj   rj  s      r   rl  z9TelegramAdapter._handle_media_message.<locals>.<dictcomp>  s    (X(X(X$!QA(X(X(Xr)   z+[Telegram] Cached user video document at %sr  z.binzapplication/octet-streamz*[Telegram] Cached user document at %s (%s)i  ztext/r  z.txtz	[^\w.\- ]rA   z[Content of z]:
ra  z'[Telegram] Failed to cache document: %s
attachmentr  )r  )Jr?  r  r   r  rL   r  ry  r  r  r  rN  ru  r   r  r  r  r  _handle_stickerr  r  r  r  r  ra  rj  r  ru   r  r  rY  r  _queue_media_group_eventr   r  r  r   r  r  rT  rL  r  rv   r_  r  rz   rw   r)  r  r  r   r  rb  r  _TELEGRAM_IMAGE_MIME_TO_EXTr{   r|  rB  r/  _TELEGRAM_IMAGE_EXTENSIONSr  r   rq   r  _TELEGRAM_IMAGE_EXT_TO_MIMEr|   r  r  rx   r}   r  r0  r   r   UnicodeDecodeError))r   r{  r  r  _observe_type_eventr  r  r~  r  r  image_bytesrf  r  cached_pathr  r  r   r  r  audio_bytesvideo_bytesr  original_filenamerA   doc_mimemime_to_extrF  	image_extvideo_mime_to_extimage_mime_to_ext_ext_mime	doc_bytes	raw_bytesr  MAX_TEXT_INJECT_BYTES_is_texttext_contentr  	injections)                                            r   r  z%TelegramAdapter._handle_media_message  s     ~ 	F44V^DD 	KKOTBBD$OO==tTJJ  
 F++FN;; 	==fnMM 	^ $ 8 8 < <222}PVP`2aa: K"&">">rz"J"JFK00V<<<<<<<<<77+v7Gv 8    Fn++C00))#x6CS)TT ; 	C55ckBBEJ ; 	&&sE222222222BB5IIE%%e,,,,,,,,,F >>uEE 9 	PP	"!&!1!1111111$,$B$B$D$DDDDDDD% "%O " "	#-3355>>yII ""+C!E" 5U;5G5GSQQQ$/= %?cjjoo%?%?$A!@+NNN!(.>!E!E! @77N8K8KUSSSSSSSSSS $ 5 5eS A AI--i??? P P PEqSWXXX77UGQOOOOOOOOOOOOOOP
 9 A	X $ A A#)_ ] ] !%!;!;EJ
PR!S!SEJKK SU\]`]fhsuyUzUz{{{--e444444444F!$!3!3!5!5555555$,$B$B$D$DDDDDDD4U;5G5GVTTT$/= %0M!@+NNNN X X XEqSWXXX77UOUVWWWWWWWWWWWWWWX Y p	U $ A A#)\ Z Z !%!;!;EJ
PR!S!SEJKK SU\]`]fhsuyUzUz{{{--e444444444F!$!3!3!5!5555555$,$B$B$D$DDDDDDD4U;5G5GVTTT$/= %0M!@+NNNN U U UEqSWXXX77ULRSTTTTTTTTTTTTTTU Y ^	U $ A A#)\ Z Z !%!;!;EJ
PR!S!SEJKK SU\]`]fhsuyUzUz{{{--e444444444F!$!3!3!5!5555555$,$B$B$D$DDDDDDD8[$77 "%: " "	#-3355>>yII ""+C!E" 5U;5G5GSQQQ$/= %:%>sK%P%P$Q!@+NNNN U U UEqSWXXX77ULRSTTTTTTTTTTTTTTU
 \ E	,CC$'M$7R!$ &W--.?@@FAs))++C  M/R6688  <x <599(BGGC <&Y&Y8P8V8X8X&Y&Y&Y)ooh;; } 8K(K(K#2{CH3$,3 3 3 J KK I3=YYY--e444444444F
 4448K8KH8U8U4%(\\^^333333H(0(F(F(H(H"H"H"H"H"H"HK'*.H'H'HNiNmNmnvx~NNI	&<U;=O=OU^&_&_&_%   'VXYdhiii=/@/`H/`PS/`W` = = = 
 #11%888888888 *5):E&(3}E$5=5H5H5R5R  *QXsXwXw  yB  DP  YQ  YQ  )RE%KK M{[[[%,S2BD%I%IN% D";;C<O<OQVWWWWWWWWWW$($9$9%$E$E	11)UCCCF Cs} C(X(X:O:U:W:W(X(X(X%+//rBBC Cs} C 9;%'E'K'M'M B Be)44UDAAAA+//rBBC///%(\\^^333333H(0(F(F(H(H"H"H"H"H"H"HK"8{9K9KQT"U"U"UK(3}E$)>s)C(DE%)4):E&KK M{[[[--e444444444F "%//////"*"@"@"B"BBBBBBB	!),,	7	CTCrXrcfcpjpXrXrss48==llRl	$/= %.K!H+W`aaa )3%"99ahn"=X=XY`=a=a I2G G G'0'7'7'@'@'8'V<Vs}f<V<V')vlC'N'N$S<$S$S\$S$S	 : 3,5)G)G5:)G)GEJJ)2EJ-    
    H!VZ[[[77a!(k4!@!@!HD 8               !&6== 	//N0C0CUKKKKKKKKKF!!%(((((((((((s   0EM9 9
O;OOBS& "BS& &
T60;T11T6BY BY 
Z$;ZZ$0B`" >C"`" "
a2,;a--a2Dx  A9x h9 8x 9
jA	jx jCx 1Ex Cx !Aw> =x >
xx 
xx 
y1Ay,,y1r  c                 J  K   |                                  rt                              d           dS | j                            |          }||| j        |<   nj|j                            |j                   |j                            |j                   |j        r%| 	                    |j        |j                  |_        | j
                            |          }|r|                                 t          j        |                     |                    | j
        |<   dS )a  Buffer Telegram media-group items so albums arrive as one logical event.

        Telegram delivers albums as multiple updates with a shared media_group_id.
        If we forward each item immediately, the gateway thinks the second image is a
        new user message and interrupts the first. We debounce briefly and merge the
        attachments into a single MessageEvent.
        z@[Telegram] Dropping media group enqueue after disconnect startedN)rE  r   r   r  r)  r  r  r  r   r   r  r;   r   r  _flush_media_group_event)r   r  r~  r  r  s        r   r  z(TelegramAdapter._queue_media_group_event  s      --// 	LL[\\\F+//??7<D$^44&&u'7888 ''(9:::z O $ 3 3HM5: N N,00@@
 	 292E)).993
 3
///r)   c                 @  K   t          j                    }	 t          j        | j                   d {V  | j                            |d           }||                                 rVt                              d           	 | j	        
                    |          |u r| j	                            |d            d S d S |                     |           d {V  nO# t           j        $ r= Y | j	        
                    |          |u r| j	                            |d            d S d S w xY w| j	        
                    |          |u r| j	                            |d            d S d S # | j	        
                    |          |u r| j	                            |d            w w xY w)Nz>[Telegram] Dropping media group flush after disconnect started)r   rL  r  MEDIA_GROUP_WAIT_SECONDSr  r  rE  r   r   r  r)  r  r   )r   r  rL  r~  s       r   r"  z(TelegramAdapter._flush_media_group_event  s     +--	B- =>>>>>>>>>,00FFE 5577 LL!abbb
 &**>::lJJ'++NDAAAAA KJ	 ))%000000000% 	 	 	&**>::lJJ'++NDAAAAA KJ	 &**>::lJJ'++NDAAAAA KJt&**>::lJJ'++NDAAAA Ks0   A*C =C E# D%(E# $D%%E# #:Frp   c                 (  K   ddl m}m}m}m}m} |j        }|j        pd}	|j        pd}
|j	        s|j
        r ||	          |_        dS  ||j                  }|rb ||d         |                    d|	          |                    d|
                    |_        t                              d|j                   dS 	 |                                 d{V }|                                 d{V }t%          t'          |          d	
          }t                              d|           ddlm}  |||           d{V }t-          j        |          }|                    d          r=|                    dd          } ||j        ||	|
            |||	|
          |_        dS  ||	rd|	 nd|	|
          |_        dS # t0          $ rA}t                              d|d            ||	rd|	 nd|	|
          |_        Y d}~dS d}~ww xY w)a  
        Describe a Telegram sticker via vision analysis, with caching.

        For static stickers (WEBP), we download, analyze with vision, and cache
        the description by file_unique_id. For animated/video stickers, we inject
        a placeholder noting the emoji.
        r   )get_cached_descriptioncache_sticker_descriptionbuild_sticker_injection build_animated_sticker_injectionSTICKER_VISION_PROMPTr   NrG  emojiset_namez [Telegram] Sticker cache hit: %sr   r  z"[Telegram] Analyzing sticker at %s)vision_analyze_tool)r~  user_promptrw  analysisz	a stickerza sticker with emoji z%[Telegram] Sticker analysis error: %sTr   )gateway.sticker_cacher&  r'  r(  r)  r*  r  r+  r,  is_animatedis_videor   file_unique_idr)  r   r  r  r  ru   r  tools.vision_toolsr-  r:  r;  r   r  )r   r  r~  r&  r'  r(  r)  r*  r  r+  r,  r  r  r  r  r-  result_jsonrG   rG  r   s                       r   r  zTelegramAdapter._handle_sticker  s     	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 +##)r  	'"2 	99%@@EJF ('(>?? 	00}%vzz'5'A'A6::jZbCcCc EJ KK:G<RSSSF	$--////////H ( > > @ @@@@@@@K0{1C1CQQQKKK<kJJJ>>>>>> 3 3%1! ! !      K Z,,Fzz)$$ 	$jj[AA))'*@+uV^___44[%RR


 547<M3E333+8 


  	 	 	NNBAPTNUUU0038I////kx EJJJJJJJ	s   ?C*G +G 
H6HHc                    	 ddl m}  |            dz  }|                                sdS ddl}t	          |dd          5 }|                    |          pi }ddd           n# 1 swxY w Y   |                    di                               d	i                               d
i                               dg           }|sg | _        t                      | _	        dS || _        d |D             | _	        |D ]}|                    d          }|s|                    dg           D ]y}	|	                    d          }
|	                    d          }|
rK|rI| d| }|| j
        vr9t          |
          | j
        |<   t                              d| j        ||
           zdS # t          $ r,}t                              d| j        |           Y d}~dS d}~ww xY w)zRe-read dm_topics from config.yaml and load any new thread_ids into cache.

        This allows topics created externally (e.g. by the agent via API) to be
        recognized without a gateway restart.
        r   r  r  Nr  r  r  r  r   r(  r   c                 @    h | ]}d |v t          |d                    S r   r   )r   r  s     r   r   z@TelegramAdapter._reload_dm_topics_from_config.<locals>.<setcomp>k  s7     ' ' '/9)WaJaJaJy)**JaJaJar)   r   r  rM  r   r  z8[%s] Hot-loaded DM topic from config: %s -> thread_id=%sz/[%s] Failed to reload dm_topics from config: %s)r!  r  r"  r#  r$  r%  r)  r-  r$  r.  r#  r  r   r  r   r   r   )r   r  r'  r(  r)  r   r   r  cidr.  tidr   r
  r   s                 r   _reload_dm_topics_from_configz-TelegramAdapter._reload_dm_topics_from_configL  s   ,	Z888888)/++m;K%%''     k3999 2Q++1r2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 

;++Z$$Wb!!["%%	   )+&*-%%' &/D"' '=F' ' 'D# (  
 nnY// #"55 
 
A%%,,C55==D t '*OOTOO	$DO;;9<SDOI6"KK Z $	9c  
	   	Z 	Z 	ZLLJDIWXYYYYYYYYY	ZsH   'F' F' A%F' %A))F' ,A)-A1F'  CF' '
G1!GGc                 x   |sdS t          |          }| j                                        D ]\  }}||k    r|                    | d          r|                    dd          d         }| j        D ]b}t          |                    d                    |k    r:|                    dg           D ]#}|                    d          |k    r|c c c S $cd|ic S |                                  | j                                        D ]\  }}||k    r|                    | d          r|                    dd          d         }| j        D ]b}t          |                    d                    |k    r:|                    dg           D ]#}|                    d          |k    r|c c c S $cd|ic S dS )zLook up DM topic config by chat_id and thread_id.

        Returns the topic config dict (name, skill, etc.) if this thread_id
        matches a known DM topic, or None.
        Nr  rv  r   r  r   )	r  r#  r|  r  rk  r-  r   r)  r:  )	r   r   rM  thread_id_intr  
cached_tidr  r  r.  s	            r   _get_dm_topic_infoz"TelegramAdapter._get_dm_topic_info  s     	4I  $4466 		, 		,OC]**s~~mmm/L/L* YYsA..q1
"&"8 ) )J:>>)4455@@!+"!=!= ) )A uuV}}
::'(  ;
++++ 	**,,,  $4466 	, 	,OC]**s~~mmm/L/L* YYsA..q1
"&"8 ) )J:>>)4455@@!+"!=!= ) )A uuV}}
::'(  ;
++++tr)   c                     | d| }|| j         vr;t          |          | j         |<   t                              d| j        ||           dS dS )zLCache a thread_id -> topic_name mapping discovered from an incoming message.r  z5[%s] Cached DM topic from message: %s -> thread_id=%sN)r#  r  r   r  r   )r   r   rM  r  r
  s        r   _cache_dm_topic_from_messagez,TelegramAdapter._cache_dm_topic_from_message  sh    ----	DO++),YDOI&KKG	9i     ,+r)   r   c                     |dS t          |t                    r|S t          |t                    r!d                     fd|D                       S t          |t                    rX|                    d          }|                     |          S |                    d          }|                     |          S dS )zFBest-effort plaintext flattener for Bot API rich-message inline nodes.Nr   c              3   B   K   | ]}                     |          V  d S r$   )_flatten_rich_inline_text)r   itemr  s     r   r  z<TelegramAdapter._flatten_rich_inline_text.<locals>.<genexpr>  s1      QQ4388>>QQQQQQr)   r   children)r  r   r  r   r  r)  rC  )r  r   r   rE  s   `   r   rC  z)TelegramAdapter._flatten_rich_inline_text  s     =2eS!! 	LeT"" 	R77QQQQ5QQQQQQeT"" 	?99V$$D44T:::yy,,H#44X>>>rr)   blocksc                 >   t          |t                    sdS g }|D ]b}t          |t                    s|                    d          }|dk    r|                    dg           D ]}t          |t                    s|                     |                    d                    }|sC|                    d          }|                                }|so|d         }	|r| d|	                                 }	|                    |	           |                    |d	d
                    Ő| 	                    |                    d                    }
|
r'|                    |
                                           dd
                    d |D                       S )z@Best-effort plaintext flattener for Bot API rich-message blocks.r   r|  r  r|  rF  r  r   r  rv  Nr   r   c              3   B   K   | ]}||                                 V  d S r$   )rstripr2  s     r   r  z7TelegramAdapter._flatten_rich_blocks.<locals>.<genexpr>  s/      AA4DAAAAAAAr)   )r  r  r  r)  _flatten_rich_blocksr8  rb  r   r  rC  r   )r  rF  linesblock
block_typerD  	item_textr  
item_lines
first_liner   s              r   rJ  z$TelegramAdapter._flatten_rich_blocks  s    &$'' 	2 	0 	0EeT** 6**JV##!IIgr22 1 1D%dD11 !  # 8 8(9K9K L LI$ !  HHW--E!*!5!5!7!7J% ! !+AJ E(-%<%<
%<%<%B%B%D%D
LL,,,LLABB00000061B1BCCD 0T__..///yyAA5AAAAAAr)   rG  c                 N   	 t          |dd          }t          |dd          }t          |          sdS  |d          }t          |dd          }t          |          sdS |                      |d                                                    }|pdS # t          $ r Y dS w xY w)zAReturn plaintext echoed by Telegram's rich_message reply payload.rr  Nr)  rh  rF  )rL   rh  rJ  rb  r   )r  rG  rr  getterrh  rich_getterr   s          r   _extract_rich_reply_textz(TelegramAdapter._extract_rich_reply_text  s    	 !1<FFJZ55FF## t!6.11L!,t<<KK(( t++KK,A,ABBHHJJD<4 	 	 	44	s   1B +B "3B 
B$#B$c                 V	   |j         }|j        }t          t          |dd                                        d          d                                         }d}|dv rd}n|dk    rd}|                     |          }d	}	d	}
|dk    r|r|                     t          |j                  |          }|r*|	                    d
          }	|	                    d          }
t          |d          rB|j        r;|j        j        }|r-|                     t          |j                  ||           |	s|}	n`|dk    rY|rV| j        j        	                    dg           }t!          |t"                    rd |                                D             }n$t!          |t&                    rd |D             }ng }|D ]}t          |	                    dd                    t          |j                  k    r|	                    dg           }t!          |t&                    sg }|D ]n}t!          |t"                    s|	                    d          }|?t          |          |k    r,|	                    d
          }	|	                    d          }
 no n|                     t          |j                  |j        pt          |d          r|j        nd	||rt          |j                  n|dv rt          |j                  nd	|r|j        n+t          |d          r|dk    r|j        n|dk    r|j        nd	||	t          |j                  |rt1          t          |dd                    nd	  	        }d	}d	}|j        rt          |j        j                  }t          |dd	          }|t          |dd	          nd	}|r|}nz|j        j        p|j        j        pd	}|s|                     |j                  }|sB	 ddlm} |                    t          |j                  |          }n# t@          $ r d	}Y nw xY wddl!m"} t          |j                  } || j        j        |p||r|nd	          }tG          |j        pd|||t          |j                  ||||
||j$                  S )aO  Build a MessageEvent from a Telegram message.

        ``update_id`` is the ``Update.update_id`` from PTB; passing it through
        lets ``/restart`` record the triggering offset so the new gateway
        process can advance past it (prevents ``/restart`` being re-delivered
        when PTB's graceful-shutdown ACK fails).
        r|  r   rB  r"  rV  >   r   rX  r   r  Nr   skillforum_topic_createdgroup_topicsc                     g | ]
\  }}||d S )r  rj   )r   cfg_chat_idr  s      r   rE  z8TelegramAdapter._build_message_event.<locals>.<listcomp>3   s4     % % %+V !,v>>% % %r)   c                 <    g | ]}t          |t                    |S rj   )r  r  )r   r  s     r   rE  z8TelegramAdapter._build_message_event.<locals>.<listcomp>8   s8     % % %#jPT>U>U%% % %r)   r   r  rM  ry  >   rV  r  is_botF)	r   	chat_namerL  rO  rN  rM  
chat_topicrn  r\  quoter   r   rx  )resolve_channel_prompt)r   r  rp  r  rn  platform_update_idr  reply_to_text
auto_skillr  r  )%rv  ru  r   rL   rk  rj  rE  r>  rw  r)  r  rW  r   r@  r   r(  r  r  r|  r  build_sourcer{  ry  rn  r'  rG  r   rN  rT  r~  ry  lookupr   r  r`  rp   date)r   r?  r  r  rv  r  telegram_chat_typerL  thread_id_strr^  topic_skill
topic_infocreated_namegroup_topics_configgroup_topics_iterr  r  r  r9  rp  rd  rb  r_  
quote_textry  r`  _chat_id_str_channel_prompts                               r   r  z$TelegramAdapter._build_message_event  s    | 
 !vr!:!:;;AA#FFrJPPRR	!888II9,,!I 99'BB
00TW}MMJ 6'^^F33
(nnW55 w 566 27;V 2&:? 255c$'llMS_```% 2%1
'!!m! #'+"3"7"7"K"K-t44 
'% %/B/H/H/J/J% % %!! /66 '% %':% % %!! %'!/  
z~~i4455TWEE'^^Hb99F%fd33 $!#!' " ")%66 %$#ii44?s3xx=/H/H).6):):J*/))G*<*<K!EE F ""LLj\wt[7Q7Q%[T^^W[ PDG&/3D&D&Dc$'lll$  t[11J6?46G6G NN(1Y(>(>$**D $!7-..;?J4h66777U+ # 
 
@ # 	-g6ABBKGWd33E9>9J555PTJ - * ,1 /7 
 % \ %)$A$A'BZ$[$[M$ --;;;;;;(7(>(>LL+) ) % - - -(,- 	BAAAAA47||00K)\)3LLt
 
 #!7-..( +'"*l
 
 
 	
s   ;.P* *P98P9c                 T    t          j        dd                                          dvS )z6Check if message reactions are enabled via config/env.TELEGRAM_REACTIONSr  >   r  r  r  )r   r   rj  r   s    r   _reactions_enabledz"TelegramAdapter._reactions_enabled   s'    y-w77==??G[[[r)   r+  c                   K   | j         sdS 	 | j                             t          |          t          |          |           d{V  dS # t          $ r-}t
                              d| j        ||           Y d}~dS d}~ww xY w)z2Set a single emoji reaction on a Telegram message.Fr   rn  reactionNTz)[%s] set_message_reaction failed (%s): %sr  set_message_reactionr   r  r   r   r   r   )r   r   rn  r+  r   s        r   _set_reactionzTelegramAdapter._set_reaction   s      y 	5		)0027;;z?? 1         
 4 	 	 	LLDdiQVXYZZZ55555	s   =A 
B"A>>Bc                 
  K   | j         sdS 	 | j                             t          |          t          |          d           d{V  dS # t          $ r,}t
                              d| j        |           Y d}~dS d}~ww xY w)uN  Clear all reactions from a Telegram message.

        Calling ``set_message_reaction`` with ``reaction=None`` (or an empty
        sequence) is the documented Bot API way to remove all bot-set
        reactions on a message — equivalent to Bot API 10.0's
        ``deleteMessageReaction`` but supported in PTB 22.6 already.
        FNru  Tz[%s] clear reactions failed: %srw  r/  s       r   _clear_reactionsz TelegramAdapter._clear_reactions   s       y 	5		)0027;;z?? 1         
 4 	 	 	LL:DIqIII55555	s   =A 
B!A==Bc                    K   |                                  sdS t          |j        dd          }t          |dd          }|r!|r!|                     ||d           d{V  dS dS dS )z;Add an in-progress reaction when message processing begins.Nr   rn  u   👀)rs  rL   rp  ry  )r   r~  r   rn  s       r   on_processing_startz#TelegramAdapter.on_processing_start   s      &&(( 	F%,	488UL$77
 	Hz 	H$$Wj,GGGGGGGGGGG	H 	H 	H 	Hr)   outcomec                 J  K   |                                  sdS t          |j        dd          }t          |dd          }|r|sdS |t          j        k    r|                     ||           d{V  dS |                     |||t          j        k    rdnd           d{V  dS )u  Swap the in-progress reaction for a final success/failure reaction.

        Unlike Discord (additive reactions), Telegram's set_message_reaction
        replaces all existing reactions in one call — no remove step needed.

        On CANCELLED outcomes (e.g. the user runs ``/stop``, or a session is
        interrupted mid-flight), we explicitly clear the 👀 in-progress
        reaction so it doesn't linger on the user's message indefinitely.
        Without this clear, the only way to remove the 👀 was to wait for
        another agent run to swap it to 👍/👎 — which never happens if the
        cancellation was the last activity in the chat.
        Nr   rn  u   👍u   👎)rs  rL   rp  rr   	CANCELLEDr{  ry  SUCCESS)r   r~  r~  r   rn  s        r   on_processing_completez&TelegramAdapter.on_processing_complete   s       &&(( 	F%,	488UL$77
 	J 	F'111''<<<<<<<<<<<$$ '+<+D D D,          r)   r0   )NN)NNNr$   r  )r   r   N)rE  N)r   )r{  rQ   r  r  r   N)Nr.   )NNNN)rf   rg   rh   __doc__r  supports_code_blockssplits_long_messagesr  RICH_MESSAGE_MAX_BYTESr  r$  r  r   r'  __annotations__r  r  r  r  staticmethodr   r   r   r   propertyr   rn   r  r:  r=  rC  rE  r   r	   rJ  rs  rS   r  r  r  classmethodr  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r	  r  r  r"  r   r<  r}  DOTALLr$  r&  r+  r)  r,  r9  r<  r>  r@  rD  rF  rH  rM  rX  r[  r#  rf  rs   r  r  r  r  r  r   r!  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r	  r4  r7  r6  r  rN  r  r  r^  r  r  r  r
  r	  r.  r2  r7  r9  rD  rU  rY  rg  r}  r  r  rz  r  r  r  r  r)  r  rA  rI  rL  rc  r   ry  r  re  r  r  r  r  r  r  r  r  r
  r  r$  r  r   r%  r)  r/  r4  Patternr  rC  rE  rI  re  rm  ro  rq  rs  ru  ry  r}  rp   r  r  r  rq   r  r  r  r  r  r  r  rw  r  r  rQ   r  r]   ri   r  r  r  r  r  r  r  r  r  r  r  r"  r  r:  r>  r@  rC  rJ  rT  r  rs  ry  r{  r}  rr   r  __classcell__)r8  s   @r   r   r     s&           # 4 "" $(D''' #  $
 &*%)   E?	
 E? 
   \6   X[?~ [? [? [? [? [? [?z" " " " " "% % % % % %ES E3 Ed Et E E E E E EFt F F F F. c3h0.	c3h. . . .& "&#'#'#'2G 2G 2G2G #	2G
 C=2G C=2G C=2G 
2G 2G 2G 2Gh:
W :
 :
 :
 :
x
?t 
? 
? 
? 
?B< B<D B< B< B< B<H A8DcN+C AQT A A A [A ?(4S>:R ?W_`cWd ? ? ? [? ?Xd38n5M ?RZ[^R_ ? ? ? [? S T    \ 

 C=
 4S>*	

 

 
 
 [
, rC r r r \r  .2'+	 3- 4S>*  }	
 
#   [ 
 .2-1'+*Q *Q*Q C=*Q 4S>*	*Q
 &c]*Q  }*Q 
c3h*Q *Q *Q [*QX HSM hsm    [
 
hsm 
QT 
 
 
 [
 8) 8 8 8 8 \8'''*'	' ' ' 'R Y 4    \ )) 4S>*) &c]	)
 
) ) ) [)d &* 1  1 1 #s(^ 1 4S>*	 1
 &c] 1  1 c] 1 
 1  1  1  1DctCy c c c c 
I 
$ 
 
 
 \
 * *t * * * \* 9     \6  	  d       \ D c D T    2d38n 2 2 2 2$	; 	; 	; 	; 	; 	;
WD 
W 
W 
W 
W "rz"BBMTVT]D]^^)rz	N
 		!    2:		 	Lc d     C3 C4 C C C CS T    ,c d    *
c 
d 
 
 
 

c 
d 
 
 
 
, BF
 

&.tCH~&>
	
 
 
 
 BF &.tCH~&>	   (3-    ( >C  6:	c3h   "%Y %4 % % % %,<9 < < < < <,*,* 3-,* 4S>*	,*
 C=,* 
%,* ,* ,* ,*\i
i
 i
 3-	i

 4S>*i
 
*	i
 i
 i
 i
` .2S? S?S? S? 	S?
 4S>*S? 
*	S? S? S? S?j
# 
$ 
 
 
 
&& & 	&
 4S>*& 
& & & &P) ) ) )V    # # # #JS	 Sc Sd S S S S44    4d _c    B|0 |0t |0 |0 |0 |0|A A A AFdu d d d d dL+@ +@ +@ +@Z=
 =
 =
 =
~Q-I Q-$ Q- Q- Q- Q-n %).21 11 1 SM	1
 'sm1 
#1 1 1 1f55 5 
#	5 5 5 5$3 3S 3c 3QU 3bjknbo 3 3 3 3j

 
 	

 

 
 
 
8 "'Hj HjHj Hj 	Hj
 Hj 
Hj Hj Hj HjTR R R Rh
 
 
 
J/ J/ J/ J/X 5: K K KT Kd K K K KZ$ 4    :-, -, -, -,^CB CB CB CBJ$Xc] $ $QU $ $ $ $0 #'-1E EE E 3-	E
 4S>*E 
E E E EZ
 .2         	  4S>*  
       P -1I? I? I?I? I? 	I? I? 4S>*I? 
I? I? I? I?V     , .2H
 H
 H
H
 H
 	H
 H
 4S>*H
 
H
 H
 H
 H
TC S T    6 $(-1> >C=> 4S>*> 
	> > > >0 .2WA WAWA WA 	WA
 4S>*WA 
WA WA WA WAr% % %P 9;-1); ););$');25);); 4S>*); 
	); ); ); );Z /-1F; F;F;%(F;7:F;F; 4S>*F; 
	F; F; F; F;T ?C.; .;.;#&.;14.;CF.;.;#+DcN#;.; 
.; .; .; .;n .2P; P;P; P; $	P;
 P; P; 4S>*P; 
P; P; P; P;t .2F; F;F; F; 	F;
 F; F; 4S>*F; 
F; F; F; F;P E5 E5$ E5c E5% E5 E5 E5 E5N'5D '5 '5 '5 '5 '5 '5RM!M!),M!	M! M! M! M!^
     2eSeS)DeS	eS eS eS eS^ )r;KUZ[%r>UZ[)r;NUZ["r;LUZ[&y;UYZ&z;MUYZ-y=UYZ-z;OUYZ%y;KUYZ%z;RUYZ \ \ 
\ \ \ \|s # #    

C 

C 

TW 

\_ 

 

 

 

R3 Rs RuTS[\_S`M`Ga R R R R$ "&"&-1Yg YgYg Yg #	Yg
 3-Yg 4S>*Yg 
Yg Yg Yg Yg Yg Yg~ .2 E EE UE 4S>*	E
 E 
E E E E E EV "&"&-1[p [p[p [p #	[p
 3-[p 4S>*[p 
[p [p [p [p [p [pB "&#'"&-14t 4t4t 4t #	4t
 C=4t 3-4t 4S>*4t 
4t 4t 4t 4t 4t 4tt "&"&-10g 0g0g 0g #	0g
 3-0g 4S>*0g 
0g 0g 0g 0g 0g 0gl "&"&-1\j \j\j \j #	\j
 3-\j 4S>*\j 
\j \j \j \j \j \jD "&"&-1-g -g-g -g #	-g
 3--g 4S>*-g 
-g -g -g -g^! ! !c3h8P !\` ! ! ! !F I3  I4S>  I  I  I  IDjc jc j j j j\d4 d d d dwd w w w w"_d _ _ _ _j$ j j j jNs3x N N N NNS N N N NNs3x N N N NS    N#c( N N N N3s8    *$4
+; $ $ $ $L4g 4$ 4 4 4 4 7 x}    [4f fD f f f f 3' 3'CH 3' 3' 3' \3'j6W 6 6 6 6 6p]7 ]t ] ] ] ]0	 	T 	 	 	 	S ST S S S SHSM hsm    1 1T 1 1 1 1f[ [ [;\ ;c ; ; ; ;


 

 

 

 


| 
P\ 
 
 
 
6$w $; $ $ $ $6[w 6[| 6[PT 6[ 6[ 6[ 6[p,Wc ,W, ,W4 ,W ,W ,W ,W\"' " " " " ' 'S 'S ' ' ' \' '+'H 'H'H 'H 	'H
 'H sm'H 
'H 'H 'H 'HZ $((,!c !c!c !c C=	!c
 %!c 
!c !c !c !cFPw P4 P P P P" OT S? S? S?w S?t S?X\ S? S? S? S?j` ` ` `2^ ^8G;L ^ ^ ^ ^( (,B[ (`d ( ( ( (B)F )\=V )[_ ) ) ) ),-)V -)lF_ -)dh -) -) -) -)f
\ 
c 
 
 
 
"
 "
$ "
 "
 "
 "
H->3 ->4 -> -> -> ->f,l , ,S , , , ,E# E$ E E E E"mc m, m4 m m m m*W)& W)<C\ W)ae W) W) W) W)r
S 
 
Z^ 
 
 
 
:BS BT B B B B ? ? ?D ? ? ? ?B2Z 2Z 2Z 2Zh%# %(3- %HUYZ]_bZbUcLd % % % %NC C UX ]a     c c    [" !B# !B# !B !B !B [!BF      [( $(	f
 f
f
 f
 C=	f

 
f
 f
 f
 f
T\D \ \ \ \3 C  PT    c s t    *H| H H H H H, IZ _c        r)   r   c                  Z   t          j        dd          } | sn	 ddlm} ddlm}  |            } ||dddd	          }|d
vr3t          |                                                                          } n# t          $ r Y nw xY w| pd} | dvrt                              d|            d} | S )zResolve the Telegram notification mode (all/important) from env or
    config.yaml display.platforms.telegram.notifications, defaulting to
    'important'.  Mirrors the post-construction logic that used to live in
    gateway/run.py::_create_adapter().HERMES_TELEGRAM_NOTIFICATIONSr   r   )load_gateway_config)cfg_getr  r  r   notifications>   Nr   r   >   r  r   z[Unknown telegram notifications mode '%s', defaulting to 'important' (valid: all, important))r   r   gateway.configr  gateway.runr  r   rb  rj  r   r   r  )r  r  r  _gw_cfg_raws        r   _resolve_notifications_moder     s    
 94b99D 		::::::++++++))++G77I{JXXD:%%4yy((..00 	 	 	D	;D'''&'+	
 	
 	
 Ks   AA6 6
BBc                 |    t          |           }	 t                      |_        n# t          $ r
 d|_        Y nw xY w|S )zFactory wrapper that constructs TelegramAdapter and applies the
    notification mode (preserving the gateway/run.py post-construction step).r   )r   r  r4  r   )r   adapters     r   _build_adapterr  !  sU     f%%G2&A&C&C## 2 2 2&1###2Ns   % 99c                     t          | dd          }|sddlm} |                    d          pd}t	          t          |                                                    S )u  Telegram is connected when a bot token is configured.

    check_telegram_requirements() only verifies the python-telegram-bot SDK is
    importable, NOT that a token is set — so without this is_connected the
    registry-driven plugin-enable pass in gateway/config.py would enable
    Telegram on any machine that merely has the SDK installed. Gate on the
    token (env or PlatformConfig.token), matching the generic token check
    Telegram had as a built-in.
    r  Nr   TELEGRAM_BOT_TOKENr   )rL   hermes_cli.gatewayr~  get_env_valuer'  r   rb  )r   r  gateway_mods      r   _is_connectedr  $!  si     FGT**E F000000))*>??E2E

  ""###r)   )rM  media_filesforce_documentc          	         K   t          | dd          pt          j        dd          }t          t          | di           o| j                            d                    }ddlm}  ||||||||	           d{V S )
aw  Out-of-process Telegram delivery. Delegates to the standalone
    ``_send_telegram`` REST sender in tools/send_message_tool.py (which already
    handles chunking-agnostic single sends, threads, media, retries, and
    parse-mode fallback). Implements the standalone_sender_fn contract so
    deliver=telegram cron jobs succeed when cron runs separately from the
    gateway.r  Nr  r   r(  r   r   )_send_telegram)r  rM  r   r  )rL   r   r   r'  r(  r)  tools.send_message_toolr  )	pconfigr   r?  rM  r  r  r  r   r  s	            r   _standalone_sendr  5!  s       GWd++Rry9Mr/R/RE "%%T'-*;*;<S*T*T  7666663%         r)   c                  :    ddl m}  |                                  dS )a`  Configure Telegram bot credentials and allowlist.

    Delegates to the existing CLI setup helpers (managed-bot QR onboarding,
    token validation, allowlist capture) via lazy import so the full wizard
    behavior is preserved without duplicating ~150 lines. Replaces the
    _PLATFORMS["telegram"] static dict dispatch in hermes_cli/gateway.py.
    r   )setupN)
hermes_clir  _setup_telegram)
_setup_mods    r   interactive_setupr  T!  s.     /.....     r)   yaml_cfgtelegram_cfgc                    ddl }i }d|v r|                    d|d                    |                    d|                     d                    }|Bt          j        d          s.t          |                                          t          j        d<   d|v r<t          j        d          s(|                    |d                   t          j        d<   d|v rHt          j        d	          s4t          |d                                                   t          j        d	<   d
|v rHt          j        d          s4t          |d
                                                   t          j        d<   d|v rHt          j        d          s4t          |d                                                   t          j        d<   d|v rHt          j        d          s4t          |d                                                   t          j        d<   |                    d          }|dt          j        d          sPt          |t                    rd                    d |D                       }t          |          t          j        d<   |                    d          }|dt          j        d          sPt          |t                    rd                    d |D                       }t          |          t          j        d<   |                    d          }|dt          j        d          sPt          |t                    rd                    d |D                       }t          |          t          j        d<   |                    d          }|dt          j        d          sPt          |t                    rd                    d |D                       }t          |          t          j        d<   d|v rHt          j        d          s4t          |d                                                   t          j        d<   d|v rHt          j        d           s4t          |d                                                   t          j        d <   t          |                    d!          t                    r|                    d!          ni }	d"|v r|d"         n|	                    d"          }
|
Jt          j        d#          s6|
d$u rd%n t          |
                                          }|t          j        d#<   |                    d&          }|dt          j        d'          sPt          |t                    rd                    d( |D                       }t          |          t          j        d'<   |                    d)          }|dt          j        d*          sPt          |t                    rd                    d+ |D                       }t          |          t          j        d*<   |                    d,          }|dt          j        d-          sPt          |t                    rd                    d. |D                       }t          |          t          j        d-<   d/D ]"}||v r|                    |||                    #h d0}|	                                D ]\  }}||vr|                    ||            |pdS )1a  Translate config.yaml telegram: keys into TELEGRAM_* env vars and
    PlatformConfig.extra entries.

    Implements the apply_yaml_config_fn contract (#24849). Mirrors the legacy
    telegram_cfg block from gateway/config.py::load_gateway_config(). Env vars
    take precedence over YAML. Returns a dict of extras to merge into
    PlatformConfig.extra (disable_topic_auto_rename + runtime flags), or None.
    r   Ndisable_topic_auto_renamer  r  r6  r7  r  r  
allow_botsTELEGRAM_ALLOW_BOTSr  r	  r  r  r  r  rf  c              3   4   K   | ]}t          |          V  d S r$   r   r  s     r   r  z%_apply_yaml_config.<locals>.<genexpr>!  s(      //a3q66//////r)   r  r  c              3   4   K   | ]}t          |          V  d S r$   r   r  s     r   r  z%_apply_yaml_config.<locals>.<genexpr>!  s(      --Q#a&&------r)   r+  r,  c              3   4   K   | ]}t          |          V  d S r$   r   r  s     r   r  z%_apply_yaml_config.<locals>.<genexpr>!  s(      %E%Ec!ff%E%E%E%E%E%Er)   r1  r2  c              3   4   K   | ]}t          |          V  d S r$   r   r  s     r   r  z%_apply_yaml_config.<locals>.<genexpr>!  s(      &G&G!s1vv&G&G&G&G&G&Gr)   	reactionsrr  r  rt  r(  r   TELEGRAM_REPLY_TO_MODEFr  r  r\  c              3   4   K   | ]}t          |          V  d S r$   r   r  s     r   r  z%_apply_yaml_config.<locals>.<genexpr>!  s(      $C$CSVV$C$C$C$C$C$Cr)   group_allow_fromr  c              3   4   K   | ]}t          |          V  d S r$   r   r  s     r   r  z%_apply_yaml_config.<locals>.<genexpr>!  (      *O*Oa3q66*O*O*O*O*O*Or)   r"  r  c              3   4   K   | ]}t          |          V  d S r$   r   r  s     r   r  z%_apply_yaml_config.<locals>.<genexpr>!  r  r)   )r  r   r  >   	dm_policyr  group_policyreply_prefixr   channel_promptsnotice_deliveryreply_in_threadr  allow_admin_fromchannel_skill_bindingsunauthorized_dm_behaviorgateway_restart_notification)r:  r  r)  r   r   r   rj  environdumpsr  r  r   rb  r  r|  )r  r  _jsonextras_effective_rmfrcacr+  r1  _telegram_extra_telegram_rtm_rtm_strallowed_usersgroup_allowed_usersr"  _key_GENERIC_MERGE_KEYS_k_vs                      r   _apply_yaml_configr  `!  s    F"l225|D_7`aaa $$%6EV8W8WXXM 3M)N)N 14]1C1C1I1I1K1K
-.\))")<W2X2X)27++lK]>^2_2_
./<//	Bc8d8d/8;LIa<b8c8c8i8i8k8k
45|##BI6K,L,L#,/\0J,K,K,Q,Q,S,S
()|##BI6K,L,L#,/\0J,K,K,Q,Q,S,S
()+|;;BIN{D|D|;DGUyHzD{D{  EB  EB  ED  ED
@A


0
1
1C
ry)GHHc4   	0((//3/////C58XX
12			/	*	*B	~bi(@AA~b$ 	.--"-----B/22ww
+,!%%&677N!")4M*N*N!nd++ 	F XX%E%En%E%E%EEEN03N0C0C
,-"&&'899O"295O+P+P"ot,, 	H!hh&G&G&G&G&GGGO14_1E1E
-.l""295I+J+J"+.|K/H+I+I+O+O+Q+Q
'(l""295E+F+F"'*<+D'E'E'K'K'M'M
#$3=l>N>Nw>W>WY]3^3^fl&&w///dfO)8L)H)H_%%  11   3K)L)L )U2255M8J8J8P8P8R8R/7
+, $$\22M 3K)L)L mT** 	DHH$C$C]$C$C$CCCM/2=/A/A
+,&**+=>>&ry9W/X/X&)400 	P"%((*O*O;N*O*O*O"O"O589L5M5M
12&**+@AA&ry9W/X/X&)400 	P"%((*O*O;N*O*O*O"O"O589L5M5M
12] 8 8<dL$6777   "'')) & &B(((b"%%%>Tr)   c                     |                      ddt          t          t          dgdt          t
          dddt          dd	d
           dS )u:   Plugin entry point — called by the Hermes plugin system.r   Telegramr  z$pip install 'hermes-agent[telegram]'r\  r  TELEGRAM_HOME_CHANNELr   u   ✈️T)r   r  adapter_factorycheck_fnis_connectedrequired_envinstall_hintsetup_fnapply_yaml_config_fnallowed_users_envallow_all_envcron_deliver_env_varstandalone_sender_fnmax_message_lengthr+  allow_update_commandN)register_platformr  r   r  r  r  r  )ctxs    r   registerr  !  s\    &,"*+;"/204-!!      r)   r0   )zr  r   r|  r   r:  loggingr   htmlrM  r   r4   r   r   r  r   r   r   r   r	   	getLoggerrf   r   objectr   r   r  r   r   rC   r=   rP   r   rQ   rR   rS   rT   rU   rW   r   r   rY   rZ   r[   r\   r   r]   r^   r   r`   ra   r   rc   r   re   syspathlibrk   r*  r  insert__file__r  parentsr  rm   rn   r  ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   'plugins.platforms.telegram.telegram_idsr   +plugins.platforms.telegram.telegram_networkr   r   r   utilsr   r   r   r
  r	  r  r'  r   r<  r   r   r   r   r   gateway.platforms.helpersr   r0  r   r  r  r   r   r  r   r  r  r  r  r  r  r  r  rj   r)   r   <module>r     s            				     				     ' ' ' ' ' ' ' ' 1 1 1 1 1 1 1 1 1 1 1 1 1 1		8	$	$
+v 
+# 
+ 
+ 
+ 
+Y', Y4 Y Y Y Y PT 5 5 5% 5 5 5 5pN N N N#V #V #V #VJ&%YYYYYYYYYYYYYY"/////// " " "!"                76666666------ % % %F
CGKN LGIH       $LLL+%. 


 ! ! ! ! ! ! 33uuX..008;<< = = = 3 3 3 3 3 3 3 3                                   $              
 5 4 4 4 4 4 4 4 4 4GGG      4T 4 4 4 4r "*<==.s .s . . . .
c c    ,  *rz9    

Is 
Is 
I 
I 
I 
I*        'BJ L  S S    H  H} H} H} H} H}) H} H} H}tzS    4  $T $ $ $ $,     >	! 	! 	! 	!^ ^T ^dTk ^ ^ ^ ^B     s6   4B8 B
 	B8 
BB8 B#B8 82C-,C-